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.

fix: tighten same-account pairing after review

leepokai7a5febfe8791
diff --git a/.env.development.example b/.env.development.example
index 80881a9f..e5a7f248 100644
--- a/.env.development.example
+++ b/.env.development.example
@@ -5,3 +5,7 @@
# accepted. `npm run dev` in a worktree uses it (apps/desktop/tools/dev-account.mjs) to sign the sandbox into
# its own test account, and `npm run dev -- --prune` to delete that account again.
CODYNC_CLERK_SECRET_KEY=sk_test_replace_me
+
+# The device certificate key (Ed25519 private key as JWK JSON) of the development cloud: `wrangler secret put
+# DEVICE_CERT_KEY --env dev` from cloud/ (cloud/README.md). Dev hosts compile in its public half.
+# CODYNC_DEVICE_CERT_KEY={"kty":"OKP","crv":"Ed25519","d":"…","x":"…"}
diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/OnboardingTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/OnboardingTest.kt
index 2e03015a..0ae72bec 100644
--- a/apps/android/app/src/androidTest/kotlin/com/codync/android/OnboardingTest.kt
+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/OnboardingTest.kt
@@ -55,7 +55,7 @@ class OnboardingTest {
compose.onNodeWithText("Scan the pairing code").assertIsDisplayed()
compose.onNodeWithContentDescription("Step 2 of 2").assertIsDisplayed()
compose.onNodeWithText("codync-host pair").assertIsDisplayed()
- compose.onNodeWithText("Or paste a ${BuildConfig.URL_SCHEME}://pair link").performScrollTo().assertIsDisplayed()
+ compose.onNodeWithText("Pairing link or code").performScrollTo().assertIsDisplayed()
compose.onNodeWithContentDescription("Pair").assertIsNotEnabled()
compose.onNode(hasSetTextAction()).performTextInput("draft-link")
compose.onNodeWithContentDescription("Pair").assertIsEnabled()
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 e3b48acb..a14238af 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("Paste a pairing link, or type the code from the computer"), singleLine = true,
+ PlainTextField(pasted, { pasted = it }, Modifier.weight(1f), tr("Pairing link or code"), 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/HostConnector.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/HostConnector.kt
index 8a7b5a28..86090215 100644
--- a/apps/android/core/src/main/kotlin/com/codync/android/core/HostConnector.kt
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/HostConnector.kt
@@ -19,7 +19,7 @@ data class Paired(val computer: Computer, val claim: JsonObject?)
object HostConnector {
/**
- * Pairs with [certificate] as the account proof; a computer in no account first asks its user (up to two minutes),
+ * Pairs with [certificate] as the account proof; a computer in no account first asks its user (up to 90 seconds),
* then signs [claim] to join the phone's account.
*/
suspend fun pair(pairing: Pairing, identity: DeviceIdentity, deviceName: String, certificate: DeviceCertificate,
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/RelayCrypto.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/RelayCrypto.kt
index b340029f..60eafd02 100644
--- a/apps/android/core/src/main/kotlin/com/codync/android/core/RelayCrypto.kt
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/RelayCrypto.kt
@@ -44,7 +44,7 @@ object RelayCrypto {
return sixDigits(sha256(label("codync/sas/v2"), hostSignKey, deviceKey, deviceNonce, hostNonce))
}
- /** The code a computer shows when it asks whether to let this phone in by pairing (host `pairing_requests::check_code`). */
+ /** The code a computer shows when it asks whether to let this phone in by pairing (host `crypto::pair_check_code`). */
fun pairCheck(deviceKey: ByteArray, hostSignKey: ByteArray): String {
require(deviceKey.size == 32 && hostSignKey.size == 32) { "Invalid pairing code" }
return sixDigits(sha256(label("codync/pair-check/v1"), deviceKey, hostSignKey))
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 7b226513..7e0f9886 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
@@ -82,8 +82,7 @@ class PairingTest {
assertFails<IllegalArgumentException> { "AA".decodeBase64Url(32) }
}
- @Test fun `the pairing check code matches the host's`() {
- assertEquals("855066", RelayCrypto.pairCheck(ByteArray(32) { 1 }, ByteArray(32) { 2 }))
+ @Test fun `a pairing's check code is this phone's with that computer`() {
val pairing = Pairing.parse(link(), "codync")
val identity = DeviceIdentity(ByteArray(32) { 3 }, ByteArray(32) { 12 })
assertEquals(RelayCrypto.pairCheck(identity.deviceKey, pairing.computer.signKey.decodeBase64Url(32)), pairing.checkCode(identity))
diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/RelayVectorsTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/RelayVectorsTest.kt
index 52e71a36..e7d96413 100644
--- a/apps/android/core/src/test/kotlin/com/codync/android/core/RelayVectorsTest.kt
+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/RelayVectorsTest.kt
@@ -95,6 +95,11 @@ class RelayVectorsTest {
assertFails<IllegalArgumentException> { RelayCrypto.sasCode(ByteArray(31), ByteArray(32), ByteArray(32), ByteArray(32)) }
}
+ @Test fun `the pairing check code matches the host's`() {
+ val pairCheck = fixture.getValue("pairCheck").jsonObject
+ assertEquals(pairCheck.text("code"), RelayCrypto.pairCheck(keys.bytes("deviceSignPub"), keys.bytes("hostSignPub")))
+ }
+
@Test fun `mailbox key derivation remains compatible with the shared vector`() {
val mailbox = fixture.getValue("mailbox").jsonObject
val secret = RelayCrypto.sharedSecret(mailbox.bytes("ephPriv"), keys.bytes("hostBoxPub"))
diff --git a/apps/desktop/src/renderer/store/app-model.ts b/apps/desktop/src/renderer/store/app-model.ts
index 0a9ad7e2..baebfba2 100644
--- a/apps/desktop/src/renderer/store/app-model.ts
+++ b/apps/desktop/src/renderer/store/app-model.ts
@@ -63,6 +63,7 @@ export class AppModel extends Observable {
private signedIn: boolean | null = null
/** Approvals closed with "later"; they come back when the request changes (its code arrives). */
private deferred = new Set<string>()
+ private answeredPairings = new Set<string>()
private storeSubscriptions = new Map<string, () => void>()
/** The signed-in account's side of this computer (claims, cloud default, account computers). */
@@ -233,13 +234,16 @@ export class AppModel extends Observable {
await client.call('decideAccessRequest', { requestId: a.request.requestId, approve }, 30_000)
}
+ /** Phones waiting to be let in, without those answered here (the host's event takes them off a moment later). */
get pairingAsks(): PairingAsk[] {
- return this.managedStores.flatMap((store) =>
- store.pairingRequests.map((request) => ({ id: `${store.computer.id}/${request.requestId}`, store, request })),
- )
+ return this.managedStores
+ .flatMap((store) => store.pairingRequests.map((request) => ({ id: `${store.computer.id}/${request.requestId}`, store, request })))
+ .filter((ask) => !this.answeredPairings.has(ask.id))
}
async decidePairing(ask: PairingAsk, approve: boolean) {
+ this.answeredPairings.add(ask.id)
+ this.changed()
const client = await ask.store.ready()
await client.call('decidePairing', { requestId: ask.request.requestId, approve }, 30_000)
}
diff --git a/apps/desktop/src/renderer/views/PairingCode.tsx b/apps/desktop/src/renderer/views/PairingCode.tsx
index 575c0505..251ee3e3 100644
--- a/apps/desktop/src/renderer/views/PairingCode.tsx
+++ b/apps/desktop/src/renderer/views/PairingCode.tsx
@@ -1,6 +1,6 @@
import { useCallback, useEffect, useRef, useState } from 'react'
import QRCode from 'qrcode'
-import type { PairingInfo } from '@shared/models'
+import type { CloudStatus, PairingInfo } from '@shared/models'
import { IconButton, Spinner } from '../components/Controls'
import { HStack, VStack } from '../components/Stack'
import { Text } from '../components/Text'
@@ -14,7 +14,7 @@ import { useTr } from '../lib/use-language'
* A new code comes when `renew` changes and when this one expires on screen; when none comes, the
* error takes the place of the old code, which may have expired.
*/
-export function PairingCode({ name, cloudOn, requestCode, renew = 0 }: { name: string; cloudOn: boolean; requestCode: () => Promise<PairingInfo>; renew?: number }) {
+export function PairingCode({ name, cloud, requestCode, renew = 0 }: { name: string; cloud: CloudStatus | null; requestCode: () => Promise<PairingInfo>; renew?: number }) {
const tr = useTr()
const [code, setCode] = useState<{ info: PairingInfo; qr: string } | null>(null)
const [error, setError] = useState<string | null>(null)
@@ -55,7 +55,12 @@ export function PairingCode({ name, cloudOn, requestCode, renew = 0 }: { name: s
<Text as="div" size="caption" tone="secondary" className="pairing-note">
{tr(`Scan with the Codync app or the iPhone Camera. No Tailscale or open ports needed: your iPhone connects directly on the same Wi-Fi, and through the encrypted relay anywhere else.`)}
</Text>
- {!cloudOn ? (
+ {cloud?.canJoinAccount ? (
+ <Text as="div" size="caption" tone="attention" className="pairing-note">
+ {tr('Not in an account: a signed-in phone that scans this asks to bring the computer into its account.')}
+ </Text>
+ ) : null}
+ {cloud?.enabled !== true ? (
<Text as="div" size="caption" tone="attention" className="pairing-note">
{code.info.urls.length === 0
? tr(`No network address found and “Reach from anywhere” is off. Connect to Wi-Fi or turn it on.`)
diff --git a/apps/desktop/src/renderer/views/PairingRequestPrompt.tsx b/apps/desktop/src/renderer/views/PairingRequestPrompt.tsx
index 61c79546..ea045ba5 100644
--- a/apps/desktop/src/renderer/views/PairingRequestPrompt.tsx
+++ b/apps/desktop/src/renderer/views/PairingRequestPrompt.tsx
@@ -1,7 +1,7 @@
-import { useEffect, useState } from 'react'
+import { useEffect } from 'react'
import { Dialog } from '../components/Overlay'
import { pairingAskText } from '../lib/account-copy'
-import { useModels } from '../lib/observable'
+import { useModel, useModels } from '../lib/observable'
import { useTr } from '../lib/use-language'
import { useApp } from '../store/context'
import { errorText } from './settings/parts'
@@ -9,15 +9,13 @@ 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.
+ * host turns the phone away after 90 seconds.
*/
export function PairingRequestPrompt() {
const tr = useTr()
- const app = useApp()
+ const app = useModel(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
+ const ask = app.pairingAsks[0] ?? 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()
@@ -25,7 +23,6 @@ export function PairingRequestPrompt() {
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
diff --git a/apps/desktop/src/renderer/views/PairingWindow.tsx b/apps/desktop/src/renderer/views/PairingWindow.tsx
index d7f64a85..f3a80b6c 100644
--- a/apps/desktop/src/renderer/views/PairingWindow.tsx
+++ b/apps/desktop/src/renderer/views/PairingWindow.tsx
@@ -9,7 +9,7 @@ export function PairingWindow() {
// By value: the host's snapshot is a new object on each of its changes (every few seconds), and
// each request issues a new code.
const { baseURL, token } = useApp().host.local ?? {}
- const [cloudOn, setCloudOn] = useState(false)
+ const [cloud, setCloud] = useState<CloudStatus | null>(null)
const [name, setName] = useState('this computer')
// The window stays open between uses: each "Pair iPhone…" shows it again, with a new code.
const [shown, setShown] = useState(0)
@@ -25,10 +25,10 @@ export function PairingWindow() {
transport.call('cloudStatus', {}, 20_000).catch(() => null) as Promise<CloudStatus | null>,
transport.call('hello', {}, 20_000).catch(() => null) as Promise<{ name?: string } | null>,
])
- setCloudOn(status?.enabled === true)
+ setCloud(status)
if (hello?.name) setName(hello.name)
return pairing
}, [baseURL, token])
- return <PairingCode name={name} cloudOn={cloudOn} requestCode={requestCode} renew={shown} />
+ return <PairingCode name={name} cloud={cloud} requestCode={requestCode} renew={shown} />
}
diff --git a/apps/desktop/src/renderer/views/settings/ComputersView.tsx b/apps/desktop/src/renderer/views/settings/ComputersView.tsx
index 335a3665..9d18df32 100644
--- a/apps/desktop/src/renderer/views/settings/ComputersView.tsx
+++ b/apps/desktop/src/renderer/views/settings/ComputersView.tsx
@@ -346,7 +346,7 @@ function PairingPanel({ store }: { store: BotStore }) {
if (!client) throw new Error(`${store.hostName} isn't connected.`)
return client.call<PairingInfo>('pairing')
}, [store])
- return <PairingCode name={store.hostName} cloudOn={store.cloud?.enabled === true} requestCode={requestCode} />
+ return <PairingCode name={store.hostName} cloud={store.cloud} requestCode={requestCode} />
}
// MARK: SSH
diff --git a/apps/desktop/src/shared/models.ts b/apps/desktop/src/shared/models.ts
index 8045cdee..e04ad211 100644
--- a/apps/desktop/src/shared/models.ts
+++ b/apps/desktop/src/shared/models.ts
@@ -577,6 +577,8 @@ export interface CloudStatus {
relay?: 'codync' | 'private' | null
/** The user's cloud assistant may message this computer's bots (`setAssistants`). */
assistants?: boolean | null
+ /** In no account while it could join one: a signed-in phone that pairs asks to bring it into its account. Absent from older hosts. */
+ canJoinAccount?: boolean | null
}
export interface ClaimSignature {
diff --git a/apps/ios/Kit/Sources/CodyncKit/Client/HostConnector.swift b/apps/ios/Kit/Sources/CodyncKit/Client/HostConnector.swift
index 6ff4f522..6a6cd0dc 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Client/HostConnector.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Client/HostConnector.swift
@@ -40,7 +40,7 @@ public enum HostConnector {
struct Res: Decodable { var computerId: ComputerID; var name: String? }
let body = try JSONEncoder().encode(Body(code: pairing.code, name: deviceName, platform: platform, certificate: certificate, claim: claim))
try await transport.ready(within: 30)
- // The computer may be waiting for its user to let this phone in (up to 2 minutes).
+ // The computer may be waiting for its user to let this phone in (up to 90 seconds).
let data = try await transport.call("pair", body: body, timeout: 150)
await transport.shutdown()
let res = try JSONDecoder().decode(Res.self, from: data)
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json
index 97ada03b..2a72cb32 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json
@@ -365,7 +365,6 @@
"On your Mac, click Codync in the menu bar, then Pair iPhone.": "Klicke auf deinem Mac in der Menüleiste auf Codync und dann auf „iPhone koppeln“.",
"On your Mac, click Codync in the menu bar, then Pair iPhone. The same code pairs this phone.": "Klicke auf deinem Mac in der Menüleiste auf Codync und dann auf „iPhone koppeln“. Derselbe Code koppelt dieses Telefon.",
"On your computer, run this in a terminal:": "Führe auf deinem Computer Folgendes in einem Terminal aus:",
- "Or paste a {scheme}://pair link": "Oder füge einen {scheme}://pair-Link ein",
"Find nearby barcodes.": "Barcodes in der Nähe suchen.",
"Camera not available. Paste the link below.": "Kamera nicht verfügbar. Füge unten den Link ein.",
"Codync, at a glance.": "Codync auf einen Blick.",
@@ -1079,7 +1078,6 @@
"Reading speed": "Lesegeschwindigkeit",
"Send after a pause of": "Nach einer Pause senden von",
"Created by": "Erstellt von",
- "Devices that were approved through the account lose access. Devices paired with a QR code keep it.": "Über das Konto genehmigte Geräte verlieren den Zugriff. Per QR-Code gekoppelte Geräte behalten ihn.",
"It disconnects right away and has to pair or ask again.": "Es wird sofort getrennt und muss sich erneut koppeln oder eine Anfrage stellen.",
"Authorization: Bearer …": "Authorization: Bearer …",
"API_KEY=…": "API_KEY=…",
@@ -1144,7 +1142,6 @@
"Revoke {name}?": "{name} den Zugriff entziehen?",
"Remove the older {name}?": "Das ältere {name} entfernen?",
"It's an earlier identity of {name} and can't be reached anymore. Removing it only cleans up your account.": "Es ist eine frühere Identität von {name}, die nicht mehr erreichbar ist. Das Entfernen räumt nur dein Konto auf.",
- "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.": "Über das Konto genehmigte Geräte verlieren den Zugriff auf {name}. Es kehrt erst zurück, wenn du es auf {name} selbst wieder zum Konto hinzufügst.",
"Any device signed in to your account gets full control of {name}: its files, terminals and bots, with no check here. If someone gets into your account, or Codync's cloud is ever compromised, they could add their own device and you'd have no chance to stop it. Devices paired with a QR code aren't affected.": "Jedes in deinem Konto angemeldete Gerät erhält ohne weitere Prüfung hier volle Kontrolle über {name}: Dateien, Terminals und Bots. Falls jemand in dein Konto eindringt oder die Codync-Cloud kompromittiert wird, könnte er ein eigenes Gerät hinzufügen, ohne dass du es verhindern kannst. Per QR-Code gekoppelte Geräte sind nicht betroffen.",
"Pair iPhone with {name}": "iPhone mit {name} koppeln",
"Waiting for your OK on the computer · {code}": "Warten auf deine Bestätigung am Computer · {code}",
@@ -1490,7 +1487,8 @@
"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",
+ "Pairing link or code": "Kopplungslink oder Code",
+ "Or type this code in the app's pairing screen: {code}": "Oder gib diesen Code auf dem Kopplungsbildschirm der App ein: {code}",
"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.",
"Installing codync-host…": "codync-host wird installiert…",
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json
index ebb0d4ae..a6c9a053 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json
@@ -365,7 +365,6 @@
"On your Mac, click Codync in the menu bar, then Pair iPhone.": "En tu Mac, haz clic en Codync en la barra de menús y luego en Vincular iPhone.",
"On your Mac, click Codync in the menu bar, then Pair iPhone. The same code pairs this phone.": "En tu Mac, haz clic en Codync en la barra de menús y luego en Vincular iPhone. El mismo código vincula este teléfono.",
"On your computer, run this in a terminal:": "En tu computadora, ejecuta esto en una terminal:",
- "Or paste a {scheme}://pair link": "O pega un enlace {scheme}://pair",
"Find nearby barcodes.": "Buscar códigos de barras cercanos.",
"Camera not available. Paste the link below.": "Cámara no disponible. Pega el enlace a continuación.",
"Codync, at a glance.": "Codync, de un vistazo.",
@@ -1079,7 +1078,6 @@
"Reading speed": "Velocidad de lectura",
"Send after a pause of": "Enviar tras una pausa de",
"Created by": "Creado por",
- "Devices that were approved through the account lose access. Devices paired with a QR code keep it.": "Los dispositivos aprobados mediante la cuenta pierden el acceso. Los vinculados por QR lo conservan.",
"It disconnects right away and has to pair or ask again.": "Se desconecta de inmediato y debe vincularse o solicitar acceso de nuevo.",
"Authorization: Bearer …": "Authorization: Bearer …",
"API_KEY=…": "API_KEY=…",
@@ -1144,7 +1142,6 @@
"Revoke {name}?": "¿Revocar {name}?",
"Remove the older {name}?": "¿Eliminar el antiguo {name}?",
"It's an earlier identity of {name} and can't be reached anymore. Removing it only cleans up your account.": "Es una identidad anterior de {name} que ya no está accesible. Eliminarla solo limpia tu cuenta.",
- "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.": "Los dispositivos aprobados mediante la cuenta pierden el acceso a {name}. Solo vuelve cuando lo añades de nuevo a la cuenta desde el propio {name}.",
"Any device signed in to your account gets full control of {name}: its files, terminals and bots, with no check here. If someone gets into your account, or Codync's cloud is ever compromised, they could add their own device and you'd have no chance to stop it. Devices paired with a QR code aren't affected.": "Cualquier dispositivo que inicie sesión en tu cuenta obtiene control total de {name}: sus archivos, terminales y bots, sin comprobación aquí. Si alguien accede a tu cuenta o la nube de Codync se ve comprometida, podría añadir su dispositivo sin que puedas impedirlo. Los dispositivos vinculados por QR no se ven afectados.",
"Pair iPhone with {name}": "Vincular iPhone con {name}",
"Waiting for your OK on the computer · {code}": "Esperando tu aprobación en la computadora · {code}",
@@ -1490,7 +1487,8 @@
"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",
+ "Pairing link or code": "Enlace o código",
+ "Or type this code in the app's pairing screen: {code}": "O escribe este código en la pantalla de emparejamiento de la app: {code}",
"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.",
"Installing codync-host…": "Instalando codync-host…",
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json
index 13c5c224..321284c1 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json
@@ -365,7 +365,6 @@
"On your Mac, click Codync in the menu bar, then Pair iPhone.": "Sur votre Mac, cliquez sur Codync dans la barre des menus, puis sur Associer un iPhone.",
"On your Mac, click Codync in the menu bar, then Pair iPhone. The same code pairs this phone.": "Sur votre Mac, cliquez sur Codync dans la barre des menus, puis sur Associer un iPhone. Le même code permet d’associer ce téléphone.",
"On your computer, run this in a terminal:": "Sur votre ordinateur, exécutez ceci dans un terminal :",
- "Or paste a {scheme}://pair link": "Ou collez un lien {scheme}://pair",
"Find nearby barcodes.": "Rechercher les codes-barres à proximité.",
"Camera not available. Paste the link below.": "Caméra indisponible. Collez le lien ci-dessous.",
"Codync, at a glance.": "Codync, en un coup d’œil.",
@@ -1079,7 +1078,6 @@
"Reading speed": "Vitesse de lecture",
"Send after a pause of": "Envoyer après une pause de",
"Created by": "Créé par",
- "Devices that were approved through the account lose access. Devices paired with a QR code keep it.": "Les appareils approuvés via le compte perdent l’accès. Ceux associés par QR code le conservent.",
"It disconnects right away and has to pair or ask again.": "Il se déconnecte immédiatement et devra être associé ou refaire une demande.",
"Authorization: Bearer …": "Authorization: Bearer …",
"API_KEY=…": "API_KEY=…",
@@ -1144,7 +1142,6 @@
"Revoke {name}?": "Révoquer {name} ?",
"Remove the older {name}?": "Supprimer l’ancien {name} ?",
"It's an earlier identity of {name} and can't be reached anymore. Removing it only cleans up your account.": "Il s’agit d’une ancienne identité de {name}, désormais inaccessible. La supprimer ne fait que nettoyer votre compte.",
- "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.": "Les appareils approuvés via le compte perdent l’accès à {name}. Il ne revient que lorsque vous l’ajoutez de nouveau au compte depuis {name} lui-même.",
"Any device signed in to your account gets full control of {name}: its files, terminals and bots, with no check here. If someone gets into your account, or Codync's cloud is ever compromised, they could add their own device and you'd have no chance to stop it. Devices paired with a QR code aren't affected.": "Tout appareil connecté à votre compte obtient le contrôle total de {name} : fichiers, terminaux et bots, sans vérification ici. Si quelqu’un accède à votre compte ou si le cloud Codync est compromis, il pourrait ajouter son appareil sans que vous puissiez l’arrêter. Les appareils associés par QR code ne sont pas concernés.",
"Pair iPhone with {name}": "Associer l’iPhone à {name}",
"Waiting for your OK on the computer · {code}": "En attente de votre accord sur l’ordinateur · {code}",
@@ -1490,7 +1487,8 @@
"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",
+ "Pairing link or code": "Lien ou code d'appairage",
+ "Or type this code in the app's pairing screen: {code}": "Ou saisissez ce code dans l'écran d'appairage de l'app : {code}",
"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.",
"Installing codync-host…": "Installation de codync-host…",
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json
index 0af03220..b6d83b2e 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json
@@ -365,7 +365,6 @@
"On your Mac, click Codync in the menu bar, then Pair iPhone.": "Mac で、メニュー バーの Codync をクリックし、iPhone をペアリングします。",
"On your Mac, click Codync in the menu bar, then Pair iPhone. The same code pairs this phone.": "Mac で、メニュー バーの Codync をクリックし、iPhone をペアリングします。同じコードでこの電話をペアリングします。",
"On your computer, run this in a terminal:": "コンピューターのターミナルでこれを実行します。",
- "Or paste a {scheme}://pair link": "または、{scheme}://pair リンクを貼り付けます",
"Find nearby barcodes.": "近くのバーコードを見つけます。",
"Camera not available. Paste the link below.": "カメラが使用できません。以下のリンクを貼り付けてください。",
"Codync, at a glance.": "Codync、一目瞭然。",
@@ -1079,7 +1078,6 @@
"Reading speed": "読書速度",
"Send after a pause of": "一時停止してから送信する",
"Created by": "作成者",
- "Devices that were approved through the account lose access. Devices paired with a QR code keep it.": "アカウントを通じて承認されたデバイスはアクセスできなくなります。 QR コードとペアリングされたデバイスはそれを保持します。",
"It disconnects right away and has to pair or ask again.": "すぐに切断されるため、ペアリングするか、再度要求する必要があります。",
"Authorization: Bearer …": "Authorization: Bearer …",
"API_KEY=…": "API_KEY=…",
@@ -1144,7 +1142,6 @@
"Revoke {name}?": "{name} を取り消しますか?",
"Remove the older {name}?": "古い {name} を削除しますか?",
"It's an earlier identity of {name} and can't be reached anymore. Removing it only cleans up your account.": "これは {name} の以前のアイデンティティであり、もうアクセスできません。削除してもアカウントがクリーンアップされるだけです。",
- "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.": "アカウントを通じて承認されたデバイスは {name} にアクセスできなくなります。{name} 自体で再びアカウントに追加するまで戻りません。",
"Any device signed in to your account gets full control of {name}: its files, terminals and bots, with no check here. If someone gets into your account, or Codync's cloud is ever compromised, they could add their own device and you'd have no chance to stop it. Devices paired with a QR code aren't affected.": "アカウントにサインインしているデバイスは、ここにチェックを入れなくても、{name} (そのファイル、端末、ボット) を完全に制御できます。誰かがあなたのアカウントに侵入したり、Codync のクラウドが侵害されたりした場合、彼らは自分のデバイスを追加する可能性があり、あなたにはそれを止める機会がありません。 QR コードとペアリングされたデバイスは影響を受けません。",
"Pair iPhone with {name}": "iPhone と {name} をペアリングする",
"Waiting for your OK on the computer · {code}": "コンピューターであなたの OK を待っています · {code}",
@@ -1490,7 +1487,8 @@
"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": "ペアリングリンクを貼り付けるか、コンピューターに表示されたコードを入力します",
+ "Pairing link or code": "ペアリングリンクまたはコード",
+ "Or type this code in the app's pairing screen: {code}": "またはアプリのペアリング画面でこのコードを入力:{code}",
"That code isn't valid. Check it on the computer.": "このコードは無効です。コンピューターで確認してください。",
"That code expired or was used. Show a new one on the computer.": "このコードは期限切れか、すでに使用されています。コンピューターで新しいコードを表示してください。",
"Installing codync-host…": "codync-host をインストール中…",
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json
index 6c0e56d2..852486af 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json
@@ -365,7 +365,6 @@
"On your Mac, click Codync in the menu bar, then Pair iPhone.": "Mac의 메뉴 막대에서 Codync를 클릭한 다음 iPhone 페어링을 클릭하세요.",
"On your Mac, click Codync in the menu bar, then Pair iPhone. The same code pairs this phone.": "Mac의 메뉴 막대에서 Codync를 클릭한 다음 iPhone 페어링을 클릭하세요. 동일한 코드가 이 전화기와 페어링됩니다.",
"On your computer, run this in a terminal:": "컴퓨터의 터미널에서 다음을 실행하세요.",
- "Or paste a {scheme}://pair link": "또는 {scheme}://pair 링크를 붙여넣으세요.",
"Find nearby barcodes.": "가까운 바코드를 찾아보세요.",
"Camera not available. Paste the link below.": "카메라를 사용할 수 없습니다. 아래 링크를 붙여넣으세요.",
"Codync, at a glance.": "Codync를 한눈에 살펴보세요.",
@@ -1079,7 +1078,6 @@
"Reading speed": "읽기 속도",
"Send after a pause of": "말을 멈춘 뒤 전송까지",
"Created by": "만든 사람",
- "Devices that were approved through the account lose access. Devices paired with a QR code keep it.": "계정을 통해 승인된 기기는 접근 권한을 잃습니다. QR 코드로 페어링된 기기는 유지됩니다.",
"It disconnects right away and has to pair or ask again.": "즉시 연결이 끊기며 다시 페어링하거나 요청해야 합니다.",
"Authorization: Bearer …": "Authorization: Bearer …",
"API_KEY=…": "API_KEY=…",
@@ -1144,7 +1142,6 @@
"Revoke {name}?": "{name}의 접근 권한을 취소할까요?",
"Remove the older {name}?": "이전 {name}을 제거할까요?",
"It's an earlier identity of {name} and can't be reached anymore. Removing it only cleans up your account.": "더 이상 접근할 수 없는 {name}의 이전 식별 정보입니다. 제거해도 계정만 정리됩니다.",
- "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.": "계정을 통해 승인된 기기는 {name}에 대한 접근 권한을 잃습니다. {name}에서 직접 계정에 다시 추가해야 돌아옵니다.",
"Any device signed in to your account gets full control of {name}: its files, terminals and bots, with no check here. If someone gets into your account, or Codync's cloud is ever compromised, they could add their own device and you'd have no chance to stop it. Devices paired with a QR code aren't affected.": "계정에 로그인한 모든 기기는 여기서 별도의 확인 없이 {name}의 파일, 터미널, 봇을 완전히 제어할 수 있습니다. 누군가 계정에 침입하거나 Codync 클라우드가 침해되면 자신의 기기를 추가할 수 있으며 이를 막을 기회가 없습니다. QR 코드로 페어링한 기기는 영향을 받지 않습니다.",
"Pair iPhone with {name}": "{name}에 iPhone 페어링",
"Waiting for your OK on the computer · {code}": "컴퓨터에서 승인 대기 중 · {code}",
@@ -1490,7 +1487,8 @@
"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": "페어링 링크를 붙여넣거나 컴퓨터에 표시된 코드를 입력하세요",
+ "Pairing link or code": "페어링 링크 또는 코드",
+ "Or type this code in the app's pairing screen: {code}": "또는 앱의 페어링 화면에 이 코드를 입력하세요: {code}",
"That code isn't valid. Check it on the computer.": "유효하지 않은 코드입니다. 컴퓨터에서 확인하세요.",
"That code expired or was used. Show a new one on the computer.": "코드가 만료되었거나 이미 사용되었습니다. 컴퓨터에서 새 코드를 표시하세요.",
"Installing codync-host…": "codync-host 설치 중…",
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 0c711c8f..4678321b 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json
@@ -365,7 +365,6 @@
"On your Mac, click Codync in the menu bar, then Pair iPhone.": "在 Mac 上点菜单栏的 Codync,然后选配对 iPhone。",
"On your Mac, click Codync in the menu bar, then Pair iPhone. The same code pairs this phone.": "在 Mac 上点菜单栏的 Codync,然后选配对 iPhone。同一个码也能配这台手机。",
"On your computer, run this in a terminal:": "在电脑上的终端里运行:",
- "Or paste a {scheme}://pair link": "或粘贴 {scheme}://pair 链接",
"Find nearby barcodes.": "寻找附近的条形码。",
"Camera not available. Paste the link below.": "相机不可用。请把链接粘贴在下面。",
"Codync, at a glance.": "一眼看到 Codync。",
@@ -1079,7 +1078,6 @@
"Reading speed": "朗读速度",
"Send after a pause of": "停顿这么久之后发送",
"Created by": "创建者",
- "Devices that were approved through the account lose access. Devices paired with a QR code keep it.": "通过账户批准的设备会失去访问。用二维码配对的设备仍然保留。",
"It disconnects right away and has to pair or ask again.": "它会立刻断开,之后必须重新配对或再次请求。",
"Authorization: Bearer …": "Authorization: Bearer …",
"API_KEY=…": "API_KEY=…",
@@ -1144,7 +1142,6 @@
"Revoke {name}?": "撤销 {name} 的访问?",
"Remove the older {name}?": "移除较早的 {name}?",
"It's an earlier identity of {name} and can't be reached anymore. Removing it only cleans up your account.": "这是 {name} 较早的身份,已经连不上了。移除它只是清理你的账户。",
- "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.": "通过账户批准的设备会失去对 {name} 的访问。只有在 {name} 本机上重新加入账户,它才会回来。",
"Any device signed in to your account gets full control of {name}: its files, terminals and bots, with no check here. If someone gets into your account, or Codync's cloud is ever compromised, they could add their own device and you'd have no chance to stop it. Devices paired with a QR code aren't affected.": "登录了你账户的任何设备都能完全控制 {name}:它的文件、终端和 Bot,这里不会再核对。如果有人进入你的账户,或 Codync 的云被攻破,对方可以自己加一台设备,你没有机会拦住。用二维码配对的设备不受影响。",
"Pair iPhone with {name}": "让 iPhone 与 {name} 配对",
"Waiting for your OK on the computer · {code}": "等你在电脑上确认 · {code}",
@@ -1490,7 +1487,8 @@
"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": "粘贴配对链接,或输入电脑上的代码",
+ "Pairing link or code": "配对链接或代码",
+ "Or type this code in the app's pairing screen: {code}": "或在 App 的配对页面输入这个代码:{code}",
"That code isn't valid. Check it on the computer.": "代码无效,请在电脑上核对。",
"That code expired or was used. Show a new one on the computer.": "代码已过期或已被使用,请在电脑上显示新的代码。",
"Installing codync-host…": "正在安装 codync-host…",
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 e955b633..4c827439 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json
@@ -365,7 +365,6 @@
"On your Mac, click Codync in the menu bar, then Pair iPhone.": "在 Mac 上點選單欄的 Codync,然後選配對 iPhone。",
"On your Mac, click Codync in the menu bar, then Pair iPhone. The same code pairs this phone.": "在 Mac 上點選單欄的 Codync,然後選配對 iPhone。同一個碼也能配這臺手機。",
"On your computer, run this in a terminal:": "在電腦上的終端裡執行:",
- "Or paste a {scheme}://pair link": "或貼上 {scheme}://pair 連結",
"Find nearby barcodes.": "尋找附近的條形碼。",
"Camera not available. Paste the link below.": "相機不可用。請把連結貼上在下面。",
"Codync, at a glance.": "一眼看到 Codync。",
@@ -1079,7 +1078,6 @@
"Reading speed": "朗讀速度",
"Send after a pause of": "停頓這麼久之後傳送",
"Created by": "建立者",
- "Devices that were approved through the account lose access. Devices paired with a QR code keep it.": "透過賬戶批准的裝置會失去訪問。用二維碼配對的裝置仍然保留。",
"It disconnects right away and has to pair or ask again.": "它會立刻斷開,之後必須重新配對或再次請求。",
"Authorization: Bearer …": "Authorization: Bearer …",
"API_KEY=…": "API_KEY=…",
@@ -1144,7 +1142,6 @@
"Revoke {name}?": "撤銷 {name} 的訪問?",
"Remove the older {name}?": "移除較早的 {name}?",
"It's an earlier identity of {name} and can't be reached anymore. Removing it only cleans up your account.": "這是 {name} 較早的身份,已經連不上了。移除它只是清理你的賬戶。",
- "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.": "透過賬戶批准的裝置會失去對 {name} 的訪問。只有在 {name} 本機上重新加入賬戶,它才會回來。",
"Any device signed in to your account gets full control of {name}: its files, terminals and bots, with no check here. If someone gets into your account, or Codync's cloud is ever compromised, they could add their own device and you'd have no chance to stop it. Devices paired with a QR code aren't affected.": "登入了你賬戶的任何裝置都能完全控制 {name}:它的檔案、終端和 Bot,這裡不會再核對。如果有人進入你的賬戶,或 Codync 的雲被攻破,對方可以自己加一臺裝置,你沒有機會攔住。用二維碼配對的裝置不受影響。",
"Pair iPhone with {name}": "讓 iPhone 與 {name} 配對",
"Waiting for your OK on the computer · {code}": "等你在電腦上確認 · {code}",
@@ -1490,7 +1487,8 @@
"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": "貼上配對連結,或輸入電腦上的代碼",
+ "Pairing link or code": "配對連結或代碼",
+ "Or type this code in the app's pairing screen: {code}": "或在 App 的配對頁面輸入這個代碼:{code}",
"That code isn't valid. Check it on the computer.": "代碼無效,請到電腦上確認。",
"That code expired or was used. Show a new one on the computer.": "代碼已過期或已使用過,請在電腦上顯示新的代碼。",
"Installing codync-host…": "正在安裝 codync-host…",
diff --git a/apps/ios/Kit/Tests/CodyncKitTests/PairingCodeTests.swift b/apps/ios/Kit/Tests/CodyncKitTests/PairingCodeTests.swift
index 61d9e913..d6ceea3f 100644
--- a/apps/ios/Kit/Tests/CodyncKitTests/PairingCodeTests.swift
+++ b/apps/ios/Kit/Tests/CodyncKitTests/PairingCodeTests.swift
@@ -57,7 +57,7 @@ private final class PairingCodeCloudStub: URLProtocol {
/// 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.",
+ for phrase in ["Pairing link or code", "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/Kit/Tests/CodyncKitTests/RelayVectorsTests.swift b/apps/ios/Kit/Tests/CodyncKitTests/RelayVectorsTests.swift
index 0453deca..6b9ff6a8 100644
--- a/apps/ios/Kit/Tests/CodyncKitTests/RelayVectorsTests.swift
+++ b/apps/ios/Kit/Tests/CodyncKitTests/RelayVectorsTests.swift
@@ -136,9 +136,9 @@ private func raw(_ key: SymmetricKey) -> Data { key.withUnsafeBytes { Data($0) }
hostNonce: v.b64("sas", "hostNonce")) == v.str("sas", "code"))
}
-/// The same digits the host shows (host/src/remote/pairing_requests.rs `check_code`).
+/// The same digits the host shows (host/src/remote/crypto.rs `pair_check_code`).
@Test func pairCheckMatchesTheHost() {
- #expect(RelayCrypto.pairCheck(deviceKey: Data(repeating: 1, count: 32), hostSignKey: Data(repeating: 2, count: 32)) == "855066")
+ #expect(RelayCrypto.pairCheck(deviceKey: v.b64("keys", "deviceSignPub"), hostSignKey: v.b64("keys", "hostSignPub")) == v.str("pairCheck", "code"))
}
@Test func claimAndACLSignaturesVerify() {
diff --git a/apps/ios/Views/PairingView.swift b/apps/ios/Views/PairingView.swift
index 88f7704b..3a460116 100644
--- a/apps/ios/Views/PairingView.swift
+++ b/apps/ios/Views/PairingView.swift
@@ -237,7 +237,7 @@ private struct ScanPage: View {
viewfinder
HStack {
- TextField(L10n.tr("Paste a pairing link, or type the code from the computer"), text: $pasted)
+ TextField(L10n.tr("Pairing link or code"), text: $pasted)
.textInputAutocapitalization(.never)
.autocorrectionDisabled()
.font(.callout.monospaced())
diff --git a/cloud/README.md b/cloud/README.md
index 95987770..c48edd36 100644
--- a/cloud/README.md
+++ b/cloud/README.md
@@ -55,9 +55,11 @@ Development deployment (see [environment readiness](../docs/guides/environments-
```bash
# Only if the database does not exist: npx wrangler d1 create codync-dev
# Confirm its database_id in [env.dev] before applying migrations.
-npx wrangler d1 migrations apply codync-dev --env dev --remote
+npx wrangler d1 migrations apply codync-dev --env dev --remote # includes 0005 (short pairing codes)
npx wrangler secret put CLERK_SECRET_KEY --env dev
npx wrangler secret put CLERK_WEBHOOK_SECRET --env dev
+# The device certificate key: without it phones can't pair (503 notConfigured).
+grep '^CODYNC_DEVICE_CERT_KEY=' ../.env.development | cut -d= -f2- | npx wrangler secret put DEVICE_CERT_KEY --env dev
npx wrangler deploy --env dev # → https://dev-api.codync.dev
```
@@ -65,11 +67,13 @@ npx wrangler deploy --env dev # → https://dev-api.codync.dev
|---|---|---|
| `CLERK_SECRET_KEY` | secret | JWKS for session tokens |
| `CLERK_WEBHOOK_SECRET` | secret | Svix signature on `/v1/webhooks/clerk` (`user.deleted`) |
+| `DEVICE_CERT_KEY` | secret | Ed25519 private key (JWK JSON) that signs device certificates (`POST /v1/devices/certificate`); hosts compile in its public half (`host/src/environment.rs`), `CODYNC_DEVICE_CERT_KEY` on a host overrides it for a self-hosted cloud. Kept in the git-ignored `.env.development` / `.env.production` as `CODYNC_DEVICE_CERT_KEY` |
| `RELEASE_GATE_TOKEN` | secret, main only | fine-grained GitHub token, *Actions: write* on `leepokai/Codync`: dispatches the release gate |
| `CLERK_ISSUER` | var | Clerk Frontend API URL; tokens must carry this `iss` |
| `CLERK_AUTHORIZED_PARTIES` | var, optional | comma-separated; a token with `azp` must match |
| `CLERK_JWT_KEY` | var, dev/e2e only | public key for networkless verification |
| `ASSISTANT_LIMITER` | rate limit binding | cloud assistant (MCP connector) requests per account, 120 per minute |
+| `PAIRING_CODE_LIMITER` | rate limit binding | short pairing codes typed per account and per IP, 10 per minute, a miss counting twice |
`RELEASE_GATE_TOKEN` is a fine-grained token without expiry. If it's revoked, set a new one with
`npx wrangler secret put RELEASE_GATE_TOKEN`: without a working token the release gate runs only after
diff --git a/cloud/src/index.ts b/cloud/src/index.ts
index db111b8f..172c4f38 100644
--- a/cloud/src/index.ts
+++ b/cloud/src/index.ts
@@ -26,6 +26,8 @@ export interface Env {
HOOK_LIMITER?: RateLimit;
/** Cloud assistant (MCP connector) requests per account. */
ASSISTANT_LIMITER?: RateLimit;
+ /** Short pairing codes typed per account and per IP. */
+ PAIRING_CODE_LIMITER?: RateLimit;
CLERK_ISSUER: string;
CLERK_SECRET_KEY?: string;
/** dev / e2e only: networkless verification with this public key. */
diff --git a/cloud/src/routes/pairing-codes.ts b/cloud/src/routes/pairing-codes.ts
index fc22c184..ac24e2e4 100644
--- a/cloud/src/routes/pairing-codes.ts
+++ b/cloud/src/routes/pairing-codes.ts
@@ -54,7 +54,11 @@ export async function createPairingCode(c: Ctx) {
}
export async function redeemPairingCode(c: Ctx, [raw]: string[]) {
- await user(c);
+ // Guessing someone else's live code is limited per IP (before any D1 work) and per account.
+ const ip = `ip:${c.req.headers.get("CF-Connecting-IP") ?? "unknown"}`;
+ await tryCode(c, ip);
+ const account = `user:${(await user(c)).userId}`;
+ await tryCode(c, account);
const code = normalizeCode(decodeURIComponent(raw ?? ""));
if (!code) throw new ApiError("notFound", "That code isn't valid. Check it on the computer.");
const row = await c.env.DB.prepare(
@@ -62,6 +66,16 @@ export async function redeemPairingCode(c: Ctx, [raw]: string[]) {
)
.bind(c.now, code)
.first<{ link: string }>();
- if (!row) throw new ApiError("notFound", "That code expired or was used. Show a new one on the computer.");
+ if (!row) {
+ // A miss counts twice: guessing runs out long before it finds a live code.
+ await Promise.all([ip, account].map((key) => c.env.PAIRING_CODE_LIMITER?.limit({ key })));
+ throw new ApiError("notFound", "That code expired or was used. Show a new one on the computer.");
+ }
return { link: row.link };
}
+
+async function tryCode(c: Ctx, key: string) {
+ if (c.env.PAIRING_CODE_LIMITER && !(await c.env.PAIRING_CODE_LIMITER.limit({ key })).success) {
+ throw new ApiError("rateLimited", "Too many codes tried. Wait a minute, then type it again.");
+ }
+}
diff --git a/cloud/test/e2e/phone.ts b/cloud/test/e2e/phone.ts
index 6c21c229..2cee855b 100644
--- a/cloud/test/e2e/phone.ts
+++ b/cloud/test/e2e/phone.ts
@@ -204,11 +204,14 @@ export class FakePhone {
return Channel.open(Wire.connect(url), this.key, hostSignPub, { relay: false });
}
- /** §4.1 over the relay: pair on a pairing link, expect the host to close it with 4100. */
- async pair(p: PairingInfo, name = "E2E iPhone"): Promise<Json> {
+ /**
+ * §4.1 over the relay: pair on a pairing link with the account's device `certificate` (and a `claim` to bring a
+ * computer in no account into it), expect the host to close it with 4100. A computer in no account asks first.
+ */
+ async pair(p: PairingInfo, proof: { certificate: Json; claim?: Json }, name = "E2E iPhone"): Promise<Json> {
const wire = this.relayWire(p.cloud!, p.computerId, ref.offerId(ref.unb64url(p.code)));
const ch = await Channel.open(wire, this.key, p.signKey, { relay: true, pair: true });
- const ok = await ch.call("pair", { code: p.code, name, platform: "ios" });
+ const ok = await ch.call("pair", { code: p.code, name, platform: "ios", ...proof }, 60_000);
const code = await wire.closed();
if (code !== 4100) throw new Error(`pairing link closed with ${code}, expected 4100`);
return ok;
diff --git a/cloud/test/e2e/relay.e2e.ts b/cloud/test/e2e/relay.e2e.ts
index d68019d9..31dcc7e5 100644
--- a/cloud/test/e2e/relay.e2e.ts
+++ b/cloud/test/e2e/relay.e2e.ts
@@ -1,9 +1,11 @@
// Cross-track integration test (spec §12.1): the real codync-host against `wrangler dev`, driven by a
// fake phone. Run with `npm run e2e` after `cargo build` in host/ (or set CODYNC_HOST_BIN).
//
-// Steps: local D1 + wrangler dev with a test Clerk key → host with CODYNC_CLOUD_URL → QR pairing over the
-// relay → chat through the relay → mailbox while the host is down → account claim + SAS access request →
-// cloud revocation → injected grant ignored → direct /channel and loopback-only bearer token.
+// Steps: local D1 + wrangler dev with a test Clerk key and device certificate key → host with CODYNC_CLOUD_URL
+// trusting that key → QR pairing over the relay with a certified phone, which the computer (in no account) lets in
+// → chat through the relay → mailbox while the host is down → account claim + SAS access request → another
+// account's phone turned away → cloud revocation → injected grant ignored → direct /channel and loopback-only
+// bearer token.
import { type ChildProcess, execFile, spawn, spawnSync } from "node:child_process";
import { generateKeyPairSync } from "node:crypto";
@@ -78,6 +80,14 @@ function d1(sql: string): Promise<Json[]> {
);
}
+// ---- device certificates ----
+
+// The cloud signs device certificates with the private half (DEVICE_CERT_KEY); the host checks them with the public
+// half (CODYNC_DEVICE_CERT_KEY), as a self-hosted cloud's hosts do.
+const certKey = generateKeyPairSync("ed25519");
+const certJwk = JSON.stringify(certKey.privateKey.export({ format: "jwk" }));
+const certPub = certKey.publicKey.export({ format: "jwk" }).x!;
+
// ---- Clerk test tokens ----
const { publicKey, privateKey } = generateKeyPairSync("rsa", { modulusLength: 2048 });
@@ -115,7 +125,11 @@ let host: ChildProcess | undefined;
async function startHost() {
hostPort ||= await freePort();
// 0.0.0.0 so step 7 can prove a non-loopback bearer token is refused.
- host = run(HOST_BIN, ["serve", "--bind", "0.0.0.0", "--port", String(hostPort)], { CODYNC_HOME: home, CODYNC_CLOUD_URL: CLOUD });
+ host = run(HOST_BIN, ["serve", "--bind", "0.0.0.0", "--port", String(hostPort)], {
+ CODYNC_HOME: home,
+ CODYNC_CLOUD_URL: CLOUD,
+ CODYNC_DEVICE_CERT_KEY: certPub,
+ });
await waitFor("host /health", () => fetch(`http://127.0.0.1:${hostPort}/health`).then((r) => r.ok || undefined).catch(() => undefined), 30_000);
}
@@ -131,6 +145,14 @@ async function loopback(method: string, body: unknown = {}): Promise<Json> {
return v;
}
+/** A phone signed in to `token`'s account: registered with it, and the cloud's certificate for its key. */
+async function certify(phone: FakePhone, token: string): Promise<Json> {
+ check((await cloud("POST", "/v1/devices", { token, key: phone.key, body: { name: "E2E iPhone", platform: "ios" } })).status === 200, "phone registered with its account");
+ const r = await cloud("POST", "/v1/devices/certificate", { token, key: phone.key });
+ check(r.status === 200, "the cloud certified the phone's key");
+ return r.body.certificate;
+}
+
/** The relay refused the upgrade (the socket never opened). */
const refused = (wire: Wire) => wire.opened.then(
() => false,
@@ -149,7 +171,10 @@ async function main() {
env: { ...process.env, CI: "1" },
});
if (migrate.status !== 0) throw new Error(`migrations failed: ${migrate.stderr}`);
- run(WRANGLER, ["dev", "--env", "local", "--ip", "127.0.0.1", "--port", String(CLOUD_PORT), "--persist-to", persist, "--var", `CLERK_JWT_KEY:${jwtKey}`]);
+ run(WRANGLER, [
+ "dev", "--env", "local", "--ip", "127.0.0.1", "--port", String(CLOUD_PORT), "--persist-to", persist,
+ "--var", `CLERK_JWT_KEY:${jwtKey}`, "--var", `DEVICE_CERT_KEY:${certJwk}`,
+ ]);
await waitFor("cloud /v1/health", () => fetch(`${CLOUD}/v1/health`).then((r) => r.ok || undefined).catch(() => undefined), 60_000);
step("2–3. host registers and comes online");
@@ -161,12 +186,19 @@ async function main() {
await waitFor("DO presence online", () => computerOnline(computerId), 20_000);
check(true, "D1 row exists and the DO marked it online");
- step("4. QR pairing over the relay, then chat");
+ step("4. QR pairing over the relay (the computer, in no account, asks first), then chat");
+ const userId = "user_e2e";
+ const token = await clerkToken(userId);
const pairing: PairingInfo = parsePairing((await loopback("pairing")).pairingUrl);
check(pairing.computerId === computerId && pairing.cloud === CLOUD, "pairing link names this computer and cloud");
const phone = new FakePhone();
- const paired = await phone.pair(pairing);
- check(paired.computerId === computerId, "pair answered, link closed with 4100");
+ // No claim: the computer stays out of the account until step 6 claims it.
+ const pairs = phone.pair(pairing, { certificate: await certify(phone, token) });
+ const ask = await waitFor("the computer asks", async () => (await loopback("pairingRequests")).requests[0]);
+ check(ask.email === `${userId}@example.com` && ask.code === ref.pairCheck(phone.key.pub, pairing.signKey), `it shows the phone's account and code (${ask.code})`);
+ await loopback("decidePairing", { requestId: ask.requestId, approve: true });
+ const paired = await pairs;
+ check(paired.computerId === computerId && paired.claim === null, "pair answered, link closed with 4100");
// 6c: the normal reconnect is not a pairing socket, so it isn't capped at 16 messages.
let ch = await phone.relay(CLOUD, computerId, pairing.signKey);
const hello = await ch.call("hello", {});
@@ -175,8 +207,7 @@ async function main() {
check(true, "more than 16 messages on the regular link");
if (process.env.CODYNC_E2E_ICONS_ONLY === "1") {
- const userId = "user_icons_e2e";
- const token = await clerkToken(userId);
+ // The phone's own account: joining another one would turn the phone away.
const claim = await cloud("POST", "/v1/claims", { token });
const signed = await loopback("claimSign", { claimId: claim.body.claimId, nonce: claim.body.nonce, userId });
check((await cloud("POST", `/v1/claims/${claim.body.claimId}/complete`, { token, body: signed })).status === 200, "icon test computer claimed");
@@ -262,14 +293,18 @@ async function main() {
check(run2.event?.event === "pull_request.opened" && run2.event?.repo === "o/r", "delivered once the host is back, as a GitHub event");
ch = await Channel.open(ch.wire, phone.key, pairing.signKey, { relay: true });
- step("6. account: claim, access request with SAS, revocation");
- const userId = "user_e2e";
- const token = await clerkToken(userId);
+ step("6. account: claim, access request with SAS, another account's phone, revocation");
const claim = await cloud("POST", "/v1/claims", { token });
const signed = await loopback("claimSign", { claimId: claim.body.claimId, nonce: claim.body.nonce, userId });
const done = await cloud("POST", `/v1/claims/${claim.body.claimId}/complete`, { token, body: signed });
check(done.status === 200 && done.body.computer.computerId === computerId, "computer claimed");
await waitFor("host sees its owner", async () => (await loopback("cloudStatus")).owner?.userId === userId || undefined);
+ check((await loopback("devices")).devices.some((d: Json) => d.key === phone.dk), "the phone paired before the claim keeps its access");
+
+ const stranger = new FakePhone();
+ const strangerPairing = parsePairing((await loopback("pairing")).pairingUrl);
+ const turnedAway = await stranger.pair(strangerPairing, { certificate: await certify(stranger, await clerkToken("someone_else")) }).catch((e: Error) => e);
+ check(turnedAway instanceof Error && turnedAway.message.includes("u•••@example.com's account"), "a phone of another account is turned away, the owner masked");
const phone2 = new FakePhone();
check((await cloud("POST", "/v1/devices", { token, key: phone2.key, body: { name: "Phone 2", platform: "ios" } })).status === 200, "phone 2 registered");
diff --git a/cloud/test/pairing-codes.test.ts b/cloud/test/pairing-codes.test.ts
index 834eeb47..1673f040 100644
--- a/cloud/test/pairing-codes.test.ts
+++ b/cloud/test/pairing-codes.test.ts
@@ -30,6 +30,15 @@ describe("pairing codes", () => {
expect((await call("GET", "/v1/pairing-codes/NOPE-0000", { token })).status).toBe(404);
});
+ it("limits guessing per account, from any address", async () => {
+ const token = await clerkToken(`user_guess_${Date.now()}`);
+ const tries: number[] = [];
+ // Misses count twice against the account's ten a minute (each call comes from another IP).
+ while (tries.length < 12 && tries.at(-1) !== 429) tries.push((await call("GET", `/v1/pairing-codes/GUES-${1000 + tries.length}`, { token })).status);
+ expect(tries.at(-1)).toBe(429);
+ expect(tries.slice(0, -1).every((status) => status === 404)).toBe(true);
+ });
+
it("normalizes what people type", () => {
expect(normalizeCode(" qrtx 4821 ")).toBe("QRTX-4821");
expect(normalizeCode("QRTX-48210")).toBeNull();
diff --git a/cloud/test/ref.ts b/cloud/test/ref.ts
index d62a2638..b4969296 100644
--- a/cloud/test/ref.ts
+++ b/cloud/test/ref.ts
@@ -241,10 +241,14 @@ export function openMailbox(hostSignPub: Uint8Array, hostBox: BoxKey, dk: Uint8A
export const sasCommit = (dk: Uint8Array, nD: Uint8Array) => sha256(concat(enc.encode("codync/sascommit/v1"), dk, nD));
export function sasCode(hostSignPub: Uint8Array, dk: Uint8Array, nD: Uint8Array, nH: Uint8Array): string {
- const h = sha256(concat(enc.encode("codync/sas/v2"), hostSignPub, dk, nD, nH));
- return String(new DataView(h.buffer, h.byteOffset).getUint32(0) % 1_000_000).padStart(6, "0");
+ return sixDigits(sha256(concat(enc.encode("codync/sas/v2"), hostSignPub, dk, nD, nH)));
}
+/** The code a pairing phone and a computer in no account both show while the computer asks. */
+export const pairCheck = (dk: Uint8Array, hostSignPub: Uint8Array) => sixDigits(sha256(concat(enc.encode("codync/pair-check/v1"), dk, hostSignPub)));
+
+const sixDigits = (h: Uint8Array) => String(new DataView(h.buffer, h.byteOffset).getUint32(0) % 1_000_000).padStart(6, "0");
+
export const offerId = (code: Uint8Array) => b64url(sha256(concat(enc.encode("codync/offer/v1"), code)).subarray(0, 16));
export const claimCanonical = (claimId: string, nonce: string, userId: string, computerId: string, boxKey: string) =>
diff --git a/cloud/test/vectors.test.ts b/cloud/test/vectors.test.ts
index 35c81ddc..ea082045 100644
--- a/cloud/test/vectors.test.ts
+++ b/cloud/test/vectors.test.ts
@@ -134,6 +134,10 @@ describe("SAS, offer, claim, push", () => {
expect(ref.sasCode(hostSign.pub, device.pub, nD, nH)).toBe(V.sas.code);
});
+ it("pairing check", () => {
+ expect(ref.pairCheck(device.pub, hostSign.pub)).toBe(V.pairCheck.code);
+ });
+
it("offer id", () => {
expect(ref.offerId(u(V.pairing.code))).toBe(V.pairing.offerId);
});
diff --git a/cloud/wrangler.toml b/cloud/wrangler.toml
index 111bf2af..bc78195a 100644
--- a/cloud/wrangler.toml
+++ b/cloud/wrangler.toml
@@ -57,6 +57,12 @@ name = "ASSISTANT_LIMITER"
namespace_id = "1031"
simple = { limit = 120, period = 60 }
+# Short pairing codes typed per account and per IP (GET /v1/pairing-codes/...); a miss counts twice.
+[[ratelimits]]
+name = "PAIRING_CODE_LIMITER"
+namespace_id = "1051"
+simple = { limit = 10, period = 60 }
+
# Sweep expired requests and nonces; wake the release gate (src/release-gate.ts).
# src/index.ts routes on these exact strings (SWEEP_CRON, RELEASE_GATE_CRON): change both together.
[triggers]
@@ -70,7 +76,7 @@ routes = [{ pattern = "dev-api.codync.dev", custom_domain = true }, { pattern =
vars = { CLERK_ISSUER = "https://sunny-mollusk-8651.clerk.accounts.dev" }
d1_databases = [{ binding = "DB", database_name = "codync-dev", database_id = "0c03c398-3cec-4f06-a76e-998176ca19ae", migrations_dir = "migrations" }]
durable_objects.bindings = [{ name = "RELAY", class_name = "ComputerRelay" }]
-ratelimits = [{ name = "ICON_LIMITER", namespace_id = "1042", simple = { limit = 30, period = 60 } }, { name = "REGISTER_LIMITER", namespace_id = "1002", simple = { limit = 10, period = 60 } }, { name = "TURN_LIMITER", namespace_id = "1012", simple = { limit = 12, period = 60 } }, { name = "HOOK_LIMITER", namespace_id = "1022", simple = { limit = 60, period = 60 } }, { name = "ASSISTANT_LIMITER", namespace_id = "1032", simple = { limit = 120, period = 60 } }]
+ratelimits = [{ name = "ICON_LIMITER", namespace_id = "1042", simple = { limit = 30, period = 60 } }, { name = "REGISTER_LIMITER", namespace_id = "1002", simple = { limit = 10, period = 60 } }, { name = "TURN_LIMITER", namespace_id = "1012", simple = { limit = 12, period = 60 } }, { name = "HOOK_LIMITER", namespace_id = "1022", simple = { limit = 60, period = 60 } }, { name = "ASSISTANT_LIMITER", namespace_id = "1032", simple = { limit = 120, period = 60 } }, { name = "PAIRING_CODE_LIMITER", namespace_id = "1052", simple = { limit = 10, period = 60 } }]
triggers = { crons = ["*/15 * * * *"] }
# local: wrangler dev / e2e with a local D1; CLERK_JWT_KEY is injected by the test (--var).
@@ -81,4 +87,4 @@ routes = []
vars = { CLERK_ISSUER = "https://clerk.test.local" }
d1_databases = [{ binding = "DB", database_name = "codync-local", database_id = "local", migrations_dir = "migrations" }]
durable_objects.bindings = [{ name = "RELAY", class_name = "ComputerRelay" }]
-ratelimits = [{ name = "ICON_LIMITER", namespace_id = "1043", simple = { limit = 30, period = 60 } }, { name = "REGISTER_LIMITER", namespace_id = "1003", simple = { limit = 10, period = 60 } }, { name = "TURN_LIMITER", namespace_id = "1013", simple = { limit = 12, period = 60 } }, { name = "HOOK_LIMITER", namespace_id = "1023", simple = { limit = 60, period = 60 } }, { name = "ASSISTANT_LIMITER", namespace_id = "1033", simple = { limit = 120, period = 60 } }]
+ratelimits = [{ name = "ICON_LIMITER", namespace_id = "1043", simple = { limit = 30, period = 60 } }, { name = "REGISTER_LIMITER", namespace_id = "1003", simple = { limit = 10, period = 60 } }, { name = "TURN_LIMITER", namespace_id = "1013", simple = { limit = 12, period = 60 } }, { name = "HOOK_LIMITER", namespace_id = "1023", simple = { limit = 60, period = 60 } }, { name = "ASSISTANT_LIMITER", namespace_id = "1033", simple = { limit = 120, period = 60 } }, { name = "PAIRING_CODE_LIMITER", namespace_id = "1053", simple = { limit = 10, period = 60 } }]
diff --git a/docs/architecture/connections.md b/docs/architecture/connections.md
index 5b79c6d5..f21205b1 100644
--- a/docs/architecture/connections.md
+++ b/docs/architecture/connections.md
@@ -74,7 +74,7 @@ A computer with only the host (SSH-only server, VPS) never signs in. It joins an
- A manager's desktop app adds it over SSH: add the SSH computer, install the host in one click, then it joins the manager app's account on its own.
- A signed-in phone scans `codync-host pair` (or types its short code) and the terminal confirms.
-`codync-host cloud` and the TUI's account screen say which account the computer is in, or how to add it to one.
+`codync-host cloud` says which account the computer is in, or how to add it to one; the terminal UI's pair sheet says when a scanning phone would bring it into its account.
### Using a Linux VPS
diff --git a/docs/guides/accounts-and-ssh.md b/docs/guides/accounts-and-ssh.md
index f5c7ccd7..e46aeb9d 100644
--- a/docs/guides/accounts-and-ssh.md
+++ b/docs/guides/accounts-and-ssh.md
@@ -104,9 +104,12 @@ on a real device before release. Build success and enabled dashboard settings do
not prove that an Apple authorization completed successfully.
Every build with Clerk requires sign-in on the phone and the desktop app
-([require sign-in](../plans/require-sign-in.md)); builds without Clerk keep the
-signed-out context. QR pairing does not yet require the phone and the computer to
-be in the same account (phase 2). The iPhone's scan step always offers **Skip**,
+([require sign-in](../plans/require-sign-in.md)). Pairing needs a signed-in build
+against a cloud that issues device certificates (or a self-hosted cloud, with
+`CODYNC_DEVICE_CERT_KEY` on the host); builds without Clerk only keep the
+pairings moved over from older versions in the signed-out context, and can't pair.
+QR pairing requires the phone and the computer to be in the same account
+(phase 2, below). The iPhone's scan step always offers **Skip**,
including when the account has no computers. Skipping finishes onboarding and opens the main
tabs; this choice survives relaunches and account changes. The empty Bots screen
offers **Computers** to pair later. Skipping while adding a computer from settings
@@ -123,10 +126,16 @@ and phones and the desktop app see it as an older copy once the new one is reach
joined the account) and offer to remove it; pair again or ask for access to reach the new one.
On the computer, open Codync in the menu bar and choose **Pair iPhone…**, then scan the
-code on the phone (or paste its `codync://pair` link). The host approves the phone's
-device key; the phone saves the computer in its current account context. This
-works when the phone uses Apple Hide My Email and the computer uses Google. Automatic
-account discovery, in contrast, requires the same Clerk user ID on both devices.
+code on the phone (or paste its `codync://pair` link, or type the short code
+`codync-host pair` prints). The phone sends a device certificate from the cloud with
+`pair`, and the host checks it offline: a computer in an account lets in phones of that
+Clerk user only and turns others away with the owner's masked email (*k•••@gmail.com*);
+a computer in no account asks first (desktop dialog, terminal UI, `codync-host pair`,
+or `codync-host access approve <code>`), both showing the same 6-digit code, then joins
+the phone's account. Apple Hide My Email and Google are different Clerk users, so a phone
+on Hide My Email doesn't pair with a computer whose desktop app uses Google: that
+refusal is correct, not a regression. Account discovery likewise requires the same
+Clerk user ID on both devices.
On 2026-09-30, the production dashboard confirmed a successful Apple registration
with a private relay address. The subsequent native `/v1/devices` and
@@ -255,6 +264,14 @@ processes and terminates only tunnels whose executable and quoted known-hosts
path match this app. It uses Windows' OpenSSH Client feature and the device's
existing SSH config and agent.
+A computer without the host shows *Install* on its card (production app only; there is no
+released development host): two SSH commands from `main/ssh-command.ts`, the released
+host into `~/.local/bin` (`packaging/install.sh --host-only`), then `codync-host install`
+on the profile's port. On Linux that step also turns on linger without sudo when it can;
+when it can't, the card shows the one `sudo loginctl enable-linger "$USER"` command. Once
+the installed computer connects, *Add to account* runs on its own when the app is signed in
+and the computer is in no account and not on a private relay (`CloudModel.joinAfterInstall`).
+
*Over SSH* also offers the `Host` entries of `~/.ssh/config` and the files it `Include`s
(`main/ssh-config.ts`, parser in `shared/ssh-config.ts`): named hosts only, not patterns, `Match`
blocks or git hosting aliases (user `git`), minus the ones already added. The app reads the file
diff --git a/docs/guides/dev-app.md b/docs/guides/dev-app.md
index ed4d95fc..ae5b4e31 100644
--- a/docs/guides/dev-app.md
+++ b/docs/guides/dev-app.md
@@ -42,8 +42,8 @@ Secrets for running the project locally live in git-ignored env files at the mai
- Dev tooling reads `.env.development` only and never loads `.env.production`; a variable already in the environment wins over the file.
- A development key is checked before use (`CODYNC_CLERK_SECRET_KEY` must be `sk_test_...`), so a production key put there by mistake is refused.
-- Deployed secrets (the Worker's `CLERK_SECRET_KEY` and the like) are set with `wrangler secret put`, not kept in these files.
-- Variables so far: `CODYNC_CLERK_SECRET_KEY` (see [Worktree sandboxes](#worktree-sandboxes)).
+- Deployed secrets (the Worker's `CLERK_SECRET_KEY` and the like) are set with `wrangler secret put`, and kept in these files only when there is no other copy: the device certificate key (`CODYNC_DEVICE_CERT_KEY`, the Worker's `DEVICE_CERT_KEY`; hosts compile in its public half, see [cloud/README.md](../../cloud/README.md#deploy)).
+- Variables so far: `CODYNC_CLERK_SECRET_KEY` (see [Worktree sandboxes](#worktree-sandboxes)) and `CODYNC_DEVICE_CERT_KEY`.
## Resource ownership
diff --git a/docs/plans/require-sign-in.md b/docs/plans/require-sign-in.md
index f55487a3..ac949625 100644
--- a/docs/plans/require-sign-in.md
+++ b/docs/plans/require-sign-in.md
@@ -11,7 +11,7 @@ Plan agreed 2026-11-02 for [connections and accounts](../architecture/connection
- **A managed computer keeps all its own settings.** "Managed computers don't manage others" is a guideline only, not enforced.
- **The desktop app may be signed in to an account other than its computer's.** It is asked once whether to move the computer; after that, one small line in the main window says so.
- **When a host changes the account it belongs to, every device of the old account is dropped**, QR-paired ones included (phase 2). Explain it in those words: the host changed its account, not the app or the phone. Networks are untouched: membership is between hosts, granted by invite, and has its own removal and rules.
-- **Builds without Clerk** (no publishable key: source builds, third parties) keep today's signed-out context. It stays only for them and as the migration source; shipping builds never show it.
+- **Builds without Clerk** (no publishable key: source builds, third parties) keep today's signed-out context, but only for pairings moved over from older versions: pairing needs a signed-in build against a cloud that issues device certificates (a self-hosted cloud needs `CODYNC_DEVICE_CERT_KEY` on its hosts). Shipping builds never show it.
## Phases
@@ -168,7 +168,7 @@ After either case the signed-out context is erased, and when computers moved an
- Hosts compile in the public half for their environment (`host/src/environment.rs` `device_cert_key`; `CODYNC_DEVICE_CERT_KEY` overrides it for a self-hosted cloud). Checking a certificate is a signature check with no network, so it works from the first run, with the cloud off or on a private relay. There is no `/v1/keys` route.
- The private keys live in the git-ignored `.env.development` / `.env.production` (`CODYNC_DEVICE_CERT_KEY`).
-**`pair` takes the certificate** (`host/src/remote/channel/pairing.rs`). The certificate and the account are checked before the one-time code is spent, so a phone that can't come in doesn't use it up. The account the computer belongs to is kept on the computer (`remote/owner.rs`, kv `account_owner`) and compared offline.
+**`pair` takes the certificate** (`host/src/remote/channel/pairing.rs`). The code is checked first without spending it, so nothing about the computer's account reaches a phone without a live code; then the certificate and the account. The code is spent only once the phone may come in (after the computer's answer), so a phone that can't come in doesn't use it up, and the relay keeps the offer, and the phone's socket, while the computer asks. The account the computer belongs to is kept on the computer (`remote/owner.rs`, kv `account_owner`) and compared offline; with the cloud off or a private relay the computer is in no account, as its status says.
| The computer | Result |
| --- | --- |
@@ -176,7 +176,7 @@ After either case the signed-out context is erased, and when computers moved an
| Certificate not valid for this device key | 403 "Couldn't confirm your Codync account. Sign in again, then scan a new code." |
| In the phone's account | The phone is let in at once |
| In another account | 403 "This computer is in k•••@example.com's account. Move it to your account in Codync on that computer, or sign in with that account." |
-| In no account | The computer asks for up to 2 minutes (`remote/pairing_requests.rs`: the loopback-only `pairingRequests` event and method, `decidePairing`): the desktop app and the terminal UI show a dialog, `codync-host pair` asks `y/N`. Both screens show the same 6-digit code, `sha256("codync/pair-check/v1" ‖ deviceKey ‖ hostSignKey)`. Declined or unanswered: 403 "The computer didn't let this phone in." Let in: the computer signs the claim the phone made (`POST /v1/claims`) and the phone completes it (`POST /v1/claims/{id}/complete`), so joining needs no new cloud route. With the cloud off or a private relay there is no claim; the phone is let in and the computer stays out of any account |
+| In no account | The computer asks for up to 90 seconds, inside the relay's 2-minute pairing socket (`remote/pairing_requests.rs`: the loopback-only `pairingRequests` event and method, `decidePairing`): the desktop app and the terminal UI show a dialog, `codync-host pair` asks `y/N` in a terminal, and `codync-host access approve <code>` answers anywhere. A phone that leaves takes the question off the screens. Both screens show the same 6-digit code, `sha256("codync/pair-check/v1" ‖ deviceKey ‖ hostSignKey)` (`crypto::pair_check_code`, vector `pairCheck`). Declined or unanswered: 403 "The computer didn't let this phone in." Let in: the computer signs the claim the phone made (`POST /v1/claims`) and the phone completes it (`POST /v1/claims/{id}/complete`), so joining needs no new cloud route. With the cloud off or a private relay there is no claim; the phone is let in and the computer stays out of any account |
**Each device records its account** (`devices.account`, schema 7). When the host changes the account it belongs to (joining one, moving, or leaving with **Remove from account**), devices of any other account are dropped. Joining a first account keeps the phones paired before devices recorded their account, so updating doesn't cost anyone a phone. The desktop's move and remove dialogs say: "Every device of {email}'s account loses access." Networks stay as they are: a computer handed to someone else is taken out of a network by the network's creator or an admin, like its SSH key is taken off the manager.
@@ -188,8 +188,8 @@ After either case the signed-out context is erased, and when computers moved an
- **One-click install over SSH** (`apps/desktop/src/main/ssh*.ts`): on `notInstalled` the card shows **Install**, which runs `install.sh --host-only` into `~/.local/bin` and `codync-host install` over the existing SSH connection (SSH state `installing`). Linger is checked and enabled without sudo where the system allows it (Ubuntu 24.04 does); otherwise the card shows `sudo loginctl enable-linger "$USER"` to copy. Codync Dev keeps showing the command, since there is no released dev host to install.
- **Joining the account after install:** once the installed computer connects, the app's **Add to account** runs on its own, when the app is signed in and the computer is in no account and not on a private relay.
-- **Headless hints:** `codync-host cloud` says how a computer out of an account joins one; the terminal UI's pair sheet says a signed-in phone that scans asks to bring the computer into its account (there is no account screen in the terminal UI).
-- **Short pairing codes:** `codync-host pair` asks the host for a code (`pairing {shortCode: true}`); the host registers its link with the cloud (`POST /v1/host/pairing-codes`, migration `0005`), and prints a code like `QRTX-4821`, valid 10 minutes, single use. The phones' paste field takes it and trades it for the link (`GET /v1/pairing-codes/{code}`, signed-in). The computer's own check code catches a cloud that hands out another link.
+- **Headless hints:** `codync-host cloud` says how a computer out of an account joins one; the terminal UI's and the desktop app's pair screens say a signed-in phone that scans asks to bring the computer into its account (there is no account screen in the terminal UI). All read the host's `cloudStatus.canJoinAccount` (in no account, the Codync cloud on). `codync-host pair --json`, or without a terminal, says how to answer the computer's question.
+- **Short pairing codes:** `codync-host pair` and the terminal UI's pair sheet ask the host for a code (`pairing {shortCode: true}`); the host registers its link with the cloud (`POST /v1/host/pairing-codes`, migration `0005`), and shows a code like `QRTX-4821`, valid 10 minutes, single use. The phones' paste field takes it and trades it for the link (`GET /v1/pairing-codes/{code}`, signed-in, limited to 10 tries a minute per account and per IP by `PAIRING_CODE_LIMITER`, a miss counting twice). The computer's own check code catches a cloud that hands out another link. `codync-host pair` waits until its code is spent (`pairingCodeOpen`, loopback only).
## Release steps
diff --git a/docs/reference/compatibility.md b/docs/reference/compatibility.md
index d2e8e5ab..78a471e7 100644
--- a/docs/reference/compatibility.md
+++ b/docs/reference/compatibility.md
@@ -141,6 +141,7 @@ Update this table in the release that changes a floor, with the reason.
| Release | Host `minApp` | Client `minHost` | Why |
|---|---|---|---|
+| 2.36.0 | 2.36.0 | 2.26.0 (unchanged) | Pairing proves the phone's account with a cloud-signed device certificate; older apps send none, so the host rejects their `pair` with `unsupportedVersion`. |
| 2.34.0 | 2.34.0 | 2.26.0 (iPhone, Android, desktop) | Custom icons are for bots only: `setIcon` rejects `agent:` targets, so older apps' agent icon editor would fail. |
| 2.26.0 | 2.21.0 | 2.26.0 (iPhone, Android, desktop) | What a call's voice hears comes from the host as `call` events (replies, approvals, failures, progress); the apps no longer derive it from the chat, so on an older host a call would never hear the bot. |
| 2.25.0 | 2.21.0 | 2.25.0 (iPhone, Android, desktop) | Voice calls run on the host: the apps start a call, run the voice's tools and end it through `startCall`, `callTool`, `callLines` and `endCall`, which older hosts lack (a Linux desktop or an SSH computer can run one). `logCall` stays for older apps. |
diff --git a/docs/reference/fixtures/remote-relay-vectors.json b/docs/reference/fixtures/remote-relay-vectors.json
index 9213d922..124d0225 100644
--- a/docs/reference/fixtures/remote-relay-vectors.json
+++ b/docs/reference/fixtures/remote-relay-vectors.json
@@ -56,6 +56,9 @@
"commit": "DYyvV-_e0NX_aq9NHh9_hexs6X7Q9zozrrV_4XgaDmk",
"code": "919055"
},
+ "pairCheck": {
+ "code": "275411"
+ },
"claim": {
"claimId": "clm_AAAAAAAAAAAAAAAAAAAAAA",
"nonce": "DAwMDAwMDAwMDAwMDAwMDA",
diff --git a/docs/reference/fixtures/remote-relay-vectors.py b/docs/reference/fixtures/remote-relay-vectors.py
index 85662c45..70ed3cc8 100644
--- a/docs/reference/fixtures/remote-relay-vectors.py
+++ b/docs/reference/fixtures/remote-relay-vectors.py
@@ -56,6 +56,8 @@ nd = b"\x0a"*32
nh = b"\x0b"*32
sas_commit = sha(b"codync/sascommit/v1" + dk + nd)
sas_n = struct.unpack(">I", sha(b"codync/sas/v2" + hk + dk + nd + nh)[:4])[0] % 1_000_000
+# The code a phone and a computer in no account both show while the computer asks (pairing, phase 2).
+pair_check_n = struct.unpack(">I", sha(b"codync/pair-check/v1" + dk + hk)[:4])[0] % 1_000_000
offer = sha(b"codync/offer/v1" + code)[:16]
# mailbox
@@ -119,6 +121,7 @@ out = {
{"dir":"d2h","c":1,"final":False,"message":'{"id":2,"m":"se',"plaintext":f_d2h1_more[1],"d":f_d2h1_more[0]},
],
"sas": {"deviceNonce": b64(nd), "hostNonce": b64(nh), "commit": b64(sas_commit), "code": "%06d" % sas_n},
+ "pairCheck": {"code": "%06d" % pair_check_n},
"claim": {"claimId": "clm_AAAAAAAAAAAAAAAAAAAAAA", "nonce": "DAwMDAwMDAwMDAwMDAwMDA", "userId": "user_2abc",
"computerId": b64(cid), "boxKey": b64(bk), "canonical": claim_canon, "sig": b64(claim_sig)},
"push": {"pushPriv": b64(b"\x0c"*32), "pushPub": b64(push_pub), "ephPriv": b64(b"\x0d"*32), "ephPub": b64(pepk),
diff --git a/docs/reference/remote-relay.md b/docs/reference/remote-relay.md
index ae073e60..9bcf87ec 100644
--- a/docs/reference/remote-relay.md
+++ b/docs/reference/remote-relay.md
@@ -317,7 +317,7 @@ blob = epk(32) ‖ sig(64) ‖ ct
| 類別 | 方法 | 允許的 caller |
|---|---|---|
-| loopback 專用 | `setScreenEnabled`, `pairing`, `computerCall`, `computerTools`, `chatCall`, `teamCall`, `manageCall`, `memoryCall`, `routineCall`, `composioCall`, `claimSign`, `unclaim`, `devices`, `revokeDevice`, `accessRequests`, `decideAccessRequest`, `cloudStatus`, `setCloud`, `setCloudUrl` | `Caller::Local`(loopback + token) |
+| loopback 專用 | `setScreenEnabled`, `pairing`, `computerCall`, `computerTools`, `chatCall`, `teamCall`, `manageCall`, `memoryCall`, `routineCall`, `composioCall`, `claimSign`, `unclaim`, `devices`, `revokeDevice`, `accessRequests`, `decideAccessRequest`, `pairingRequests`, `decidePairing`, `pairingCodeOpen`, `cloudStatus`, `setCloud`, `setCloudUrl` | `Caller::Local`(loopback + token);`pairingRequests` 事件也只送給 loopback |
| 配對中 | `pair` | 只在 pairing 狀態的 channel;配對完成後不可再呼叫 |
| screen scope | `screenPrepare`, `screenOffer`, `screenCandidate`, `screenClose`, `screenTakeover` | Local,或 scopes 含 `screen` 的裝置 |
| control scope | 其餘所有既有方法(`hello`, `history`, `createBot`, `updateBot`, `renameSection`, `deleteBot`, `markRead`, `send`, `stop`, `newSession`, `respondPermission`, `registerDevice`, `unregisterDevice`, `forgetDevice`, `registerActivity`, `refreshBackends`, `usage`, `listDirs`, market/skills/connectors、`agentSetup`, `agentAuth`, `agentAuthenticate`, `setAgentEnv`, `termInput`, `termResize`, `termClose`, `screenStatus`) | Local,或 scopes 含 `control` 的裝置 |
diff --git a/host/src/api/devices.rs b/host/src/api/devices.rs
index 90f8bb8d..b3f9f1f3 100644
--- a/host/src/api/devices.rs
+++ b/host/src/api/devices.rs
@@ -66,6 +66,7 @@ const LOCAL_ONLY: &[&str] = &[
// Letting a phone in that brings this computer into its account is decided at the computer.
"pairingRequests",
"decidePairing",
+ "pairingCodeOpen",
"cloudStatus",
"setCloud",
"setCloudUrl",
@@ -235,17 +236,27 @@ impl Pairing {
true
}
- /// Uses up `code` if it is valid (constant-time over every live code).
+ /// Whether `code` is live, without using it up.
+ pub fn valid(&mut self, code: &str) -> bool {
+ self.find(code).is_some()
+ }
+
+ /// Uses up `code` if it is valid.
pub fn redeem(&mut self, code: &str) -> bool {
+ self.find(code).map(|i| self.codes.remove(i)).is_some()
+ }
+
+ /// Where `code` is among the live codes (constant-time over every one).
+ fn find(&mut self, code: &str) -> Option<usize> {
self.prune(now_ms());
- let Ok(given) = crypto::unb64_n::<16>(code) else { return false };
+ let given = crypto::unb64_n::<16>(code).ok()?;
let mut found = None;
for (i, c) in self.codes.iter().enumerate() {
if crypto::ct_eq(&c.code, &given) {
found = Some(i);
}
}
- found.map(|i| self.codes.remove(i)).is_some()
+ found
}
}
@@ -290,6 +301,8 @@ mod tests {
let offer = crypto::offer_id(&crypto::unb64_n(&first.code).unwrap());
assert_eq!(p.offers(), [(offer, first.expires_at)]);
assert!(!p.redeem("CAgICAgICAgICAgICAgICA"));
+ assert!(p.valid(&first.code) && p.valid(&first.code), "checking doesn't use it up");
+ assert!(!p.valid("CAgICAgICAgICAgICAgICA"));
assert!(p.redeem(&first.code));
assert!(!p.redeem(&first.code), "single use");
assert!(!p.open());
diff --git a/host/src/api/mod.rs b/host/src/api/mod.rs
index 3ae439d8..f6b9ef55 100644
--- a/host/src/api/mod.rs
+++ b/host/src/api/mod.rs
@@ -15,7 +15,6 @@ mod remote;
pub use events::{events_stream, term_events};
pub use http::router;
-pub(crate) use remote::claim_sign;
use crate::api::devices::{Caller, Forbidden};
use crate::hub::Hub;
diff --git a/host/src/api/remote.rs b/host/src/api/remote.rs
index e8ad8443..8f49affd 100644
--- a/host/src/api/remote.rs
+++ b/host/src/api/remote.rs
@@ -84,6 +84,8 @@ pub(super) async fn call(hub: &Arc<Hub>, caller: &Caller, method: &str, b: Value
"forgetDevice" => revoke(hub, caller.device_key())?,
"accessRequests" => json!({"requests": hub.cloud.requests_json()}),
"pairingRequests" => json!({"requests": hub.pairing_requests.json()}),
+ // `codync-host pair` waits until its code is used.
+ "pairingCodeOpen" => json!({"open": hub.pairing.locked().valid(str_arg(&b, "code")?)}),
"decidePairing" => {
let approve = b["approve"].as_bool().ok_or_else(|| anyhow!("`approve` is required"))?;
crate::remote::pairing_requests::decide(hub, str_arg(&b, "requestId")?, approve)?;
@@ -121,7 +123,10 @@ pub(super) async fn call(hub: &Arc<Hub>, caller: &Caller, method: &str, b: Value
let on = b["enabled"].as_bool().ok_or_else(|| anyhow!("`enabled` is required"))?;
serde_json::to_value(crate::chat::team::assistant::set_enabled(hub, on)?)?
}
- "claimSign" => claim_sign(hub, &b).await?,
+ "claimSign" => {
+ let (claim_id, nonce, user_id) = (str_arg(&b, "claimId")?, str_arg(&b, "nonce")?, str_arg(&b, "userId")?);
+ crate::remote::owner::sign_claim(hub, claim_id, nonce, user_id).await?
+ }
_ => return Ok(ControlFlow::Continue(b)),
}))
}
@@ -168,33 +173,6 @@ async fn pairing(hub: &Arc<Hub>, short_code: bool) -> Result<Value> {
Ok(json!({"pairingUrl": url, "urls": urls, "expiresAt": issued.expires_at, "shortCode": short_code}))
}
-/// Signs this computer into an account claim (§4.2 A) for the signed-in desktop app to complete.
-pub(crate) async fn claim_sign(hub: &Arc<Hub>, b: &Value) -> Result<Value> {
- crate::remote::cloud::require_accounts(&hub.store)?;
- let field = |k: &str| -> Result<&str> {
- let v = str_arg(b, k)?;
- // Fields are newline-separated in the signed string: a newline would forge another field.
- if v.is_empty() || v.contains('\n') {
- bail!("`{k}` is invalid");
- }
- Ok(v)
- };
- let (claim_id, nonce, user_id) = (field("claimId")?, field("nonce")?, field("userId")?);
- let computer_id = hub.identity.computer_id();
- let box_key = hub.identity.box_pub_b64();
- let input = crypto::claim_input(claim_id, nonce, user_id, &computer_id, &box_key);
- Ok(json!({
- "computerId": computer_id,
- "signKey": hub.identity.sign_pub_b64(),
- "boxKey": box_key,
- "name": crate::service::host_name(),
- "platform": std::env::consts::OS,
- "device": tokio::task::spawn_blocking(crate::service::device).await?,
- "version": env!("CARGO_PKG_VERSION"),
- "sig": crypto::b64(&hub.identity.sign(input.as_bytes())),
- }))
-}
-
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
diff --git a/host/src/cloud_cli.rs b/host/src/cloud_cli.rs
index d1f9b537..f1fdba63 100644
--- a/host/src/cloud_cli.rs
+++ b/host/src/cloud_cli.rs
@@ -92,10 +92,10 @@ fn account_hint(status: &serde_json::Value) -> Option<&'static str> {
if !status["owner"].is_null() {
return None;
}
- Some(if status["enabled"] != true || status["relay"] == "private" {
- "Not in an account. Phones pair with `codync-host pair` and a QR code; joining an account needs the Codync cloud (`codync-host cloud --enable`)."
- } else {
+ Some(if status["canJoinAccount"] == true {
"Not in an account. Add it from a signed-in phone: run `codync-host pair` and scan the code, or type the short code it prints. Or, from a desktop app that reaches this computer over SSH, choose Add to account."
+ } else {
+ "Not in an account. Phones pair with `codync-host pair` and a QR code; joining an account needs the Codync cloud (`codync-host cloud --enable`)."
})
}
@@ -105,12 +105,8 @@ mod tests {
#[test]
fn a_computer_out_of_an_account_says_how_to_join_one() {
- assert_eq!(account_hint(&json!({"owner": {"userId": "u"}, "enabled": true})), None);
- assert!(
- account_hint(&json!({"owner": null, "enabled": true, "relay": "codync"}))
- .unwrap()
- .contains("signed-in phone")
- );
- assert!(account_hint(&json!({"owner": null, "enabled": false})).unwrap().contains("--enable"));
+ assert_eq!(account_hint(&json!({"owner": {"userId": "u"}, "canJoinAccount": false})), None);
+ assert!(account_hint(&json!({"owner": null, "canJoinAccount": true})).unwrap().contains("signed-in phone"));
+ assert!(account_hint(&json!({"owner": null, "canJoinAccount": false})).unwrap().contains("--enable"));
}
}
diff --git a/host/src/main.rs b/host/src/main.rs
index 3a29fe0f..c47475f3 100644
--- a/host/src/main.rs
+++ b/host/src/main.rs
@@ -17,6 +17,7 @@ mod market;
mod mcp;
mod network;
mod network_cli;
+mod pair_cli;
mod remote;
mod routines;
mod screen;
@@ -36,7 +37,7 @@ use remote::identity;
use anyhow::{Context, Result};
use clap::{Parser, Subcommand};
-use serde_json::{Value, json};
+use serde_json::json;
use std::fmt::Write as _;
use std::future::IntoFuture;
use std::io::Read;
@@ -108,12 +109,13 @@ enum Sub {
#[command(subcommand)]
action: Option<DevicesAction>,
},
- /// List, approve or deny account devices asking to use this computer.
+ /// List, approve or deny devices asking to use this computer: account devices, and phones pairing with a
+ /// computer in no account.
Access {
#[arg(long, default_value_t = service::DEFAULT_PORT)]
port: u16,
#[command(subcommand)]
- action: Option<AccessAction>,
+ action: Option<pair_cli::AccessAction>,
},
/// Show or change the Codync cloud (reach this computer from anywhere).
Cloud(cloud_cli::CloudArgs),
@@ -209,16 +211,6 @@ enum DevicesAction {
Revoke { key: String },
}
-#[derive(Subcommand)]
-enum AccessAction {
- /// Show pending requests with the code each device shows (the default).
- List,
- /// Approve a request, by its id or by the 6-digit code shown on the device.
- Approve { request: String },
- /// Deny a request.
- Deny { request: String },
-}
-
#[derive(Subcommand)]
enum McpServer {
/// Launch a local connector without exposing its credentials in ACP config.
@@ -352,7 +344,7 @@ async fn main() -> Result<()> {
let cli = Cli::parse();
match cli.cmd.unwrap_or(Sub::Serve { port: service::DEFAULT_PORT, bind: "0.0.0.0".into() }) {
Sub::Serve { port, bind } => serve(&bind, port).await,
- Sub::Pair { port, json } => pair(port, json).await,
+ Sub::Pair { port, json } => pair_cli::pair(port, json).await,
Sub::Info { port, json } => info(port, json).await,
Sub::Send(args) => send_cli::run(args).await,
Sub::Import(args) => import_cli::run(args).await,
@@ -377,7 +369,7 @@ async fn main() -> Result<()> {
Ok(())
}
},
- Sub::Access { port, action } => access(port, action.unwrap_or(AccessAction::List)).await,
+ Sub::Access { port, action } => pair_cli::access(port, action.unwrap_or(pair_cli::AccessAction::List)).await,
Sub::Cloud(args) => cloud_cli::run(args).await,
Sub::Network(args) => network_cli::run(args).await,
Sub::Install { port } => {
@@ -580,123 +572,6 @@ async fn shutdown_signal() {
}
}
-async fn pair(port: u16, as_json: bool) -> Result<()> {
- let hello = local_call(port, "hello", json!({})).await?;
- let p = local_call(port, "pairing", json!({"shortCode": true})).await?;
- if as_json {
- println!(
- "{}",
- json!({
- "name": hello["name"], "computerId": hello["computerId"], "signKey": hello["signKey"],
- "boxKey": hello["boxKey"], "urls": p["urls"], "cloud": hello["cloud"],
- "pairingUrl": p["pairingUrl"], "expiresAt": p["expiresAt"], "shortCode": p["shortCode"],
- })
- );
- return Ok(());
- }
- let url = p["pairingUrl"].as_str().unwrap_or_default();
- let code = qrcode::QrCode::new(url.as_bytes())?;
- println!("{}", code.render::<qrcode::render::unicode::Dense1x2>().quiet_zone(true).build());
- println!("Scan with the Codync iOS app within 10 minutes, or open this link on the phone:\n{url}\n");
- if let Some(code) = p["shortCode"].as_str() {
- println!("Or type this code where the app's pairing screen asks for a link: {code}\n");
- }
- if hello["cloud"].is_null()
- && p["urls"].as_array().is_none_or(|u| {
- !u.iter().any(|u| {
- u.as_str().is_some_and(|u| u.contains("://100.") || u.contains(".ts.net") || u.starts_with("https://"))
- })
- })
- {
- println!(
- "Tip: the phone reaches this computer on the same network only. Turn on the Codync cloud or Tailscale to reach it from anywhere."
- );
- }
- if std::io::IsTerminal::is_terminal(&std::io::stdin()) {
- answer_pairing(port, p["expiresAt"].as_i64().unwrap_or_default()).await?;
- }
- Ok(())
-}
-
-/// A computer in no account asks before a phone brings it into its own account: answered here, in the terminal,
-/// until the code is used or expires (docs/plans/require-sign-in.md, phase 2).
-async fn answer_pairing(port: u16, expires_at: i64) -> Result<()> {
- let count = |v: &Value| v["devices"].as_array().map_or(0, Vec::len);
- let before = count(&local_call(port, "devices", json!({})).await?);
- println!("Waiting for the phone… (Ctrl-C to stop)");
- while store::now_ms() < expires_at {
- tokio::time::sleep(Duration::from_secs(1)).await;
- let requests = local_call(port, "pairingRequests", json!({})).await?;
- if let Some(r) = requests["requests"].as_array().and_then(|r| r.first()) {
- let email = r["email"].as_str().unwrap_or("a Codync account");
- println!(
- "
-{} wants to use this computer. It joins {email}'s account.
-Check the phone shows {}.",
- r["deviceName"].as_str().unwrap_or("A phone"),
- r["code"].as_str().unwrap_or_default()
- );
- let approve = ask_yes_no("Let it in? [y/N] ").await?;
- local_call(port, "decidePairing", json!({"requestId": r["requestId"], "approve": approve})).await?;
- println!("{}", if approve { "Paired. The computer is joining that account." } else { "Turned away." });
- return Ok(());
- }
- if count(&local_call(port, "devices", json!({})).await?) > before {
- println!("Paired.");
- return Ok(());
- }
- }
- println!("The code expired. Run codync-host pair again.");
- Ok(())
-}
-
-async fn ask_yes_no(prompt: &str) -> Result<bool> {
- use std::io::Write as _;
- print!("{prompt}");
- std::io::stdout().flush()?;
- let line = tokio::task::spawn_blocking(|| {
- let mut line = String::new();
- std::io::stdin().read_line(&mut line).map(|_| line)
- })
- .await??;
- Ok(matches!(line.trim().to_ascii_lowercase().as_str(), "y" | "yes"))
-}
-
-async fn access(port: u16, action: AccessAction) -> Result<()> {
- let list = local_call(port, "accessRequests", json!({})).await?;
- let requests = list["requests"].as_array().cloned().unwrap_or_default();
- let (request, approve) = match action {
- AccessAction::List => {
- if requests.is_empty() {
- println!("No devices are asking for access.");
- }
- for r in &requests {
- println!(
- "{} {} ({}, {}) code {}",
- r["requestId"].as_str().unwrap_or_default(),
- r["deviceName"].as_str().unwrap_or_default(),
- r["platform"].as_str().unwrap_or_default(),
- r["email"].as_str().unwrap_or("no email"),
- r["code"].as_str().unwrap_or("(waiting for the device)"),
- );
- }
- return Ok(());
- }
- AccessAction::Approve { request } => (request, true),
- AccessAction::Deny { request } => (request, false),
- };
- // A 6-digit code picks the request showing it; it must be the only one.
- let matching: Vec<&Value> =
- requests.iter().filter(|r| r["requestId"] == request.as_str() || r["code"] == request.as_str()).collect();
- let [r] = matching.as_slice() else {
- anyhow::bail!("No single request matches {request}. See `codync-host access list`.");
- };
- let id = r["requestId"].as_str().unwrap_or_default();
- local_call(port, "decideAccessRequest", json!({"requestId": id, "approve": approve})).await?;
- println!("{}", if approve { "Approved." } else { "Denied." });
- Ok(())
-}
-
/// Reads the identity and token only; never creates them (that's `serve`'s job).
async fn info(port: u16, as_json: bool) -> Result<()> {
let dir = service::data_dir();
@@ -737,7 +612,7 @@ async fn info(port: u16, as_json: bool) -> Result<()> {
async fn statusline(port: u16, wrapped: String) {
let mut input = String::new();
let _ = std::io::stdin().read_to_string(&mut input);
- let v: Value = serde_json::from_str(&input).unwrap_or_default();
+ let v: serde_json::Value = serde_json::from_str(&input).unwrap_or_default();
if let Ok(token) = std::fs::read_to_string(service::data_dir().join("token")) {
let _ = http()
.post(format!("http://127.0.0.1:{port}/ingest/statusline"))
diff --git a/host/src/pair_cli.rs b/host/src/pair_cli.rs
new file mode 100644
index 00000000..933cf5fd
--- /dev/null
+++ b/host/src/pair_cli.rs
@@ -0,0 +1,178 @@
+//! `codync-host pair` and `codync-host access`: letting phones and devices in from a terminal. A computer in no
+//! account asks before a signed-in phone comes in and brings it into its account (docs/plans/require-sign-in.md,
+//! phase 2): `pair` answers in a terminal, `access approve` / `deny` anywhere (scripts, SSH without a terminal).
+
+use crate::local_api::local_call;
+use anyhow::{Result, bail};
+use serde_json::{Value, json};
+use std::io::{IsTerminal as _, Write as _};
+use std::time::Duration;
+
+#[derive(clap::Subcommand)]
+pub enum AccessAction {
+ /// Show pending requests (account devices asking for access, phones asking to pair) with the code each device
+ /// shows (the default).
+ List,
+ /// Approve a request, by its id or by the 6-digit code shown on the device.
+ Approve { request: String },
+ /// Deny a request.
+ Deny { request: String },
+}
+
+const ASKS: &str = "This computer isn't in an account, so it asks before a phone comes in. Answer within 90 seconds \
+ with `codync-host access approve <code>` (the 6 digits the phone shows), or in the Codync desktop \
+ app or the terminal UI.";
+
+pub async fn pair(port: u16, as_json: bool) -> Result<()> {
+ let hello = local_call(port, "hello", json!({})).await?;
+ let p = local_call(port, "pairing", json!({"shortCode": true})).await?;
+ let asks = local_call(port, "cloudStatus", json!({})).await?["owner"].is_null();
+ if as_json {
+ println!(
+ "{}",
+ json!({
+ "name": hello["name"], "computerId": hello["computerId"], "signKey": hello["signKey"],
+ "boxKey": hello["boxKey"], "urls": p["urls"], "cloud": hello["cloud"],
+ "pairingUrl": p["pairingUrl"], "expiresAt": p["expiresAt"], "shortCode": p["shortCode"],
+ })
+ );
+ if asks {
+ eprintln!("{ASKS}");
+ }
+ return Ok(());
+ }
+ let url = p["pairingUrl"].as_str().unwrap_or_default();
+ let code = qrcode::QrCode::new(url.as_bytes())?;
+ println!("{}", code.render::<qrcode::render::unicode::Dense1x2>().quiet_zone(true).build());
+ println!("Scan with the Codync iOS app within 10 minutes, or open this link on the phone:\n{url}\n");
+ if let Some(code) = p["shortCode"].as_str() {
+ println!("Or type this code where the app's pairing screen asks for a link: {code}\n");
+ }
+ if hello["cloud"].is_null()
+ && p["urls"].as_array().is_none_or(|u| {
+ !u.iter().any(|u| {
+ u.as_str().is_some_and(|u| u.contains("://100.") || u.contains(".ts.net") || u.starts_with("https://"))
+ })
+ })
+ {
+ println!(
+ "Tip: the phone reaches this computer on the same network only. Turn on the Codync cloud or Tailscale to reach it from anywhere."
+ );
+ }
+ if !std::io::stdin().is_terminal() {
+ if asks {
+ println!("{ASKS}");
+ }
+ return Ok(());
+ }
+ wait(port, url, p["expiresAt"].as_i64().unwrap_or_default()).await
+}
+
+/// In a terminal, `pair` stays until its code is used or expires, and answers the phone the computer asks about.
+async fn wait(port: u16, url: &str, expires_at: i64) -> Result<()> {
+ let code = reqwest::Url::parse(url)?
+ .query_pairs()
+ .find_map(|(k, v)| (k == "code").then(|| v.into_owned()))
+ .unwrap_or_default();
+ println!("Waiting for the phone… (Ctrl-C to stop)");
+ while crate::store::now_ms() < expires_at {
+ tokio::time::sleep(Duration::from_secs(1)).await;
+ let requests = local_call(port, "pairingRequests", json!({})).await?;
+ if let Some(r) = requests["requests"].as_array().and_then(|r| r.first()) {
+ println!(
+ "\n{} wants to use this computer. It joins {}'s account.\nCheck the phone shows {}.",
+ r["deviceName"].as_str().unwrap_or("A phone"),
+ r["email"].as_str().unwrap_or("a Codync account"),
+ spaced(r["code"].as_str().unwrap_or_default()),
+ );
+ let approve = ask_yes_no("Let it in? [y/N] ").await?;
+ let answered = local_call(port, "decidePairing", json!({"requestId": r["requestId"], "approve": approve}));
+ if answered.await.is_err() {
+ println!("The phone stopped waiting, or it was answered elsewhere.");
+ } else if !approve {
+ println!("Turned away.");
+ return Ok(());
+ }
+ }
+ if local_call(port, "pairingCodeOpen", json!({"code": code})).await?["open"] != true {
+ println!("Paired.");
+ return Ok(());
+ }
+ }
+ println!("The code expired. Run codync-host pair again.");
+ Ok(())
+}
+
+/// `123 456`, as the phone shows it.
+fn spaced(code: &str) -> String {
+ match code.split_at_checked(3) {
+ Some((a, b)) if code.len() == 6 => format!("{a} {b}"),
+ _ => code.to_owned(),
+ }
+}
+
+async fn ask_yes_no(prompt: &str) -> Result<bool> {
+ print!("{prompt}");
+ std::io::stdout().flush()?;
+ let line = tokio::task::spawn_blocking(|| {
+ let mut line = String::new();
+ std::io::stdin().read_line(&mut line).map(|_| line)
+ })
+ .await??;
+ Ok(matches!(line.trim().to_ascii_lowercase().as_str(), "y" | "yes"))
+}
+
+/// Requests waiting for this computer's answer, each with the method that answers it.
+async fn requests(port: u16) -> Result<Vec<(Value, &'static str)>> {
+ let mut all = vec![];
+ for (list, decide) in [("accessRequests", "decideAccessRequest"), ("pairingRequests", "decidePairing")] {
+ let v = local_call(port, list, json!({})).await?;
+ all.extend(v["requests"].as_array().into_iter().flatten().map(|r| (r.clone(), decide)));
+ }
+ Ok(all)
+}
+
+pub async fn access(port: u16, action: AccessAction) -> Result<()> {
+ let requests = requests(port).await?;
+ let (request, approve) = match action {
+ AccessAction::List => {
+ if requests.is_empty() {
+ println!("No devices are asking for access.");
+ }
+ for (r, decide) in &requests {
+ println!(
+ "{} {} ({}, {}) code {}{}",
+ r["requestId"].as_str().unwrap_or_default(),
+ r["deviceName"].as_str().unwrap_or_default(),
+ r["platform"].as_str().unwrap_or_default(),
+ r["email"].as_str().unwrap_or("no email"),
+ r["code"].as_str().unwrap_or("(waiting for the device)"),
+ if *decide == "decidePairing" { " pairing: the computer joins this account" } else { "" },
+ );
+ }
+ return Ok(());
+ }
+ AccessAction::Approve { request } => (request, true),
+ AccessAction::Deny { request } => (request, false),
+ };
+ // A 6-digit code picks the request showing it; it must be the only one.
+ let matching: Vec<_> =
+ requests.iter().filter(|(r, _)| r["requestId"] == request.as_str() || r["code"] == request.as_str()).collect();
+ let [(r, decide)] = matching.as_slice() else {
+ bail!("No single request matches {request}. See `codync-host access list`.");
+ };
+ local_call(port, decide, json!({"requestId": r["requestId"], "approve": approve})).await?;
+ println!("{}", if approve { "Approved." } else { "Denied." });
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn the_check_code_reads_as_on_the_phone() {
+ assert_eq!(spaced("165780"), "165 780");
+ assert_eq!(spaced(""), "");
+ }
+}
diff --git a/host/src/remote/channel.rs b/host/src/remote/channel.rs
index bd1ddd29..1f7c8e78 100644
--- a/host/src/remote/channel.rs
+++ b/host/src/remote/channel.rs
@@ -390,13 +390,17 @@ impl Channel {
// Gone from the table while connected: it was revoked.
let code = if code == RejectCode::Unauthorized { RejectCode::Revoked } else { code };
tracing::info!(device = self.key, ?code, "closing channel: device no longer authorized");
- let reject = json!({"t": "reject", "code": code, "message": code.message()});
- let _ = self.tx.send(ToDevice::Plain(reject)).await;
- Err((code.close_code(), "rejected"))
+ Err(self.reject(code).await)
}
}
}
+ /// Sends `reject` (outside the channel's encryption) and says how to close.
+ async fn reject(&self, code: RejectCode) -> CloseWith {
+ let _ = self.tx.send(ToDevice::Plain(json!({"t": "reject", "code": code, "message": code.message()}))).await;
+ (code.close_code(), if code == RejectCode::RateLimited { "rateLimited" } else { "rejected" })
+ }
+
async fn serve(
&mut self,
incoming: &mut mpsc::Receiver<Value>,
@@ -516,9 +520,10 @@ mod tests {
use crate::store::Store;
use ed25519_dalek::SigningKey;
- /// A computer in `user_1`'s account, so phones of that account pair without asking.
+ /// A computer in `user_1`'s account (on the Codync cloud), so phones of that account pair without asking.
fn temp_hub() -> Arc<Hub> {
let hub = unowned_hub();
+ hub.store.kv_set("test_cloud_url", "https://dev-api.codync.dev").unwrap();
let owner = crate::remote::cloud::Owner { user_id: "user_1".into(), email: Some("[email protected]".into()) };
crate::remote::owner::remember(&hub, Some(&owner)).unwrap();
hub
diff --git a/host/src/remote/channel/pairing.rs b/host/src/remote/channel/pairing.rs
index ba7a2031..cd921623 100644
--- a/host/src/remote/channel/pairing.rs
+++ b/host/src/remote/channel/pairing.rs
@@ -3,76 +3,44 @@
//! that account only; one in no account asks first, then joins the phone's account.
use super::*;
-use crate::remote::certificate::{self, Refusal};
+use crate::remote::certificate::{self, Certified, Refusal};
+use crate::remote::cloud::Owner;
use crate::remote::{owner, pairing_requests};
+const PROTOCOL: CloseWith = (close::PROTOCOL, "protocolError");
+const EXPIRED: &str = "This pairing code expired. Show a new one on the computer.";
+
impl Channel {
pub(super) async fn pair(
&mut self,
incoming: &mut mpsc::Receiver<Value>,
- mut opener: Opener,
+ opener: Opener,
source: &str,
) -> CloseWith {
- let protocol = (close::PROTOCOL, "protocolError");
- let deadline = Instant::now() + PAIRING_MAX_AGE;
- let bytes = loop {
- let msg = tokio::select! {
- msg = incoming.recv() => msg,
- () = sleep_until(deadline) => return (close::PAIRING_EXPIRED, "pairingExpired"),
- };
- let Some(msg) = msg else { return (close::NORMAL, "") };
- match opener.open(&msg) {
- Ok(Some(bytes)) => break bytes,
- Ok(None) => {}
- Err(e) => return frame_close(&e),
- }
+ let (id, b) = match read_pair(incoming, opener).await {
+ Ok(request) => request,
+ Err(close) => return close,
};
- let Ok(v) = serde_json::from_slice::<Value>(&bytes) else { return protocol };
- let Some(id) = v["id"].as_u64() else { return protocol };
- if v["m"] != "pair" {
- return protocol;
- }
- let b = &v["b"];
let name = b["name"].as_str().map(str::trim).filter(|n| !n.is_empty() && n.chars().count() <= 100);
let platform = b["platform"].as_str().filter(|p| matches!(*p, "ios" | "macos" | "android"));
let (Some(name), Some(platform)) = (name, platform) else {
self.send(err(id, 400, "`name` and `platform` (ios, macos or android) are required")).await;
- return protocol;
+ return PROTOCOL;
};
- if !self.hub.pairing.locked().attempt(source) {
- return self.reject(RejectCode::RateLimited).await;
- }
- // The code is spent only on a phone that may come in, so a phone of the wrong account doesn't use it up.
- let account = match certificate::check(&b["certificate"], &self.key, now_ms()) {
- Ok(account) => account,
- Err(Refusal::Missing) => return self.reject(RejectCode::UnsupportedVersion).await,
- Err(Refusal::Invalid) => {
- self.send(err(id, 403, "Couldn't confirm your Codync account. Sign in again, then scan a new code."))
- .await;
- return (close::UNAUTHORIZED, "unauthorized");
- }
+ let code = b["code"].as_str().unwrap_or_default();
+ let (account, owner) = match self.admit(id, &b, code, source).await {
+ Ok(admitted) => admitted,
+ Err(close) => return close,
};
- let owner = owner::owner(&self.hub.store);
- if let Some(owner) = owner.as_ref().filter(|o| o.user_id != account.user_id) {
- let whose =
- owner.email.as_deref().map_or_else(|| "another".into(), |e| format!("{}'s", certificate::masked(e)));
- let message = format!(
- "This computer is in {whose} account. Move it to your account in Codync on that computer, or sign in with that account."
- );
- self.send(err(id, 403, &message)).await;
- return (close::UNAUTHORIZED, "otherAccount");
+ if owner.is_none()
+ && let Err(close) = self.ask(id, name, platform, account.email.as_deref(), incoming).await
+ {
+ return close;
}
- if !self.hub.pairing.locked().redeem(b["code"].as_str().unwrap_or_default()) {
- self.send(err(id, 403, "This pairing code expired. Show a new one on the computer.")).await;
- return (close::UNAUTHORIZED, "unauthorized");
- }
- if owner.is_none() {
- let Ok(device_key) = crypto::unb64_n::<32>(&self.key) else { return protocol };
- let code = pairing_requests::check_code(&device_key, &self.hub.identity.sign_pub());
- if !pairing_requests::ask(&self.hub, name, platform, account.email.as_deref(), code).await {
- self.send(err(id, 403, "The computer didn't let this phone in.")).await;
- return (close::UNAUTHORIZED, "declined");
- }
+ // Spent only now: a phone turned away leaves the code to the right one, and while the computer asks the
+ // relay keeps the offer, and with it this socket.
+ if !self.hub.pairing.locked().redeem(code) {
+ return self.refuse(id, EXPIRED, "unauthorized").await;
}
let device = Device {
key: self.key.clone(),
@@ -103,24 +71,101 @@ impl Channel {
(close::PAIRED, "paired")
}
+ /// Who may come in, before the code is spent: a live code first, so nothing about this computer's account
+ /// reaches a phone without one; then the phone's account, which must be this computer's when it is in one.
+ /// Returns the phone's account and this computer's.
+ async fn admit(
+ &self,
+ id: u64,
+ b: &Value,
+ code: &str,
+ source: &str,
+ ) -> Result<(Certified, Option<Owner>), CloseWith> {
+ if !self.hub.pairing.locked().attempt(source) {
+ return Err(self.reject(RejectCode::RateLimited).await);
+ }
+ if !self.hub.pairing.locked().valid(code) {
+ return Err(self.refuse(id, EXPIRED, "unauthorized").await);
+ }
+ let account = match certificate::check(&b["certificate"], &self.key, now_ms()) {
+ Ok(account) => account,
+ Err(Refusal::Missing) => return Err(self.reject(RejectCode::UnsupportedVersion).await),
+ Err(Refusal::Invalid) => {
+ let message = "Couldn't confirm your Codync account. Sign in again, then scan a new code.";
+ return Err(self.refuse(id, message, "unauthorized").await);
+ }
+ };
+ let owner = owner::owner(&self.hub.store);
+ if let Some(owner) = owner.as_ref().filter(|o| o.user_id != account.user_id) {
+ let whose =
+ owner.email.as_deref().map_or_else(|| "another".into(), |e| format!("{}'s", certificate::masked(e)));
+ let message = format!(
+ "This computer is in {whose} account. Move it to your account in Codync on that computer, or sign in with that account."
+ );
+ return Err(self.refuse(id, &message, "otherAccount").await);
+ }
+ Ok((account, owner))
+ }
+
+ /// A computer in no account asks its user before the phone comes in; a phone that leaves meanwhile takes the
+ /// question off the computer's screens.
+ async fn ask(
+ &self,
+ id: u64,
+ name: &str,
+ platform: &str,
+ email: Option<&str>,
+ incoming: &mut mpsc::Receiver<Value>,
+ ) -> Result<(), CloseWith> {
+ let Ok(device_key) = crypto::unb64_n::<32>(&self.key) else { return Err(PROTOCOL) };
+ let code = crypto::pair_check_code(&device_key, &self.hub.identity.sign_pub());
+ let let_in = tokio::select! {
+ let_in = pairing_requests::ask(&self.hub, name, platform, email, code) => let_in,
+ // Nothing else comes on a pairing channel: its end means the phone gave up.
+ () = async { while incoming.recv().await.is_some() {} } => return Err((close::NORMAL, "")),
+ };
+ if let_in { Ok(()) } else { Err(self.refuse(id, "The computer didn't let this phone in.", "declined").await) }
+ }
+
/// 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() || crate::remote::cloud::codync_url(&self.hub).is_err() {
+ let (Some(claim_id), Some(nonce)) = (claim["claimId"].as_str(), claim["nonce"].as_str()) else {
+ return Value::Null;
+ };
+ if crate::remote::cloud::codync_url(&self.hub).is_err() {
return Value::Null;
}
- let request = json!({"claimId": claim["claimId"], "nonce": claim["nonce"], "userId": user_id});
- match api::claim_sign(&self.hub, &request).await {
- Ok(signed) => signed,
- Err(e) => {
- tracing::info!(error = format!("{e:#}"), "paired without joining the account");
- Value::Null
- }
- }
+ owner::sign_claim(&self.hub, claim_id, nonce, user_id).await.unwrap_or_else(|e| {
+ tracing::info!(error = format!("{e:#}"), "paired without joining the account");
+ Value::Null
+ })
+ }
+
+ async fn refuse(&self, id: u64, message: &str, reason: &'static str) -> CloseWith {
+ self.send(err(id, 403, message)).await;
+ (close::UNAUTHORIZED, reason)
}
+}
- async fn reject(&self, code: RejectCode) -> CloseWith {
- let _ = self.tx.send(ToDevice::Plain(json!({"t": "reject", "code": code, "message": code.message()}))).await;
- (code.close_code(), if code == RejectCode::RateLimited { "rateLimited" } else { "rejected" })
+/// Waits for the phone's one `pair`: its id and body.
+async fn read_pair(incoming: &mut mpsc::Receiver<Value>, mut opener: Opener) -> Result<(u64, Value), CloseWith> {
+ let deadline = Instant::now() + PAIRING_MAX_AGE;
+ let bytes = loop {
+ let msg = tokio::select! {
+ msg = incoming.recv() => msg,
+ () = sleep_until(deadline) => return Err((close::PAIRING_EXPIRED, "pairingExpired")),
+ };
+ let Some(msg) = msg else { return Err((close::NORMAL, "")) };
+ match opener.open(&msg) {
+ Ok(Some(bytes)) => break bytes,
+ Ok(None) => {}
+ Err(e) => return Err(frame_close(&e)),
+ }
+ };
+ let Ok(mut v) = serde_json::from_slice::<Value>(&bytes) else { return Err(PROTOCOL) };
+ match v["id"].as_u64() {
+ Some(id) if v["m"] == "pair" => Ok((id, v["b"].take())),
+ _ => Err(PROTOCOL),
}
}
diff --git a/host/src/remote/channel/tests/accounts.rs b/host/src/remote/channel/tests/accounts.rs
index 8df0cd11..97b76c87 100644
--- a/host/src/remote/channel/tests/accounts.rs
+++ b/host/src/remote/channel/tests/accounts.rs
@@ -37,6 +37,32 @@ async fn a_phone_of_another_account_is_refused_with_the_owner_masked() {
assert_eq!(p.call(1, "pair", forged).await["err"]["status"], 403, "a certificate for another key");
}
+#[tokio::test]
+async fn without_a_live_code_a_phone_learns_nothing_about_the_account() {
+ let hub = temp_hub();
+ let (mut p, _) = pairing_phone(&hub).await;
+ let reply = p.call(1, "pair", pair_body(&p, "CAgICAgICAgICAgICAgICA", "Pixel", "android", "user_2")).await;
+ let message = reply["err"]["message"].as_str().unwrap();
+ assert!(message.contains("expired") && !message.contains("example.com"), "{message}");
+}
+
+#[tokio::test]
+async fn a_phone_that_leaves_while_the_computer_asks_is_not_let_in() {
+ let hub = unowned_hub();
+ let (mut p, code) = pairing_phone(&hub).await;
+ p.send(json!({"id": 1, "m": "pair", "b": pair_body(&p, &code, "Pixel", "android", "user_2")})).await;
+ while hub.pairing_requests.json().is_empty() {
+ tokio::task::yield_now().await;
+ }
+ // The computer still has the offer while it asks: the relay keeps the phone's socket.
+ assert!(hub.pairing.locked().open());
+ let dk = p.dk();
+ drop(p.tx);
+ p.run.await.unwrap();
+ assert!(hub.pairing_requests.json().is_empty(), "the question goes with the phone");
+ assert!(hub.store.device(&dk).is_none());
+}
+
#[tokio::test]
async fn a_computer_in_no_account_asks_then_joins_the_phones() {
let hub = unowned_hub();
@@ -53,7 +79,7 @@ async fn a_computer_in_no_account_asks_then_joins_the_phones() {
let request = hub.pairing_requests.json()[0].clone();
assert_eq!(request["email"], "[email protected]");
let device_key = crypto::unb64_n::<32>(&p.dk()).unwrap();
- let expected = crate::remote::pairing_requests::check_code(&device_key, &hub.identity.sign_pub());
+ let expected = crypto::pair_check_code(&device_key, &hub.identity.sign_pub());
assert_eq!(request["code"], expected.as_str(), "the code the phone shows too");
crate::remote::pairing_requests::decide(&hub, request["requestId"].as_str().unwrap(), approve).unwrap();
let reply = p.recv().await.unwrap();
diff --git a/host/src/remote/cloud.rs b/host/src/remote/cloud.rs
index 7d778366..dff995da 100644
--- a/host/src/remote/cloud.rs
+++ b/host/src/remote/cloud.rs
@@ -64,6 +64,9 @@ pub struct CloudStatus {
pub assistants: bool,
/// Whose relay: on a private one there is no account, access request or relayed screen.
pub relay: RelayKind,
+ /// In no account while it could join one (the Codync cloud on): a signed-in phone that pairs asks to bring it
+ /// into its account. Kept by [`update_status`], so every app words it the same.
+ pub can_join_account: bool,
}
/// How account devices get in (`setApproval`, local only).
@@ -144,6 +147,7 @@ pub fn update_status(hub: &Hub, f: impl FnOnce(&mut CloudStatus)) {
let mut s = hub.cloud.status.locked();
let before = s.clone();
f(&mut s);
+ s.can_join_account = s.enabled && s.relay == RelayKind::Codync && s.owner.is_none();
(*s != before).then(|| s.clone())
};
if let Some(s) = changed {
diff --git a/host/src/remote/crypto.rs b/host/src/remote/crypto.rs
index 188c6507..33a99412 100644
--- a/host/src/remote/crypto.rs
+++ b/host/src/remote/crypto.rs
@@ -283,9 +283,17 @@ pub fn sas_commit(dk: &[u8; 32], device_nonce: &[u8; 32]) -> [u8; 32] {
/// The 6-digit code both screens show.
pub fn sas_code(host_sign_pub: &[u8; 32], dk: &[u8; 32], device_nonce: &[u8; 32], host_nonce: &[u8; 32]) -> String {
- let h = sha256(&[b"codync/sas/v2", host_sign_pub, dk, device_nonce, host_nonce]);
- let n = u32::from_be_bytes([h[0], h[1], h[2], h[3]]) % 1_000_000;
- format!("{n:06}")
+ six_digits(&sha256(&[b"codync/sas/v2", host_sign_pub, dk, device_nonce, host_nonce]))
+}
+
+/// The code a pairing phone and a computer in no account both show while the computer asks: a phone that
+/// isn't the one in the user's hand shows another code.
+pub fn pair_check_code(dk: &[u8; 32], host_sign_pub: &[u8; 32]) -> String {
+ six_digits(&sha256(&[b"codync/pair-check/v1", dk, host_sign_pub]))
+}
+
+fn six_digits(h: &[u8; 32]) -> String {
+ format!("{:06}", u32::from_be_bytes([h[0], h[1], h[2], h[3]]) % 1_000_000)
}
/// The ACL `offers[].id` (and relay `pair=`) for a pairing code.
@@ -494,6 +502,7 @@ mod tests {
let (nd, nh) = (b32(&s["deviceNonce"]), b32(&s["hostNonce"]));
assert_eq!(b64(&sas_commit(&dk, &nd)), s["commit"]);
assert_eq!(sas_code(k.host.verifying_key().as_bytes(), &dk, &nd, &nh), s["code"]);
+ assert_eq!(pair_check_code(&dk, k.host.verifying_key().as_bytes()), v["pairCheck"]["code"]);
let p = &v["pairing"];
assert_eq!(offer_id(&unb64_n(p["code"].as_str().unwrap()).unwrap()), p["offerId"]);
diff --git a/host/src/remote/owner.rs b/host/src/remote/owner.rs
index 64651386..247a5567 100644
--- a/host/src/remote/owner.rs
+++ b/host/src/remote/owner.rs
@@ -2,39 +2,72 @@
//! even with the cloud unreachable, and a change of account drops the old account's devices
//! (docs/architecture/connections.md: "the host changed its account").
-use super::cloud::Owner;
+use super::cloud::{Owner, RelayKind};
+use super::crypto;
use crate::hub::Hub;
use crate::store::Store;
-use anyhow::Result;
+use anyhow::{Result, bail};
+use serde_json::{Value, json};
const OWNER: &str = "account_owner";
-/// The account as last seen from the cloud; `None` when the computer isn't in one (or never heard yet).
+/// The account as last seen from the cloud; `None` when the computer isn't in one (or never heard yet), and
+/// with the Codync cloud off or a private relay, where it is in no account either (as its status says).
pub fn owner(store: &Store) -> Option<Owner> {
+ super::cloud::current(store).filter(|address| address.kind == RelayKind::Codync)?;
store.kv_get(OWNER).and_then(|v| serde_json::from_str::<Option<Owner>>(&v).ok()).flatten()
}
/// Records the account the cloud reports. When it is another one than before (joining one, moving, or leaving),
/// every device let in for another account goes; joining a first account keeps the phones paired before devices
-/// recorded their account. The first record after an upgrade only records.
+/// recorded their account. The first record after an upgrade only records. The devices go first, so a failure
+/// leaves the old account recorded and the next pull tries again.
pub fn remember(hub: &Hub, now: Option<&Owner>) -> Result<()> {
let saved = serde_json::to_string(&now)?;
let before = hub.store.kv_get(OWNER);
if before.as_deref() == Some(saved.as_str()) {
return Ok(());
}
- hub.store.kv_set(OWNER, &saved)?;
- let Some(before) = before else { return Ok(()) };
- let before = serde_json::from_str::<Option<Owner>>(&before).ok().flatten().map(|o| o.user_id);
- let now = now.map(|o| o.user_id.as_str());
- if before.as_deref() != now {
- let gone = hub.store.keep_devices_of(now, before.is_none())?;
- tracing::info!(devices = gone.len(), "the computer changed its account; the old account's devices are gone");
- if !gone.is_empty() {
- hub.auth_changed();
+ if let Some(before) = before {
+ let before = serde_json::from_str::<Option<Owner>>(&before).ok().flatten().map(|o| o.user_id);
+ let now = now.map(|o| o.user_id.as_str());
+ if before.as_deref() != now {
+ let gone = hub.store.keep_devices_of(now, before.is_none())?;
+ tracing::info!(
+ devices = gone.len(),
+ "the computer changed its account; the old account's devices are gone"
+ );
+ if !gone.is_empty() {
+ hub.auth_changed();
+ }
}
}
- Ok(())
+ hub.store.kv_set(OWNER, &saved)
+}
+
+/// Signs this computer into an account claim (§4.2 A) for a signed-in app to complete: the desktop app's
+/// Add to account, or a phone pairing with a computer in no account.
+pub async fn sign_claim(hub: &Hub, claim_id: &str, nonce: &str, user_id: &str) -> Result<Value> {
+ super::cloud::require_accounts(&hub.store)?;
+ for (k, v) in [("claimId", claim_id), ("nonce", nonce), ("userId", user_id)] {
+ // Fields are newline-separated in the signed string: a newline would forge another field.
+ if v.is_empty() || v.contains('\n') {
+ bail!("`{k}` is invalid");
+ }
+ }
+ let computer_id = hub.identity.computer_id();
+ let box_key = hub.identity.box_pub_b64();
+ let input = crypto::claim_input(claim_id, nonce, user_id, &computer_id, &box_key);
+ Ok(json!({
+ "computerId": computer_id,
+ "signKey": hub.identity.sign_pub_b64(),
+ "boxKey": box_key,
+ "name": crate::service::host_name(),
+ "platform": std::env::consts::OS,
+ "device": tokio::task::spawn_blocking(crate::service::device).await?,
+ "version": env!("CARGO_PKG_VERSION"),
+ "sig": crypto::b64(&hub.identity.sign(input.as_bytes())),
+ }))
}
#[cfg(test)]
@@ -45,16 +78,13 @@ mod tests {
use crate::store::{Device, DeviceSource, Scope};
use std::sync::Arc;
+ /// On the Codync cloud, where a computer can be in an account.
fn hub() -> Arc<Hub> {
let dir = std::env::temp_dir().join(format!("codync-owner-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&dir).unwrap();
- Hub::new(
- Store::open(&dir.join("t.db")).unwrap(),
- "host".into(),
- Identity::load_or_create(&dir).unwrap(),
- "t".into(),
- 0,
- )
+ let store = Store::open(&dir.join("t.db")).unwrap();
+ store.kv_set("test_cloud_url", "https://dev-api.codync.dev").unwrap();
+ Hub::new(store, "host".into(), Identity::load_or_create(&dir).unwrap(), "t".into(), 0)
}
fn device(hub: &Hub, key: &str, account: Option<&str>) {
@@ -114,4 +144,14 @@ mod tests {
remember(&hub, Some(&account("user_a"))).unwrap();
assert_eq!(keys(&hub), ["legacy", "mine"]);
}
+
+ #[test]
+ fn with_the_cloud_off_or_a_private_relay_the_computer_is_in_no_account() {
+ let hub = hub();
+ remember(&hub, Some(&account("user_a"))).unwrap();
+ hub.store.kv_set("test_cloud_token", "relay-token").unwrap();
+ assert!(owner(&hub.store).is_none(), "a private relay has no accounts");
+ hub.store.kv_set("cloud_enabled", "false").unwrap();
+ assert!(owner(&hub.store).is_none(), "nor does a computer with its cloud off");
+ }
}
diff --git a/host/src/remote/pairing_requests.rs b/host/src/remote/pairing_requests.rs
index 7c30c99e..2449d26e 100644
--- a/host/src/remote/pairing_requests.rs
+++ b/host/src/remote/pairing_requests.rs
@@ -1,10 +1,10 @@
//! A signed-in phone scanning a computer that isn't in an account (docs/plans/require-sign-in.md, phase 2):
-//! the computer confirms in the desktop app, the terminal UI or `codync-host pair` before the phone gets in
-//! and the computer joins the phone's account. Both screens show the same 6-digit code.
+//! the computer confirms in the desktop app, the terminal UI, `codync-host pair` or `codync-host access` before
+//! the phone gets in and the computer joins the phone's account. Both screens show the same 6-digit code
+//! ([`crate::remote::crypto::pair_check_code`]).
use crate::LockExt;
use crate::hub::Hub;
-use crate::remote::crypto;
use crate::store::now_ms;
use anyhow::{Result, anyhow};
use serde_json::{Value, json};
@@ -12,8 +12,9 @@ use std::sync::Mutex;
use std::time::Duration;
use tokio::sync::oneshot;
-/// How long the computer has to answer; the phone waits as long.
-pub const ASK_FOR: Duration = Duration::from_mins(2);
+/// How long the computer has to answer: inside the 2 minutes the relay keeps a pairing socket open, so an
+/// answer still reaches the phone, which waits longer.
+pub const ASK_FOR: Duration = Duration::from_secs(90);
struct Pending {
id: String,
@@ -42,15 +43,8 @@ impl PairingRequests {
}
}
-/// The code a phone and this computer both show: the phone's key and the computer's, hashed. A phone that
-/// isn't the one in the user's hand shows another code.
-pub fn check_code(device_key: &[u8; 32], host_sign_key: &[u8; 32]) -> String {
- let h = crypto::sha256(&[b"codync/pair-check/v1", device_key, host_sign_key]);
- format!("{:06}", u32::from_be_bytes([h[0], h[1], h[2], h[3]]) % 1_000_000)
-}
-
-/// Asks this computer whether the phone may in and bring it into `email`'s account; false when it says no
-/// or nobody answers in time.
+/// Asks this computer whether the phone may come in and bring it into `email`'s account; false when it says
+/// no or nobody answers in time. Dropping the future (the phone left) withdraws the question.
pub async fn ask(hub: &Hub, device_name: &str, platform: &str, email: Option<&str>, code: String) -> bool {
let (tx, rx) = oneshot::channel();
let id = uuid::Uuid::new_v4().to_string();
@@ -64,10 +58,21 @@ pub async fn ask(hub: &Hub, device_name: &str, platform: &str, email: Option<&st
answer: Some(tx),
});
emit(hub);
- let answer = tokio::time::timeout(ASK_FOR, rx).await;
- hub.pairing_requests.0.locked().retain(|p| p.id != id);
- emit(hub);
- matches!(answer, Ok(Ok(true)))
+ let _withdraw = Withdraw { hub, id };
+ matches!(tokio::time::timeout(ASK_FOR, rx).await, Ok(Ok(true)))
+}
+
+/// Takes a question off every screen once it is answered, unanswered, or the phone is gone.
+struct Withdraw<'a> {
+ hub: &'a Hub,
+ id: String,
+}
+
+impl Drop for Withdraw<'_> {
+ fn drop(&mut self) {
+ self.hub.pairing_requests.0.locked().retain(|p| p.id != self.id);
+ emit(self.hub);
+ }
}
/// `decidePairing`: this computer's answer to one request.
@@ -96,24 +101,21 @@ mod tests {
use crate::store::Store;
use std::sync::Arc;
- /// The vector the phones check against (apps/ios, apps/android).
- #[test]
- fn check_code_vector() {
- assert_eq!(check_code(&[1; 32], &[2; 32]), "855066");
- assert_ne!(check_code(&[1; 32], &[2; 32]), check_code(&[3; 32], &[2; 32]));
- }
-
- #[tokio::test]
- async fn the_computer_answers() {
+ fn hub() -> Arc<Hub> {
let dir = std::env::temp_dir().join(format!("codync-pr-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&dir).unwrap();
- let hub = Hub::new(
+ Hub::new(
Store::open(&dir.join("t.db")).unwrap(),
"h".into(),
Identity::load_or_create(&dir).unwrap(),
"t".into(),
0,
- );
+ )
+ }
+
+ #[tokio::test]
+ async fn the_computer_answers() {
+ let hub = hub();
for approve in [true, false] {
let asking = tokio::spawn({
let hub = Arc::clone(&hub);
@@ -130,4 +132,19 @@ mod tests {
}
assert!(decide(&hub, "gone", true).is_err());
}
+
+ #[tokio::test]
+ async fn a_phone_that_leaves_takes_its_question_along() {
+ let hub = hub();
+ let asking = tokio::spawn({
+ let hub = Arc::clone(&hub);
+ async move { ask(&hub, "Pixel", "android", None, "123456".into()).await }
+ });
+ while hub.pairing_requests.json().is_empty() {
+ tokio::task::yield_now().await;
+ }
+ asking.abort();
+ let _ = asking.await;
+ assert!(hub.pairing_requests.json().is_empty(), "no screen keeps asking about a phone that is gone");
+ }
}
diff --git a/host/src/store/devices.rs b/host/src/store/devices.rs
index 971637a7..ddabed26 100644
--- a/host/src/store/devices.rs
+++ b/host/src/store/devices.rs
@@ -54,6 +54,14 @@ pub struct PushTicket {
const DEVICE_COLS: &str =
"key, name, platform, source, grant_id, scopes, lease_until, created_at, last_seen_at, account";
+/// A device with its push and Live Activity tickets; the number of device rows removed.
+fn delete_device(tx: &rusqlite::Transaction, key: &str) -> rusqlite::Result<usize> {
+ let n = tx.execute("DELETE FROM devices WHERE key = ?1", [key])?;
+ tx.execute("DELETE FROM push_tickets WHERE device_key = ?1", [key])?;
+ tx.execute("DELETE FROM activity_tickets WHERE device_key = ?1", [key])?;
+ Ok(n)
+}
+
fn row_device(r: &rusqlite::Row) -> rusqlite::Result<Device> {
let source: String = r.get(3)?;
let scopes: String = r.get(5)?;
@@ -113,9 +121,7 @@ impl Store {
pub fn remove_device(&self, key: &str) -> Result<bool> {
let mut c = self.db.locked();
let tx = c.transaction()?;
- let n = tx.execute("DELETE FROM devices WHERE key = ?1", [key])?;
- tx.execute("DELETE FROM push_tickets WHERE device_key = ?1", [key])?;
- tx.execute("DELETE FROM activity_tickets WHERE device_key = ?1", [key])?;
+ let n = delete_device(&tx, key)?;
tx.commit()?;
Ok(n > 0)
}
@@ -134,9 +140,7 @@ impl Store {
st.query_map(params![account, keep_unrecorded], |r| r.get(0))?.collect::<rusqlite::Result<_>>()?
};
for key in &gone {
- tx.execute("DELETE FROM devices WHERE key = ?1", [key])?;
- tx.execute("DELETE FROM push_tickets WHERE device_key = ?1", [key])?;
- tx.execute("DELETE FROM activity_tickets WHERE device_key = ?1", [key])?;
+ delete_device(&tx, key)?;
}
tx.commit()?;
Ok(gone)
diff --git a/host/src/tui/app/overlay_keys.rs b/host/src/tui/app/overlay_keys.rs
index 9ace9394..9858a25a 100644
--- a/host/src/tui/app/overlay_keys.rs
+++ b/host/src/tui/app/overlay_keys.rs
@@ -137,7 +137,7 @@ impl App {
}
// 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);
+ self.request_pairing_code();
Some(Overlay::Pair(PairCode::Loading))
}
Overlay::LeadAgent(scroll) => {
diff --git a/host/src/tui/app/pair.rs b/host/src/tui/app/pair.rs
index 5241123c..be9e70b4 100644
--- a/host/src/tui/app/pair.rs
+++ b/host/src/tui/app/pair.rs
@@ -8,11 +8,16 @@ 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.request_pairing_code();
self.call("cloudStatus", json!({}), After::Cloud);
self.call("pairingRequests", json!({}), After::PairingRequests);
}
+ /// A new code, with a short one to type where the QR is hard to scan (a terminal over SSH).
+ pub(super) fn request_pairing_code(&mut self) {
+ self.call("pairing", json!({"shortCode": true}), After::Pairing);
+ }
+
pub(super) fn pair_reply(&mut self, after: &After, r: Result<Value, String>) {
match (after, r) {
(After::Pairing, r) => {
@@ -22,7 +27,10 @@ impl App {
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()),
+ |url| PairCode::Ready {
+ url: url.to_owned(),
+ short_code: v["shortCode"].as_str().map(str::to_owned),
+ },
),
};
}
@@ -49,13 +57,10 @@ impl App {
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.
+ /// Known to be in no account while it could join one (the host's `canJoinAccount`): a signed-in phone that
+ /// scans the code asks to bring the computer into its own.
pub fn outside_account(&self) -> bool {
- self.cloud.is_object()
- && self.cloud["owner"].is_null()
- && self.cloud["enabled"] == true
- && self.cloud["relay"] != "private"
+ self.cloud["canJoinAccount"] == true
}
}
@@ -72,13 +77,9 @@ mod tests {
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})));
+ app.pair_reply(&After::Cloud, Ok(json!({"canJoinAccount": true, "owner": null})));
assert!(app.outside_account());
- app.pair_reply(&After::Cloud, Ok(json!({"enabled": true, "owner": {"userId": "user_1"}})));
+ app.pair_reply(&After::Cloud, Ok(json!({"canJoinAccount": false, "owner": {"userId": "user_1"}})));
assert!(!app.outside_account());
app.pairing_requests_changed(&json!({"requests": [{"requestId": "a", "deviceName": "Pixel", "code": "123456"},
diff --git a/host/src/tui/app/ui.rs b/host/src/tui/app/ui.rs
index b88b2b0d..bcafa4d3 100644
--- a/host/src/tui/app/ui.rs
+++ b/host/src/tui/app/ui.rs
@@ -308,10 +308,11 @@ pub struct GroupForm {
pub saving: bool,
}
-/// The pair-a-phone sheet's code: on its way, shown (its pairing link), or why none came.
+/// The pair-a-phone sheet's code: on its way, shown (its pairing link, and the short code to type when the
+/// Codync cloud holds one), or why none came.
pub enum PairCode {
Loading,
- Ready(String),
+ Ready { url: String, short_code: Option<String> },
Failed(String),
}
diff --git a/host/src/tui/view/pair.rs b/host/src/tui/view/pair.rs
index 672c72ab..644b9dbb 100644
--- a/host/src/tui/view/pair.rs
+++ b/host/src/tui/view/pair.rs
@@ -10,7 +10,7 @@ use serde_json::Value;
use super::super::app::{App, PairCode};
use super::super::l10n::tr;
-use super::super::md::{truncate, width as w, wrap};
+use super::super::md::{width as w, wrap};
use super::buffer::{centered, frame_box, put, put_line, u};
use super::style::theme;
@@ -20,7 +20,9 @@ pub(super) fn pair(buf: &mut Buffer, area: Rect, app: &App, code: &PairCode) {
}
let t = theme();
let (text, style) = match code {
- PairCode::Ready(url) => return qr(buf, area, url, app.outside_account()),
+ PairCode::Ready { url, short_code } => {
+ return qr(buf, area, url, short_code.as_deref(), app.outside_account());
+ }
PairCode::Loading => ("Getting the pairing code…", t.secondary),
PairCode::Failed(e) => (e.as_str(), t.red),
};
@@ -62,27 +64,37 @@ 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) {
+fn qr(buf: &mut Buffer, area: Rect, url: &str, short_code: Option<&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 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)
+ // Under the QR, each in full: how to scan, the link, the code to type, and that the computer is in no account.
+ let below = |width: usize| {
+ let scan = if url.starts_with("codync-dev:") {
+ "Scan with Codync Dev on your iPhone:"
+ } else {
+ "Scan with the Codync iPhone app, or open on the phone:"
+ };
+ let mut below = note(scan.to_owned(), width, t.secondary.patch(t.panel));
+ below.extend(note(url.to_owned(), width, t.dim.patch(t.panel)));
+ if let Some(code) = short_code {
+ let text = tr("Or type this code in the app's pairing screen: {code}").replace("{code}", code);
+ below.extend(note(text, width, t.text.patch(t.panel)));
+ }
+ if outside_account {
+ let text =
+ tr("Not in an account: a signed-in phone that scans this asks to bring the computer into its account.");
+ below.extend(note(text.into_owned(), width, t.amber.patch(t.panel)));
+ }
+ below
};
- let r = centered(area, bw, bh);
+ let wide = below(qw.max(50));
+ let fits = u(lines.len() + 4 + wide.len()) <= area.height && u(qw + 4) <= area.width;
+ let (bw, qr_rows, below) = if fits { (u(qw.max(50) + 4), lines.len(), wide) } else { (70, 1, below(66)) };
+ let r = centered(area, bw, u(qr_rows + 4 + below.len()));
let inner = frame_box(buf, r, t.text, t.panel, Some(("Pair a phone", t.text)));
let mut y = inner.y;
if fits {
@@ -97,20 +109,7 @@ fn qr(buf: &mut Buffer, area: Rect, url: &str, outside_account: bool) {
put(buf, inner.x, y, inner.width, "Make the window taller to show the QR code.", t.secondary.patch(t.panel));
y += 1;
}
- put(
- buf,
- inner.x,
- y,
- inner.width,
- if url.starts_with("codync-dev:") {
- "Scan with Codync Dev on your iPhone:"
- } else {
- "Scan with the Codync iPhone app, or open on the phone:"
- },
- 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) {
+ for (y, line) in (y..).zip(&below) {
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));
@@ -150,8 +149,21 @@ mod tests {
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);
+ qr(&mut buf, area, "codync://pair?id=x&code=y", None, outside);
assert_eq!(shown(&buf).contains(&first), says);
}
}
+
+ #[test]
+ fn the_whole_link_and_the_short_code_show() {
+ let url = format!("codync://pair?v=3&id={}&code=end", "x".repeat(120));
+ for height in [60, 12] {
+ let mut buf = Buffer::empty(Rect::new(0, 0, 100, height));
+ let area = buf.area;
+ qr(&mut buf, area, &url, Some("QRTX-4821"), false);
+ let text = shown(&buf);
+ assert!(text.contains("code=end") && !text.contains('…'), "the link isn't cut short\n{text}");
+ assert!(text.contains("QRTX-4821"), "{text}");
+ }
+ }
}
diff --git a/host/tests/common/mod.rs b/host/tests/common/mod.rs
index faecdd48..713bc2fb 100644
--- a/host/tests/common/mod.rs
+++ b/host/tests/common/mod.rs
@@ -6,9 +6,6 @@ use std::path::Path;
use std::process::{Child, Command, Stdio};
use std::time::{Duration, Instant};
-/// Runs `codync-host serve` for `home` until it answers: the process and its base URL. A port
-/// picked here is only free for a moment; when something else takes it before the host binds, the
-/// host exits and this starts it again on another one.
/// The seed of the cloud key a test host trusts for device certificates.
pub const TEST_CLOUD_SEED: [u8; 32] = [9; 32];
@@ -18,6 +15,9 @@ fn test_cloud_key() -> String {
base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(key.as_bytes())
}
+/// Runs `codync-host serve` for `home` until it answers: the process and its base URL. A port
+/// picked here is only free for a moment; when something else takes it before the host binds, the
+/// host exits and this starts it again on another one.
pub async fn serve(home: &Path) -> (Child, String) {
let deadline = Instant::now() + Duration::from_secs(30);
let _ = std::fs::create_dir_all(home);
diff --git a/host/tests/e2e.rs b/host/tests/e2e.rs
index 61f75796..71ce58f4 100644
--- a/host/tests/e2e.rs
+++ b/host/tests/e2e.rs
@@ -40,14 +40,7 @@ fn test_certificate(device_key: &str, user_id: &str) -> Value {
let payload = json!({"v": 1, "deviceKey": device_key, "userId": user_id, "email": "[email protected]", "exp": exp})
.to_string();
let key = SigningKey::from_bytes(&common::TEST_CLOUD_SEED);
- let sig = crypto::sign(
- &key,
- format!(
- "codync/device-cert/v1
-{payload}"
- )
- .as_bytes(),
- );
+ let sig = crypto::sign(&key, format!("codync/device-cert/v1\n{payload}").as_bytes());
json!({"payload": payload, "sig": crypto::b64(&sig)})
}
diff --git a/web/content/docs/getting-started.mdx b/web/content/docs/getting-started.mdx
index 7d6be94a..88303aab 100644
--- a/web/content/docs/getting-started.mdx
+++ b/web/content/docs/getting-started.mdx
@@ -70,7 +70,7 @@ Every iPhone release goes through Apple's App Review first, so the App Store ver
## 3. Pair your iPhone
-Pairing connects your phone to your computer with a QR code. The phone needs to be signed in first, with Apple or Google.
+Pairing connects your phone to your computer with a QR code. The phone needs to be signed in first, with Apple or Google, and with the same account as the desktop app: a computer in another account turns the phone away. Apple with Hide My Email on one and Google on the other are two different accounts (more in [Remote access](/docs/remote-access#pairing)).
On the computer, show the pairing code:
diff --git a/web/content/docs/linux-servers.mdx b/web/content/docs/linux-servers.mdx
index 79432189..85e98755 100644
--- a/web/content/docs/linux-servers.mdx
+++ b/web/content/docs/linux-servers.mdx
@@ -42,7 +42,7 @@ codync-host status
## Pair your phone
-With the host running, run `codync-host pair` over SSH. It prints a QR code and a short code like `QRTX-4821`. On the iPhone, signed in, scan the QR code from the welcome screen or later from **Manage computers → Pair a computer** (tap the connection status at the top of the Bots tab, such as **1 connected**), or type the short code into the field under the scanner. A server that isn't in an account yet asks in the terminal whether to let the phone in and join your account: check the phone shows the same 6-digit code, then answer `y`. `codync-host cloud` says which account the server is in.
+With the host running, run `codync-host pair` over SSH. It prints a QR code and a short code like `QRTX-4821`. On the iPhone, signed in, scan the QR code from the welcome screen or later from **Manage computers → Pair a computer** (tap the connection status at the top of the Bots tab, such as **1 connected**), or type the short code into the field under the scanner. A server that isn't in an account yet asks in the terminal whether to let the phone in and join your account: check the phone shows the same 6-digit code, then answer `y` within 90 seconds. With `codync-host pair --json`, or SSH without a terminal, answer with `codync-host access approve <code>` instead. `codync-host cloud` says which account the server is in.
The code works once and expires after 10 minutes. More about pairing and accounts: [Remote access](/docs/remote-access).
diff --git a/web/content/docs/remote-access.mdx b/web/content/docs/remote-access.mdx
index c3a99e30..10a058ee 100644
--- a/web/content/docs/remote-access.mdx
+++ b/web/content/docs/remote-access.mdx
@@ -23,7 +23,7 @@ Pairing introduces your phone and your computer to each other. The computer show
Show the code on the computer:
- **Desktop app:** open Codync in the menu bar (macOS) or the tray (Windows, Linux) and choose **Pair iPhone…**. You can also open **Settings → Computers** and use the QR code button on the computer's card.
-- **Terminal:** run `codync-host pair`. It prints the QR code in the terminal. `codync-host pair --json` prints the link instead.
+- **Terminal:** run `codync-host pair`. It prints the QR code in the terminal, and waits to answer when the computer asks about a phone (see below). `codync-host pair --json` prints the link instead and doesn't wait.
- **Terminal UI:** press `^k` and choose **Pair a phone…**.
Then, on the iPhone, scan it from the welcome screen, or later from **Manage computers → Pair a computer** (tap the connection status at the top of the Bots tab, such as **1 connected**). You can also paste the `codync://pair` link instead of scanning, or type the short code `codync-host pair` prints, like `QRTX-4821`.
@@ -34,7 +34,7 @@ Pairing checks your account, so a phone and a computer pair only when they're in
- **The computer is in your account:** the phone is let in right away.
- **The computer is in someone else's account:** the phone says whose (for example *k•••@example.com*). Move the computer to your account on that computer, or sign in to that account.
-- **The computer isn't in an account yet:** the computer asks first. The desktop app asks whether to let the phone in, and the terminal UI and `codync-host pair` ask you to answer `y`. Check that the phone shows the same 6-digit code, then let it in. The computer joins your account.
+- **The computer isn't in an account yet:** the computer asks first, for 90 seconds. The desktop app asks whether to let the phone in, and the terminal UI and `codync-host pair` ask you to answer `y`. Without any of them (`codync-host pair --json`, a script, SSH with no terminal), run `codync-host access approve <code>` with the 6 digits the phone shows. Check that the phone shows the same 6-digit code, then let it in. The computer joins your account; with its cloud off or on a private relay, the phone gets in and the computer stays out of any account.
Changing the account a computer belongs to (moving it, or **Remove from account**) takes away access from every device of the old account. A computer joining its first account keeps the phones that were already paired.
@@ -48,7 +48,7 @@ The iPhone, Android and desktop apps ask you to sign in with Apple or Google bef
On a computer without the desktop app, use `codync-host access` to list requests and `codync-host access approve <code>` to approve one.
-Signing out of the desktop app keeps the computer in your account. If you then sign in with a different account, the app asks whether to move the computer there. Choose **Move here** and your phone, signed in to the new account, finds it under **Manage computers**. Devices approved through the old account lose access. Moving it turns **Skip the 6-digit check** off, so new devices ask with the 6-digit code; turn it back on in **Settings → Computers** if you want. Choose **Keep it there** to leave it where it is; you can still move it later with **Remove from account** and then **Add to account**.
+Signing out of the desktop app keeps the computer in your account. If you then sign in with a different account, the app asks whether to move the computer there. Choose **Move here** and your phone, signed in to the new account, finds it under **Manage computers**. Every device of the old account loses access, phones paired with a QR code included. Moving it turns **Skip the 6-digit check** off, so new devices ask with the 6-digit code; turn it back on in **Settings → Computers** if you want. Choose **Keep it there** to leave it where it is; you can still move it later with **Remove from account** and then **Add to account**.
When the computer and the desktop app's account differ, an amber notice at the bottom of the sidebar says how (in the narrow sidebar, an amber icon; point at it to read it):
@@ -158,5 +158,5 @@ Webhook deliveries are **not** end-to-end encrypted. The relay receives them ove
- **On the computer:** in **Settings → Computers**, the list **Devices that can use** the computer has **Revoke access** for each device. Without the desktop app, use `codync-host devices` to list devices and `codync-host devices revoke <key>` to remove one. The device disconnects right away and has to pair or ask again.
- **On the iPhone:** in **Manage computers**, remove a paired computer, or revoke this phone's account access to one. The computer keeps its bots and chats.
-- **Remove from account** on a computer's card disconnects devices approved through the account. Devices paired with a QR code keep their access.
-- **A computer that's gone** (reset, reinstalled or given away) stays offline in your account. In the desktop app, **Settings → Computers** lists it under **Other computers in your account**; choose **Remove from account** on its row. Any offline computer has it, so first make sure it's gone rather than asleep: devices approved through the account lose access, and it rejoins only when you add it again on that computer. Only the desktop app removes a computer from the account; on a phone you can only forget a computer you paired with a QR code.
+- **Remove from account** on a computer's card disconnects every device of the account, phones paired with a QR code included. They have to pair again.
+- **A computer that's gone** (reset, reinstalled or given away) stays offline in your account. In the desktop app, **Settings → Computers** lists it under **Other computers in your account**; choose **Remove from account** on its row. Any offline computer has it, so first make sure it's gone rather than asleep: every device of the account loses access, and it rejoins only when you add it again on that computer. Only the desktop app removes a computer from the account; on a phone you can only forget a computer you paired with a QR code.