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.

Reach your computer from anywhere through an end-to-end encrypted Cloudflare relay, with accounts, multiple computers and SSH

leepokaic477a7f93ac4
diff --git a/.github/workflows/cloud.yml b/.github/workflows/cloud.yml
new file mode 100644
index 00000000..08d76561
--- /dev/null
+++ b/.github/workflows/cloud.yml
@@ -0,0 +1,41 @@
+name: codync-cloud
+
+on:
+ push:
+ branches: [main, v2]
+ paths: ["cloud/**", "relay/**", "docs/remote-relay-vectors.json", ".github/workflows/cloud.yml"]
+ pull_request:
+ paths: ["cloud/**", "relay/**", "docs/remote-relay-vectors.json"]
+
+jobs:
+ cloud:
+ runs-on: ubuntu-latest
+ defaults:
+ run:
+ working-directory: cloud
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 24
+ cache: npm
+ cache-dependency-path: cloud/package-lock.json
+ - run: npm ci
+ - run: npm run typecheck
+ - run: npm test
+
+ relay:
+ runs-on: ubuntu-latest
+ defaults:
+ run:
+ working-directory: relay
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 24
+ cache: npm
+ cache-dependency-path: relay/package-lock.json
+ - run: npm ci
+ - run: npm run typecheck
+ - run: npm test
diff --git a/.github/workflows/kit.yml b/.github/workflows/kit.yml
new file mode 100644
index 00000000..5b5461d1
--- /dev/null
+++ b/.github/workflows/kit.yml
@@ -0,0 +1,22 @@
+name: CodyncKit
+
+on:
+ push:
+ branches: [main, v2]
+ paths: ["kit/**", "docs/remote-relay-vectors.json", ".github/workflows/kit.yml"]
+ pull_request:
+ paths: ["kit/**", "docs/remote-relay-vectors.json"]
+
+jobs:
+ test:
+ runs-on: macos-latest
+ defaults:
+ run:
+ working-directory: kit
+ steps:
+ - uses: actions/checkout@v4
+ - uses: maxim-lobanov/setup-xcode@v1
+ with:
+ xcode-version: latest-stable
+ - run: swift build
+ - run: swift test
diff --git a/.github/workflows/release-macos.yml b/.github/workflows/release-macos.yml
index be9b3d5e..12d86827 100644
--- a/.github/workflows/release-macos.yml
+++ b/.github/workflows/release-macos.yml
@@ -68,6 +68,8 @@ jobs:
- name: Sign app with Developer ID
run: |
APP_PATH=$(find build/derived -name "Codync.app" -path "*/Release/*" | head -1)
+ # Sign-in and the cloud relay read their settings from here.
+ test -f "$APP_PATH/Contents/Resources/AccountConfig.plist" || { echo "AccountConfig.plist missing"; exit 1; }
# Nested helper first (the bundled Rust host), then the app itself.
codesign --force --options runtime --timestamp \
--sign "Developer ID Application" "$APP_PATH/Contents/MacOS/codync-host"
diff --git a/Codync.xcodeproj/project.pbxproj b/Codync.xcodeproj/project.pbxproj
index 4bdc1bdb..5d07faa4 100644
--- a/Codync.xcodeproj/project.pbxproj
+++ b/Codync.xcodeproj/project.pbxproj
@@ -17,16 +17,24 @@
2D724C1001CF872BAFCAE7EA /* IconButton.swift in Sources */ = {isa = PBXBuildFile; fileRef = D3831394C093AF3A4E504BC5 /* IconButton.swift */; };
2F0A1C29DBBD1D700C10BE46 /* CodyncApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = F45CCA6BBDCF412897AEC105 /* CodyncApp.swift */; };
31A78A067C217F77FBDEDFD0 /* Push.swift in Sources */ = {isa = PBXBuildFile; fileRef = 55AABA9596547D7459B1CC5B /* Push.swift */; };
+ 331338197BF906B069159B11 /* SSHTunnel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3A4EBC39B2AC89EAA4F5033F /* SSHTunnel.swift */; };
+ 44FDF4571F4536E3215679E8 /* AccountConfig.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3454B60AEA40B1DCFA5E54AE /* AccountConfig.plist */; };
484455D97513F09142D21D0D /* Capture.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE4D28E8291EEB43E17B11FA /* Capture.swift */; };
48DAAA1384E5B8D0BA27C895 /* SwiftUI.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1E47C60032C326157E0386B8 /* SwiftUI.framework */; };
498C81B8C82557C85F912238 /* HostLink.swift in Sources */ = {isa = PBXBuildFile; fileRef = 75CAC64DDC41D4A222A12DDE /* HostLink.swift */; };
+ 4ACFCBCDB8253091EF9D8D1A /* ComputerStatus.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0C143ED8FF93F6BBD82F942 /* ComputerStatus.swift */; };
513F59BF65DED5379AB950A1 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = D2C705F063CD20F5B3036BD4 /* Assets.xcassets */; };
52CF04B855C6AAEC47B75B8F /* CodyncKit in Frameworks */ = {isa = PBXBuildFile; productRef = 1285DDFA0390A76ECDAAD6C0 /* CodyncKit */; };
5F9AE9B8E7FF66F194162BDC /* ScreenHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = AB932B6C1849B8DF7CF7C2E3 /* ScreenHelper.swift */; };
- 6A15821964A5EE5AEBB0C420 /* ClerkConfig.plist in Resources */ = {isa = PBXBuildFile; fileRef = 19D41F16A62FEF37BE0AD1FC /* ClerkConfig.plist */; };
+ 72A907055F1AAEF8F10EAD72 /* NotificationService.appex in Embed Foundation Extensions */ = {isa = PBXBuildFile; fileRef = 7B7E845BA1B8696B266CF578 /* NotificationService.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };
+ 76E73EDD79B063940B5D8B8E /* ComputersView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 57DFD81025893713D631B5D7 /* ComputersView.swift */; };
826FEDA23997E436D632E579 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = 4CFB70DD8757C90695CDA211 /* PrivacyInfo.xcprivacy */; };
8AC8D90C21B92480E2809758 /* AccountSession.swift in Sources */ = {isa = PBXBuildFile; fileRef = E4B8EAB09016D328195FE2AD /* AccountSession.swift */; };
+ 8BB3FC79EB798CE4347E6FD3 /* CodyncKit in Frameworks */ = {isa = PBXBuildFile; productRef = 50F314172CC2AD1C5CDC916A /* CodyncKit */; };
8CD641A45F144BF41D703D2A /* CodyncMacApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2969919CCC8BC89F277C43A6 /* CodyncMacApp.swift */; };
+ 9593C1951D727D36D6B8C0E9 /* ComputerStatus.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0C143ED8FF93F6BBD82F942 /* ComputerStatus.swift */; };
+ 9D0736B9670D57132AFBB34E /* NotificationService.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9C60BD13E7283ECB7A1AE4D3 /* NotificationService.swift */; };
+ 9FE9864DA43399578A892992 /* AccountConfig.plist in Resources */ = {isa = PBXBuildFile; fileRef = D5252F097812608BF90F7647 /* AccountConfig.plist */; };
AA601649E43A5AF73DCF5B5E /* WebRTC in Frameworks */ = {isa = PBXBuildFile; productRef = 2D9748E611692583AFC5A152 /* WebRTC */; };
ACCB28F3DB9C89108B7911E3 /* Input.swift in Sources */ = {isa = PBXBuildFile; fileRef = 842DA106CA15E3810C3C9461 /* Input.swift */; };
AFC0CD8BD1FA61F810C96057 /* com.pokai.Codync.screen.plist in CopyFiles */ = {isa = PBXBuildFile; fileRef = 895BB6C2EB8986266EB4159A /* com.pokai.Codync.screen.plist */; };
@@ -34,8 +42,8 @@
B75DD137E6F645F797B60B09 /* PairingView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 739EC95223CC8F8717C33736 /* PairingView.swift */; };
B8B86B2B7F8D9EE8639A9E09 /* CodyncUI in Frameworks */ = {isa = PBXBuildFile; productRef = BEE30A9D5C73E5A151F34180 /* CodyncUI */; };
C937F66F810AA238B73E8363 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = 4EDD440CC0624F03363AC1BA /* PrivacyInfo.xcprivacy */; };
- CA1174F732B066EAFA3D963C /* ClerkConfig.plist in Resources */ = {isa = PBXBuildFile; fileRef = D81BA172C8FED5521B00D5CF /* ClerkConfig.plist */; };
CC9F6FB8055C38D5D625F738 /* BotListView.swift in Sources */ = {isa = PBXBuildFile; fileRef = C5E57711E223A292872322C5 /* BotListView.swift */; };
+ CEB634F257363FE66E0BBCF1 /* AccessRequestView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1233BBE848155CA9E177A7E2 /* AccessRequestView.swift */; };
D4AB92074A9C0D9C72B4080A /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = E8B808BC2A9AA0ECD666A454 /* Assets.xcassets */; };
DEF7478AB86DB605F52905F5 /* SettingsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = DE4AE9A34F61B3D28E0C2550 /* SettingsView.swift */; };
E430F9317B690366F62164DB /* RootView.swift in Sources */ = {isa = PBXBuildFile; fileRef = E1B79D48C1D6F90D53751B3F /* RootView.swift */; };
@@ -65,6 +73,13 @@
remoteGlobalIDString = A27E4E88D6A5B9850734B594;
remoteInfo = Widgets;
};
+ DA04088A6786CD5F92C67AED /* PBXContainerItemProxy */ = {
+ isa = PBXContainerItemProxy;
+ containerPortal = 5B6351DD20AF4506794D6460 /* Project object */;
+ proxyType = 1;
+ remoteGlobalIDString = C42E5E078332C6C2B35AF5FA;
+ remoteInfo = NotificationService;
+ };
/* End PBXContainerItemProxy section */
/* Begin PBXCopyFilesBuildPhase section */
@@ -75,6 +90,7 @@
dstSubfolderSpec = 13;
files = (
F842AE1C5ED96AF9A7F5D16C /* Widgets.appex in Embed Foundation Extensions */,
+ 72A907055F1AAEF8F10EAD72 /* NotificationService.appex in Embed Foundation Extensions */,
);
name = "Embed Foundation Extensions";
runOnlyForDeploymentPostprocessing = 0;
@@ -104,16 +120,20 @@
/* Begin PBXFileReference section */
00F135A0B168269BD6C2A199 /* CodyncWidgets.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodyncWidgets.swift; sourceTree = "<group>"; };
- 19D41F16A62FEF37BE0AD1FC /* ClerkConfig.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; path = ClerkConfig.plist; sourceTree = "<group>"; };
+ 0E789EF9DE58D45EDE33F76D /* NotificationService.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = NotificationService.entitlements; sourceTree = "<group>"; };
+ 1233BBE848155CA9E177A7E2 /* AccessRequestView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AccessRequestView.swift; sourceTree = "<group>"; };
1E47C60032C326157E0386B8 /* SwiftUI.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = SwiftUI.framework; path = System/Library/Frameworks/SwiftUI.framework; sourceTree = SDKROOT; };
1F16B11B2920E9D05621AFE7 /* ViewingBadge.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ViewingBadge.swift; sourceTree = "<group>"; };
22F1B304BD18E48C91FC73E3 /* Widgets.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = Widgets.entitlements; sourceTree = "<group>"; };
232B2C00B9575BFF7068BB62 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; path = Info.plist; sourceTree = "<group>"; };
2969919CCC8BC89F277C43A6 /* CodyncMacApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodyncMacApp.swift; sourceTree = "<group>"; };
+ 3454B60AEA40B1DCFA5E54AE /* AccountConfig.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; path = AccountConfig.plist; sourceTree = "<group>"; };
+ 3A4EBC39B2AC89EAA4F5033F /* SSHTunnel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SSHTunnel.swift; sourceTree = "<group>"; };
47BCE8E2AFA6CA829DBC489A /* UsageView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UsageView.swift; sourceTree = "<group>"; };
4CFB70DD8757C90695CDA211 /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; path = PrivacyInfo.xcprivacy; sourceTree = "<group>"; };
4EDD440CC0624F03363AC1BA /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; path = PrivacyInfo.xcprivacy; sourceTree = "<group>"; };
55AABA9596547D7459B1CC5B /* Push.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Push.swift; sourceTree = "<group>"; };
+ 57DFD81025893713D631B5D7 /* ComputersView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ComputersView.swift; sourceTree = "<group>"; };
60422D3CA8FEBCDC5AC465E0 /* iOS.app */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = wrapper.application; path = iOS.app; sourceTree = BUILT_PRODUCTS_DIR; };
6D734BEE7CD3F84677B0218B /* Widgets.appex */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = "wrapper.app-extension"; path = Widgets.appex; sourceTree = BUILT_PRODUCTS_DIR; };
739EC95223CC8F8717C33736 /* PairingView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PairingView.swift; sourceTree = "<group>"; };
@@ -121,21 +141,25 @@
74BB0269490A0689868F05F7 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; path = Info.plist; sourceTree = "<group>"; };
75CAC64DDC41D4A222A12DDE /* HostLink.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HostLink.swift; sourceTree = "<group>"; };
7A2F5A7F5A648909D8CC5C19 /* kit */ = {isa = PBXFileReference; lastKnownFileType = folder; name = kit; path = kit; sourceTree = SOURCE_ROOT; };
+ 7B7E845BA1B8696B266CF578 /* NotificationService.appex */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = "wrapper.app-extension"; path = NotificationService.appex; sourceTree = BUILT_PRODUCTS_DIR; };
842DA106CA15E3810C3C9461 /* Input.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Input.swift; sourceTree = "<group>"; };
895BB6C2EB8986266EB4159A /* com.pokai.Codync.screen.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; path = com.pokai.Codync.screen.plist; sourceTree = "<group>"; };
93A9881C76B67297BE26D8FD /* HostController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HostController.swift; sourceTree = "<group>"; };
97876A72710A37EB86A082C1 /* AXTree.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AXTree.swift; sourceTree = "<group>"; };
991A0FD3EAAD4B446F3BF14E /* macOS.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = macOS.app; sourceTree = BUILT_PRODUCTS_DIR; };
9A59E3A7670EAF57F2F4C9B9 /* ChatWindow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatWindow.swift; sourceTree = "<group>"; };
+ 9C60BD13E7283ECB7A1AE4D3 /* NotificationService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NotificationService.swift; sourceTree = "<group>"; };
+ 9FBFED8E9C171912F6822C04 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; path = Info.plist; sourceTree = "<group>"; };
AB932B6C1849B8DF7CF7C2E3 /* ScreenHelper.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScreenHelper.swift; sourceTree = "<group>"; };
AFE4E0839DCD380109300DF1 /* AccountSwitcherView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AccountSwitcherView.swift; sourceTree = "<group>"; };
B274A0195CB3B2409EA4C194 /* WidgetKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = WidgetKit.framework; path = System/Library/Frameworks/WidgetKit.framework; sourceTree = SDKROOT; };
+ C0C143ED8FF93F6BBD82F942 /* ComputerStatus.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ComputerStatus.swift; sourceTree = "<group>"; };
C5E57711E223A292872322C5 /* BotListView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BotListView.swift; sourceTree = "<group>"; };
CE4D28E8291EEB43E17B11FA /* Capture.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Capture.swift; sourceTree = "<group>"; };
D0A657FB98BBE0D73807B263 /* Session.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Session.swift; sourceTree = "<group>"; };
D2C705F063CD20F5B3036BD4 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
D3831394C093AF3A4E504BC5 /* IconButton.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IconButton.swift; sourceTree = "<group>"; };
- D81BA172C8FED5521B00D5CF /* ClerkConfig.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; path = ClerkConfig.plist; sourceTree = "<group>"; };
+ D5252F097812608BF90F7647 /* AccountConfig.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; path = AccountConfig.plist; sourceTree = "<group>"; };
DE4AE9A34F61B3D28E0C2550 /* SettingsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsView.swift; sourceTree = "<group>"; };
E1B79D48C1D6F90D53751B3F /* RootView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RootView.swift; sourceTree = "<group>"; };
E4B8EAB09016D328195FE2AD /* AccountSession.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AccountSession.swift; sourceTree = "<group>"; };
@@ -183,12 +207,21 @@
);
runOnlyForDeploymentPostprocessing = 0;
};
+ E1D104105458D21A2FA289CD /* Frameworks */ = {
+ isa = PBXFrameworksBuildPhase;
+ buildActionMask = 2147483647;
+ files = (
+ 8BB3FC79EB798CE4347E6FD3 /* CodyncKit in Frameworks */,
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ };
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
1E45A5D617A608D762EC7EC5 /* Views */ = {
isa = PBXGroup;
children = (
+ 1233BBE848155CA9E177A7E2 /* AccessRequestView.swift */,
AFE4E0839DCD380109300DF1 /* AccountSwitcherView.swift */,
C5E57711E223A292872322C5 /* BotListView.swift */,
739EC95223CC8F8717C33736 /* PairingView.swift */,
@@ -233,6 +266,7 @@
children = (
60422D3CA8FEBCDC5AC465E0 /* iOS.app */,
991A0FD3EAAD4B446F3BF14E /* macOS.app */,
+ 7B7E845BA1B8696B266CF578 /* NotificationService.appex */,
741B706007BA1B91CB853699 /* Screen.app */,
6D734BEE7CD3F84677B0218B /* Widgets.appex */,
);
@@ -243,10 +277,21 @@
isa = PBXGroup;
children = (
E4B8EAB09016D328195FE2AD /* AccountSession.swift */,
+ C0C143ED8FF93F6BBD82F942 /* ComputerStatus.swift */,
);
path = shared;
sourceTree = "<group>";
};
+ 54C0301F153CCE10AB5C3DA7 /* NotificationService */ = {
+ isa = PBXGroup;
+ children = (
+ 9FBFED8E9C171912F6822C04 /* Info.plist */,
+ 0E789EF9DE58D45EDE33F76D /* NotificationService.entitlements */,
+ 9C60BD13E7283ECB7A1AE4D3 /* NotificationService.swift */,
+ );
+ path = NotificationService;
+ sourceTree = "<group>";
+ };
5893B7E84BB07F9649417F2D /* App */ = {
isa = PBXGroup;
children = (
@@ -270,6 +315,7 @@
isa = PBXGroup;
children = (
9A59E3A7670EAF57F2F4C9B9 /* ChatWindow.swift */,
+ 57DFD81025893713D631B5D7 /* ComputersView.swift */,
D3831394C093AF3A4E504BC5 /* IconButton.swift */,
);
path = Views;
@@ -295,6 +341,7 @@
isa = PBXGroup;
children = (
5893B7E84BB07F9649417F2D /* App */,
+ 54C0301F153CCE10AB5C3DA7 /* NotificationService */,
E5F3C27CC2117EB5AF702188 /* Resources */,
1E45A5D617A608D762EC7EC5 /* Views */,
2095D7AA44080F7BCB6E9204 /* Widgets */,
@@ -307,6 +354,7 @@
children = (
2969919CCC8BC89F277C43A6 /* CodyncMacApp.swift */,
93A9881C76B67297BE26D8FD /* HostController.swift */,
+ 3A4EBC39B2AC89EAA4F5033F /* SSHTunnel.swift */,
);
path = App;
sourceTree = "<group>";
@@ -335,8 +383,8 @@
E5F3C27CC2117EB5AF702188 /* Resources */ = {
isa = PBXGroup;
children = (
+ 3454B60AEA40B1DCFA5E54AE /* AccountConfig.plist */,
D2C705F063CD20F5B3036BD4 /* Assets.xcassets */,
- D81BA172C8FED5521B00D5CF /* ClerkConfig.plist */,
232B2C00B9575BFF7068BB62 /* Info.plist */,
F0B6AECA1FDDD3064F3D4447 /* iOS.entitlements */,
4EDD440CC0624F03363AC1BA /* PrivacyInfo.xcprivacy */,
@@ -361,8 +409,8 @@
FBD5ECB1F12422DB8CC87897 /* Resources */ = {
isa = PBXGroup;
children = (
+ D5252F097812608BF90F7647 /* AccountConfig.plist */,
E8B808BC2A9AA0ECD666A454 /* Assets.xcassets */,
- 19D41F16A62FEF37BE0AD1FC /* ClerkConfig.plist */,
);
path = Resources;
sourceTree = "<group>";
@@ -428,6 +476,7 @@
);
dependencies = (
40DF4BEA40A82C095F51AB76 /* PBXTargetDependency */,
+ 0BA52D71EA0FB37D52E4AE22 /* PBXTargetDependency */,
);
name = iOS;
packageProductDependencies = (
@@ -459,6 +508,25 @@
productReference = 6D734BEE7CD3F84677B0218B /* Widgets.appex */;
productType = "com.apple.product-type.app-extension";
};
+ C42E5E078332C6C2B35AF5FA /* NotificationService */ = {
+ isa = PBXNativeTarget;
+ buildConfigurationList = A6955F60D2D95C77124AC81A /* Build configuration list for PBXNativeTarget "NotificationService" */;
+ buildPhases = (
+ D14636C3DD3126603BE23791 /* Sources */,
+ E1D104105458D21A2FA289CD /* Frameworks */,
+ );
+ buildRules = (
+ );
+ dependencies = (
+ );
+ name = NotificationService;
+ packageProductDependencies = (
+ 50F314172CC2AD1C5CDC916A /* CodyncKit */,
+ );
+ productName = NotificationService;
+ productReference = 7B7E845BA1B8696B266CF578 /* NotificationService.appex */;
+ productType = "com.apple.product-type.app-extension";
+ };
/* End PBXNativeTarget section */
/* Begin PBXProject section */
@@ -484,6 +552,10 @@
DevelopmentTeam = 7FUM8A8H72;
ProvisioningStyle = Automatic;
};
+ C42E5E078332C6C2B35AF5FA = {
+ DevelopmentTeam = 7FUM8A8H72;
+ ProvisioningStyle = Automatic;
+ };
};
};
buildConfigurationList = F977CF173B7D60769B393751 /* Build configuration list for PBXProject "Codync" */;
@@ -505,6 +577,7 @@
projectDirPath = "";
projectRoot = "";
targets = (
+ C42E5E078332C6C2B35AF5FA /* NotificationService */,
907F1F4A709111FC7178EAE9 /* Screen */,
A27E4E88D6A5B9850734B594 /* Widgets */,
913BDA9F79CE8C35A9E35830 /* iOS */,
@@ -518,8 +591,8 @@
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
+ 9FE9864DA43399578A892992 /* AccountConfig.plist in Resources */,
D4AB92074A9C0D9C72B4080A /* Assets.xcassets in Resources */,
- 6A15821964A5EE5AEBB0C420 /* ClerkConfig.plist in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -527,8 +600,8 @@
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
+ 44FDF4571F4536E3215679E8 /* AccountConfig.plist in Resources */,
513F59BF65DED5379AB950A1 /* Assets.xcassets in Resources */,
- CA1174F732B066EAFA3D963C /* ClerkConfig.plist in Resources */,
C937F66F810AA238B73E8363 /* PrivacyInfo.xcprivacy in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
@@ -593,10 +666,12 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
+ CEB634F257363FE66E0BBCF1 /* AccessRequestView.swift in Sources */,
FF6CF0FBF496B5B50F09E063 /* AccountSession.swift in Sources */,
28DE92C4209739829F6AD1A1 /* AccountSwitcherView.swift in Sources */,
CC9F6FB8055C38D5D625F738 /* BotListView.swift in Sources */,
2F0A1C29DBBD1D700C10BE46 /* CodyncApp.swift in Sources */,
+ 4ACFCBCDB8253091EF9D8D1A /* ComputerStatus.swift in Sources */,
B75DD137E6F645F797B60B09 /* PairingView.swift in Sources */,
31A78A067C217F77FBDEDFD0 /* Push.swift in Sources */,
E430F9317B690366F62164DB /* RootView.swift in Sources */,
@@ -605,6 +680,14 @@
);
runOnlyForDeploymentPostprocessing = 0;
};
+ D14636C3DD3126603BE23791 /* Sources */ = {
+ isa = PBXSourcesBuildPhase;
+ buildActionMask = 2147483647;
+ files = (
+ 9D0736B9670D57132AFBB34E /* NotificationService.swift in Sources */,
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ };
FD97D0661DD7AA54EB7DE077 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
@@ -612,14 +695,22 @@
8AC8D90C21B92480E2809758 /* AccountSession.swift in Sources */,
03774684DC8344D81AFED53B /* ChatWindow.swift in Sources */,
8CD641A45F144BF41D703D2A /* CodyncMacApp.swift in Sources */,
+ 9593C1951D727D36D6B8C0E9 /* ComputerStatus.swift in Sources */,
+ 76E73EDD79B063940B5D8B8E /* ComputersView.swift in Sources */,
F0A26FABD15480810021C86A /* HostController.swift in Sources */,
2D724C1001CF872BAFCAE7EA /* IconButton.swift in Sources */,
+ 331338197BF906B069159B11 /* SSHTunnel.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
+ 0BA52D71EA0FB37D52E4AE22 /* PBXTargetDependency */ = {
+ isa = PBXTargetDependency;
+ target = C42E5E078332C6C2B35AF5FA /* NotificationService */;
+ targetProxy = DA04088A6786CD5F92C67AED /* PBXContainerItemProxy */;
+ };
403D98EE1C95EF3BA01D41CB /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = 907F1F4A709111FC7178EAE9 /* Screen */;
@@ -685,7 +776,7 @@
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 18.0;
MACOSX_DEPLOYMENT_TARGET = 14.0;
- MARKETING_VERSION = 2.1.0;
+ MARKETING_VERSION = 3.0.0;
MTL_ENABLE_DEBUG_INFO = NO;
MTL_FAST_MATH = YES;
PRODUCT_NAME = "$(TARGET_NAME)";
@@ -760,6 +851,26 @@
};
name = Debug;
};
+ 8B4776624C6CD584BCA689AF /* Debug */ = {
+ isa = XCBuildConfiguration;
+ buildSettings = {
+ CODE_SIGN_ENTITLEMENTS = apps/ios/NotificationService/NotificationService.entitlements;
+ GENERATE_INFOPLIST_FILE = YES;
+ INFOPLIST_FILE = apps/ios/NotificationService/Info.plist;
+ INFOPLIST_KEY_CFBundleDisplayName = Codync;
+ LD_RUNPATH_SEARCH_PATHS = (
+ "$(inherited)",
+ "@executable_path/Frameworks",
+ "@executable_path/../../Frameworks",
+ );
+ PRODUCT_BUNDLE_IDENTIFIER = com.pokai.Codync.ios.NotificationService;
+ PRODUCT_NAME = CodyncNotificationService;
+ SDKROOT = iphoneos;
+ SKIP_INSTALL = YES;
+ TARGETED_DEVICE_FAMILY = "1,2";
+ };
+ name = Debug;
+ };
8BF1ED628DCBF23F16CFD028 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
@@ -840,7 +951,7 @@
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 18.0;
MACOSX_DEPLOYMENT_TARGET = 14.0;
- MARKETING_VERSION = 2.1.0;
+ MARKETING_VERSION = 3.0.0;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES;
@@ -882,6 +993,26 @@
};
name = Debug;
};
+ D4128E0292901EF39924C449 /* Release */ = {
+ isa = XCBuildConfiguration;
+ buildSettings = {
+ CODE_SIGN_ENTITLEMENTS = apps/ios/NotificationService/NotificationService.entitlements;
+ GENERATE_INFOPLIST_FILE = YES;
+ INFOPLIST_FILE = apps/ios/NotificationService/Info.plist;
+ INFOPLIST_KEY_CFBundleDisplayName = Codync;
+ LD_RUNPATH_SEARCH_PATHS = (
+ "$(inherited)",
+ "@executable_path/Frameworks",
+ "@executable_path/../../Frameworks",
+ );
+ PRODUCT_BUNDLE_IDENTIFIER = com.pokai.Codync.ios.NotificationService;
+ PRODUCT_NAME = CodyncNotificationService;
+ SDKROOT = iphoneos;
+ SKIP_INSTALL = YES;
+ TARGETED_DEVICE_FAMILY = "1,2";
+ };
+ name = Release;
+ };
D8FAD997F1279E25370608C5 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
@@ -984,6 +1115,15 @@
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Debug;
};
+ A6955F60D2D95C77124AC81A /* Build configuration list for PBXNativeTarget "NotificationService" */ = {
+ isa = XCConfigurationList;
+ buildConfigurations = (
+ 8B4776624C6CD584BCA689AF /* Debug */,
+ D4128E0292901EF39924C449 /* Release */,
+ );
+ defaultConfigurationIsVisible = 0;
+ defaultConfigurationName = Debug;
+ };
EC3A304F5821443C1DD50876 /* Build configuration list for PBXNativeTarget "Screen" */ = {
isa = XCConfigurationList;
buildConfigurations = (
@@ -1044,6 +1184,10 @@
package = 979123F21565A4068586B502 /* XCRemoteSwiftPackageReference "WebRTC" */;
productName = WebRTC;
};
+ 50F314172CC2AD1C5CDC916A /* CodyncKit */ = {
+ isa = XCSwiftPackageProductDependency;
+ productName = CodyncKit;
+ };
59F5D19A417A7A50596902FA /* CodyncKit */ = {
isa = XCSwiftPackageProductDependency;
productName = CodyncKit;
diff --git a/apps/ios/App/CodyncApp.swift b/apps/ios/App/CodyncApp.swift
index 673b5c5b..3fea8103 100644
--- a/apps/ios/App/CodyncApp.swift
+++ b/apps/ios/App/CodyncApp.swift
@@ -9,59 +9,39 @@ import WidgetKit
struct CodyncApp: App {
@UIApplicationDelegateAdaptor(AppDelegate.self) private var delegate
@State private var app = AppStore.shared
- private var model: BotStore { app.model }
@Environment(\.scenePhase) private var scenePhase
- @State private var tab = AppTab.bots
var body: some Scene {
WindowGroup {
- RootView(tab: $tab)
+ RootView()
.id(app.contextID)
- .environment(model)
+ .environment(app)
+ .environment(app.accounts)
.environment(app.account)
.tint(Palette.accent)
.sheet(isPresented: Bindable(app.account).showSwitcher) {
- NavigationStack { AccountSwitcherView().environment(app.account).environment(model) }
+ NavigationStack { AccountSwitcherView() }
+ .environment(app)
+ .environment(app.accounts)
+ .environment(app.account)
}
.onChange(of: app.account.userID, initial: true) { _, userID in
app.switchAccount(to: userID)
- tab = .bots
- }
- .onOpenURL { url in
- if url.scheme == "com.pokai.Codync.ios" {
- Task { await app.account.handle(url) }
- } else if let p = Pairing(url: url) {
- model.pair(p)
- } else if url.host() == "bot" {
- guard model.storage.acceptsBotURL(url) else { return }
- model.selection = url.lastPathComponent
- } else if url.host() == "plugins" {
- model.selection = nil
- tab = .bots
- model.showPlugins = true
- } else if url.host() == "usage" {
- tab = .usage
- } else if url.host() == "computers" {
- model.selection = nil
- tab = .bots
- model.showProfile = true
- } else if url.host() == "screen" {
- model.screenRequest = ScreenRequest()
- }
}
+ .onOpenURL { url in app.open(url) }
.onChange(of: scenePhase, initial: true) { _, phase in
- model.setActive(phase == .active)
+ app.accounts.setActive(phase == .active)
}
#if DEBUG
.task {
// Simulator/UI-test pairing: SIMCTL_CHILD_CODYNC_PAIR_URL=codync://pair?...
if let s = ProcessInfo.processInfo.environment["CODYNC_PAIR_URL"], let p = Pairing(string: s) {
- model.pair(p)
+ _ = try? await app.pair(p)
}
- if ProcessInfo.processInfo.environment["CODYNC_OPEN_USAGE"] != nil { tab = .usage }
+ if ProcessInfo.processInfo.environment["CODYNC_OPEN_USAGE"] != nil { app.tab = .usage }
if ProcessInfo.processInfo.environment["CODYNC_OPEN_SCREEN"] != nil {
try? await Task.sleep(for: .seconds(2))
- model.screenRequest = ScreenRequest()
+ app.currentStore?.screenRequest = ScreenRequest()
}
}
#endif
@@ -69,56 +49,154 @@ struct CodyncApp: App {
}
}
-/// A new host mirror for each account prevents in-flight work from being
-/// applied to another user's screen or storage. Cloud ownership is separate.
+enum AppTab: Hashable { case bots, usage }
+
+/// One `AccountStore` per account context: switching accounts retires the old one so
+/// in-flight work can't land on another user's screen or storage.
@MainActor
@Observable
final class AppStore {
static let shared = AppStore()
- let account = AccountSession()
- private(set) var model: BotStore
+ let account: AccountSession
+ private(set) var accounts: AccountStore
+ /// The signed-in account's cloud; nil when signed out or the build has no cloud.
+ private(set) var cloud: CloudClient?
private(set) var contextID: String
+ var tab = AppTab.bots
+ var showComputers = false
+ /// The computer whose marketplace is open.
+ var marketplace: ComputerID?
private init() {
- let storage = SharedStore.Context(accountID: account.userID)
- SharedStore.activeAccountID = account.userID
+ let session = AccountSession()
+ let storage = SharedStore.Context(accountID: session.userID)
+ SharedStore.activeAccountID = session.userID
+ account = session
contextID = storage.id
- model = Self.makeStore(storage)
+ (accounts, cloud) = Self.makeAccounts(storage, session: session)
+ }
+
+ var storage: SharedStore.Context { accounts.storage }
+
+ /// The computer the Usage tab, widgets and "open screen" links act on: the last active one.
+ var currentStore: BotStore? {
+ accounts.storage.lastComputerId.flatMap(accounts.store(for:)) ?? accounts.computers.first.flatMap { accounts.store(for: $0.id) }
}
func switchAccount(to userID: String?) {
let storage = SharedStore.Context(accountID: userID)
guard storage.id != contextID else { return }
- model.retire()
+ accounts.retire()
PushRegistrar.shared.deactivate()
LiveActivities.shared.endAll()
SharedStore.activeAccountID = userID
storage.bots = []
- storage.usage = nil
contextID = storage.id
- model = Self.makeStore(storage)
+ tab = .bots
+ showComputers = false
+ marketplace = nil
+ (accounts, cloud) = Self.makeAccounts(storage, session: account)
BotsWidgetFeed.reset()
WidgetCenter.shared.reloadAllTimelines()
- model.setActive(true)
}
- private static func makeStore(_ storage: SharedStore.Context) -> BotStore {
- let store = BotStore(pairing: storage.pairing, clientKind: "ios", persistsPairing: true, storage: storage)
- store.onPaired = { PushRegistrar.shared.syncDevice(with: $0) }
- store.onBotUpdated = { [weak store] bot in
- guard let store else { return }
- LiveActivities.shared.update(bot: bot)
- BotsWidgetFeed.update(store.roster)
+ /// Signing out forgets this account on this iPhone: its device keys, computers and caches (spec §3.2).
+ func signOut() async {
+ guard let userID = account.userID else { return }
+ await account.signOut()
+ guard account.userID != userID, !account.accounts.contains(where: { $0.id == userID }) else { return }
+ // Retire its stores first: a retiring store saves its cache one last time.
+ switchAccount(to: account.userID)
+ SharedStore.Context(accountID: userID).erase()
+ }
+
+ func pair(_ pairing: Pairing) async throws -> Computer {
+ let computer = try await accounts.pair(pairing, deviceName: UIDevice.current.name, platform: "ios")
+ Task { _ = await PushRegistrar.shared.requestAuthorization() }
+ return computer
+ }
+
+ func open(_ url: URL) {
+ if url.scheme == "com.pokai.Codync.ios" {
+ Task { await account.handle(url) }
+ return
+ }
+ switch url.host() {
+ case "pair":
+ // Scanned with the Camera app: pair right away.
+ let accounts = accounts
+ Task {
+ do { _ = try await pair(try Pairing.parse(url)) } catch { accounts.lastError = error.localizedDescription }
+ }
+ case "bot":
+ guard let ref = storage.reference(from: url), accounts.store(for: ref.computerId) != nil else { return }
+ tab = .bots
+ accounts.selection = ref
+ case "plugins":
+ accounts.selection = nil
+ tab = .bots
+ marketplace = currentStore?.computer.id
+ case "usage":
+ tab = .usage
+ case "computers":
+ accounts.selection = nil
+ tab = .bots
+ showComputers = true
+ case "screen":
+ currentStore?.screenRequest = ScreenRequest()
+ default:
+ break
+ }
+ }
+
+ private static func makeAccounts(_ storage: SharedStore.Context, session: AccountSession) -> (AccountStore, CloudClient?) {
+ let identity = storage.accountID == nil ? nil : try? DeviceIdentity.load(context: storage)
+ let cloud = session.cloudClient(for: storage.accountID, identity: identity)
+ let accounts = AccountStore(storage: storage, clientKind: "ios", cloud: cloud)
+ accounts.onConnected = { store in
+ PushRegistrar.shared.syncDevice(with: store)
+ store.onUsageChanged = { _, _ in WidgetCenter.shared.reloadTimelines(ofKind: "CodyncUsage") }
}
- store.onSent = { [weak store] bot in
- guard let store else { return }
- LiveActivities.shared.start(for: bot, model: store)
+ accounts.onBotUpdated = { [weak accounts] ref, bot in
+ guard let accounts else { return }
+ LiveActivities.shared.update(ref, bot: bot)
+ BotsWidgetFeed.update(accounts.roster, storage: storage)
+ }
+ accounts.onSent = { [weak accounts] ref, bot in
+ guard let store = accounts?.store(for: ref.computerId) else { return }
+ LiveActivities.shared.start(ref, bot: bot, store: store)
+ }
+ if let cloud {
+ // Signed in: make this iPhone known to the account, then list its computers.
+ Task { [weak accounts] in
+ do {
+ try await cloud.registerDevice(name: UIDevice.current.name, platform: "ios")
+ } catch {
+ accounts?.lastError = error.localizedDescription
+ }
+ await accounts?.refreshCloud()
+ }
}
- store.onUsageChanged = { usage in
- storage.usage = usage
- WidgetCenter.shared.reloadAllTimelines()
+ return (accounts, cloud)
+ }
+
+ /// Takes back this iPhone's account access to a computer (its grant), and forgets the computer here.
+ /// Also the way out when an earlier install was approved but this one never checked the code.
+ func revokeAccess(_ id: ComputerID) async {
+ guard let cloud else { return }
+ let accounts = accounts
+ do {
+ let identity = try DeviceIdentity.load(context: accounts.storage)
+ if let device = try await cloud.devices().first(where: { $0.deviceKey == identity.publicKey }) {
+ for grant in try await cloud.grants(id) where grant.deviceId == device.deviceId {
+ try await cloud.revokeGrant(id, grantId: grant.grantId)
+ }
+ }
+ accounts.forget(id)
+ await accounts.refreshCloud()
+ } catch {
+ accounts.lastError = error.localizedDescription
}
- return store
}
}
@@ -138,15 +216,15 @@ final class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCent
}
nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {
- let botId = response.notification.request.content.userInfo["botId"] as? String
- if let botId {
- await MainActor.run {
- // Legacy push payloads have no account/computer identity. Never
- // route one into a signed-in account using only a naked bot ID.
- let app = AppStore.shared
- guard app.account.userID == nil, app.model.bots[botId] != nil else { return }
- app.model.selection = botId
- }
+ let info = response.notification.request.content.userInfo
+ guard let ctx = info["ctx"] as? String, let computerId = info["computerId"] as? String,
+ let botId = info["botId"] as? String else { return }
+ await MainActor.run {
+ // Only open it in the account it was sent to, on a computer that account still has.
+ let accounts = AppStore.shared.accounts
+ guard ctx == accounts.storage.id, accounts.store(for: computerId) != nil else { return }
+ AppStore.shared.tab = .bots
+ accounts.selection = BotReference(accountId: accounts.accountId, computerId: computerId, botId: botId)
}
}
@@ -164,9 +242,9 @@ enum BotsWidgetFeed {
static func reset() { shown = "" }
- static func update(_ roster: [Bot]) {
- SharedStore.bots = roster
- let signature = roster.map { "\($0.id):\($0.status):\($0.unread)" }.joined(separator: ",")
+ static func update(_ roster: [RosterItem], storage: SharedStore.Context) {
+ storage.bots = roster.map { BotSnapshot(computerId: $0.ref.computerId, bot: $0.bot) }
+ let signature = roster.map { "\($0.ref.computerId)/\($0.bot.id):\($0.bot.status):\($0.bot.unread)" }.joined(separator: ",")
guard signature != shown else { return }
shown = signature
WidgetCenter.shared.reloadTimelines(ofKind: "CodyncBots")
diff --git a/apps/ios/App/Push.swift b/apps/ios/App/Push.swift
index 74bcbdcc..0735c716 100644
--- a/apps/ios/App/Push.swift
+++ b/apps/ios/App/Push.swift
@@ -28,19 +28,22 @@ private func relayTicket(token: Data, kind: String) async throws -> String {
return try JSONDecoder().decode(Res.self, from: data).ticket
}
-/// Registers this phone for "needs you" / "done" alerts with the paired host.
+/// Registers this phone for "needs you" / "done" alerts with every computer it's connected to.
+/// Each ticket carries this context's push key so the computer can seal the alert text (spec §6.7).
@MainActor
final class PushRegistrar {
static let shared = PushRegistrar()
private var deviceToken: Data?
- private weak var model: BotStore?
- private var registrationTask: Task<Void, Never>?
+ private var stores: [ComputerID: WeakStore] = [:]
+ private var registrations: [ComputerID: Task<Void, Never>] = [:]
+
+ private struct WeakStore { weak var store: BotStore? }
func deactivate() {
- registrationTask?.cancel()
- registrationTask = nil
- model = nil
+ registrations.values.forEach { $0.cancel() }
+ registrations = [:]
+ stores = [:]
}
func requestAuthorization() async -> Bool {
@@ -51,12 +54,13 @@ final class PushRegistrar {
func didRegister(token: Data) {
deviceToken = token
- if let model { syncDevice(with: model) }
+ for entry in stores.values { if let store = entry.store { syncDevice(with: store) } }
}
- /// Sends our ticket to the host whenever we have both a token and a pairing.
- func syncDevice(with model: BotStore) {
- self.model = model
+ /// Sends our ticket to a computer whenever we have both a token and a connection to it.
+ func syncDevice(with store: BotStore) {
+ let id = store.computer.id
+ stores[id] = WeakStore(store: store)
guard let token = deviceToken else {
Task {
let settings = await UNUserNotificationCenter.current().notificationSettings()
@@ -64,17 +68,19 @@ final class PushRegistrar {
}
return
}
- registrationTask?.cancel()
- let pairing = model.storage.orderedPairing
- registrationTask = Task { [weak model] in
+ registrations[id]?.cancel()
+ let storage = store.storage
+ registrations[id] = Task { [weak store] in
do {
+ let identity = try DeviceIdentity.load(context: storage)
let ticket = try await relayTicket(token: token, kind: "alert")
try Task.checkCancellation()
- guard let model, self.model === model, let pairing,
- let client = await HostClient.resolve(pairing) else { return }
- try Task.checkCancellation()
- try await client.registerDevice(ticket: ticket, relay: SharedStore.relayURL, name: UIDevice.current.name)
- log.info("device registered with host")
+ guard let client = store?.client else { return }
+ try await client.registerDevice(ticket: ticket, relay: SharedStore.relayURL, name: UIDevice.current.name,
+ pushKey: identity.pushKey, ctx: storage.id)
+ log.info("device registered with a computer")
+ } catch is CancellationError {
+ return
} catch {
log.error("device registration failed: \(error.localizedDescription)")
}
@@ -100,13 +106,13 @@ final class LiveActivities {
}
}
- private nonisolated static func find(_ botId: String) -> Activity<BotActivityAttributes>? {
- Activity<BotActivityAttributes>.activities.first { $0.attributes.botId == botId }
+ private nonisolated static func find(_ ref: BotReference) -> Activity<BotActivityAttributes>? {
+ Activity<BotActivityAttributes>.activities.first { $0.attributes.botId == ref.botId && $0.attributes.computerId == ref.computerId }
}
- func start(for bot: Bot, model: BotStore) {
- guard ActivityAuthorizationInfo().areActivitiesEnabled, Self.find(bot.id) == nil, let client = model.client else { return }
- let attributes = BotActivityAttributes(bot: bot, link: model.storage.botURL(bot.id))
+ func start(_ ref: BotReference, bot: Bot, store: BotStore) {
+ guard ActivityAuthorizationInfo().areActivitiesEnabled, Self.find(ref) == nil, let client = store.client else { return }
+ let attributes = BotActivityAttributes(bot: bot, computerId: ref.computerId, link: store.storage.botURL(ref))
let id = UUID()
requests[id] = Task.detached { [weak self] in
await Self.request(attributes: attributes, client: client)
@@ -117,7 +123,8 @@ final class LiveActivities {
private func finishedRequest(_ id: UUID) { requests[id] = nil }
private nonisolated static func request(attributes: BotActivityAttributes, client: HostClient) async {
- let state = BotActivityAttributes.ContentState(status: "working", activity: "Starting…", startedAt: .now)
+ // Status only: pushes never carry free text, so local updates don't either.
+ let state = BotActivityAttributes.ContentState(status: "working", activity: "", startedAt: .now)
do {
try Task.checkCancellation()
let activity = try Activity.request(attributes: attributes, content: .init(state: state, staleDate: nil), pushType: .token)
@@ -133,20 +140,20 @@ final class LiveActivities {
}
}
- /// Local updates while the app is open; the host pushes them otherwise.
- func update(bot: Bot) {
- guard Self.find(bot.id) != nil else { return }
+ /// Local updates while the app is open; the computer pushes them otherwise.
+ func update(_ ref: BotReference, bot: Bot) {
+ guard Self.find(ref) != nil else { return }
let state = BotActivityAttributes.ContentState(
status: bot.status,
- activity: bot.activity,
+ activity: "",
startedAt: bot.startedAt.map(Date.init(milliseconds:))
)
- let botId = bot.id, working = bot.isWorking
- Task.detached { await Self.apply(botId: botId, state: state, end: !working) }
+ let working = bot.isWorking
+ Task.detached { await Self.apply(ref, state: state, end: !working) }
}
- private nonisolated static func apply(botId: String, state: BotActivityAttributes.ContentState, end: Bool) async {
- guard let activity = find(botId) else { return }
+ private nonisolated static func apply(_ ref: BotReference, state: BotActivityAttributes.ContentState, end: Bool) async {
+ guard let activity = find(ref) else { return }
if end {
await activity.end(.init(state: state, staleDate: nil), dismissalPolicy: .after(.now + 60))
} else {
diff --git a/apps/ios/NotificationService/Info.plist b/apps/ios/NotificationService/Info.plist
new file mode 100644
index 00000000..86cc7405
--- /dev/null
+++ b/apps/ios/NotificationService/Info.plist
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>CodyncKeychainGroup</key>
+ <string>$(AppIdentifierPrefix)com.pokai.Codync</string>
+ <key>NSExtension</key>
+ <dict>
+ <key>NSExtensionPointIdentifier</key>
+ <string>com.apple.usernotifications.service</string>
+ <key>NSExtensionPrincipalClass</key>
+ <string>$(PRODUCT_MODULE_NAME).NotificationService</string>
+ </dict>
+</dict>
+</plist>
diff --git a/apps/ios/NotificationService/NotificationService.entitlements b/apps/ios/NotificationService/NotificationService.entitlements
new file mode 100644
index 00000000..c5f86e3a
--- /dev/null
+++ b/apps/ios/NotificationService/NotificationService.entitlements
@@ -0,0 +1,14 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>com.apple.security.application-groups</key>
+ <array>
+ <string>group.com.pokai.Codync</string>
+ </array>
+ <key>keychain-access-groups</key>
+ <array>
+ <string>$(AppIdentifierPrefix)com.pokai.Codync</string>
+ </array>
+</dict>
+</plist>
diff --git a/apps/ios/NotificationService/NotificationService.swift b/apps/ios/NotificationService/NotificationService.swift
new file mode 100644
index 00000000..ba2436f6
--- /dev/null
+++ b/apps/ios/NotificationService/NotificationService.swift
@@ -0,0 +1,21 @@
+import CodyncKit
+import UserNotifications
+
+/// APNs and the push relay only carry "Needs you" / "Done"; the real title and text arrive
+/// sealed to this account's push key (spec §6.7). Opening them is local work only: no network.
+final class NotificationService: UNNotificationServiceExtension {
+ override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
+ let info = request.content.userInfo
+ guard let content = request.content.mutableCopy() as? UNMutableNotificationContent,
+ let sealed = info["sealed"] as? String,
+ let computerId = info["computerId"] as? String,
+ let ctx = info["ctx"] as? String,
+ let alert = DeviceIdentity.openPush(sealed: sealed, computerId: computerId, contextID: ctx) else {
+ contentHandler(request.content)
+ return
+ }
+ content.title = alert.title
+ content.body = alert.body
+ contentHandler(content)
+ }
+}
diff --git a/apps/ios/Resources/ClerkConfig.plist b/apps/ios/Resources/AccountConfig.plist
similarity index 68%
rename from apps/ios/Resources/ClerkConfig.plist
rename to apps/ios/Resources/AccountConfig.plist
index 400a55f7..54f36659 100644
--- a/apps/ios/Resources/ClerkConfig.plist
+++ b/apps/ios/Resources/AccountConfig.plist
@@ -2,7 +2,9 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
- <key>publishableKey</key>
+ <key>clerkPublishableKey</key>
<string>pk_test_c3VubnktbW9sbHVzay04NjUxLmNsZXJrLmFjY291bnRzLmRldiQ</string>
+ <key>cloudURL</key>
+ <string>https://codync-cloud-staging.kevin2005ha.workers.dev</string>
</dict>
</plist>
diff --git a/apps/ios/Resources/Info.plist b/apps/ios/Resources/Info.plist
index 7beeeadb..64d4c0a1 100644
--- a/apps/ios/Resources/Info.plist
+++ b/apps/ios/Resources/Info.plist
@@ -2,6 +2,8 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
+ <key>CodyncKeychainGroup</key>
+ <string>$(AppIdentifierPrefix)com.pokai.Codync</string>
<key>CFBundleURLTypes</key>
<array>
<dict>
diff --git a/apps/ios/Resources/iOS.entitlements b/apps/ios/Resources/iOS.entitlements
index 0a770bc1..17fa6661 100644
--- a/apps/ios/Resources/iOS.entitlements
+++ b/apps/ios/Resources/iOS.entitlements
@@ -8,5 +8,9 @@
<array>
<string>group.com.pokai.Codync</string>
</array>
+ <key>keychain-access-groups</key>
+ <array>
+ <string>$(AppIdentifierPrefix)com.pokai.Codync</string>
+ </array>
</dict>
</plist>
diff --git a/apps/ios/Views/AccessRequestView.swift b/apps/ios/Views/AccessRequestView.swift
new file mode 100644
index 00000000..8b346c47
--- /dev/null
+++ b/apps/ios/Views/AccessRequestView.swift
@@ -0,0 +1,116 @@
+import CodyncKit
+import CodyncUI
+import SwiftUI
+
+/// Asking a computer in the account for access (spec §4.2 B): once both sides committed,
+/// the same 6-digit code shows here and on the computer. The user approves there only if they match.
+struct AccessRequestView: View {
+ let computer: CloudComputer
+ @Environment(AccountStore.self) private var accounts
+ @Environment(\.dismiss) private var dismiss
+ @State private var error: String?
+ /// A code was shown: when it goes away without an approval, the request is over (denied or expired).
+ @State private var sawTicket: Bool
+
+ init(computer: CloudComputer, pending: Bool) {
+ self.computer = computer
+ _sawTicket = State(initialValue: pending)
+ }
+
+ private var ticket: AccessTicket? { accounts.pendingAccess[computer.computerId] }
+ private var approved: Bool { accounts.store(for: computer.computerId) != nil }
+
+ var body: some View {
+ VStack(spacing: 24) {
+ ComputerBadge(Computer(id: computer.computerId, name: computer.name, signKey: computer.signKey, device: computer.device), size: 64)
+ .padding(.top, 32)
+
+ if approved {
+ Label("\(computer.name) approved this iPhone", systemImage: "checkmark.circle.fill")
+ .font(.headline)
+ .foregroundStyle(Palette.added)
+ } else if let ticket {
+ VStack(spacing: 10) {
+ Text("Check the code on \(computer.name)")
+ .font(.headline)
+ .foregroundStyle(Palette.text)
+ Text(spaced(ticket.code))
+ .font(.system(size: 52, weight: .semibold, design: .monospaced))
+ .foregroundStyle(Palette.text)
+ .textSelection(.enabled)
+ .accessibilityLabel("Code \(ticket.code.map(String.init).joined(separator: " "))")
+ Text("Approve only if the computer shows exactly this code. If it doesn't, deny it there: someone may be trying to get in.")
+ .font(.subheadline)
+ .foregroundStyle(Palette.secondary)
+ .multilineTextAlignment(.center)
+ }
+ HStack(spacing: 8) {
+ ProgressView()
+ Text("Waiting for approval…").foregroundStyle(Palette.secondary)
+ }
+ .font(.subheadline)
+ } else if let error {
+ Text(error)
+ .foregroundStyle(Palette.danger)
+ .multilineTextAlignment(.center)
+ Button("Try again") { self.error = nil }
+ .buttonStyle(.bordered)
+ } else if sawTicket {
+ Text(accounts.lastError ?? "\(computer.name) didn't approve this request.")
+ .foregroundStyle(Palette.secondary)
+ .multilineTextAlignment(.center)
+ Button("Ask again") {
+ accounts.lastError = nil
+ sawTicket = false
+ }
+ .buttonStyle(.bordered)
+ } else {
+ VStack(spacing: 10) {
+ ProgressView()
+ Text(computer.isOnline ? "Asking \(computer.name)…" : "\(computer.name) is offline. Turn it on to continue.")
+ .font(.subheadline)
+ .foregroundStyle(Palette.secondary)
+ .multilineTextAlignment(.center)
+ }
+ .task { await request() }
+ }
+ Spacer()
+ }
+ .padding(24)
+ .frame(maxWidth: .infinity)
+ .background(Palette.background)
+ .navigationTitle("Access")
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar {
+ ToolbarItem(placement: .cancellationAction) {
+ // Closing keeps waiting in the background; the computer shows up once approved.
+ Button("Close", systemImage: "xmark") { dismiss() }.labelStyle(.iconOnly)
+ }
+ }
+ .onChange(of: ticket?.requestId) { _, id in if id != nil { sawTicket = true } }
+ .onChange(of: approved) { _, done in
+ guard done else { return }
+ Task {
+ try? await Task.sleep(for: .seconds(1))
+ dismiss()
+ }
+ }
+ }
+
+ /// Runs until the computer answered with its nonce; closing the sheet cancels it.
+ private func request() async {
+ do {
+ _ = try await accounts.requestAccess(computer.computerId)
+ } catch is CancellationError {
+ return
+ } catch {
+ guard !Task.isCancelled else { return }
+ self.error = error.localizedDescription
+ }
+ }
+
+ private func spaced(_ code: String) -> String {
+ guard code.count == 6 else { return code }
+ return "\(code.prefix(3)) \(code.suffix(3))"
+ }
+}
diff --git a/apps/ios/Views/AccountSwitcherView.swift b/apps/ios/Views/AccountSwitcherView.swift
index a91ff452..73f1e4a6 100644
--- a/apps/ios/Views/AccountSwitcherView.swift
+++ b/apps/ios/Views/AccountSwitcherView.swift
@@ -20,6 +20,7 @@ struct AccountSwitcherButton: View {
}
struct AccountSwitcherView: View {
+ @Environment(AppStore.self) private var app
@Environment(AccountSession.self) private var account
@Environment(\.dismiss) private var dismiss
@@ -66,25 +67,24 @@ struct AccountSwitcherView: View {
Label("Computers & settings", systemImage: "desktopcomputer")
}
} footer: {
- Text("Computer connections are saved separately for each account on this iPhone. Pair a computer to see its bots.")
+ Text("Computers are kept separately for each account on this iPhone. Signed in, you also see the computers added to your account.")
}
if account.isSignedIn {
Section {
Button("Sign out of this account", role: .destructive) {
- Task { await account.signOut() }
+ Task { await app.signOut() }
}
.disabled(account.isBusy)
} footer: {
- if !account.supportsMultipleAccounts {
- Text("Sign out to use a different Google account.")
- }
+ Text("Signing out removes this account's computers and keys from this iPhone."
+ + (account.supportsMultipleAccounts ? "" : " Sign out to use a different Google account."))
}
}
if !account.isConfigured {
Section {
- Text("Account sign-in isn't configured in this build. Local pairing is available.")
+ Text("Account sign-in isn't configured in this build. Pairing with a code works without it.")
.foregroundStyle(Palette.secondary)
}
}
diff --git a/apps/ios/Views/BotListView.swift b/apps/ios/Views/BotListView.swift
index 172ed29e..eeb44893 100644
--- a/apps/ios/Views/BotListView.swift
+++ b/apps/ios/Views/BotListView.swift
@@ -2,114 +2,214 @@ import CodyncKit
import CodyncUI
import SwiftUI
-/// The roster: every bot is a person you can message (Grok Bot sidebar, phone-sized).
+/// The roster: every bot on every computer is a person you can message (Grok Bot sidebar, phone-sized).
struct BotListView: View {
- @Environment(BotStore.self) private var model
- @State private var editing: EditorRequest?
- @State private var confirmDelete: Bot?
+ @Environment(AppStore.self) private var app
+ @Environment(AccountStore.self) private var accounts
+ @State private var editing: EditTarget?
+ @State private var pickingComputer = false
+ @State private var confirmDelete: RosterItem?
+
+ /// Computers that can take a new bot right now.
+ private var onlineStores: [BotStore] {
+ accounts.computers.compactMap { accounts.store(for: $0.id) }.filter { $0.connection == .online }
+ }
var body: some View {
- let roster = model.roster
+ let roster = accounts.roster
List {
- Section {
- ConnectionBanner()
+ // One banner per computer that isn't reachable; the others keep working.
+ ForEach(accounts.computers) { computer in
+ if let store = accounts.store(for: computer.id), store.connection != .online {
+ ConnectionBanner()
+ .environment(store)
+ .listRowSeparator(.hidden)
+ .listRowBackground(Color.clear)
+ .listRowInsets(EdgeInsets(top: 4, leading: 16, bottom: 4, trailing: 16))
+ }
}
- .listRowSeparator(.hidden)
- .listRowBackground(Color.clear)
- .listRowInsets(EdgeInsets(top: 4, leading: 16, bottom: 4, trailing: 16))
if roster.isEmpty {
- EmptyRoster { editing = EditorRequest(BotDraft()) }
+ EmptyRoster(canCreate: !onlineStores.isEmpty, hasComputer: !accounts.computers.isEmpty,
+ create: newBot, showComputers: { app.showComputers = true })
.listRowSeparator(.hidden)
.listRowBackground(Color.clear)
}
- ForEach(roster) { bot in
- // A plain button instead of a NavigationLink: same push, no chevron.
- Button { model.selection = bot.id } label: {
- BotRow(bot: bot)
- }
- .buttonStyle(.plain)
- .listRowBackground(Palette.background)
- .listRowSeparator(.hidden)
- .listRowInsets(EdgeInsets(top: 0, leading: 16, bottom: 0, trailing: 16))
- .swipeActions(edge: .leading) {
- Button(bot.pinned ? "Unpin" : "Pin", systemImage: bot.pinned ? "pin.slash" : "pin") {
- model.setPinned(bot, !bot.pinned)
- }
- .tint(Palette.accentDim)
- }
- .swipeActions(edge: .trailing) {
- Button("Delete", systemImage: "trash", role: .destructive) { confirmDelete = bot }
- Button("Hide", systemImage: "eye.slash") { model.setHidden(bot, true) }
- }
- .contextMenu {
- Button(bot.pinned ? "Unpin" : "Pin", systemImage: "pin") { model.setPinned(bot, !bot.pinned) }
- Button("Edit profile", systemImage: "pencil") { editing = EditorRequest(BotDraft(bot)) }
- Button("Mark as read", systemImage: "checkmark.message") { model.markRead(bot.id) }
- Button("Hide from list", systemImage: "eye.slash") { model.setHidden(bot, true) }
- Button("Delete", systemImage: "trash", role: .destructive) { confirmDelete = bot }
+ ForEach(roster) { item in
+ if let store = accounts.store(for: item.ref.computerId) {
+ row(item, store: store)
}
}
}
.listStyle(.plain)
.scrollContentBackground(.hidden)
.background(Palette.background)
- .navigationTitle(model.hostName)
+ .navigationTitle("Bots")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .topBarLeading) {
AccountSwitcherButton()
}
- // Grok-style bare top bar: no visible title, just the two buttons.
+ // Grok-style bare top bar: no visible title, just the buttons.
ToolbarItem(placement: .principal) { Color.clear.frame(width: 1, height: 1) }
- if model.screen != nil {
- ToolbarItem(placement: .topBarTrailing) {
- Button("Screen", systemImage: "display") { model.screenRequest = ScreenRequest() }
- .disabled(model.connection != .online)
- }
+ ToolbarItem(placement: .topBarTrailing) {
+ Button("Computers", systemImage: "desktopcomputer") { app.showComputers = true }
}
ToolbarItem(placement: .topBarTrailing) {
- Button("New bot", systemImage: "plus") {
- editing = EditorRequest(BotDraft())
- }
- .disabled(model.connection != .online)
+ Button("New bot", systemImage: "plus", action: newBot)
+ .disabled(onlineStores.isEmpty)
}
}
- .refreshable { model.restartStream() }
- .sheet(item: $editing) { request in
- NavigationStack { BotEditorView(draft: request.draft) }
+ .refreshable {
+ for computer in accounts.computers { accounts.store(for: computer.id)?.restartStream() }
+ await accounts.refreshCloud()
+ }
+ .sheet(item: $editing) { target in
+ if let store = accounts.store(for: target.computerId) {
+ NavigationStack { BotEditorView(draft: target.draft) }
+ .environment(store)
+ .onChange(of: store.selection) { _, botId in
+ // A new bot opens its chat, on the computer it was created on.
+ guard let botId else { return }
+ store.selection = nil
+ accounts.selection = BotReference(accountId: accounts.accountId, computerId: target.computerId, botId: botId)
+ }
+ }
}
- .sheet(isPresented: Bindable(model).showPlugins) {
+ .sheet(isPresented: $pickingComputer) {
NavigationStack {
- MarketplaceView { model.showPlugins = false }
+ ComputerPicker(stores: onlineStores) { store in
+ pickingComputer = false
+ editing = EditTarget(computerId: store.computer.id, draft: BotDraft())
+ }
}
+ .presentationDetents([.medium])
}
- .sheet(isPresented: Bindable(model).showProfile) {
- NavigationStack { SettingsView() }
+ .confirmationDialog("Delete \(confirmDelete?.bot.name ?? "bot")?",
+ isPresented: Binding(get: { confirmDelete != nil }, set: { if !$0 { confirmDelete = nil } }),
+ titleVisibility: .visible) {
+ Button("Delete bot and its conversation", role: .destructive) {
+ if let item = confirmDelete { accounts.store(for: item.ref.computerId)?.delete(item.bot) }
+ }
+ } message: {
+ Text("Files it changed on your computer stay as they are.")
+ }
+ }
+
+ private func row(_ item: RosterItem, store: BotStore) -> some View {
+ let bot = item.bot
+ // A plain button instead of a NavigationLink: same push, no chevron.
+ return Button { accounts.selection = item.ref } label: {
+ VStack(alignment: .leading, spacing: 0) {
+ BotRow(bot: bot)
+ ComputerCaption(store: store)
+ .padding(.leading, 58)
+ .padding(.bottom, 6)
+ .offset(y: -6)
+ }
+ .environment(store)
+ }
+ .buttonStyle(.plain)
+ .listRowBackground(Palette.background)
+ .listRowSeparator(.hidden)
+ .listRowInsets(EdgeInsets(top: 0, leading: 16, bottom: 0, trailing: 16))
+ .swipeActions(edge: .leading) {
+ Button(bot.pinned ? "Unpin" : "Pin", systemImage: bot.pinned ? "pin.slash" : "pin") {
+ store.setPinned(bot, !bot.pinned)
+ }
+ .tint(Palette.accentDim)
+ }
+ .swipeActions(edge: .trailing) {
+ Button("Delete", systemImage: "trash", role: .destructive) { confirmDelete = item }
+ Button("Hide", systemImage: "eye.slash") { store.setHidden(bot, true) }
+ }
+ .contextMenu {
+ Button(bot.pinned ? "Unpin" : "Pin", systemImage: "pin") { store.setPinned(bot, !bot.pinned) }
+ Button("Edit profile", systemImage: "pencil") { editing = EditTarget(computerId: item.ref.computerId, draft: BotDraft(bot)) }
+ Button("Mark as read", systemImage: "checkmark.message") { store.markRead(bot.id) }
+ Button("Hide from list", systemImage: "eye.slash") { store.setHidden(bot, true) }
+ Button("Delete", systemImage: "trash", role: .destructive) { confirmDelete = item }
+ }
+ }
+
+ /// A new bot lives on one computer: pick it first when there's a choice.
+ private func newBot() {
+ let stores = onlineStores
+ if stores.count == 1, let store = stores.first {
+ editing = EditTarget(computerId: store.computer.id, draft: BotDraft())
+ } else if stores.count > 1 {
+ pickingComputer = true
+ }
+ }
+}
+
+private struct EditTarget: Identifiable {
+ let id = UUID()
+ let computerId: ComputerID
+ let draft: BotDraft
+}
+
+/// "Which computer should it run on?" — only computers that are online.
+private struct ComputerPicker: View {
+ let stores: [BotStore]
+ let pick: (BotStore) -> Void
+ @Environment(\.dismiss) private var dismiss
+
+ var body: some View {
+ List(stores, id: \.computer.id) { store in
+ Button { pick(store) } label: {
+ HStack(spacing: 12) {
+ ComputerBadge(store.computer, size: 36)
+ VStack(alignment: .leading, spacing: 2) {
+ Text(store.hostName).font(.body.weight(.semibold)).foregroundStyle(Palette.text)
+ Text("\(store.roster.count) bot\(store.roster.count == 1 ? "" : "s")")
+ .font(.subheadline).foregroundStyle(Palette.secondary)
+ }
+ Spacer()
+ RouteIcon(route: store.hostRoute).foregroundStyle(Palette.tertiary)
+ }
+ }
+ }
+ .navigationTitle("Run it on")
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar {
+ ToolbarItem(placement: .cancellationAction) {
+ Button("Close", systemImage: "xmark") { dismiss() }.labelStyle(.iconOnly)
+ }
}
- .deleteBotConfirmation($confirmDelete)
}
}
private struct EmptyRoster: View {
+ let canCreate: Bool
+ let hasComputer: Bool
let create: () -> Void
+ let showComputers: () -> Void
var body: some View {
VStack(spacing: 14) {
CharacterAvatar(shape: "cloud", color: "green", size: 72)
Text("No bots yet").font(.title3.weight(.semibold)).foregroundStyle(Palette.text)
- Text("Create a bot for each kind of work — a reviewer, a fixer, a docs writer — and point it at a project.")
+ Text(hasComputer
+ ? "Create a bot for each kind of work — a reviewer, a fixer, a docs writer — and point it at a project."
+ : "Ask one of your account's computers for access, or pair one with its code.")
.font(.subheadline)
.foregroundStyle(Palette.secondary)
.multilineTextAlignment(.center)
- Button("Create your first bot", action: create)
- .buttonStyle(.borderedProminent)
- .tint(Palette.accentFill)
- .foregroundStyle(Palette.onAccent)
+ if canCreate {
+ Button("Create your first bot", action: create)
+ .buttonStyle(.borderedProminent)
+ .tint(Palette.accentFill)
+ .foregroundStyle(Palette.onAccent)
+ } else if !hasComputer {
+ Button("Computers", action: showComputers)
+ .buttonStyle(.borderedProminent)
+ .tint(Palette.accentFill)
+ .foregroundStyle(Palette.onAccent)
+ }
}
.frame(maxWidth: .infinity)
.padding(.vertical, 40)
}
}
-
diff --git a/apps/ios/Views/PairingView.swift b/apps/ios/Views/PairingView.swift
index 102bcf51..c05c8494 100644
--- a/apps/ios/Views/PairingView.swift
+++ b/apps/ios/Views/PairingView.swift
@@ -5,10 +5,11 @@ import VisionKit
/// First run: explain the model, then pair with a computer running codync-host.
struct PairingView: View {
- /// Set when adding another computer from the profile sheet; shows a close button.
+ /// Set when adding another computer from the computers sheet; shows a close button.
var onDone: (() -> Void)?
- @Environment(BotStore.self) private var model
+ @Environment(AppStore.self) private var app
@State private var scanning = false
+ @State private var pairing = false
@State private var pasted = ""
@State private var error: String?
@State private var tailscaleOn = Tailscale.isConnected
@@ -46,14 +47,20 @@ struct PairingView: View {
Button {
scanning = true
} label: {
- Label("Scan pairing code", systemImage: "qrcode.viewfinder")
- .font(.headline)
- .frame(maxWidth: .infinity, minHeight: 50)
+ Group {
+ if pairing {
+ ProgressView().tint(Palette.onAccent)
+ } else {
+ Label("Scan pairing code", systemImage: "qrcode.viewfinder")
+ }
+ }
+ .font(.headline)
+ .frame(maxWidth: .infinity, minHeight: 50)
}
.buttonStyle(.borderedProminent)
.tint(Palette.accentFill)
.foregroundStyle(Palette.onAccent)
- .disabled(!DataScannerViewController.isSupported)
+ .disabled(!DataScannerViewController.isSupported || pairing)
HStack {
TextField("…or paste a codync://pair link", text: $pasted)
@@ -63,7 +70,7 @@ struct PairingView: View {
Button("Pair", systemImage: "arrow.right.circle.fill") { pair(pasted) }
.labelStyle(.iconOnly)
.font(.title3)
- .disabled(pasted.isEmpty)
+ .disabled(pasted.isEmpty || pairing)
}
.padding(12)
.background(Palette.surface, in: RoundedRectangle(cornerRadius: 12))
@@ -74,7 +81,7 @@ struct PairingView: View {
}
}
- Text("Pair this computer with the account currently selected on this iPhone. Your phone connects over Tailscale or local Wi-Fi; your code and chats stay on the computer.")
+ Text("No Tailscale or open ports needed: on the same Wi-Fi your iPhone talks to the computer directly, anywhere else through Codync's relay. Either way it's end-to-end encrypted, and your code and chats stay on the computer.")
.font(.footnote)
.foregroundStyle(Palette.tertiary)
}
@@ -104,14 +111,25 @@ struct PairingView: View {
}
private func pair(_ text: String) {
- guard let p = Pairing(string: text) else {
- error = "That isn't a Codync pairing code."
+ let p: Pairing
+ do {
+ p = try Pairing.parse(text.trimmingCharacters(in: .whitespacesAndNewlines))
+ } catch {
+ self.error = error.localizedDescription
return
}
error = nil
- model.pair(p)
- onDone?()
- Task { _ = await PushRegistrar.shared.requestAuthorization() }
+ pairing = true
+ Task {
+ defer { pairing = false }
+ do {
+ _ = try await app.pair(p)
+ pasted = ""
+ onDone?()
+ } catch {
+ self.error = error.localizedDescription
+ }
+ }
}
}
@@ -147,20 +165,20 @@ private struct Step: View {
}
}
-/// Optional step: Tailscale is what lets the phone reach the computer off the home Wi-Fi.
+/// Optional: Tailscale is an alternative way in for people who already use it; the relay doesn't need it.
private struct TailscaleStep: View {
let connected: Bool
var body: some View {
HStack(alignment: .top, spacing: 12) {
- Text("04")
+ Text("")
.font(.system(size: 12, weight: .medium, design: .monospaced))
.frame(width: 24, alignment: .leading)
.padding(.top, 2)
.foregroundStyle(Palette.tertiary)
VStack(alignment: .leading, spacing: 6) {
- Text("Away from home (optional)").font(.headline).foregroundStyle(Palette.text)
- Text("Without it, Codync works on the same Wi-Fi as your computer. Install Tailscale on this iPhone and on the computer, and sign in to both with the same account.")
+ Text("Already use Tailscale? (optional)").font(.headline).foregroundStyle(Palette.text)
+ Text("Codync works away from home without it. If Tailscale runs on this iPhone and the computer, Codync connects over it directly instead of the relay.")
.font(.subheadline)
.foregroundStyle(Palette.secondary)
if connected {
diff --git a/apps/ios/Views/RootView.swift b/apps/ios/Views/RootView.swift
index 84574716..dc241737 100644
--- a/apps/ios/Views/RootView.swift
+++ b/apps/ios/Views/RootView.swift
@@ -1,21 +1,20 @@
import CodyncKit
import CodyncUI
import SwiftUI
-
-enum AppTab: Hashable { case bots, usage }
+import WidgetKit
struct RootView: View {
- @Environment(BotStore.self) private var model
- @Binding var tab: AppTab
+ @Environment(AppStore.self) private var app
+ @Environment(AccountStore.self) private var accounts
/// The open bot, as a NavigationStack path.
- private var path: Binding<[String]> {
- Binding(get: { model.selection.map { [$0] } ?? [] }, set: { model.selection = $0.last })
+ private var path: Binding<[BotReference]> {
+ Binding(get: { accounts.selection.map { [$0] } ?? [] }, set: { accounts.selection = $0.last })
}
var body: some View {
Group {
- if model.pairing == nil {
+ if accounts.computers.isEmpty && accounts.cloudComputers.isEmpty {
NavigationStack {
PairingView()
.toolbar {
@@ -23,29 +22,130 @@ struct RootView: View {
}
}
} else {
- TabView(selection: $tab) {
+ TabView(selection: Bindable(app).tab) {
Tab("Bots", systemImage: "bubble.left.and.bubble.right.fill", value: .bots) {
NavigationStack(path: path) {
BotListView()
- .navigationDestination(for: String.self) { botId in
- ThreadView(botId: botId)
+ .navigationDestination(for: BotReference.self) { ref in
+ ChatScreen(ref: ref)
.toolbar(.hidden, for: .tabBar)
}
}
}
Tab("Usage", systemImage: "chart.bar.fill", value: .usage) {
- NavigationStack { UsageView() }
+ NavigationStack { UsageTab() }
}
}
// Opening a bot (notification, widget, link) always lands on the Bots tab.
- .onChange(of: model.selection) { _, id in if id != nil { tab = .bots } }
+ .onChange(of: accounts.selection) { _, ref in if ref != nil { app.tab = .bots } }
}
}
.background(Palette.background)
- .storeErrorAlert(model)
- .fullScreenCover(item: Bindable(model).screenRequest) { request in
- ScreenView(watching: request.watching)
- .environment(model)
+ .alert("Something went wrong", isPresented: errorShown) {
+ Button("OK", role: .cancel) {}
+ } message: {
+ Text(errorMessage ?? "")
+ }
+ .fullScreenCover(item: screenTarget) { target in
+ if let store = accounts.store(for: target.computerId) {
+ ScreenView(watching: target.request.watching)
+ .environment(store)
+ }
+ }
+ .sheet(isPresented: Bindable(app).showComputers) {
+ NavigationStack { SettingsView() }
+ }
+ .sheet(isPresented: Binding(get: { app.marketplace != nil }, set: { if !$0 { app.marketplace = nil } })) {
+ if let store = app.marketplace.flatMap(accounts.store(for:)) {
+ NavigationStack {
+ MarketplaceView { app.marketplace = nil }
+ }
+ .environment(store)
+ }
+ }
+ }
+
+ // MARK: one place for every computer's errors and screen requests
+
+ private var errorMessage: String? {
+ accounts.lastError ?? accounts.computers.lazy.compactMap { accounts.store(for: $0.id)?.lastError }.first
+ }
+
+ private var errorShown: Binding<Bool> {
+ Binding(get: { errorMessage != nil }, set: { shown in
+ guard !shown else { return }
+ accounts.lastError = nil
+ for computer in accounts.computers { accounts.store(for: computer.id)?.lastError = nil }
+ })
+ }
+
+ private struct ScreenTarget: Identifiable {
+ let computerId: ComputerID
+ let request: ScreenRequest
+ var id: String { "\(computerId)/\(request.id)" }
+ }
+
+ /// Any computer's "open the screen" request (thread toolbar, computers list, `codync://screen`).
+ private var screenTarget: Binding<ScreenTarget?> {
+ Binding(get: {
+ accounts.computers.lazy.compactMap { c in
+ accounts.store(for: c.id)?.screenRequest.map { ScreenTarget(computerId: c.id, request: $0) }
+ }.first
+ }, set: { target in
+ guard target == nil else { return }
+ for computer in accounts.computers { accounts.store(for: computer.id)?.screenRequest = nil }
+ })
+ }
+}
+
+/// A conversation, talking to the computer the bot lives on.
+private struct ChatScreen: View {
+ let ref: BotReference
+ @Environment(AccountStore.self) private var accounts
+
+ var body: some View {
+ if let store = accounts.store(for: ref.computerId) {
+ ThreadView(botId: ref.botId)
+ .environment(store)
+ } else {
+ ContentUnavailableView("This computer was removed", systemImage: "desktopcomputer.trianglebadge.exclamationmark")
+ }
+ }
+}
+
+/// Usage for one computer at a time: the last active one, which the Usage widget shows too.
+private struct UsageTab: View {
+ @Environment(AppStore.self) private var app
+ @Environment(AccountStore.self) private var accounts
+ /// Picked here; also becomes the computer the Usage widget shows.
+ @State private var picked: ComputerID?
+
+ var body: some View {
+ if let store = picked.flatMap(accounts.store(for:)) ?? app.currentStore {
+ UsageView()
+ .environment(store)
+ .toolbar {
+ if accounts.computers.count > 1 {
+ ToolbarItem(placement: .topBarTrailing) {
+ Menu {
+ Picker("Computer", selection: Binding(get: { store.computer.id }, set: { id in
+ picked = id
+ accounts.storage.lastComputerId = id
+ WidgetCenter.shared.reloadTimelines(ofKind: "CodyncUsage")
+ })) {
+ ForEach(accounts.computers) { Text($0.name).tag($0.id) }
+ }
+ } label: {
+ ComputerBadge(store.computer, size: 28)
+ }
+ .accessibilityLabel("Computer: \(store.computer.name)")
+ }
+ }
+ }
+ .id(store.computer.id)
+ } else {
+ ContentUnavailableView("No computer yet", systemImage: "chart.bar",
+ description: Text("Usage shows up once a computer is connected."))
}
}
}
diff --git a/apps/ios/Views/SettingsView.swift b/apps/ios/Views/SettingsView.swift
index 0d276052..4ade06b0 100644
--- a/apps/ios/Views/SettingsView.swift
+++ b/apps/ios/Views/SettingsView.swift
@@ -3,60 +3,59 @@ import CodyncUI
import SwiftUI
import UserNotifications
-/// Computer connections and settings for the currently selected account.
+/// Every computer this iPhone can use or ask for — paired here and in the account, merged by
+/// computer ID — plus settings for the selected account.
struct SettingsView: View {
- @Environment(BotStore.self) private var model
+ @Environment(AppStore.self) private var app
+ @Environment(AccountStore.self) private var accounts
@Environment(\.dismiss) private var dismiss
@State private var notificationsAllowed: Bool?
@State private var addingComputer = false
- @State private var confirmForget: Pairing?
+ @State private var confirmForget: Computer?
+ @State private var confirmRevoke: CloudComputer?
+ @State private var access: AccessTarget?
var body: some View {
Form {
Section {
- ForEach(model.computers, id: \.token) { computer in
- ComputerRow(computer: computer, active: computer.token == model.pairing?.token)
- .contentShape(Rectangle())
- .onTapGesture { if computer.token != model.pairing?.token { model.pair(computer) } }
- .swipeActions {
- Button("Remove", systemImage: "trash", role: .destructive) { confirmForget = computer }
- }
- .contextMenu {
- Menu("Color", systemImage: "paintpalette") {
- ForEach(AvatarPalette.colors) { swatch in
- Button { model.setColor(computer, swatch.id) } label: {
- // Menus drop SwiftUI tints; an original-mode UIImage keeps the swatch colored.
- Label {
- Text(swatch.label)
- } icon: {
- Image(uiImage: UIImage(systemName: computer.color == swatch.id ? "checkmark.circle.fill" : "circle.fill")!
- .withTintColor(UIColor(swatch.color), renderingMode: .alwaysOriginal))
- }
- }
- }
+ ForEach(accounts.computers) { computer in
+ if let store = accounts.store(for: computer.id) {
+ ComputerRow(store: store, inAccount: cloudComputer(computer.id))
+ .swipeActions {
+ Button("Remove", systemImage: "trash", role: .destructive) { confirmForget = computer }
}
- Button("Remove", systemImage: "trash", role: .destructive) { confirmForget = computer }
- }
+ .contextMenu { menu(for: computer, store: store) }
+ }
+ }
+ ForEach(accountOnly) { computer in
+ AccountComputerRow(computer: computer, ticket: accounts.pendingAccess[computer.computerId],
+ ask: { access = AccessTarget(computer: computer) },
+ revoke: { confirmRevoke = computer })
}
Button {
addingComputer = true
} label: {
- Label("Add a computer", systemImage: "plus")
+ Label("Pair a computer", systemImage: "qrcode.viewfinder")
.foregroundStyle(Palette.text)
}
} header: {
- Text("Computers on this iPhone")
+ Text("Computers")
} footer: {
- Text("Each bot runs on its own computer. Tap a computer to view its bots.")
+ Text(app.account.isSignedIn
+ ? "Computers in your account need your OK on the computer before this iPhone can use them."
+ : "Each bot runs on its own computer. Sign in to see the computers in your account.")
}
Section {
- NavigationLink {
- MarketplaceView()
- } label: {
- VStack(alignment: .leading, spacing: 2) {
- Text("Marketplace")
- Text("Agents, connectors and skills for your bots").font(.subheadline).foregroundStyle(Palette.secondary)
+ ForEach(onlineStores, id: \.computer.id) { store in
+ Button {
+ closeSheets()
+ app.marketplace = store.computer.id
+ } label: {
+ VStack(alignment: .leading, spacing: 2) {
+ Text(onlineStores.count > 1 ? "Marketplace on \(store.hostName)" : "Marketplace").foregroundStyle(Palette.text)
+ Text("Agents, connectors and skills for your bots").font(.subheadline).foregroundStyle(Palette.secondary)
+ }
}
}
}
@@ -65,23 +64,24 @@ struct SettingsView: View {
notificationsRow
}
- if !model.hiddenBots.isEmpty {
+ if !hiddenBots.isEmpty {
Section("Hidden bots") {
- ForEach(model.hiddenBots) { bot in
+ ForEach(hiddenBots) { item in
+ let store = item.store, bot = item.bot
HStack {
CharacterAvatar(bot: bot, size: 28, animated: false)
- Text(bot.name)
+ VStack(alignment: .leading, spacing: 1) {
+ Text(bot.name)
+ Text(store.hostName).font(.caption).foregroundStyle(Palette.tertiary)
+ }
Spacer()
- Button("Unhide", systemImage: "eye") { model.setHidden(bot, false) }.labelStyle(.iconOnly)
+ Button("Unhide", systemImage: "eye") { store.setHidden(bot, false) }.labelStyle(.iconOnly)
}
}
}
}
Section {
- if let hello = model.hello {
- LabeledContent("Host version", value: hello.version)
- }
LabeledContent("App version", value: Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "")
Link("Source code", destination: URL(string: "https://github.com/leepokai/Codync")!)
.foregroundStyle(Palette.text)
@@ -96,17 +96,28 @@ struct SettingsView: View {
Button("Close", systemImage: "xmark") { dismiss() }.labelStyle(.iconOnly)
}
}
+ .refreshable { await accounts.refreshCloud() }
+ .task { await accounts.refreshCloud() }
.sheet(isPresented: $addingComputer) {
PairingView { addingComputer = false }
}
+ .sheet(item: $access) { target in
+ NavigationStack { AccessRequestView(computer: target.computer, pending: accounts.pendingAccess[target.id] != nil) }
+ }
.confirmationDialog("Remove \(confirmForget?.name ?? "computer")?", isPresented: Binding(get: { confirmForget != nil }, set: { if !$0 { confirmForget = nil } }), titleVisibility: .visible) {
Button("Remove", role: .destructive) {
- if let c = confirmForget { model.forget(c) }
- if model.pairing == nil { dismiss() }
+ if let c = confirmForget { accounts.forget(c.id) }
}
} message: {
Text("Its bots and conversations stay on that computer. You can pair again any time.")
}
+ .confirmationDialog("Revoke this iPhone's access to \(confirmRevoke?.name ?? "the computer")?", isPresented: Binding(get: { confirmRevoke != nil }, set: { if !$0 { confirmRevoke = nil } }), titleVisibility: .visible) {
+ Button("Revoke", role: .destructive) {
+ if let c = confirmRevoke { Task { await app.revokeAccess(c.computerId) } }
+ }
+ } message: {
+ Text("You can ask for access again; the computer will show a new code to confirm.")
+ }
.task {
let status = await UNUserNotificationCenter.current().notificationSettings().authorizationStatus
notificationsAllowed = switch status {
@@ -117,6 +128,74 @@ struct SettingsView: View {
}
}
+ private struct AccessTarget: Identifiable {
+ let computer: CloudComputer
+ var id: ComputerID { computer.computerId }
+ }
+
+ private func cloudComputer(_ id: ComputerID) -> CloudComputer? {
+ accounts.cloudComputers.first { $0.computerId == id }
+ }
+
+ /// Account computers this iPhone isn't set up for yet.
+ private var accountOnly: [CloudComputer] {
+ accounts.cloudComputers.filter { c in !accounts.computers.contains { $0.id == c.computerId } }
+ }
+
+ private var onlineStores: [BotStore] {
+ accounts.computers.compactMap { accounts.store(for: $0.id) }.filter { $0.connection == .online }
+ }
+
+ private struct HiddenBot: Identifiable {
+ let store: BotStore
+ let bot: Bot
+ let id: String
+ }
+
+ private var hiddenBots: [HiddenBot] {
+ accounts.computers.compactMap { accounts.store(for: $0.id) }.flatMap { store in
+ store.hiddenBots.map { HiddenBot(store: store, bot: $0, id: "\(store.computer.id)/\($0.id)") }
+ }
+ }
+
+ @ViewBuilder private func menu(for computer: Computer, store: BotStore) -> some View {
+ Menu("Color", systemImage: "paintpalette") {
+ ForEach(AvatarPalette.colors) { swatch in
+ Button { accounts.setColor(computer.id, swatch.id) } label: {
+ // Menus drop SwiftUI tints; an original-mode UIImage keeps the swatch colored.
+ Label {
+ Text(swatch.label)
+ } icon: {
+ Image(uiImage: UIImage(systemName: computer.color == swatch.id ? "checkmark.circle.fill" : "circle.fill")!
+ .withTintColor(UIColor(swatch.color), renderingMode: .alwaysOriginal))
+ }
+ }
+ }
+ }
+ if store.screen != nil, store.connection == .online {
+ Button("Screen", systemImage: "display") { openScreen(store) }
+ }
+ if let cloud = cloudComputer(computer.id), cloud.access == "granted" {
+ Button("Revoke this iPhone's access", systemImage: "lock.slash", role: .destructive) { confirmRevoke = cloud }
+ }
+ Button("Remove", systemImage: "trash", role: .destructive) { confirmForget = computer }
+ }
+
+ /// This screen is a sheet of its own or inside Accounts; the marketplace and screen open over the app.
+ private func closeSheets() {
+ app.showComputers = false
+ app.account.showSwitcher = false
+ }
+
+ private func openScreen(_ store: BotStore) {
+ closeSheets()
+ Task {
+ // Let the sheet finish closing before covering the screen.
+ try? await Task.sleep(for: .milliseconds(450))
+ store.screenRequest = ScreenRequest()
+ }
+ }
+
@ViewBuilder private var notificationsRow: some View {
if notificationsAllowed == true {
LabeledContent("Notifications", value: "On")
@@ -135,50 +214,79 @@ struct SettingsView: View {
}
}
+/// A computer this iPhone can use: its connection, how it's reached, and whether it's in the account.
private struct ComputerRow: View {
- let computer: Pairing
- let active: Bool
- @Environment(BotStore.self) private var model
+ let store: BotStore
+ let inAccount: CloudComputer?
var body: some View {
HStack(spacing: 12) {
- ComputerBadge(computer, size: 40)
+ ComputerBadge(store.computer, size: 40)
VStack(alignment: .leading, spacing: 2) {
- Text(computer.name).font(.body.weight(.semibold)).foregroundStyle(Palette.text)
- Text(status).font(.subheadline).foregroundStyle(Palette.secondary).lineLimit(1)
+ Text(store.hostName).font(.body.weight(.semibold)).foregroundStyle(Palette.text)
+ HStack(spacing: 4) {
+ Text(detail).lineLimit(1)
+ if store.connection == .online { RouteIcon(route: store.hostRoute) }
+ }
+ .font(.subheadline)
+ .foregroundStyle(store.isOffline ? Palette.warning : Palette.secondary)
}
Spacer()
- if !active || model.screen != nil {
- Button("Screen", systemImage: "display") { openScreen() }
- .labelStyle(.iconOnly)
- .buttonStyle(.borderless)
- .foregroundStyle(Palette.text)
- }
- if active {
- Image(systemName: "checkmark").font(.body.weight(.semibold)).foregroundStyle(Palette.text)
+ if inAccount != nil {
+ Image(systemName: "person.crop.circle.badge.checkmark")
+ .foregroundStyle(Palette.tertiary)
+ .accessibilityLabel("In your account")
}
}
.padding(.vertical, 2)
}
- /// Only the active computer is connected: switch to this one first, then open its screen.
- private func openScreen() {
- if !active { model.pair(computer) }
- model.showProfile = false
- Task {
- // Let the sheet finish closing before covering the screen.
- try? await Task.sleep(for: .milliseconds(450))
- model.screenRequest = ScreenRequest()
+ private var detail: String {
+ guard store.connection == .online else { return store.statusText }
+ let count = store.roster.count
+ let route = switch store.hostRoute {
+ case .direct: " · Direct"
+ case .relay: " · Relay"
+ default: ""
}
+ return "\(count) bot\(count == 1 ? "" : "s")\(route)"
+ }
+}
+
+/// A computer in the account that this iPhone can't use yet.
+private struct AccountComputerRow: View {
+ let computer: CloudComputer
+ let ticket: AccessTicket?
+ let ask: () -> Void
+ let revoke: () -> Void
+
+ var body: some View {
+ HStack(spacing: 12) {
+ ComputerBadge(Computer(id: computer.computerId, name: computer.name, signKey: computer.signKey, device: computer.device), size: 40)
+ .opacity(0.5)
+ VStack(alignment: .leading, spacing: 2) {
+ Text(computer.name).font(.body.weight(.semibold)).foregroundStyle(Palette.text)
+ Text(detail).font(.subheadline).foregroundStyle(Palette.secondary).lineLimit(2)
+ }
+ Spacer()
+ if ticket != nil {
+ Button("Code", action: ask).buttonStyle(.bordered)
+ } else if computer.access == "granted" {
+ Button("Revoke", role: .destructive, action: revoke).buttonStyle(.bordered)
+ } else {
+ Button("Ask for access", action: ask).buttonStyle(.bordered)
+ }
+ }
+ .padding(.vertical, 2)
}
- private var status: String {
- guard active else { return "\(computer.urls.count) address\(computer.urls.count == 1 ? "" : "es")" }
- return switch model.connection {
- case .online: "Connected · \(model.bots.count) bot\(model.bots.count == 1 ? "" : "s")"
- case .connecting: "Connecting…"
- case .offline: "Offline"
- case .unpaired: "Not paired"
+ private var detail: String {
+ let online = computer.isOnline ? "Online" : "Offline"
+ if let ticket { return "Waiting for your OK on the computer · \(ticket.code)" }
+ return switch computer.access {
+ case "granted": "Approved for an earlier install of Codync. Revoke it, then ask again."
+ case "pending": "\(online) · A request is waiting"
+ default: "\(online) · In your account"
}
}
}
diff --git a/apps/ios/Widgets/CodyncWidgets.swift b/apps/ios/Widgets/CodyncWidgets.swift
index adc867ea..a3febe2b 100644
--- a/apps/ios/Widgets/CodyncWidgets.swift
+++ b/apps/ios/Widgets/CodyncWidgets.swift
@@ -16,27 +16,47 @@ struct CodyncWidgets: WidgetBundle {
// MARK: - Bots at a glance
+/// A bot on one of the account's computers; bot IDs are only unique per computer.
+struct WidgetBot: Identifiable {
+ let bot: Bot
+ let link: URL?
+ let id: String
+
+ init(_ snapshot: BotSnapshot, storage: SharedStore.Context?) {
+ bot = snapshot.bot
+ link = storage?.botURL(BotReference(accountId: storage?.accountID, computerId: snapshot.computerId, botId: snapshot.bot.id))
+ id = "\(snapshot.computerId)/\(snapshot.bot.id)"
+ }
+}
+
struct BotsEntry: TimelineEntry {
let date: Date
- let bots: [Bot]
+ let bots: [WidgetBot]
let paired: Bool
- var links: [String: URL] = [:]
+
+ /// The app's snapshot of every computer's bots in the selected account.
+ static func current(preview: Bool = false) -> BotsEntry {
+ let storage = SharedStore.activeContext
+ let bots = storage.bots.map { WidgetBot($0, storage: storage) }
+ if bots.isEmpty && preview { return .sample }
+ return BotsEntry(date: .now, bots: bots, paired: !storage.computers.isEmpty)
+ }
+
+ static var sample: BotsEntry {
+ BotsEntry(date: .now, bots: Bot.samples.map { WidgetBot(BotSnapshot(computerId: "sample", bot: $0), storage: nil) }, paired: true)
+ }
}
struct BotsTimeline: TimelineProvider {
- func placeholder(in context: Context) -> BotsEntry { BotsEntry(date: .now, bots: Bot.samples, paired: true) }
+ func placeholder(in context: Context) -> BotsEntry { .sample }
func getSnapshot(in context: Context, completion: @escaping (BotsEntry) -> Void) {
- let bots = SharedStore.bots
- completion(BotsEntry(date: .now, bots: bots.isEmpty && context.isPreview ? Bot.samples : bots, paired: true))
+ completion(.current(preview: context.isPreview))
}
/// The app writes the roster and reloads this widget when a bot's state changes.
func getTimeline(in context: Context, completion: @escaping (Timeline<BotsEntry>) -> Void) {
- let storage = SharedStore.activeContext
- let entry = BotsEntry(date: .now, bots: storage.bots, paired: storage.pairing != nil,
- links: Dictionary(storage.bots.map { ($0.id, storage.botURL($0.id)) }, uniquingKeysWith: { a, _ in a }))
- completion(Timeline(entries: [entry], policy: .never))
+ completion(Timeline(entries: [.current()], policy: .never))
}
}
@@ -56,21 +76,23 @@ struct BotsWidgetView: View {
let entry: BotsEntry
@Environment(\.widgetFamily) private var family
+ private var bots: [Bot] { entry.bots.map(\.bot) }
+
/// Needs you first, then working, then most recent.
- private var ordered: [Bot] {
- entry.bots.filter { !$0.hidden }.sorted {
+ private var ordered: [WidgetBot] {
+ entry.bots.filter { !$0.bot.hidden }.sorted { a, b in
let rank = { (b: Bot) in b.needsInput ? 0 : b.isWorking ? 1 : 2 }
- return rank($0) != rank($1) ? rank($0) < rank($1) : $0.lastAt > $1.lastAt
+ return rank(a.bot) != rank(b.bot) ? rank(a.bot) < rank(b.bot) : a.bot.lastAt > b.bot.lastAt
}
}
- private var needing: Int { entry.bots.filter(\.needsInput).count }
- private var working: Int { entry.bots.filter { $0.isWorking && !$0.needsInput }.count }
+ private var needing: Int { bots.filter(\.needsInput).count }
+ private var working: Int { bots.filter { $0.isWorking && !$0.needsInput }.count }
/// The one line that sums up the roster.
private var headline: (count: Int, label: String, needs: Bool) {
if needing > 0 { return (needing, needing == 1 ? "needs you" : "need you", true) }
if working > 0 { return (working, "working", false) }
- return (entry.bots.count, entry.bots.count == 1 ? "bot, all quiet" : "bots, all quiet", false)
+ return (bots.count, bots.count == 1 ? "bot, all quiet" : "bots, all quiet", false)
}
var body: some View {
@@ -89,8 +111,8 @@ struct BotsWidgetView: View {
case .accessoryRectangular:
VStack(alignment: .leading, spacing: 1) {
Text("\(headline.count) \(headline.label)").font(.headline).widgetAccentable()
- ForEach(ordered.prefix(2)) { bot in
- Text("\(bot.name) · \(line(bot))").font(.caption2).lineLimit(1)
+ ForEach(ordered.prefix(2)) { item in
+ Text("\(item.bot.name) · \(line(item.bot))").font(.caption2).lineLimit(1)
}
}
.frame(maxWidth: .infinity, alignment: .leading)
@@ -98,8 +120,8 @@ struct BotsWidgetView: View {
HStack(alignment: .top, spacing: 16) {
summary.frame(width: 104, alignment: .leading)
VStack(alignment: .leading, spacing: 10) {
- ForEach(ordered.prefix(3)) { bot in
- Link(destination: entry.links[bot.id] ?? URL(string: "codync://computers")!) { BotLine(bot: bot, detail: line(bot)) }
+ ForEach(ordered.prefix(3)) { item in
+ Link(destination: item.link ?? URL(string: "codync://computers")!) { BotLine(bot: item.bot, detail: line(item.bot)) }
}
Spacer(minLength: 0)
}
@@ -107,15 +129,15 @@ struct BotsWidgetView: View {
default:
VStack(alignment: .leading, spacing: 0) {
HStack(spacing: -6) {
- ForEach(ordered.prefix(3)) { bot in
- CharacterAvatar(bot: bot, size: 30, animated: false)
+ ForEach(ordered.prefix(3)) { item in
+ CharacterAvatar(bot: item.bot, size: 30, animated: false)
}
}
Spacer(minLength: 6)
summary
}
.frame(maxWidth: .infinity, alignment: .leading)
- .widgetURL(ordered.first.flatMap { entry.links[$0.id] })
+ .widgetURL(ordered.first?.link)
}
}
}
@@ -127,7 +149,7 @@ struct BotsWidgetView: View {
.foregroundStyle(headline.needs ? Palette.warning : Palette.text)
.contentTransition(.numericText())
Text(headline.label).font(.subheadline).foregroundStyle(Palette.secondary)
- if family == .systemSmall, let first = ordered.first, first.isWorking {
+ if family == .systemSmall, let first = ordered.first?.bot, first.isWorking {
Text(first.name).font(.caption).foregroundStyle(Palette.tertiary).lineLimit(1).padding(.top, 2)
}
}
@@ -200,7 +222,7 @@ struct UsageTimeline: AppIntentTimelineProvider {
}
func snapshot(for configuration: UsageIntent, in context: Context) async -> UsageEntry {
- UsageEntry(date: .now, usage: SharedStore.usage ?? .sample)
+ UsageEntry(date: .now, usage: Self.cached ?? .sample)
}
/// Refreshes every 30 minutes, or right after the next limit resets if that's sooner.
@@ -210,19 +232,31 @@ struct UsageTimeline: AppIntentTimelineProvider {
static func timeline() async -> Timeline<UsageEntry> {
let fetched = await fetch()
- let usage = fetched ?? SharedStore.usage ?? Usage()
+ let usage = fetched ?? cached ?? Usage()
let nextReset = usage.providers.flatMap(\.windows).compactMap(\.resetDate).filter { $0 > .now }.min()
var next = Date.now + (fetched == nil ? 5 * 60 : 30 * 60)
if let nextReset, nextReset + 1 < next { next = max(nextReset + 1, .now + 5 * 60) }
return Timeline(entries: [UsageEntry(date: .now, usage: usage)], policy: .after(next))
}
- /// Asks the paired host directly (works over Tailscale), falling back to the app's cache.
- /// `refresh` makes the host re-read the limits first instead of answering from its cache.
+ /// The last active computer's usage, as the app last saw it.
+ static var cached: Usage? {
+ let storage = SharedStore.activeContext
+ return storage.lastComputerId.flatMap { storage.usage[$0] }
+ }
+
+ /// Asks the last active computer directly or through the relay, one call, then disconnects;
+ /// nil falls back to the app's cache. `refresh` makes the host re-read the limits first.
static func fetch(refresh: Bool = false) async -> Usage? {
- guard let pairing = SharedStore.orderedPairing, let client = await HostClient.resolve(pairing),
- let usage = try? await client.usage(refresh: refresh) else { return nil }
- SharedStore.usage = usage
+ let storage = SharedStore.activeContext
+ // Keys exist once a computer is saved; the widget never creates them.
+ guard let id = storage.lastComputerId, let computer = storage.computers.first(where: { $0.id == id }),
+ let identity = try? DeviceIdentity.load(context: storage),
+ let transport = try? await HostConnector.connect(computer, identity: identity) else { return nil }
+ let usage = try? await HostClient(transport: transport).usage(refresh: refresh)
+ await transport.shutdown()
+ guard let usage else { return nil }
+ storage.usage[id] = usage
return usage
}
}
@@ -299,7 +333,7 @@ struct UsageWidgetView: View {
} else if family == .accessoryInline || family == .accessoryCircular || family == .accessoryRectangular {
Text("No usage yet")
} else {
- EmptyWidget(text: SharedStore.pairing == nil ? "Open Codync to pair with your computer." : "No usage reported yet.")
+ EmptyWidget(text: SharedStore.activeContext.computers.isEmpty ? "Open Codync to pair with your computer." : "No usage reported yet.")
}
}
@@ -369,7 +403,7 @@ struct ProviderUsageTimeline: AppIntentTimelineProvider {
}
func snapshot(for configuration: ProviderUsageIntent, in context: Context) async -> ProviderUsageEntry {
- let usage = SharedStore.usage.flatMap { $0.providers.isEmpty ? nil : $0 } ?? .preview
+ let usage = UsageTimeline.cached.flatMap { $0.providers.isEmpty ? nil : $0 } ?? .preview
return ProviderUsageEntry(date: .now, usage: usage, provider: configuration.provider)
}
@@ -449,7 +483,7 @@ struct ProviderUsageView: View {
}
}
} else {
- EmptyWidget(text: SharedStore.pairing == nil ? "Open Codync to pair with your computer."
+ EmptyWidget(text: SharedStore.activeContext.computers.isEmpty ? "Open Codync to pair with your computer."
: "No \(entry.provider.rawValue.capitalized) usage reported yet.")
}
}
@@ -531,10 +565,11 @@ struct BotLiveActivity: Widget {
}
}
+/// Status only: Live Activity pushes never carry free text (spec §6.7).
private func statusText(_ s: BotActivityAttributes.ContentState) -> String {
switch s.status {
- case "needsInput": s.activity.isEmpty ? "Needs your approval" : s.activity
- case "working": s.activity.isEmpty ? "Working…" : s.activity
+ case "needsInput": "Needs your approval"
+ case "working": "Working…"
case "error": "Stopped with an error"
default: "Done"
}
diff --git a/apps/ios/Widgets/Resources/Info.plist b/apps/ios/Widgets/Resources/Info.plist
index 046bb469..8246c8b6 100644
--- a/apps/ios/Widgets/Resources/Info.plist
+++ b/apps/ios/Widgets/Resources/Info.plist
@@ -2,6 +2,8 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
+ <key>CodyncKeychainGroup</key>
+ <string>$(AppIdentifierPrefix)com.pokai.Codync</string>
<key>NSExtension</key>
<dict>
<key>NSExtensionPointIdentifier</key>
diff --git a/apps/ios/Widgets/Resources/Widgets.entitlements b/apps/ios/Widgets/Resources/Widgets.entitlements
index 291cf12d..c5f86e3a 100644
--- a/apps/ios/Widgets/Resources/Widgets.entitlements
+++ b/apps/ios/Widgets/Resources/Widgets.entitlements
@@ -6,5 +6,9 @@
<array>
<string>group.com.pokai.Codync</string>
</array>
+ <key>keychain-access-groups</key>
+ <array>
+ <string>$(AppIdentifierPrefix)com.pokai.Codync</string>
+ </array>
</dict>
</plist>
diff --git a/apps/macos/App/CodyncMacApp.swift b/apps/macos/App/CodyncMacApp.swift
index e4aa5866..a364bb3a 100644
--- a/apps/macos/App/CodyncMacApp.swift
+++ b/apps/macos/App/CodyncMacApp.swift
@@ -5,10 +5,16 @@ import SwiftUI
@main
struct CodyncMacApp: App {
- @State private var host = HostController()
- @State private var account = AccountSession()
+ @State private var host: HostController
+ @State private var account: AccountSession
@Environment(\.openWindow) private var openWindow
+ init() {
+ let account = AccountSession()
+ _account = State(initialValue: account)
+ _host = State(initialValue: HostController(account: account))
+ }
+
var body: some Scene {
MenuBarExtra {
MenuView()
@@ -22,6 +28,13 @@ struct CodyncMacApp: App {
host.start()
openWindow(id: "chat")
}
+ .onChange(of: account.userID) { _, userID in host.switchAccount(to: userID) }
+ // A device asking for access: bring up the window that holds the approval sheet.
+ .onChange(of: host.currentApproval?.id) { _, id in
+ guard id != nil else { return }
+ openWindow(id: "chat")
+ NSApp.activate()
+ }
}
.menuBarExtraStyle(.window)
@@ -44,8 +57,8 @@ struct MenuView: View {
VStack(alignment: .leading, spacing: 0) {
header
VStack(spacing: 8) {
- if showPairing {
- PairingPanel()
+ if showPairing, let store = host.store {
+ PairingPanel(store: store)
.tile()
// Grows out of the QR button that opened it, and goes back into it.
.transition(.scale(0.97, anchor: .topTrailing).combined(with: .opacity))
@@ -86,7 +99,6 @@ struct MenuView: View {
}
IconButton("Pair iPhone", systemImage: "qrcode", selected: showPairing) {
showPairing.toggle()
- if showPairing { host.loadPairing() }
}
}
}
@@ -103,7 +115,9 @@ struct MenuView: View {
case .starting: ("Connecting…", nil)
case .failed: ("Host problem", Palette.danger)
case .running:
- if host.needsAttention {
+ if !host.approvals.isEmpty {
+ ("A device asks for access", Palette.warning)
+ } else if host.needsAttention {
("A bot needs you", Palette.warning)
} else if host.working > 0 {
("\(host.working) bot\(host.working == 1 ? "" : "s") working", Palette.accent)
@@ -151,6 +165,14 @@ struct MenuView: View {
}
.tile()
case .running:
+ if let approval = host.approvals.first {
+ ApprovalLine(approval: approval) {
+ host.reviewApprovals()
+ openWindow(id: "chat")
+ NSApp.activate()
+ }
+ .tile()
+ }
bots
if host.screen != nil {
RemoteScreenSection().tile()
@@ -165,7 +187,7 @@ struct MenuView: View {
}
@ViewBuilder private var bots: some View {
- if host.bots.isEmpty {
+ if host.roster.isEmpty {
HStack(spacing: 12) {
CharacterAvatar(shape: "cloud", color: "gray", size: 32)
VStack(alignment: .leading, spacing: 2) {
@@ -178,11 +200,11 @@ struct MenuView: View {
} else {
ScrollView {
VStack(spacing: 0) {
- ForEach(host.bots) { bot in
- BotLine(bot: bot) { host.stop(bot) }
+ ForEach(host.roster) { item in
+ BotLine(bot: item.bot, computer: host.accounts.computers.count > 1 ? item.computer : nil) { host.stop(item) }
.contentShape(Rectangle())
.onTapGesture {
- host.store?.selection = bot.id
+ host.accounts.selection = item.ref
openWindow(id: "chat")
NSApp.activate()
}
@@ -191,7 +213,7 @@ struct MenuView: View {
.padding(4)
}
// ScrollView has no intrinsic height inside a MenuBarExtra window.
- .frame(height: min(CGFloat(host.bots.count) * 46 + 8, 320))
+ .frame(height: min(CGFloat(host.roster.count) * 46 + 8, 320))
.tile(padding: 0)
}
}
@@ -297,7 +319,7 @@ private struct RemoteScreenSection: View {
if !screen.connected { return "Starting Codync Screen…" }
if !screen.capture || !screen.input { return "Needs permission" }
if screen.viewers > 0 { return screen.viewers == 1 ? "Your iPhone is viewing" : "\(screen.viewers) viewers" }
- if let bot = screen.agentBot, let name = host.bots.first(where: { $0.id == bot })?.name { return "\(name) is using it" }
+ if let bot = screen.agentBot, let name = host.store?.bots[bot]?.name { return "\(name) is using it" }
let display = screen.displays.first(where: \.main)?.name ?? screen.displays.first?.name
return display.map { "Ready · \($0)" } ?? "Ready"
}
@@ -385,6 +407,8 @@ private struct ThinBar: View {
private struct BotLine: View {
let bot: Bot
+ /// Shown when bots from more than one computer are listed.
+ let computer: Computer?
let stop: () -> Void
@State private var hovering = false
@@ -392,7 +416,13 @@ private struct BotLine: View {
HStack(spacing: 10) {
AvatarWithStatus(bot: bot, size: 30)
VStack(alignment: .leading, spacing: 1) {
- Text(bot.name).font(.callout.weight(.medium)).foregroundStyle(Palette.text)
+ HStack(spacing: 4) {
+ Text(bot.name).font(.callout.weight(.medium)).foregroundStyle(Palette.text)
+ if let computer {
+ ComputerBadge(computer, size: 13)
+ Text(computer.name).font(.caption2).foregroundStyle(Palette.tertiary).lineLimit(1)
+ }
+ }
Text(bot.isWorking ? (bot.activity.isEmpty ? "Working…" : bot.activity) : (bot.lastMessage ?? bot.folderName))
.font(.caption)
.foregroundStyle(bot.needsInput ? Palette.warning : bot.isWorking ? Palette.accent : Palette.secondary)
@@ -413,12 +443,15 @@ private struct BotLine: View {
}
}
-private struct PairingPanel: View {
- @Environment(HostController.self) private var host
+/// A one-time pairing QR (v3) from a computer this Mac manages: its keys, a code, and how to reach it.
+struct PairingPanel: View {
+ let store: BotStore
+ @State private var info: PairingInfo?
+ @State private var error: String?
var body: some View {
VStack(spacing: 12) {
- if let info = host.pairInfo {
+ if let info {
if let image = qr(info.pairingUrl) {
Image(nsImage: image)
.interpolation(.none)
@@ -426,27 +459,56 @@ private struct PairingPanel: View {
.frame(width: 200, height: 200)
.padding(10)
.background(.white, in: RoundedRectangle(cornerRadius: 12))
+ .accessibilityLabel("Pairing code for \(store.hostName)")
}
- Text("Scan with the Codync app or the iPhone Camera.")
+ Text("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.")
.font(.caption)
.foregroundStyle(Palette.secondary)
- if info.urls.isEmpty {
- Text("No network address found. Connect this Mac to Wi-Fi or Tailscale.")
+ .multilineTextAlignment(.center)
+ .fixedSize(horizontal: false, vertical: true)
+ if store.cloud?.enabled != true {
+ Text(info.urls.isEmpty
+ ? "No network address found and “Reach from anywhere” is off. Connect to Wi-Fi or turn it on."
+ : "“Reach from anywhere” is off, so the iPhone only reaches \(store.hostName) on the same network.")
.font(.caption)
.foregroundStyle(Palette.warning)
- } else if !info.urls.contains(where: Tailscale.isAddress) {
- TailscaleTip()
+ .multilineTextAlignment(.center)
+ .fixedSize(horizontal: false, vertical: true)
}
- IconButton("Copy pairing link", systemImage: "doc.on.doc") {
- NSPasteboard.general.clearContents()
- NSPasteboard.general.setString(info.pairingUrl, forType: .string)
+ HStack(spacing: 4) {
+ if let expires = info.expiresAt {
+ Text("Works once, until \(Date(milliseconds: expires).formatted(date: .omitted, time: .shortened))")
+ .font(.caption2).foregroundStyle(Palette.tertiary)
+ }
+ IconButton("New code", systemImage: "arrow.clockwise") { Task { await load() } }
+ IconButton("Copy pairing link", systemImage: "doc.on.doc") {
+ NSPasteboard.general.clearContents()
+ NSPasteboard.general.setString(info.pairingUrl, forType: .string)
+ }
}
+ } else if let error {
+ Text(error).font(.caption).foregroundStyle(Palette.danger).multilineTextAlignment(.center)
+ IconButton("Try again", systemImage: "arrow.clockwise") { Task { await load() } }
} else {
ProgressView()
}
}
.frame(maxWidth: .infinity)
.padding(16)
+ .task(id: store.computer.id) { await load() }
+ }
+
+ private func load() async {
+ guard let client = store.client else {
+ error = "\(store.hostName) isn't connected."
+ return
+ }
+ do {
+ info = try await client.pairing()
+ error = nil
+ } catch {
+ self.error = error.localizedDescription
+ }
}
private func qr(_ string: String) -> NSImage? {
@@ -461,24 +523,22 @@ private struct PairingPanel: View {
}
}
-/// Without Tailscale the iPhone only reaches this Mac on the same Wi-Fi.
-private struct TailscaleTip: View {
- private static let app = URL(fileURLWithPath: "/Applications/Tailscale.app")
- private let installed = FileManager.default.fileExists(atPath: app.path)
+/// A pending access request in the menu; the decision happens in the approval sheet.
+private struct ApprovalLine: View {
+ let approval: Approval
+ let review: () -> Void
var body: some View {
- VStack(spacing: 6) {
- Text(installed
- ? "Tailscale isn't connected. Open it and sign in to reach your bots away from home."
- : "Install Tailscale on this Mac and your iPhone to reach your bots away from home.")
- .font(.caption)
- .foregroundStyle(Palette.tertiary)
- .multilineTextAlignment(.center)
- if installed {
- Button("Open Tailscale") { NSWorkspace.shared.open(Self.app) }.controlSize(.small)
- } else {
- Link("Get Tailscale", destination: Tailscale.downloadURL).font(.caption)
+ HStack(spacing: 10) {
+ Image(systemName: "person.badge.key")
+ .foregroundStyle(Palette.warning)
+ .accessibilityHidden(true)
+ VStack(alignment: .leading, spacing: 1) {
+ Text("\(approval.request.deviceName) asks for access").font(.callout.weight(.medium)).foregroundStyle(Palette.text)
+ Text(approval.store.hostName).font(.caption).foregroundStyle(Palette.secondary)
}
+ Spacer()
+ Button("Review", action: review).controlSize(.small)
}
}
}
diff --git a/apps/macos/App/HostController.swift b/apps/macos/App/HostController.swift
index a7f3070f..574ccb49 100644
--- a/apps/macos/App/HostController.swift
+++ b/apps/macos/App/HostController.swift
@@ -1,11 +1,27 @@
+import AppKit
import CodyncKit
import CodyncUI
import Foundation
import Observation
import ServiceManagement
-/// Manages the local codync-host: finds the binary, installs the background
-/// service, and owns the BotStore the menu and the chat window share.
+/// A device asking a computer this Mac manages (itself or over SSH) for access.
+@MainActor
+struct Approval: Identifiable {
+ let store: BotStore
+ let request: AccessRequest
+ let id: String
+
+ init(store: BotStore, request: AccessRequest) {
+ self.store = store
+ self.request = request
+ id = "\(store.computer.id)/\(request.requestId)"
+ }
+}
+
+/// Manages the local codync-host (binary, background service) and owns the `AccountStore`
+/// the menu and the chat window share: this Mac over loopback, SSH computers through their
+/// tunnels, and the account's other computers over the encrypted channel.
@MainActor
@Observable
final class HostController {
@@ -22,25 +38,81 @@ final class HostController {
static let port = devPort ?? 19222
static let dataDir = ProcessInfo.processInfo.environment["CODYNC_HOME"].map { URL(filePath: $0) }
?? FileManager.default.homeDirectoryForCurrentUser.appending(path: ".codync")
+ static let baseURL = URL(string: "http://127.0.0.1:\(port)")!
+
+ let account: AccountSession
+ let ssh = SSHComputers()
+ /// One per account context; switching accounts retires it.
+ private(set) var accounts: AccountStore
+ /// The signed-in account's cloud; nil when signed out or the build has no cloud.
+ private(set) var cloud: CloudClient?
+ private(set) var contextID: String
+ /// This Mac's own host, once it answered.
+ private(set) var local: Computer?
+ private var localToken: String?
private(set) var state: State = .starting
- /// Live mirror of the host (same store the iPhone uses), once it's reachable.
- private(set) var store: BotStore?
- private(set) var pairInfo: PairingInfo?
- private(set) var version: String?
var launchAtLogin: Bool = SMAppService.mainApp.status == .enabled
/// Codync Screen (capture + input for Remote screen), a launchd agent inside this app.
private let screenAgent = SMAppService.agent(plistName: "com.pokai.Codync.screen.plist")
private(set) var screenAgentNeedsApproval = false
private(set) var screenError: String?
+ /// Approvals closed with "later"; they come back when the request changes (e.g. its code arrives).
+ private var deferred: Set<String> = []
private var streamTask: Task<Void, Never>?
- var bots: [Bot] { store?.roster ?? [] }
+ init(account: AccountSession) {
+ #if DEBUG
+ SSH.selfCheck()
+ #endif
+ self.account = account
+ let storage = SharedStore.Context(accountID: account.userID)
+ SharedStore.activeAccountID = account.userID
+ contextID = storage.id
+ (accounts, cloud) = Self.makeAccounts(storage, session: account)
+ ssh.onAttach = { [weak self] attachment in
+ self?.accounts.attach(attachment.computer, route: .loopback(baseURL: attachment.baseURL, token: attachment.token))
+ }
+ ssh.onDetach = { [weak self] id in self?.accounts.detach(id) }
+ // ssh children outlive the app unless stopped.
+ NotificationCenter.default.addObserver(forName: NSApplication.willTerminateNotification, object: nil, queue: .main) { [weak self] _ in
+ MainActor.assumeIsolated { self?.ssh.disconnectAll() }
+ }
+ }
+
+ /// The Mac's own host store.
+ var store: BotStore? { local.flatMap { accounts.store(for: $0.id) } }
+
+ /// Computers this Mac manages over loopback (itself and SSH tunnels): they take approvals, pairing and claims.
+ var managedStores: [BotStore] {
+ accounts.computers.compactMap { accounts.store(for: $0.id) }.filter(\.isLoopback)
+ }
+
+ var approvals: [Approval] {
+ managedStores.flatMap { store in store.accessRequests.map { Approval(store: store, request: $0) } }
+ }
+
+ /// The approval to show now: the first one not put off, or put off before its code arrived.
+ var currentApproval: Approval? {
+ approvals.first { !deferred.contains(deferKey($0)) }
+ }
+
+ func deferApproval(_ approval: Approval) { deferred.insert(deferKey(approval)) }
+
+ /// Brings every waiting request back (the menu's Review).
+ func reviewApprovals() { deferred = [] }
+
+ private func deferKey(_ a: Approval) -> String { "\(a.id)/\(a.request.code ?? "")" }
+
+ var roster: [RosterItem] { accounts.roster }
var usage: Usage { store?.usage ?? Usage() }
var screen: ScreenState? { store?.screen }
- var needsAttention: Bool { bots.contains(where: \.needsInput) }
- var working: Int { bots.filter(\.isWorking).count }
+ var version: String? { store?.hello?.version }
+ var needsAttention: Bool { roster.contains(where: \.bot.needsInput) || !approvals.isEmpty }
+ var working: Int { roster.filter(\.bot.isWorking).count }
+
+ func isSSH(_ id: ComputerID) -> Bool { ssh.attachments.values.contains { $0.computer.id == id } }
/// Bundled next to the app executable, else a Homebrew / cargo install.
var binaryURL: URL? {
@@ -63,6 +135,7 @@ final class HostController {
func start() {
refresh()
+ ssh.connectAll()
}
func refresh() {
@@ -106,16 +179,13 @@ final class HostController {
streamTask?.cancel()
Task {
_ = await Self.run(bin, ["uninstall"])
- store = nil
+ if let local { accounts.detach(local.id) }
+ local = nil
+ localToken = nil
state = .notInstalled
}
}
- func loadPairing() {
- guard let client = client() else { return }
- Task { pairInfo = try? await client.pairing() }
- }
-
func setLaunchAtLogin(_ on: Bool) {
do {
if on { try SMAppService.mainApp.register() } else { try SMAppService.mainApp.unregister() }
@@ -151,13 +221,108 @@ final class HostController {
screenAgentNeedsApproval = screenAgent.status == .requiresApproval
}
- func stop(_ bot: Bot) {
- Task { try? await client()?.stop(bot.id) }
+ func stop(_ item: RosterItem) {
+ accounts.store(for: item.ref.computerId)?.stop(item.bot.id)
+ }
+
+ // MARK: account
+
+ func switchAccount(to userID: String?) {
+ let storage = SharedStore.Context(accountID: userID)
+ guard storage.id != contextID else { return }
+ accounts.retire()
+ SharedStore.activeAccountID = userID
+ contextID = storage.id
+ deferred = []
+ (accounts, cloud) = Self.makeAccounts(storage, session: account)
+ // This Mac and the SSH tunnels belong to the Mac, not to an account: they follow into the new context.
+ if let local, let localToken { accounts.attach(local, route: .loopback(baseURL: Self.baseURL, token: localToken)) }
+ for attachment in ssh.attachments.values {
+ accounts.attach(attachment.computer, route: .loopback(baseURL: attachment.baseURL, token: attachment.token))
+ }
+ }
+
+ /// Signing out forgets the account on this Mac: its device keys, computers and caches (spec §3.2).
+ func signOut() async {
+ guard let userID = account.userID else { return }
+ await account.signOut()
+ guard account.userID != userID, !account.accounts.contains(where: { $0.id == userID }) else { return }
+ switchAccount(to: account.userID)
+ SharedStore.Context(accountID: userID).erase()
+ }
+
+ /// §4.2 A: makes a computer this Mac manages part of the signed-in account. Its relay is turned on first,
+ /// since joining the account is about reaching it from anywhere.
+ func claim(_ store: BotStore) async {
+ guard let cloud, let userID = account.userID, let client = store.client else {
+ accounts.lastError = "Sign in first."
+ return
+ }
+ do {
+ if store.cloud?.enabled != true { _ = try await enableCloud(client, store: store) }
+ let challenge = try await cloud.createClaim()
+ let signed = try await client.claimSign(claimId: challenge.claimId, nonce: challenge.nonce, userId: userID)
+ _ = try await cloud.completeClaim(challenge.claimId, signed: signed)
+ await accounts.refreshCloud()
+ } catch {
+ accounts.lastError = error.localizedDescription
+ }
+ }
+
+ func unclaim(_ store: BotStore) async {
+ do {
+ try await store.client?.unclaim()
+ await accounts.refreshCloud()
+ } catch {
+ accounts.lastError = error.localizedDescription
+ }
}
- private func client() -> HostClient? {
- guard let token = try? String(contentsOf: tokenURL, encoding: .utf8) else { return nil }
- return HostClient(baseURL: URL(string: "http://127.0.0.1:\(Self.port)")!, token: token.trimmingCharacters(in: .whitespacesAndNewlines))
+ func setCloud(_ store: BotStore, enabled: Bool) async {
+ guard let client = store.client else { return }
+ do {
+ _ = enabled ? try await enableCloud(client, store: store) : try await client.setCloud(enabled: false)
+ } catch {
+ accounts.lastError = error.localizedDescription
+ }
+ }
+
+ /// A host without a cloud URL of its own gets this app's.
+ private func enableCloud(_ client: HostClient, store: BotStore) async throws -> CloudStatus {
+ let url = store.cloud?.url == nil ? account.cloudURL : nil
+ guard store.cloud?.url != nil || url != nil else {
+ throw CloudError(status: 400, code: "badRequest", message: "This build of Codync has no cloud to connect to.")
+ }
+ return try await client.setCloud(enabled: true, url: url)
+ }
+
+ func decide(_ approval: Approval, approve: Bool) async throws {
+ guard let client = approval.store.client else { throw HostError.unreachable }
+ try await client.decideAccessRequest(approval.request.requestId, approve: approve)
+ }
+
+ private static func makeAccounts(_ storage: SharedStore.Context, session: AccountSession) -> (AccountStore, CloudClient?) {
+ let identity = storage.accountID == nil ? nil : try? DeviceIdentity.load(context: storage)
+ let cloud = session.cloudClient(for: storage.accountID, identity: identity)
+ let accounts = AccountStore(storage: storage, clientKind: "mac", cloud: cloud)
+ if let cloud {
+ // Signed in: make this Mac known to the account, then list its computers.
+ Task { [weak accounts] in
+ do {
+ try await cloud.registerDevice(name: Host.current().localizedName ?? "Mac", platform: "macos")
+ } catch {
+ accounts?.lastError = error.localizedDescription
+ }
+ await accounts?.refreshCloud()
+ }
+ }
+ return (accounts, cloud)
+ }
+
+ // MARK: local host
+
+ private func readToken() -> String? {
+ (try? String(contentsOf: tokenURL, encoding: .utf8)).map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
}
/// Watches the host's health; the BotStore handles the event stream itself.
@@ -167,18 +332,8 @@ final class HostController {
var failures = 0
while !Task.isCancelled {
guard let self else { return }
- if let client = self.client(), await client.healthy(timeout: 2) {
+ if await self.attachLocal() {
failures = 0
- if self.store == nil || self.store?.pairing?.token != client.token {
- self.version = (try? await client.hello())?.version
- let store = BotStore(
- pairing: Pairing(name: Host.current().localizedName ?? "This Mac", token: client.token, urls: [client.baseURL.absoluteString]),
- clientKind: "mac",
- persistsPairing: false
- )
- store.restartStream()
- self.store = store
- }
self.state = .running
self.syncScreenAgent()
} else {
@@ -191,20 +346,33 @@ final class HostController {
}
}
- nonisolated static func run(_ bin: URL, _ args: [String]) async -> (status: Int32, output: String) {
- await withCheckedContinuation { cont in
- let p = Process()
- p.executableURL = bin
- p.arguments = args
- // The host rebuilds PATH from the login shell itself (backends::hydrate_path).
- let pipe = Pipe()
- p.standardOutput = pipe
- p.standardError = pipe
- p.terminationHandler = { proc in
- let data = pipe.fileHandleForReading.readDataToEndOfFile()
- cont.resume(returning: (proc.terminationStatus, String(decoding: data, as: UTF8.self)))
- }
- do { try p.run() } catch { cont.resume(returning: (-1, error.localizedDescription)) }
+ /// Attaches the local host once it answers, and again when its token or identity changed.
+ private func attachLocal() async -> Bool {
+ guard let token = readToken(), let health = await HostHealth.fetch(Self.baseURL), let id = health.computerId else {
+ return false
}
+ if local?.id == id, localToken == token, store != nil { return true }
+ guard let hello = try? await HostClient(baseURL: Self.baseURL, token: token).hello(),
+ hello.computerId == id, let signKey = hello.signKey else { return false }
+ let computer = Computer(id: id, name: hello.name, signKey: signKey, boxKey: hello.boxKey, urls: hello.urls ?? [],
+ cloud: hello.cloud.flatMap(URL.init(string:)), device: hello.device,
+ color: store?.computer.color)
+ if let old = local, old.id != id { accounts.detach(old.id) }
+ local = computer
+ localToken = token
+ accounts.attach(computer, route: .loopback(baseURL: Self.baseURL, token: token))
+ return true
+ }
+
+ nonisolated static func run(_ bin: URL, _ args: [String]) async -> (status: Int32, output: String) {
+ // The host rebuilds PATH from the login shell itself (backends::hydrate_path).
+ let result = await ProcessRunner.run(bin, args)
+ return (result.status, (result.text + result.stderr).trimmingCharacters(in: .whitespacesAndNewlines))
+ }
+}
+
+extension BotStore {
+ var isLoopback: Bool {
+ if case .loopback = route { true } else { false }
}
}
diff --git a/apps/macos/App/SSHTunnel.swift b/apps/macos/App/SSHTunnel.swift
new file mode 100644
index 00000000..6f72df59
--- /dev/null
+++ b/apps/macos/App/SSHTunnel.swift
@@ -0,0 +1,594 @@
+import CodyncKit
+import Darwin
+import Foundation
+import Observation
+import OSLog
+
+private let log = Logger(subsystem: "com.pokai.Codync", category: "ssh")
+
+/// A computer reached over SSH (spec §11.4). Nothing secret: keys stay in ssh-agent or on disk.
+struct SSHProfile: Codable, Hashable, Identifiable, Sendable {
+ var id = UUID()
+ /// An `~/.ssh/config` alias or a hostname.
+ var host: String
+ var port: Int?
+ var user: String?
+ var identityFile: String?
+ var remotePort = 19222
+ /// Remembered after the first connection; a different computer behind the same address is refused.
+ var computerId: ComputerID?
+ var name: String
+}
+
+/// Everything that turns a profile into OpenSSH argv, and reads OpenSSH's output back.
+/// Pure functions: arguments are always an argv array, never a shell string.
+enum SSH {
+ static let ssh = URL(filePath: "/usr/bin/ssh")
+ static let keygen = URL(filePath: "/usr/bin/ssh-keygen")
+ static let keyscan = URL(filePath: "/usr/bin/ssh-keyscan")
+ static let lsof = URL(filePath: "/usr/sbin/lsof")
+ static let installCommand = "brew install leepokai/codync/codync-host && codync-host install"
+
+ static var home: String { FileManager.default.homeDirectoryForCurrentUser.path }
+
+ /// A reason the profile can't be used, or nil.
+ static func validate(_ p: SSHProfile) -> String? {
+ if p.host.hasPrefix("-") || !matches(p.host, #"^[A-Za-z0-9._-]+$"#) {
+ return "Use an SSH alias or a hostname: letters, digits, dots, dashes and underscores."
+ }
+ if let user = p.user, !matches(user, #"^[A-Za-z_][A-Za-z0-9._-]*$"#) { return "That user name isn't valid." }
+ if let port = p.port, !(1...65535).contains(port) { return "The SSH port must be between 1 and 65535." }
+ if !(1...65535).contains(p.remotePort) { return "The Codync port must be between 1 and 65535." }
+ if let file = p.identityFile {
+ var isDir: ObjCBool = false
+ guard file.hasPrefix("/"), FileManager.default.fileExists(atPath: file, isDirectory: &isDir), !isDir.boolValue else {
+ return "The key file doesn't exist."
+ }
+ }
+ return nil
+ }
+
+ static func knownHostsFiles(home: String) -> [String] {
+ ["\(home)/.ssh/known_hosts", "\(home)/.codync/ssh_known_hosts"]
+ }
+
+ /// ssh's config tokenizer splits `UserKnownHostsFile` on spaces, so each path carries literal quotes.
+ static func hostKeyOptions(home: String) -> [String] {
+ ["-o", "UserKnownHostsFile=" + knownHostsFiles(home: home).map { "\"\($0)\"" }.joined(separator: " "),
+ "-o", "StrictHostKeyChecking=yes"]
+ }
+
+ static func targetOptions(_ p: SSHProfile) -> [String] {
+ var args: [String] = []
+ if let port = p.port { args += ["-p", "\(port)"] }
+ if let key = p.identityFile { args += ["-i", key] }
+ if let user = p.user { args += ["-l", user] }
+ return args
+ }
+
+ static func resolveArguments(_ p: SSHProfile) -> [String] {
+ var args = ["-G"]
+ if let port = p.port { args += ["-p", "\(port)"] }
+ if let user = p.user { args += ["-l", user] }
+ return args + ["--", p.host]
+ }
+
+ /// The remote command is fixed; only the validated port number goes into it.
+ static func infoArguments(_ p: SSHProfile, home: String) -> [String] {
+ ["-T", "-o", "BatchMode=yes", "-o", "ConnectTimeout=10", "-o", "ForwardAgent=no", "-o", "ForwardX11=no"]
+ + hostKeyOptions(home: home) + targetOptions(p)
+ + ["--", p.host, "sh -lc 'codync-host info --json --port \(p.remotePort)'"]
+ }
+
+ static func tunnelArguments(_ p: SSHProfile, localPort: Int, home: String) -> [String] {
+ ["-N", "-T", "-o", "ExitOnForwardFailure=yes", "-o", "ServerAliveInterval=15", "-o", "ServerAliveCountMax=3",
+ "-o", "ForwardAgent=no", "-o", "ForwardX11=no", "-o", "BatchMode=yes"]
+ + hostKeyOptions(home: home)
+ + ["-L", "127.0.0.1:\(localPort):127.0.0.1:\(p.remotePort)"]
+ + targetOptions(p) + ["--", p.host]
+ }
+
+ /// What `ssh -G` resolved the destination to.
+ struct Resolved: Equatable, Sendable {
+ var hostname: String
+ var port: Int
+ var hostKeyAlias: String?
+ var proxyJump: String?
+ var proxyCommand: String?
+
+ var usesProxy: Bool { proxyJump != nil || proxyCommand != nil }
+ /// The name ssh looks up in known_hosts.
+ var knownHostsName: String {
+ let name = hostKeyAlias ?? hostname
+ return port == 22 ? name : "[\(name)]:\(port)"
+ }
+ }
+
+ static func parseConfig(_ text: String) -> Resolved? {
+ var values: [String: String] = [:]
+ for line in text.split(whereSeparator: \.isNewline) {
+ let parts = line.split(separator: " ", maxSplits: 1)
+ guard parts.count == 2 else { continue }
+ let key = parts[0].lowercased()
+ if values[key] == nil { values[key] = String(parts[1]).trimmingCharacters(in: .whitespaces) }
+ }
+ func set(_ key: String) -> String? { values[key].flatMap { $0.isEmpty || $0 == "none" ? nil : $0 } }
+ guard let hostname = set("hostname"), let port = values["port"].flatMap(Int.init) else { return nil }
+ return Resolved(hostname: hostname, port: port, hostKeyAlias: set("hostkeyalias"),
+ proxyJump: set("proxyjump"), proxyCommand: set("proxycommand"))
+ }
+
+ static func keyscanArguments(_ r: Resolved) -> [String] {
+ ["-T", "5", "-p", "\(r.port)", "--", r.hostname]
+ }
+
+ /// `type key` of each host key line (known_hosts or ssh-keyscan output); comments and revoked keys skipped.
+ static func hostKeys(_ text: String) -> Set<String> {
+ Set(text.split(whereSeparator: \.isNewline).compactMap { line in
+ var fields = line.split(whereSeparator: \.isWhitespace)
+ guard let first = fields.first, !first.hasPrefix("#") else { return nil }
+ if first.hasPrefix("@") {
+ guard first == "@cert-authority" else { return nil }
+ fields.removeFirst()
+ }
+ return fields.count >= 3 ? "\(fields[1]) \(fields[2])" : nil
+ })
+ }
+
+ /// ssh-keyscan's lines, filed under the name ssh will look up.
+ static func knownHostsLines(scan: String, name: String) -> [String] {
+ hostKeys(scan).sorted().map { "\(name) \($0)" }
+ }
+
+ private static func matches(_ s: String, _ pattern: String) -> Bool {
+ s.range(of: pattern, options: .regularExpression) != nil
+ }
+
+ #if DEBUG
+ /// Runs at launch in debug builds (spec §11.5).
+ static func selfCheck() {
+ let home = "/Users/k"
+ let p = SSHProfile(host: "box", port: 2222, user: "kevin", name: "Box")
+ assert(hostKeyOptions(home: home) == [
+ "-o", #"UserKnownHostsFile="/Users/k/.ssh/known_hosts" "/Users/k/.codync/ssh_known_hosts""#,
+ "-o", "StrictHostKeyChecking=yes",
+ ])
+ assert(resolveArguments(p) == ["-G", "-p", "2222", "-l", "kevin", "--", "box"])
+ assert(Array(tunnelArguments(p, localPort: 50000, home: home).suffix(8))
+ == ["-L", "127.0.0.1:50000:127.0.0.1:19222", "-p", "2222", "-l", "kevin", "--", "box"])
+ assert(infoArguments(p, home: home).last == "sh -lc 'codync-host info --json --port 19222'")
+ assert(tunnelArguments(p, localPort: 1, home: home).contains("ExitOnForwardFailure=yes"))
+ assert(validate(p) == nil)
+ assert(validate(SSHProfile(host: "-oProxyCommand=x", name: "")) != nil)
+ assert(validate(SSHProfile(host: "a b", name: "")) != nil)
+ assert(validate(SSHProfile(host: "box;rm", name: "")) != nil)
+ assert(validate(SSHProfile(host: "box", user: "1x", name: "")) != nil)
+ assert(validate(SSHProfile(host: "box", port: 0, name: "")) != nil)
+ assert(validate(SSHProfile(host: "box", identityFile: "/nonexistent/key", name: "")) != nil)
+ let config = "user kevin\nhostname 10.0.0.5\nport 2222\nhostkeyalias devbox\nproxycommand none\n"
+ let r = parseConfig(config)
+ assert(r == Resolved(hostname: "10.0.0.5", port: 2222, hostKeyAlias: "devbox", proxyJump: nil, proxyCommand: nil))
+ assert(r?.knownHostsName == "[devbox]:2222")
+ assert(parseConfig("hostname box\nport 22\nproxyjump gw\n")?.knownHostsName == "box")
+ assert(parseConfig("hostname box\nport 22\nproxyjump gw\n")?.usesProxy == true)
+ let scan = "# box:22 SSH-2.0\nbox ssh-ed25519 AAAA1\n[box]:22 ecdsa-sha2-nistp256 BBBB\n"
+ assert(hostKeys(scan) == ["ssh-ed25519 AAAA1", "ecdsa-sha2-nistp256 BBBB"])
+ assert(hostKeys("@revoked box ssh-ed25519 AAAA1\n").isEmpty)
+ assert(knownHostsLines(scan: scan, name: "[devbox]:2222")
+ == ["[devbox]:2222 ecdsa-sha2-nistp256 BBBB", "[devbox]:2222 ssh-ed25519 AAAA1"])
+ }
+ #endif
+}
+
+struct ProcessResult: Sendable {
+ var status: Int32
+ var stdout: Data
+ var stderr: String
+ var text: String { String(decoding: stdout, as: UTF8.self) }
+ /// The last thing the tool said, for showing next to an error.
+ var detail: String {
+ stderr.split(whereSeparator: \.isNewline).last.map(String.init) ?? ""
+ }
+}
+
+enum ProcessRunner {
+ /// Runs a tool to completion; both pipes are drained while it runs.
+ static func run(_ executable: URL, _ args: [String], input: Data? = nil) async -> ProcessResult {
+ let process = Process()
+ process.executableURL = executable
+ process.arguments = args
+ let out = Pipe()
+ let err = Pipe()
+ let inPipe = Pipe()
+ process.standardOutput = out
+ process.standardError = err
+ process.standardInput = input == nil ? FileHandle.nullDevice : inPipe
+ let outHandle = out.fileHandleForReading
+ let errHandle = err.fileHandleForReading
+ async let stdout = Task.detached { outHandle.readDataToEndOfFile() }.value
+ async let stderr = Task.detached { errHandle.readDataToEndOfFile() }.value
+ let status: Int32 = await withCheckedContinuation { cont in
+ process.terminationHandler = { cont.resume(returning: $0.terminationStatus) }
+ do {
+ try process.run()
+ } catch {
+ process.terminationHandler = nil
+ try? out.fileHandleForWriting.close()
+ try? err.fileHandleForWriting.close()
+ cont.resume(returning: -1)
+ return
+ }
+ if let input {
+ inPipe.fileHandleForWriting.write(input)
+ try? inPipe.fileHandleForWriting.close()
+ }
+ }
+ return await ProcessResult(status: status, stdout: stdout, stderr: String(decoding: stderr, as: UTF8.self))
+ }
+}
+
+/// What `codync-host info --json` prints.
+private struct RemoteInfo: Decodable {
+ var name: String
+ var computerId: ComputerID
+ var signKey: String
+ var boxKey: String?
+ var version: String?
+ var token: String
+ var running: Bool
+}
+
+/// `GET /health` on a loopback host.
+struct HostHealth: Decodable {
+ var hostId: String?
+ var computerId: ComputerID?
+ var version: String?
+
+ static func fetch(_ baseURL: URL, timeout: TimeInterval = 2) async -> HostHealth? {
+ var request = URLRequest(url: baseURL.appending(path: "health"))
+ request.timeoutInterval = timeout
+ guard let (data, response) = try? await URLSession.shared.data(for: request),
+ (response as? HTTPURLResponse)?.statusCode == 200 else { return nil }
+ return try? JSONDecoder().decode(HostHealth.self, from: data)
+ }
+}
+
+/// SSH computers: profiles (UserDefaults), host key checks and one OpenSSH tunnel per connected profile.
+/// Connected ones are handed to the account as loopback computers.
+@MainActor
+@Observable
+final class SSHComputers {
+ enum Status: Equatable {
+ case idle
+ case connecting(String)
+ /// First time: the user compares these fingerprints before anything connects.
+ case confirmHostKey(name: String, fingerprints: [String], lines: [String])
+ case connected(localPort: Int)
+ /// A retry is scheduled.
+ case retrying(String)
+ /// Needs the user (settings, the remote side, or a security problem); nothing retries.
+ case failed(String)
+ case notInstalled
+ }
+
+ struct Attachment {
+ var computer: Computer
+ var baseURL: URL
+ var token: String
+ }
+
+ private static let defaultsKey = "sshProfiles"
+
+ private(set) var profiles: [SSHProfile] = []
+ private(set) var status: [UUID: Status] = [:]
+ private(set) var attachments: [UUID: Attachment] = [:]
+
+ var onAttach: ((Attachment) -> Void)?
+ var onDetach: ((ComputerID) -> Void)?
+
+ private var tunnels: [UUID: Process] = [:]
+ private var tasks: [UUID: Task<Void, Never>] = [:]
+ private var backoff: [UUID: Double] = [:]
+ private var connectedAt: [UUID: Date] = [:]
+
+ init() {
+ profiles = UserDefaults.standard.data(forKey: Self.defaultsKey)
+ .flatMap { try? JSONDecoder().decode([SSHProfile].self, from: $0) } ?? []
+ }
+
+ func status(of id: UUID) -> Status { status[id] ?? .idle }
+
+ func connectAll() {
+ for p in profiles where tasks[p.id] == nil && tunnels[p.id] == nil { connect(p.id) }
+ }
+
+ func add(_ profile: SSHProfile) {
+ profiles.append(profile)
+ persist()
+ connect(profile.id)
+ }
+
+ func update(_ profile: SSHProfile) {
+ guard let i = profiles.firstIndex(where: { $0.id == profile.id }) else { return }
+ disconnect(profile.id)
+ profiles[i] = profile
+ persist()
+ connect(profile.id)
+ }
+
+ func remove(_ id: UUID) {
+ disconnect(id)
+ profiles.removeAll { $0.id == id }
+ status[id] = nil
+ backoff[id] = nil
+ persist()
+ }
+
+ func connect(_ id: UUID) {
+ tasks[id]?.cancel()
+ tasks[id] = Task { [weak self] in await self?.run(id) }
+ }
+
+ /// Ends the tunnel for this session (bots on it go away until the next connect).
+ func disconnect(_ id: UUID) {
+ tasks.removeValue(forKey: id)?.cancel()
+ stopTunnel(id)
+ status[id] = .idle
+ }
+
+ func disconnectAll() {
+ for id in Array(tunnels.keys) + Array(tasks.keys) { disconnect(id) }
+ }
+
+ /// The user compared the fingerprints: remember the key in Codync's known_hosts and go on.
+ func trustHostKey(_ id: UUID) {
+ guard case let .confirmHostKey(_, _, lines) = status(of: id) else { return }
+ do {
+ let dir = URL(filePath: SSH.home).appending(path: ".codync")
+ try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])
+ let file = dir.appending(path: "ssh_known_hosts")
+ if !FileManager.default.fileExists(atPath: file.path) {
+ FileManager.default.createFile(atPath: file.path, contents: nil, attributes: [.posixPermissions: 0o600])
+ }
+ let handle = try FileHandle(forWritingTo: file)
+ defer { try? handle.close() }
+ try handle.seekToEnd()
+ try handle.write(contentsOf: Data((lines.joined(separator: "\n") + "\n").utf8))
+ } catch {
+ status[id] = .failed("Couldn't save the host key: \(error.localizedDescription)")
+ return
+ }
+ connect(id)
+ }
+
+ // MARK: connecting
+
+ private enum Outcome {
+ case attached
+ case stop(Status)
+ case retry(String)
+ }
+
+ private func run(_ id: UUID) async {
+ while !Task.isCancelled {
+ guard let profile = profiles.first(where: { $0.id == id }) else { return }
+ let outcome = await attach(profile)
+ // Disconnected or replaced meanwhile: the newer task owns the state now.
+ guard !Task.isCancelled else { return }
+ switch outcome {
+ case .attached:
+ backoff[id] = nil
+ tasks[id] = nil
+ return
+ case let .stop(final):
+ status[id] = final
+ tasks[id] = nil
+ return
+ case let .retry(message):
+ let delay = backoff[id] ?? 1
+ backoff[id] = min(delay * 2, 30)
+ status[id] = .retrying(message)
+ // Full jitter, like the device relay backoff.
+ try? await Task.sleep(for: .seconds(Double.random(in: 0.5...max(0.5, delay))))
+ }
+ }
+ }
+
+ private func attach(_ profile: SSHProfile) async -> Outcome {
+ let id = profile.id
+ if let problem = SSH.validate(profile) { return .stop(.failed(problem)) }
+ status[id] = .connecting("Reading SSH settings…")
+ let config = await ProcessRunner.run(SSH.ssh, SSH.resolveArguments(profile))
+ guard !Task.isCancelled else { return .stop(.idle) }
+ guard config.status == 0, let resolved = SSH.parseConfig(config.text) else {
+ return .stop(.failed("SSH couldn't read the settings for \(profile.host). \(config.detail)"))
+ }
+
+ // Host key (never by reading ssh's error text).
+ let recorded = await recordedKeys(resolved.knownHostsName)
+ if recorded.isEmpty {
+ if resolved.usesProxy {
+ return .stop(.failed("\(profile.host) goes through a jump host. Connect once with ssh in Terminal to confirm its host key, then try again."))
+ }
+ status[id] = .connecting("Reading the host key…")
+ let scan = await ProcessRunner.run(SSH.keyscan, SSH.keyscanArguments(resolved))
+ let lines = SSH.knownHostsLines(scan: scan.text, name: resolved.knownHostsName)
+ guard !lines.isEmpty else { return .retry("Can't reach \(resolved.hostname):\(resolved.port).") }
+ let prints = await ProcessRunner.run(SSH.keygen, ["-l", "-f", "-"], input: Data((lines.joined(separator: "\n") + "\n").utf8))
+ let fingerprints = prints.text.split(whereSeparator: \.isNewline).map(String.init)
+ guard prints.status == 0, !fingerprints.isEmpty else { return .stop(.failed("Couldn't read the host key of \(profile.host).")) }
+ return .stop(.confirmHostKey(name: resolved.knownHostsName, fingerprints: fingerprints, lines: lines))
+ }
+
+ status[id] = .connecting("Signing in…")
+ let result = await ProcessRunner.run(SSH.ssh, SSH.infoArguments(profile, home: SSH.home))
+ guard !Task.isCancelled else { return .stop(.idle) }
+ if result.status == 255 {
+ if !resolved.usesProxy {
+ let scan = await ProcessRunner.run(SSH.keyscan, SSH.keyscanArguments(resolved))
+ let current = SSH.hostKeys(scan.text)
+ if !current.isEmpty, current.isDisjoint(with: recorded) {
+ return .stop(.failed("The host key of \(profile.host) changed. This can mean someone is intercepting the connection. Codync won't connect until the old key is removed from known_hosts."))
+ }
+ }
+ return .retry("SSH couldn't connect to \(profile.host). \(result.detail)")
+ }
+ if result.status == 127 { return .stop(.notInstalled) }
+ guard let info = try? JSONDecoder().decode(RemoteInfo.self, from: result.stdout) else {
+ if result.status == 0 { return .stop(.notInstalled) }
+ return .stop(.failed("codync-host on \(profile.host) couldn't report its identity. Run `codync-host install` there. \(result.detail)"))
+ }
+ let computer = Computer(id: info.computerId, name: info.name, signKey: info.signKey, boxKey: info.boxKey)
+ guard computer.isConsistent else { return .stop(.failed("\(profile.host) reported an invalid identity.")) }
+ if let known = profile.computerId, known != info.computerId {
+ return .stop(.failed("\(profile.host) is now a different computer than the one saved. If it was reinstalled, remove it and add it again."))
+ }
+ if profile.computerId == nil { remember(info.computerId, name: info.name, for: id) }
+ guard info.running else {
+ return .retry("codync-host is installed on \(info.name) but not running. Run `codync-host install` there.")
+ }
+
+ // Tunnel: a free loopback port each attempt; a port taken in between just makes ssh exit (ExitOnForwardFailure).
+ var lastProblem = ""
+ for _ in 0..<3 {
+ guard let port = Self.freeLocalPort() else { return .retry("No free local port for the tunnel.") }
+ status[id] = .connecting("Opening the tunnel…")
+ let process: Process
+ let errPipe = Pipe()
+ do {
+ process = try startTunnel(profile, localPort: port, stderr: errPipe)
+ } catch {
+ return .stop(.failed("Couldn't start ssh: \(error.localizedDescription)"))
+ }
+ let baseURL = URL(string: "http://127.0.0.1:\(port)")!
+ var health: HostHealth?
+ for _ in 0..<60 where process.isRunning && !Task.isCancelled {
+ if let h = await HostHealth.fetch(baseURL, timeout: 1) {
+ health = h
+ break
+ }
+ try? await Task.sleep(for: .milliseconds(250))
+ }
+ guard !Task.isCancelled else {
+ process.terminate()
+ return .stop(.idle)
+ }
+ guard let health else {
+ // Only read ssh's message once it exited: reading a live pipe would block.
+ if process.isRunning {
+ process.terminate()
+ } else {
+ let err = String(decoding: errPipe.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self)
+ lastProblem = err.split(whereSeparator: \.isNewline).last.map(String.init) ?? ""
+ }
+ continue
+ }
+ guard health.computerId == info.computerId else {
+ process.terminate()
+ return .stop(.failed("The tunnel to \(profile.host) reached a different computer than expected."))
+ }
+ // /health is public, so the answer alone doesn't prove it came through ssh: another
+ // local user could have taken the port. Only a listener ssh owns gets the token.
+ guard await Self.sshListens(pid: process.processIdentifier, port: port), process.isRunning else {
+ log.error("tunnel port \(port) answered by something other than ssh")
+ process.terminate()
+ lastProblem = "Another program answered on the tunnel's local port."
+ continue
+ }
+ watch(process, id: id, stderr: errPipe)
+ tunnels[id] = process
+ connectedAt[id] = .now
+ status[id] = .connected(localPort: port)
+ let attachment = Attachment(computer: computer, baseURL: baseURL, token: info.token)
+ attachments[id] = attachment
+ onAttach?(attachment)
+ return .attached
+ }
+ return .retry("Couldn't open the tunnel to \(profile.host). \(lastProblem)")
+ }
+
+ private func recordedKeys(_ name: String) async -> Set<String> {
+ var keys = Set<String>()
+ for file in SSH.knownHostsFiles(home: SSH.home) where FileManager.default.fileExists(atPath: file) {
+ let found = await ProcessRunner.run(SSH.keygen, ["-F", name, "-f", file])
+ if found.status == 0 { keys.formUnion(SSH.hostKeys(found.text)) }
+ }
+ return keys
+ }
+
+ private func startTunnel(_ profile: SSHProfile, localPort: Int, stderr: Pipe) throws -> Process {
+ let process = Process()
+ process.executableURL = SSH.ssh
+ process.arguments = SSH.tunnelArguments(profile, localPort: localPort, home: SSH.home)
+ process.standardInput = FileHandle.nullDevice
+ process.standardOutput = FileHandle.nullDevice
+ process.standardError = stderr
+ try process.run()
+ return process
+ }
+
+ /// A tunnel that drops is reopened with backoff (reset once it stayed up a minute).
+ private func watch(_ process: Process, id: UUID, stderr: Pipe) {
+ let handle = stderr.fileHandleForReading
+ process.terminationHandler = { [weak self] _ in
+ let detail = String(decoding: handle.readDataToEndOfFile(), as: UTF8.self)
+ .split(whereSeparator: \.isNewline).last.map(String.init) ?? ""
+ Task { @MainActor [weak self] in self?.tunnelEnded(id, detail: detail) }
+ }
+ }
+
+ private func tunnelEnded(_ id: UUID, detail: String) {
+ guard tunnels[id] != nil else { return }
+ log.info("ssh tunnel ended: \(detail, privacy: .public)")
+ if let since = connectedAt[id], Date.now.timeIntervalSince(since) >= 60 { backoff[id] = nil }
+ stopTunnel(id)
+ status[id] = .retrying("The SSH connection dropped. \(detail)")
+ connect(id)
+ }
+
+ private func stopTunnel(_ id: UUID) {
+ if let process = tunnels.removeValue(forKey: id) {
+ process.terminationHandler = nil
+ process.terminate()
+ }
+ connectedAt[id] = nil
+ if let attachment = attachments.removeValue(forKey: id) { onDetach?(attachment.computer.id) }
+ }
+
+ private func remember(_ computerId: ComputerID, name: String, for id: UUID) {
+ guard let i = profiles.firstIndex(where: { $0.id == id }) else { return }
+ profiles[i].computerId = computerId
+ if profiles[i].name.isEmpty { profiles[i].name = name }
+ persist()
+ }
+
+ private func persist() {
+ if let data = try? JSONEncoder().encode(profiles) { UserDefaults.standard.set(data, forKey: Self.defaultsKey) }
+ }
+
+ /// Whether process `pid` holds the listening socket on 127.0.0.1:`port`.
+ nonisolated static func sshListens(pid: Int32, port: Int) async -> Bool {
+ let found = await ProcessRunner.run(SSH.lsof, ["-a", "-n", "-P", "-p", String(pid), "[email protected]:\(port)", "-sTCP:LISTEN", "-t"])
+ return found.status == 0 && found.text.split(whereSeparator: \.isNewline).contains(Substring(String(pid)))
+ }
+
+ /// Binds port 0 on loopback to learn a free port.
+ nonisolated static func freeLocalPort() -> Int? {
+ let fd = socket(AF_INET, SOCK_STREAM, 0)
+ guard fd >= 0 else { return nil }
+ defer { close(fd) }
+ var addr = sockaddr_in()
+ addr.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
+ addr.sin_family = sa_family_t(AF_INET)
+ addr.sin_port = 0
+ addr.sin_addr.s_addr = inet_addr("127.0.0.1")
+ var len = socklen_t(MemoryLayout<sockaddr_in>.size)
+ let bound = withUnsafeMutablePointer(to: &addr) { ptr in
+ ptr.withMemoryRebound(to: sockaddr.self, capacity: 1) { sa in
+ bind(fd, sa, len) == 0 && getsockname(fd, sa, &len) == 0
+ }
+ }
+ guard bound else { return nil }
+ return Int(UInt16(bigEndian: addr.sin_port))
+ }
+}
diff --git a/apps/macos/Resources/ClerkConfig.plist b/apps/macos/Resources/AccountConfig.plist
similarity index 68%
rename from apps/macos/Resources/ClerkConfig.plist
rename to apps/macos/Resources/AccountConfig.plist
index 400a55f7..54f36659 100644
--- a/apps/macos/Resources/ClerkConfig.plist
+++ b/apps/macos/Resources/AccountConfig.plist
@@ -2,7 +2,9 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
- <key>publishableKey</key>
+ <key>clerkPublishableKey</key>
<string>pk_test_c3VubnktbW9sbHVzay04NjUxLmNsZXJrLmFjY291bnRzLmRldiQ</string>
+ <key>cloudURL</key>
+ <string>https://codync-cloud-staging.kevin2005ha.workers.dev</string>
</dict>
</plist>
diff --git a/apps/macos/Views/ChatWindow.swift b/apps/macos/Views/ChatWindow.swift
index 376c49ac..906d8037 100644
--- a/apps/macos/Views/ChatWindow.swift
+++ b/apps/macos/Views/ChatWindow.swift
@@ -9,8 +9,8 @@ struct ChatWindow: View {
var body: some View {
Group {
- if let store = host.store {
- ChatSplitView().environment(store)
+ if host.state == .running || !host.accounts.computers.isEmpty {
+ ChatSplitView().id(host.contextID)
} else {
ContentUnavailableView(
"Codync host isn't running",
@@ -23,21 +23,42 @@ struct ChatWindow: View {
.background(Palette.background)
.tint(Palette.accent)
.ignoresSafeArea(.container, edges: .top)
+ // Approving a device: the code the device shows must match (spec §4.2 B).
+ // It closes when the request is decided or put off (both change `currentApproval`).
+ .sheet(item: Binding(get: { host.currentApproval }, set: { _ in })) {
+ ApprovalSheet(approval: $0)
+ }
}
}
+/// A bot together with the store of the computer it lives on.
+@MainActor
+private struct BotTarget {
+ let bot: Bot
+ let store: BotStore
+}
+
+private struct EditTarget: Identifiable {
+ let request: EditorRequest
+ let store: BotStore
+ var id: UUID { request.id }
+}
+
private struct ChatSplitView: View {
- @Environment(BotStore.self) private var model
+ @Environment(HostController.self) private var host
@Environment(AccountSession.self) private var account
- @State private var editing: EditorRequest?
- @State private var confirmDelete: Bot?
- @State private var contextBot: Bot?
+ @State private var editing: EditTarget?
+ @State private var confirmDelete: BotTarget?
+ @State private var contextBot: BotTarget?
@State private var contextPoint = CGPoint.zero
- @State private var newSessionBot: Bot?
+ @State private var newSessionBot: BotTarget?
@State private var composing = false
- @State private var previousSelection: String?
- @State private var hoveredBot: String?
- @State private var showPlugins = false
+ /// The computer a new chat goes to.
+ @State private var composeComputer: ComputerID?
+ @State private var previousSelection: BotReference?
+ @State private var hoveredBot: BotReference?
+ @State private var marketplace: ComputerID?
+ @State private var showComputers = false
@State private var search = ""
@State private var showUsage = false
@State private var showAccount = false
@@ -53,6 +74,23 @@ private struct ChatSplitView: View {
private var sheetHeight: CGFloat { max(420, windowSize.height - 76) }
+ private var accounts: AccountStore { host.accounts }
+ /// Every computer with a store, in the account's order.
+ private var stores: [BotStore] { accounts.computers.compactMap { accounts.store(for: $0.id) } }
+ private var onlineStores: [BotStore] { stores.filter { $0.connection == .online } }
+ private var selectedStore: BotStore? { accounts.selection.flatMap { accounts.store(for: $0.computerId) } }
+ private var composeStore: BotStore? { composeComputer.flatMap { accounts.store(for: $0) } }
+ private var showsComputers: Bool { stores.count > 1 && !compact }
+
+ private func ref(_ bot: Bot, _ store: BotStore) -> BotReference {
+ BotReference(accountId: accounts.accountId, computerId: store.computer.id, botId: bot.id)
+ }
+
+ /// Kit views (new chat, bot editor) select a new bot on their own store; that becomes the account's selection.
+ private var storeSelection: BotReference? {
+ stores.lazy.compactMap { store in store.selection.map { BotReference(accountId: accounts.accountId, computerId: store.computer.id, botId: $0) } }.first
+ }
+
var body: some View {
HStack(spacing: 0) {
VStack(spacing: 0) {
@@ -63,7 +101,7 @@ private struct ChatSplitView: View {
.buttonStyle(.plain)
.help("New chat (⌘N)")
.keyboardShortcut("n")
- .disabled(model.connection != .online)
+ .disabled(onlineStores.isEmpty)
}
.padding(.leading, compact ? 0 : 80)
.padding(.trailing, 18)
@@ -73,63 +111,40 @@ private struct ChatSplitView: View {
.accessibilityHidden(compact)
ScrollView {
LazyVStack(spacing: 2) {
- ForEach(filteredBots) { bot in
- Button {
- model.selection = bot.id
- } label: {
- BotRow(bot: bot, compact: compact)
- .padding(.horizontal, compact ? 0 : 8)
- .frame(maxWidth: .infinity, alignment: .leading)
- .background(
- model.selection == bot.id
- ? Palette.bubbleUser : hoveredBot == bot.id ? Palette.bubbleAgent : Color.clear,
- in: RoundedRectangle(cornerRadius: 10)
- )
- .contentShape(Rectangle())
- }
- .buttonStyle(.plain)
- .accessibilityLabel(bot.name)
- .accessibilityAddTraits(model.selection == bot.id ? .isSelected : [])
- .help(bot.name)
- .onHover { hoveredBot = $0 ? bot.id : nil }
- .overlay {
- GeometryReader { geometry in
- SecondaryClickCapture { point in
- let frame = geometry.frame(in: .named("chat-window"))
- contextPoint = CGPoint(x: frame.minX + point.x, y: frame.minY + point.y)
- contextBot = bot
- }
- }
- }
- .accessibilityAction(named: "Conversation actions") {
- contextPoint = CGPoint(x: compact ? 64 : sidebarWidth - 24, y: 100)
- contextBot = bot
+ ForEach(stores, id: \.computer.id) { store in
+ let bots = filteredBots(store)
+ if showsComputers && !(bots.isEmpty && !search.isEmpty) {
+ ComputerHeader(store: store, ssh: host.isSSH(store.computer.id))
}
+ ForEach(bots) { bot in row(bot, store) }
}
}
.padding(.horizontal, 12)
.padding(.top, 4)
}
.onMoveCommand { direction in
- guard direction == .up || direction == .down, !filteredBots.isEmpty else { return }
- let current = filteredBots.firstIndex { $0.id == model.selection } ?? -1
- let next = direction == .down ? min(current + 1, filteredBots.count - 1) : max(current - 1, 0)
- model.selection = filteredBots[next].id
+ let refs = stores.flatMap { store in filteredBots(store).map { ref($0, store) } }
+ guard direction == .up || direction == .down, !refs.isEmpty else { return }
+ let current = refs.firstIndex { $0 == accounts.selection } ?? -1
+ let next = direction == .down ? min(current + 1, refs.count - 1) : max(current - 1, 0)
+ accounts.selection = refs[next]
}
.scrollContentBackground(.hidden)
.background(Palette.surface)
.safeAreaInset(edge: .top, spacing: 0) {
if !compact {
- VStack(spacing: 0) {
+ VStack(spacing: 4) {
searchField
- ConnectionBanner().padding(.horizontal, 12)
+ ForEach(stores, id: \.computer.id) { store in
+ ConnectionBanner().environment(store).padding(.horizontal, 12)
+ }
}
.frame(width: sidebarWidth)
.transition(.opacity)
}
}
.overlay {
- if filteredBots.isEmpty && !compact {
+ if stores.allSatisfy({ filteredBots($0).isEmpty }) && !compact {
VStack(spacing: 8) {
Text(search.isEmpty ? "No bots yet" : "No matching bots")
.font(.system(size: 13, weight: .medium))
@@ -160,17 +175,23 @@ private struct ChatSplitView: View {
.clipped()
sidebarDivider
Group {
- if composing {
- // The To: row takes the title bar's place instead of sitting under an empty one.
- NewChatView {
- composing = false
- if model.selection == nil { model.selection = previousSelection }
+ if composing, let store = composeStore {
+ VStack(spacing: 0) {
+ if onlineStores.count > 1 { computerPicker }
+ // The To: row takes the title bar's place instead of sitting under an empty one.
+ NewChatView {
+ composing = false
+ if accounts.selection == nil { accounts.selection = previousSelection }
+ }
+ .environment(store)
+ .id(store.computer.id)
}
.ignoresSafeArea(.container, edges: .top)
- } else if let id = model.selection, model.bots[id] != nil {
- ThreadView(botId: id)
- .id(id)
+ } else if let ref = accounts.selection, let store = selectedStore, store.bots[ref.botId] != nil {
+ ThreadView(botId: ref.botId)
+ .environment(store)
+ .id(ref)
.transition(.asymmetric(insertion: .opacity, removal: .identity))
} else {
VStack(spacing: 14) {
@@ -191,6 +212,7 @@ private struct ChatSplitView: View {
.padding(.vertical, 9)
.background(Palette.accentFill, in: Capsule())
.foregroundStyle(Palette.onAccent)
+ .disabled(onlineStores.isEmpty)
}
.padding(32)
.frame(maxWidth: .infinity, maxHeight: .infinity)
@@ -220,15 +242,17 @@ private struct ChatSplitView: View {
onAuthenticate: {
dismissAccountMenu()
Task {
- if account.isSignedIn { await account.signOut() }
+ if account.isSignedIn { await host.signOut() }
else { await account.signIn() }
if account.errorMessage != nil { showAccount = true }
}
},
compact: compact,
- usage: model.usage.providers.flatMap(\.windows).map(\.percent).max(),
+ usage: stores.flatMap(\.usage.providers).flatMap(\.windows).map(\.percent).max(),
+ approvals: host.approvals.count,
onDismiss: dismissAccountMenu,
onUsage: { dismissAccountMenu(); showUsage = true },
+ onComputers: { dismissAccountMenu(); showComputers = true },
onToggleSidebar: {
dismissAccountMenu()
compact.toggle()
@@ -250,7 +274,7 @@ private struct ChatSplitView: View {
.onTapGesture { contextBot = nil }
.accessibilityLabel("Dismiss conversation menu")
.accessibilityAddTraits(.isButton)
- DesktopActionMenu(items: botActions(bot), onDismiss: { contextBot = nil })
+ DesktopActionMenu(items: botActions(bot.bot, bot.store), onDismiss: { contextBot = nil })
.frame(width: 260)
.offset(x: min(max(8, contextPoint.x), windowSize.width - 268),
y: min(max(8, contextPoint.y), max(8, windowSize.height - 344)))
@@ -260,15 +284,23 @@ private struct ChatSplitView: View {
}
.animation(Motion.reduced(Motion.fade, reduceMotion), value: showAccount)
.ignoresSafeArea(.container, edges: .top)
- .sheet(item: $editing) { request in
- NavigationStack { BotEditorView(draft: request.draft) }
+ .sheet(item: $editing) { target in
+ NavigationStack { BotEditorView(draft: target.request.draft) }
+ .environment(target.store)
.frame(width: 520, height: min(680, sheetHeight))
}
- .sheet(isPresented: $showPlugins) {
- NavigationStack {
- MarketplaceView { showPlugins = false }
+ .sheet(isPresented: Binding(get: { marketplace != nil }, set: { if !$0 { marketplace = nil } })) {
+ if let store = marketplace.flatMap(accounts.store(for:)) {
+ NavigationStack {
+ MarketplaceView { marketplace = nil }
+ }
+ .environment(store)
+ .frame(width: min(920, windowSize.width - 80), height: sheetHeight)
}
- .frame(width: min(920, windowSize.width - 80), height: sheetHeight)
+ }
+ .sheet(isPresented: $showComputers) {
+ ComputersView { showComputers = false }
+ .frame(width: 620, height: sheetHeight)
}
.sheet(isPresented: $showUsage) {
VStack(alignment: .leading, spacing: 20) {
@@ -277,10 +309,17 @@ private struct ChatSplitView: View {
Spacer()
Button("Done") { showUsage = false }.keyboardShortcut(.cancelAction)
}
- if model.usage.providers.isEmpty {
+ let withUsage = stores.filter { !$0.usage.providers.isEmpty }
+ if withUsage.isEmpty {
Text("No usage information yet.").foregroundStyle(Palette.secondary)
} else {
- UsageStrip(usage: model.usage)
+ ForEach(withUsage, id: \.computer.id) { store in
+ if stores.count > 1 {
+ Label { Text(store.hostName) } icon: { ComputerBadge(store.computer, size: 16) }
+ .font(.headline)
+ }
+ UsageStrip(usage: store.usage)
+ }
}
}
.padding(24)
@@ -306,27 +345,47 @@ private struct ChatSplitView: View {
get: { newSessionBot != nil },
set: { if !$0 { newSessionBot = nil } }
), titleVisibility: .visible) {
- if let bot = newSessionBot {
- Button("New session") { model.newSession(bot.id); newSessionBot = nil }
+ if let target = newSessionBot {
+ Button("New session") { target.store.newSession(target.bot.id); newSessionBot = nil }
}
} message: {
Text("The conversation stays here, but the agent starts with a fresh context.")
}
- .deleteBotConfirmation($confirmDelete)
- .storeErrorAlert(model)
- .animation(Motion.reduced(Motion.fade, reduceMotion), value: model.selection)
+ .confirmationDialog("Delete \(confirmDelete?.bot.name ?? "bot")?", isPresented: Binding(
+ get: { confirmDelete != nil },
+ set: { if !$0 { confirmDelete = nil } }
+ ), titleVisibility: .visible) {
+ if let target = confirmDelete {
+ Button("Delete bot and its conversation", role: .destructive) { target.store.delete(target.bot) }
+ }
+ } message: {
+ Text("Files it changed on your computer stay as they are.")
+ }
+ .alert("Something went wrong", isPresented: Binding(get: { errorMessage != nil }, set: { if !$0 { clearErrors() } })) {
+ Button("OK", role: .cancel) {}
+ } message: {
+ Text(errorMessage ?? "")
+ }
+ .animation(Motion.reduced(Motion.fade, reduceMotion), value: accounts.selection)
.animation(Motion.reduced(Motion.fade, reduceMotion), value: composing)
- .onChange(of: model.selection) { _, id in if id != nil { composing = false } }
+ .onChange(of: accounts.selection) { _, ref in if ref != nil { composing = false } }
+ .onChange(of: storeSelection) { _, ref in
+ guard let ref else { return }
+ accounts.store(for: ref.computerId)?.selection = nil
+ accounts.selection = ref
+ }
#if DEBUG
.onAppear {
- // Screenshot/UI checks: CODYNC_DEBUG_OPEN=compose | plugins | <bot name>
+ // Screenshot/UI checks: CODYNC_DEBUG_OPEN=compose | plugins | computers | <bot name>
let target = ProcessInfo.processInfo.environment["CODYNC_DEBUG_OPEN"]
if target == "compose" {
- composing = true
+ compose()
} else if target == "plugins" {
- showPlugins = true
- } else if let target, let bot = model.roster.first(where: { $0.name == target }) {
- model.selection = bot.id
+ marketplace = host.store?.computer.id
+ } else if target == "computers" {
+ showComputers = true
+ } else if let target, let item = accounts.roster.first(where: { $0.bot.name == target }) {
+ accounts.selection = item.ref
}
}
#endif
@@ -372,10 +431,10 @@ extension ChatSplitView {
}
}
- fileprivate var filteredBots: [Bot] {
+ fileprivate func filteredBots(_ store: BotStore) -> [Bot] {
let query = search.trimmingCharacters(in: .whitespacesAndNewlines)
- if compact { return model.roster }
- return model.roster.filter {
+ if compact { return store.roster }
+ return store.roster.filter {
query.isEmpty || $0.name.localizedCaseInsensitiveContains(query)
|| ($0.lastMessage?.localizedCaseInsensitiveContains(query) ?? false)
}
@@ -412,6 +471,70 @@ extension ChatSplitView {
private var localProfileName: String { "Account" }
+ private func row(_ bot: Bot, _ store: BotStore) -> some View {
+ let ref = ref(bot, store)
+ return Button {
+ accounts.selection = ref
+ } label: {
+ BotRow(bot: bot, compact: compact)
+ .environment(store)
+ .padding(.horizontal, compact ? 0 : 8)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .background(
+ accounts.selection == ref
+ ? Palette.bubbleUser : hoveredBot == ref ? Palette.bubbleAgent : Color.clear,
+ in: RoundedRectangle(cornerRadius: 10)
+ )
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ .accessibilityLabel(stores.count > 1 ? "\(bot.name), on \(store.hostName)" : bot.name)
+ .accessibilityAddTraits(accounts.selection == ref ? .isSelected : [])
+ .help(stores.count > 1 ? "\(bot.name) · \(store.hostName)" : bot.name)
+ .onHover { hoveredBot = $0 ? ref : nil }
+ .overlay {
+ GeometryReader { geometry in
+ SecondaryClickCapture { point in
+ let frame = geometry.frame(in: .named("chat-window"))
+ contextPoint = CGPoint(x: frame.minX + point.x, y: frame.minY + point.y)
+ contextBot = BotTarget(bot: bot, store: store)
+ }
+ }
+ }
+ .accessibilityAction(named: "Conversation actions") {
+ contextPoint = CGPoint(x: compact ? 64 : sidebarWidth - 24, y: 100)
+ contextBot = BotTarget(bot: bot, store: store)
+ }
+ }
+
+ /// Which computer a new chat goes to, when more than one is online.
+ fileprivate var computerPicker: some View {
+ HStack(spacing: 8) {
+ Text("On").foregroundStyle(Palette.secondary)
+ Picker("Computer", selection: Binding(get: { composeComputer ?? "" }, set: { composeComputer = $0 })) {
+ ForEach(onlineStores, id: \.computer.id) { store in
+ Text(store.hostName).tag(store.computer.id)
+ }
+ }
+ .labelsHidden()
+ .pickerStyle(.menu)
+ .fixedSize()
+ Spacer()
+ }
+ .font(.callout)
+ .padding(.horizontal, 22)
+ .padding(.top, 12)
+ }
+
+ private var errorMessage: String? {
+ accounts.lastError ?? stores.lazy.compactMap(\.lastError).first
+ }
+
+ private func clearErrors() {
+ accounts.lastError = nil
+ for store in stores { store.lastError = nil }
+ }
+
private var profileAvatar: some View {
Group {
if let url = account.avatarURL {
@@ -436,7 +559,7 @@ extension ChatSplitView {
fileprivate var sidebarFooter: some View {
VStack(spacing: 4) {
Button {
- showPlugins = true
+ marketplace = (selectedStore ?? host.store ?? onlineStores.first)?.computer.id
} label: {
HStack(spacing: 10) {
Image(systemName: "square.grid.2x2")
@@ -487,8 +610,12 @@ extension ChatSplitView {
}
fileprivate func compose() {
- if !composing { previousSelection = model.selection }
- model.selection = nil
+ // The selected bot's computer if it's online, else this Mac, else any online one.
+ let target = [selectedStore, host.store].compactMap { $0 }.first { $0.connection == .online } ?? onlineStores.first
+ guard let target else { return }
+ if !composing { previousSelection = accounts.selection }
+ composeComputer = target.computer.id
+ accounts.selection = nil
composing = true
}
@@ -509,18 +636,20 @@ extension ChatSplitView {
fileprivate var railActions: some View {
VStack(spacing: 4) {
Button("New chat", systemImage: "plus", action: compose)
- .disabled(model.connection != .online)
+ .disabled(onlineStores.isEmpty)
.help("New chat")
.labelStyle(.iconOnly)
.buttonStyle(IconButtonStyle(size: 36))
- Button("Marketplace", systemImage: "square.grid.2x2") { showPlugins = true }
+ Button("Marketplace", systemImage: "square.grid.2x2") {
+ marketplace = (selectedStore ?? host.store ?? onlineStores.first)?.computer.id
+ }
.help("Marketplace")
.labelStyle(.iconOnly)
.buttonStyle(IconButtonStyle(size: 36))
Button { showAccount.toggle() } label: {
profileAvatar
.overlay(alignment: .bottomTrailing) {
- Circle().fill(model.connection == .online ? Palette.switchOn : Palette.tertiary)
+ Circle().fill(host.store?.connection == .online ? Palette.switchOn : Palette.tertiary)
.frame(width: 7, height: 7)
.overlay(Circle().stroke(Palette.surface, lineWidth: 1.5))
}
@@ -539,20 +668,21 @@ extension ChatSplitView {
.padding(.bottom, 10)
}
- private func botActions(_ bot: Bot) -> [DesktopActionMenu.Item] {
- [
+ private func botActions(_ bot: Bot, _ model: BotStore) -> [DesktopActionMenu.Item] {
+ let target = BotTarget(bot: bot, store: model)
+ return [
.init(title: bot.pinned ? "Unpin" : "Pin", icon: "pin", action: { model.setPinned(bot, !bot.pinned) }),
.init(title: "Mark as Read", icon: "bell.badge", action: { model.markRead(bot.id) }),
.init(title: "Edit Profile…", icon: "square.and.pencil", divider: true,
- action: { editing = EditorRequest(BotDraft(bot)) }),
+ action: { editing = EditTarget(request: EditorRequest(BotDraft(bot)), store: model) }),
.init(title: "Copy conversation ID", icon: "square.on.square", divider: true, action: {
NSPasteboard.general.clearContents()
NSPasteboard.general.setString(bot.id, forType: .string)
}),
- .init(title: "New session", icon: "arrow.counterclockwise", action: { newSessionBot = bot }),
+ .init(title: "New session", icon: "arrow.counterclockwise", action: { newSessionBot = target }),
.init(title: "Hide from sidebar", icon: "eye.slash", divider: true,
action: { model.setHidden(bot, true) }),
- .init(title: "Delete", icon: "trash", destructive: true, action: { confirmDelete = bot })
+ .init(title: "Delete", icon: "trash", destructive: true, action: { confirmDelete = target })
]
}
}
@@ -573,8 +703,10 @@ private struct SidebarAccountPanel: View {
let onAuthenticate: () -> Void
let compact: Bool
let usage: Double?
+ let approvals: Int
let onDismiss: () -> Void
let onUsage: () -> Void
+ let onComputers: () -> Void
let onToggleSidebar: () -> Void
let onSearch: () -> Void
@State private var page = "main"
@@ -610,6 +742,8 @@ private struct SidebarAccountPanel: View {
return [
Item(title: "Usage", icon: "gauge.with.dots.needle.33percent",
detail: usage.map { "\(Int($0.rounded()))%" }, chevron: true, action: onUsage),
+ Item(title: "Computers & devices", icon: "desktopcomputer",
+ detail: approvals > 0 ? "\(approvals)" : nil, chevron: true, action: onComputers),
Item(title: "Get Codync for mobile", icon: "iphone", action: { open("https://apps.apple.com/app/id6760984418") }),
Item(title: "Support", icon: "book.closed", chevron: true, action: { navigate("support") }),
Item(title: "Settings", icon: "gearshape", action: { navigate("settings") }),
@@ -655,8 +789,8 @@ private struct SidebarAccountPanel: View {
}
@ViewBuilder private func menuRow(_ item: Item, index: Int) -> some View {
- if index == (page == "main" ? 4 : 1) { divider }
- if page == "main" && index == 5 { accountIdentity }
+ if index == (page == "main" ? 5 : 1) { divider }
+ if page == "main" && index == 6 { accountIdentity }
AccountPanelRow(title: item.title, icon: item.icon, detail: item.detail,
chevron: item.chevron, keyboardFocused: highlighted == index, action: item.action)
.disabled(item.disabled)
diff --git a/apps/macos/Views/ComputersView.swift b/apps/macos/Views/ComputersView.swift
new file mode 100644
index 00000000..44234137
--- /dev/null
+++ b/apps/macos/Views/ComputersView.swift
@@ -0,0 +1,601 @@
+import AppKit
+import CodyncKit
+import CodyncUI
+import SwiftUI
+import UniformTypeIdentifiers
+
+/// A computer's name over its bots in the sidebar, with how it's reached.
+struct ComputerHeader: View {
+ let store: BotStore
+ let ssh: Bool
+
+ var body: some View {
+ HStack(spacing: 6) {
+ ComputerBadge(store.computer, size: 16)
+ Text(store.hostName).font(.system(size: 11, weight: .semibold)).lineLimit(1)
+ RouteLabel(store: store, ssh: ssh)
+ Spacer()
+ if store.connection != .online {
+ Text(store.statusText).font(.system(size: 11)).foregroundStyle(store.isOffline ? Palette.warning : Palette.tertiary)
+ }
+ }
+ .foregroundStyle(Palette.secondary)
+ .padding(.horizontal, 8)
+ .padding(.top, 10)
+ .padding(.bottom, 2)
+ .accessibilityElement(children: .combine)
+ .accessibilityAddTraits(.isHeader)
+ }
+}
+
+/// How this Mac reaches a computer: itself, an SSH tunnel, direct LAN or the encrypted relay.
+struct RouteLabel: View {
+ let store: BotStore
+ let ssh: Bool
+
+ var body: some View {
+ if ssh {
+ Image(systemName: "terminal").help("Over SSH").accessibilityLabel("Over SSH")
+ } else if store.connection == .online {
+ RouteIcon(route: store.hostRoute).help(store.hostRoute == .relay ? "Through the encrypted relay" : "Direct connection")
+ }
+ }
+}
+
+// MARK: - Approval
+
+/// A device asks for access through the account (spec §4.2 B). The code is the only thing
+/// that tells a real request from a cloud swapping keys, so it's big and Approve is never the default.
+struct ApprovalSheet: View {
+ let approval: Approval
+ @Environment(HostController.self) private var host
+ @State private var busy = false
+ @State private var error: String?
+
+ private var request: AccessRequest { approval.request }
+
+ var body: some View {
+ VStack(spacing: 16) {
+ HStack {
+ Spacer()
+ IconButton("Decide later", systemImage: "xmark") { host.deferApproval(approval) }
+ }
+ Image(systemName: request.platform == "macos" ? "laptopcomputer" : "iphone")
+ .font(.system(size: 40, weight: .light))
+ .foregroundStyle(Palette.secondary)
+ .accessibilityHidden(true)
+ VStack(spacing: 4) {
+ Text("\(request.deviceName) wants to use \(approval.store.hostName)")
+ .font(.title3.weight(.semibold))
+ .multilineTextAlignment(.center)
+ if let email = request.email {
+ Text("Signed in as \(email)").font(.callout).foregroundStyle(Palette.secondary)
+ }
+ }
+ if let code = request.code {
+ Text(Self.spaced(code))
+ .font(.system(size: 48, weight: .semibold, design: .monospaced))
+ .foregroundStyle(Palette.text)
+ .textSelection(.enabled)
+ .accessibilityLabel("Code \(code.map(String.init).joined(separator: " "))")
+ Text("Approve only if \(request.deviceName) shows exactly this code. If it doesn't, deny: someone may be trying to get in.")
+ .font(.callout)
+ .foregroundStyle(Palette.secondary)
+ .multilineTextAlignment(.center)
+ .fixedSize(horizontal: false, vertical: true)
+ } else {
+ ProgressView().controlSize(.small)
+ Text("Waiting for \(request.deviceName) to show its code…")
+ .font(.callout)
+ .foregroundStyle(Palette.secondary)
+ }
+ if let error {
+ Text(error).font(.caption).foregroundStyle(Palette.danger).multilineTextAlignment(.center)
+ }
+ HStack(spacing: 12) {
+ Button("Deny", role: .destructive) { decide(false) }
+ .disabled(busy)
+ Button("Approve") { decide(true) }
+ .buttonStyle(.borderedProminent)
+ .tint(Palette.accentFill)
+ .disabled(busy || request.code == nil)
+ }
+ .controlSize(.large)
+ }
+ .padding(24)
+ .frame(width: 420)
+ }
+
+ private func decide(_ approve: Bool) {
+ busy = true
+ Task {
+ defer { busy = false }
+ do {
+ try await host.decide(approval, approve: approve)
+ // The host's accessRequests event removes it; don't wait for that to close.
+ host.deferApproval(approval)
+ } catch {
+ self.error = error.localizedDescription
+ }
+ }
+ }
+
+ private static func spaced(_ code: String) -> String {
+ code.count == 6 ? "\(code.prefix(3)) \(code.suffix(3))" : code
+ }
+}
+
+// MARK: - Computers & devices
+
+/// Computers this Mac manages (itself and SSH), with their account, relay and authorized devices;
+/// SSH profiles; and the account's other computers.
+struct ComputersView: View {
+ let close: () -> Void
+ @Environment(HostController.self) private var host
+ @Environment(AccountSession.self) private var account
+ @State private var editingSSH: SSHProfile?
+
+ var body: some View {
+ VStack(spacing: 0) {
+ HStack {
+ Text("Computers & devices").font(.title2.bold())
+ Spacer()
+ Button("Done", action: close).keyboardShortcut(.cancelAction)
+ }
+ .padding(20)
+ ScrollView {
+ VStack(alignment: .leading, spacing: 22) {
+ ForEach(host.managedStores, id: \.computer.id) { store in
+ ManagedComputerCard(store: store, ssh: host.isSSH(store.computer.id))
+ }
+ sshSection
+ accountSection
+ }
+ .padding(.horizontal, 20)
+ .padding(.bottom, 20)
+ }
+ }
+ .background(Palette.background)
+ .sheet(item: $editingSSH) { profile in
+ SSHProfileEditor(profile: profile, isNew: !host.ssh.profiles.contains { $0.id == profile.id }) { editingSSH = nil }
+ }
+ }
+
+ private var sshSection: some View {
+ VStack(alignment: .leading, spacing: 8) {
+ HStack {
+ SectionTitle("Over SSH")
+ Spacer()
+ IconButton("Add SSH computer", systemImage: "plus") {
+ editingSSH = SSHProfile(host: "", name: "")
+ }
+ }
+ if host.ssh.profiles.isEmpty {
+ Text("Run bots on another computer you reach with SSH. It needs codync-host installed; your SSH keys stay on this Mac.")
+ .font(.callout)
+ .foregroundStyle(Palette.secondary)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ ForEach(host.ssh.profiles) { profile in
+ SSHRow(profile: profile) { editingSSH = profile }
+ }
+ }
+ }
+
+ @ViewBuilder private var accountSection: some View {
+ let managed = Set(host.managedStores.map(\.computer.id))
+ let reached = host.accounts.computers.filter { !managed.contains($0.id) }
+ let others = host.accounts.cloudComputers.filter { c in !managed.contains(c.id) && !reached.contains { $0.id == c.id } }
+ VStack(alignment: .leading, spacing: 8) {
+ HStack {
+ SectionTitle("In your account")
+ Spacer()
+ if account.isSignedIn {
+ IconButton("Refresh", systemImage: "arrow.clockwise") { Task { await host.accounts.refreshCloud() } }
+ }
+ }
+ if !account.isSignedIn {
+ Text("Sign in to reach the other computers in your account from this Mac.")
+ .font(.callout).foregroundStyle(Palette.secondary)
+ } else if reached.isEmpty && others.isEmpty {
+ Text("No other computers in your account yet.").font(.callout).foregroundStyle(Palette.secondary)
+ }
+ ForEach(reached) { computer in
+ if let store = host.accounts.store(for: computer.id) {
+ HStack(spacing: 10) {
+ ComputerBadge(store.computer, size: 22)
+ VStack(alignment: .leading, spacing: 1) {
+ Text(store.hostName).font(.callout.weight(.medium))
+ Text(store.statusText).font(.caption).foregroundStyle(Palette.secondary)
+ }
+ RouteLabel(store: store, ssh: false).foregroundStyle(Palette.tertiary)
+ Spacer()
+ IconButton("Remove from this Mac", systemImage: "minus.circle") { host.accounts.forget(computer.id) }
+ }
+ .card()
+ }
+ }
+ ForEach(others) { computer in
+ AccountComputerRow(computer: computer)
+ }
+ }
+ }
+}
+
+private struct SectionTitle: View {
+ let title: String
+ init(_ title: String) { self.title = title }
+ var body: some View {
+ Text(title).font(.headline).foregroundStyle(Palette.text).accessibilityAddTraits(.isHeader)
+ }
+}
+
+/// An account computer this Mac isn't authorized on: ask, then compare the code shown there.
+private struct AccountComputerRow: View {
+ let computer: CloudComputer
+ @Environment(HostController.self) private var host
+ @State private var busy = false
+
+ var body: some View {
+ let ticket = host.accounts.pendingAccess[computer.id]
+ VStack(alignment: .leading, spacing: 8) {
+ HStack(spacing: 10) {
+ ComputerBadge(Computer(id: computer.id, name: computer.name, signKey: computer.signKey, device: computer.device), size: 22)
+ VStack(alignment: .leading, spacing: 1) {
+ Text(computer.name).font(.callout.weight(.medium))
+ Text(computer.isOnline ? "Online" : "Offline").font(.caption).foregroundStyle(Palette.secondary)
+ }
+ Spacer()
+ if ticket == nil {
+ Button(busy ? "Asking…" : "Ask for access") {
+ busy = true
+ Task {
+ defer { busy = false }
+ do { _ = try await host.accounts.requestAccess(computer.id) } catch {
+ host.accounts.lastError = error.localizedDescription
+ }
+ }
+ }
+ .disabled(busy)
+ }
+ }
+ if let ticket {
+ HStack(spacing: 12) {
+ Text(ticket.code.count == 6 ? "\(ticket.code.prefix(3)) \(ticket.code.suffix(3))" : ticket.code)
+ .font(.system(size: 26, weight: .semibold, design: .monospaced))
+ .accessibilityLabel("Code \(ticket.code.map(String.init).joined(separator: " "))")
+ Text("Approve on \(computer.name) only if it shows this code.")
+ .font(.callout).foregroundStyle(Palette.secondary)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ }
+ }
+ .card()
+ }
+}
+
+/// This Mac or an SSH computer: relay, account membership, pairing and authorized devices.
+private struct ManagedComputerCard: View {
+ let store: BotStore
+ let ssh: Bool
+ @Environment(HostController.self) private var host
+ @Environment(AccountSession.self) private var account
+ @State private var devices: [AuthorizedDevice]?
+ @State private var busy = false
+ @State private var showPairing = false
+ @State private var confirmRevoke: AuthorizedDevice?
+ @State private var confirmUnclaim = false
+
+ private var cloud: CloudStatus? { store.cloud }
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 12) {
+ HStack(spacing: 10) {
+ ComputerBadge(store.computer, size: 26)
+ VStack(alignment: .leading, spacing: 1) {
+ Text(store.hostName).font(.headline)
+ Text(ssh ? "Over SSH · \(store.statusText)" : "This Mac · \(store.statusText)")
+ .font(.caption).foregroundStyle(Palette.secondary)
+ }
+ Spacer()
+ IconButton("Pair iPhone", systemImage: "qrcode", selected: showPairing) { showPairing.toggle() }
+ .disabled(store.connection != .online)
+ .popover(isPresented: $showPairing, arrowEdge: .bottom) {
+ PairingPanel(store: store).frame(width: 300)
+ }
+ }
+
+ Toggle(isOn: Binding(get: { cloud?.enabled ?? false }, set: { on in run { await host.setCloud(store, enabled: on) } })) {
+ VStack(alignment: .leading, spacing: 1) {
+ Text("Reach from anywhere")
+ Text(cloudLine).font(.caption).foregroundStyle(cloud?.lastError == nil ? Palette.secondary : Palette.warning)
+ }
+ }
+ .toggleStyle(.switch)
+ .disabled(busy || store.connection != .online)
+
+ accountLine
+
+ VStack(alignment: .leading, spacing: 6) {
+ Text("Devices that can use \(store.hostName)").font(.subheadline.weight(.semibold))
+ if let devices {
+ if devices.isEmpty {
+ Text("None yet. Pair an iPhone, or approve one from your account.").font(.caption).foregroundStyle(Palette.secondary)
+ }
+ ForEach(devices) { device in deviceRow(device) }
+ } else {
+ ProgressView().controlSize(.small)
+ }
+ }
+ }
+ .card()
+ .task(id: "\(store.computer.id)/\(store.connection == .online)/\(store.accessRequests.count)") { await loadDevices() }
+ .confirmationDialog("Revoke \(confirmRevoke?.name ?? "device")?", isPresented: Binding(
+ get: { confirmRevoke != nil }, set: { if !$0 { confirmRevoke = nil } }
+ ), titleVisibility: .visible) {
+ if let device = confirmRevoke {
+ Button("Revoke access", role: .destructive) {
+ run {
+ do { try await store.client?.revokeDevice(device.key) } catch { host.accounts.lastError = error.localizedDescription }
+ await loadDevices()
+ }
+ }
+ }
+ } message: {
+ Text("It disconnects right away and has to pair or ask again.")
+ }
+ .confirmationDialog("Remove \(store.hostName) from the account?", isPresented: $confirmUnclaim, titleVisibility: .visible) {
+ Button("Remove from account", role: .destructive) { run { await host.unclaim(store) } }
+ } message: {
+ Text("Devices that were approved through the account lose access. Devices paired with a QR code keep it.")
+ }
+ }
+
+ private var cloudLine: String {
+ guard let cloud, cloud.enabled else { return "Off: only devices on the same network reach it." }
+ if let error = cloud.lastError { return error }
+ return cloud.connected == true ? "Connected to the encrypted relay." : "Connecting to the relay…"
+ }
+
+ @ViewBuilder private var accountLine: some View {
+ HStack(spacing: 8) {
+ if let owner = cloud?.owner {
+ Image(systemName: "person.crop.circle.badge.checkmark").foregroundStyle(Palette.secondary).accessibilityHidden(true)
+ Text(owner.userId == account.userID ? "In your account" : "In \(owner.email ?? "another") account")
+ .font(.callout)
+ Spacer()
+ Button("Remove from account") { confirmUnclaim = true }
+ .disabled(busy || store.connection != .online)
+ } else {
+ Image(systemName: "person.crop.circle.badge.plus").foregroundStyle(Palette.secondary).accessibilityHidden(true)
+ Text(account.isSignedIn ? "Not in your account" : "Sign in to add it to your account").font(.callout)
+ Spacer()
+ if account.isSignedIn {
+ Button(busy ? "Adding…" : "Add to account") { run { await host.claim(store) } }
+ .disabled(busy || store.connection != .online)
+ }
+ }
+ }
+ }
+
+ private func deviceRow(_ device: AuthorizedDevice) -> some View {
+ HStack(spacing: 8) {
+ Image(systemName: device.platform == "macos" ? "laptopcomputer" : "iphone")
+ .frame(width: 18)
+ .foregroundStyle(Palette.secondary)
+ .accessibilityHidden(true)
+ VStack(alignment: .leading, spacing: 1) {
+ Text(device.name).font(.callout)
+ Text(detail(device)).font(.caption).foregroundStyle(Palette.tertiary)
+ }
+ Spacer()
+ IconButton("Revoke access", systemImage: "xmark.circle") { confirmRevoke = device }
+ }
+ .accessibilityElement(children: .combine)
+ }
+
+ private func detail(_ device: AuthorizedDevice) -> String {
+ var parts = [device.source == "account" ? "Approved through the account" : "Paired with a QR code"]
+ if device.connected == true {
+ parts.append("connected")
+ } else if let seen = device.lastSeenAt {
+ parts.append("seen \(RelativeTime.day(Date(milliseconds: seen)))")
+ }
+ return parts.joined(separator: " · ")
+ }
+
+ private func loadDevices() async {
+ guard let client = store.client, store.connection == .online else { return }
+ devices = (try? await client.devices()) ?? devices
+ }
+
+ private func run(_ work: @escaping @MainActor () async -> Void) {
+ busy = true
+ Task {
+ await work()
+ busy = false
+ }
+ }
+}
+
+// MARK: - SSH
+
+private struct SSHRow: View {
+ let profile: SSHProfile
+ let edit: () -> Void
+ @Environment(HostController.self) private var host
+
+ var body: some View {
+ let status = host.ssh.status(of: profile.id)
+ VStack(alignment: .leading, spacing: 8) {
+ HStack(spacing: 10) {
+ Image(systemName: "terminal").frame(width: 22).foregroundStyle(Palette.secondary).accessibilityHidden(true)
+ VStack(alignment: .leading, spacing: 1) {
+ Text(profile.name.isEmpty ? profile.host : profile.name).font(.callout.weight(.medium))
+ Text(line(status)).font(.caption).foregroundStyle(isProblem(status) ? Palette.warning : Palette.secondary)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ Spacer()
+ switch status {
+ case .connected, .connecting, .retrying:
+ IconButton("Disconnect", systemImage: "stop.circle") { host.ssh.disconnect(profile.id) }
+ default:
+ IconButton("Connect", systemImage: "arrow.clockwise") { host.ssh.connect(profile.id) }
+ }
+ IconButton("Edit", systemImage: "pencil", action: edit)
+ IconButton("Remove", systemImage: "trash") { host.ssh.remove(profile.id) }
+ }
+ if case let .confirmHostKey(name, fingerprints, _) = status {
+ VStack(alignment: .leading, spacing: 6) {
+ Text("First connection to \(name). Check that its host key fingerprint matches what the computer's owner sees (`ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub`).")
+ .font(.caption).foregroundStyle(Palette.secondary)
+ .fixedSize(horizontal: false, vertical: true)
+ ForEach(fingerprints, id: \.self) { Text($0).font(.caption.monospaced()).textSelection(.enabled) }
+ HStack {
+ Button("Trust and connect") { host.ssh.trustHostKey(profile.id) }
+ Button("Cancel") { host.ssh.disconnect(profile.id) }
+ }
+ .controlSize(.small)
+ }
+ }
+ if status == .notInstalled {
+ HStack(spacing: 6) {
+ Text(SSH.installCommand)
+ .font(.caption.monospaced())
+ .textSelection(.enabled)
+ .padding(6)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .background(Palette.codeBackground, in: RoundedRectangle(cornerRadius: 6))
+ IconButton("Copy install command", systemImage: "doc.on.doc") {
+ NSPasteboard.general.clearContents()
+ NSPasteboard.general.setString(SSH.installCommand, forType: .string)
+ }
+ }
+ }
+ }
+ .card()
+ }
+
+ private func line(_ status: SSHComputers.Status) -> String {
+ let target = [profile.user.map { "\($0)@" } ?? "", profile.host, profile.port.map { ":\($0)" } ?? ""].joined()
+ switch status {
+ case .idle: return "\(target) · Not connected"
+ case let .connecting(step): return step
+ case .confirmHostKey: return "\(target) · Confirm the host key"
+ case .connected: return "\(target) · Connected"
+ case let .retrying(message): return "\(message) Retrying…"
+ case let .failed(message): return message
+ case .notInstalled: return "codync-host isn't installed on \(profile.host). Install it there:"
+ }
+ }
+
+ private func isProblem(_ status: SSHComputers.Status) -> Bool {
+ switch status {
+ case .retrying, .failed, .notInstalled: true
+ default: false
+ }
+ }
+}
+
+/// Add or change an SSH computer. Only fields ssh takes as separate arguments; nothing goes through a shell.
+private struct SSHProfileEditor: View {
+ @State var profile: SSHProfile
+ let isNew: Bool
+ let close: () -> Void
+ @Environment(HostController.self) private var host
+ @State private var port = ""
+ @State private var remotePort = ""
+ @State private var user = ""
+ @State private var chooseKey = false
+ @State private var problem: String?
+
+ init(profile: SSHProfile, isNew: Bool, close: @escaping () -> Void) {
+ _profile = State(initialValue: profile)
+ self.isNew = isNew
+ self.close = close
+ _port = State(initialValue: profile.port.map(String.init) ?? "")
+ _remotePort = State(initialValue: String(profile.remotePort))
+ _user = State(initialValue: profile.user ?? "")
+ }
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 16) {
+ Text(isNew ? "Add SSH computer" : "Edit SSH computer").font(.title3.bold())
+ Form {
+ TextField("Name", text: $profile.name, prompt: Text("Optional"))
+ TextField("Host", text: $profile.host, prompt: Text("SSH alias or hostname"))
+ TextField("User", text: $user, prompt: Text("From SSH config"))
+ TextField("SSH port", text: $port, prompt: Text("From SSH config"))
+ HStack {
+ Text("Key")
+ Spacer()
+ Text(profile.identityFile.map { URL(filePath: $0).lastPathComponent } ?? "ssh-agent / SSH config")
+ .foregroundStyle(Palette.secondary)
+ IconButton("Choose key file", systemImage: "key") { chooseKey = true }
+ if profile.identityFile != nil {
+ IconButton("Use ssh-agent", systemImage: "xmark.circle") { profile.identityFile = nil }
+ }
+ }
+ TextField("Codync port", text: $remotePort)
+ }
+ .formStyle(.grouped)
+ Text("Codync opens an SSH tunnel to codync-host on that computer's loopback. It uses your SSH config and ssh-agent; agent forwarding stays off.")
+ .font(.caption).foregroundStyle(Palette.secondary)
+ .fixedSize(horizontal: false, vertical: true)
+ if let problem {
+ Text(problem).font(.caption).foregroundStyle(Palette.danger)
+ }
+ HStack {
+ Spacer()
+ Button("Cancel", action: close).keyboardShortcut(.cancelAction)
+ Button(isNew ? "Add" : "Save", action: save).keyboardShortcut(.defaultAction)
+ }
+ }
+ .padding(20)
+ .frame(width: 460)
+ .fileImporter(isPresented: $chooseKey, allowedContentTypes: [.item]) { result in
+ if case let .success(url) = result { profile.identityFile = url.path }
+ }
+ }
+
+ private func save() {
+ var p = profile
+ p.host = p.host.trimmingCharacters(in: .whitespaces)
+ p.name = p.name.trimmingCharacters(in: .whitespaces)
+ let u = user.trimmingCharacters(in: .whitespaces)
+ p.user = u.isEmpty ? nil : u
+ let portText = port.trimmingCharacters(in: .whitespaces)
+ if portText.isEmpty {
+ p.port = nil
+ } else if let n = Int(portText) {
+ p.port = n
+ } else {
+ problem = "The SSH port must be a number."
+ return
+ }
+ guard let remote = Int(remotePort.trimmingCharacters(in: .whitespaces)) else {
+ problem = "The Codync port must be a number."
+ return
+ }
+ p.remotePort = remote
+ if !isNew, let old = host.ssh.profiles.first(where: { $0.id == p.id }), old.host != p.host || old.port != p.port {
+ // A different address may be a different computer: learn its identity again.
+ p.computerId = nil
+ }
+ if let problem = SSH.validate(p) {
+ self.problem = problem
+ return
+ }
+ if isNew { host.ssh.add(p) } else { host.ssh.update(p) }
+ close()
+ }
+}
+
+private extension View {
+ func card() -> some View {
+ padding(12)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .background(Palette.surface, in: RoundedRectangle(cornerRadius: 12, style: .continuous))
+ .overlay(RoundedRectangle(cornerRadius: 12, style: .continuous).strokeBorder(Palette.border, lineWidth: 0.5))
+ }
+}
diff --git a/apps/shared/AccountSession.swift b/apps/shared/AccountSession.swift
index b589153c..416b9440 100644
--- a/apps/shared/AccountSession.swift
+++ b/apps/shared/AccountSession.swift
@@ -1,10 +1,11 @@
import AuthenticationServices
import ClerkKit
+import CodyncKit
import Foundation
import Observation
-/// Clerk owns OAuth, session restoration and Keychain persistence. Host pairing
-/// remains separate: an account session never grants access to a local host.
+/// Clerk owns OAuth, session restoration and Keychain persistence. An account session
+/// never grants access to a computer by itself: each one still approves this device (spec §4.2).
@MainActor
@Observable
final class AccountSession {
@@ -35,6 +36,8 @@ final class AccountSession {
var supportsMultipleAccounts: Bool { clerk?.environment?.authConfig.singleSessionMode == false }
var isConfigured: Bool { clerk != nil }
+ /// The Codync cloud (accounts and the encrypted relay); nil in builds without one.
+ let cloudURL: URL?
var isSignedIn: Bool { userID != nil }
var email: String? { clerk?.user?.primaryEmailAddress?.emailAddress }
var avatarURL: URL? {
@@ -43,11 +46,14 @@ final class AccountSession {
}
init() {
- let environmentKey = ProcessInfo.processInfo.environment["CODYNC_CLERK_PUBLISHABLE_KEY"]
- let config = Bundle.main.url(forResource: "ClerkConfig", withExtension: "plist")
+ let env = ProcessInfo.processInfo.environment
+ let config = Bundle.main.url(forResource: "AccountConfig", withExtension: "plist")
.flatMap { try? Data(contentsOf: $0) }
.flatMap { try? PropertyListDecoder().decode(Configuration.self, from: $0) }
- let key = (environmentKey ?? config?.publishableKey ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
+ cloudURL = (env["CODYNC_CLOUD_URL"] ?? config?.cloudURL)
+ .flatMap { URL(string: $0.trimmingCharacters(in: .whitespacesAndNewlines)) }
+ .flatMap { Pairing.isCloudURL($0) ? $0 : nil }
+ let key = (env["CODYNC_CLERK_PUBLISHABLE_KEY"] ?? config?.clerkPublishableKey ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
guard key.hasPrefix("pk_test_") || key.hasPrefix("pk_live_") else {
clerk = nil
return
@@ -59,6 +65,27 @@ final class AccountSession {
))
}
+ /// The signed-in session's JWT for the Codync cloud (Clerk caches it for a minute).
+ func sessionToken() async throws -> String {
+ guard let clerk, isSignedIn, let token = try await clerk.auth.getToken() else { throw SessionError.signedOut }
+ return token
+ }
+
+ /// The Codync cloud for `userID`'s context; nil when signed out or the build has no cloud.
+ /// Requests stop working once another account becomes active, so one account's calls never carry another's token.
+ func cloudClient(for userID: String?, identity: DeviceIdentity?) -> CloudClient? {
+ guard let userID, let cloudURL, isConfigured else { return nil }
+ return CloudClient(baseURL: cloudURL, identity: identity) { [weak self] in
+ guard let self, await self.userID == userID else { throw SessionError.signedOut }
+ return try await self.sessionToken()
+ }
+ }
+
+ enum SessionError: LocalizedError {
+ case signedOut
+ var errorDescription: String? { "Sign in again to reach your account." }
+ }
+
func signIn() async {
guard !isBusy else { return }
guard let clerk else {
@@ -120,7 +147,9 @@ final class AccountSession {
catch { errorMessage = "Couldn't finish signing in. Please try again." }
}
+ /// `AccountConfig.plist` (`CODYNC_CLERK_PUBLISHABLE_KEY` / `CODYNC_CLOUD_URL` override it).
private struct Configuration: Decodable {
- let publishableKey: String
+ let clerkPublishableKey: String?
+ let cloudURL: String?
}
}
diff --git a/apps/shared/ComputerStatus.swift b/apps/shared/ComputerStatus.swift
new file mode 100644
index 00000000..b3998576
--- /dev/null
+++ b/apps/shared/ComputerStatus.swift
@@ -0,0 +1,53 @@
+import CodyncKit
+import CodyncUI
+import SwiftUI
+
+extension BotStore {
+ /// One short line for a computer's connection, used next to its name.
+ var statusText: String {
+ switch connection {
+ case .online: "Online"
+ case .connecting: "Connecting…"
+ case let .computerOffline(lastSeen): lastSeen.map { "Offline · seen \(RelativeTime.day($0))" } ?? "Offline"
+ case .offline: "Can't reach"
+ case .unauthorized: "No access"
+ case .unpaired: "Not paired"
+ }
+ }
+}
+
+/// How the phone reaches a computer right now: a subtle icon, direct Wi-Fi/LAN or the encrypted relay.
+struct RouteIcon: View {
+ let route: HostRoute?
+
+ var body: some View {
+ switch route {
+ case .direct:
+ Image(systemName: "wifi").accessibilityLabel("Direct connection")
+ case .relay:
+ Image(systemName: "cloud").accessibilityLabel("Through the encrypted relay")
+ case .loopback, nil:
+ EmptyView()
+ }
+ }
+}
+
+/// "MacBook · Online ☁︎": which computer a bot lives on and how that computer is doing.
+struct ComputerCaption: View {
+ let store: BotStore
+
+ var body: some View {
+ HStack(spacing: 4) {
+ ComputerBadge(store.computer, size: 14)
+ Text(store.hostName).lineLimit(1)
+ if store.connection != .online {
+ Text("·")
+ Text(store.statusText).foregroundStyle(store.isOffline ? Palette.warning : Palette.tertiary)
+ }
+ if store.connection == .online { RouteIcon(route: store.hostRoute).imageScale(.small) }
+ }
+ .font(.caption2)
+ .foregroundStyle(Palette.tertiary)
+ .accessibilityElement(children: .combine)
+ }
+}
diff --git a/cloud/.gitignore b/cloud/.gitignore
new file mode 100644
index 00000000..8fbcf8f7
--- /dev/null
+++ b/cloud/.gitignore
@@ -0,0 +1,3 @@
+node_modules/
+.wrangler/
+.dev.vars*
diff --git a/cloud/README.md b/cloud/README.md
new file mode 100644
index 00000000..b389ef52
--- /dev/null
+++ b/cloud/README.md
@@ -0,0 +1,64 @@
+# Codync cloud
+
+Cloudflare Worker for accounts and the off-LAN relay (spec: [docs/remote-relay-spec.md](../docs/remote-relay-spec.md)).
+
+- **`/v1` API** (`src/api.ts`): Clerk-authenticated account routes (devices, claims, computers, access
+ requests, grants), `Codync-Sig`-authenticated host routes (`/v1/host/*`), the Clerk webhook, and a
+ 15-minute cron that expires requests and prunes nonces. D1 schema: `migrations/0001_init.sql`.
+- **`ComputerRelay`** (`src/relay.ts`): one Durable Object per computer (SQLite storage, WebSocket
+ Hibernation). It admits device sockets against the host-signed ACL, forwards channel frames it can't
+ read, reports presence, and holds the offline mailbox. It is reachable only through requests the Worker
+ builds itself (`X-Codync-Internal: 1`); `/internal/*` has no public route.
+- **Auth** (`src/auth.ts`): Clerk session JWTs via `@clerk/backend` (`CLERK_SECRET_KEY` → JWKS fetched and
+ cached per isolate; `CLERK_JWT_KEY` → networkless, dev/e2e only) and Ed25519 request signatures
+ (WebCrypto).
+
+The cloud sees ciphertext and routing metadata only. It can shorten access (revoke, block) but never grant
+it: new devices come from the host's own QR pairing or its approval, and the ACL is signed by the host.
+
+## Test
+
+```bash
+npm ci
+npm run typecheck
+npm test # vitest in workerd: vectors, Codync-Sig, API, DO relay/mailbox
+```
+
+`test/ref.ts` is a device/host reference implementation on `@noble/*`, checked against
+`docs/remote-relay-vectors.json` and reused by the relay tests and the e2e harness.
+
+The vitest pool's bundled workerd may trail wrangler's; `vitest.config.ts` pins the test compatibility
+date to the newest one it supports. `wrangler.toml` keeps the deploy date.
+
+### End to end (spec §12.1)
+
+```bash
+(cd ../host && cargo build)
+npm run e2e # local D1 + wrangler dev + real codync-host + test/e2e/phone.ts
+```
+
+Env: `CODYNC_HOST_BIN` (default `../host/target/debug/codync-host`), `CODYNC_E2E_CLOUD_PORT` (default
+8787), `E2E_VERBOSE=1` to stream wrangler and host logs. Needs `python3` for the fake agent.
+
+## Deploy
+
+Staging (the integration stage runs this; production needs the owner):
+
+```bash
+npx wrangler d1 create codync-staging # put database_id into [env.staging]
+npx wrangler d1 migrations apply codync-staging --env staging --remote
+npx wrangler secret put CLERK_SECRET_KEY --env staging
+npx wrangler secret put CLERK_WEBHOOK_SECRET --env staging
+npx wrangler deploy --env staging # → https://codync-cloud-staging.<subdomain>.workers.dev
+```
+
+| Name | Kind | Purpose |
+|---|---|---|
+| `CLERK_SECRET_KEY` | secret | JWKS for session tokens |
+| `CLERK_WEBHOOK_SECRET` | secret | Svix signature on `/v1/webhooks/clerk` (`user.deleted`) |
+| `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 |
+
+New computers are limited to 10 per IP per minute with the Workers Rate Limiting binding
+`REGISTER_LIMITER` (`[[ratelimits]]`; each environment needs its own `namespace_id`).
diff --git a/cloud/migrations/0001_init.sql b/cloud/migrations/0001_init.sql
new file mode 100644
index 00000000..d0a970bb
--- /dev/null
+++ b/cloud/migrations/0001_init.sql
@@ -0,0 +1,99 @@
+CREATE TABLE accounts (
+ user_id TEXT PRIMARY KEY, -- Clerk sub
+ email TEXT,
+ status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active','deleted')),
+ created_at INTEGER NOT NULL,
+ deleted_at INTEGER
+);
+
+CREATE TABLE computers (
+ id TEXT PRIMARY KEY, -- computerId
+ sign_pub TEXT NOT NULL UNIQUE,
+ box_pub TEXT NOT NULL,
+ owner_user_id TEXT REFERENCES accounts(user_id),
+ name TEXT NOT NULL,
+ platform TEXT NOT NULL CHECK (platform IN ('macos','linux')),
+ device TEXT, -- laptop|macmini|…|linux(host 的 Device)
+ version TEXT NOT NULL,
+ status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active','blocked')),
+ online INTEGER NOT NULL DEFAULT 0, -- DO 寫入
+ last_seen_at INTEGER, -- DO 寫入
+ claimed_at INTEGER,
+ created_at INTEGER NOT NULL,
+ updated_at INTEGER NOT NULL
+);
+CREATE INDEX computers_owner ON computers(owner_user_id);
+
+CREATE TABLE devices (
+ id TEXT PRIMARY KEY, -- dev_…
+ owner_user_id TEXT NOT NULL REFERENCES accounts(user_id),
+ sign_pub TEXT NOT NULL,
+ name TEXT NOT NULL,
+ platform TEXT NOT NULL CHECK (platform IN ('ios','macos')),
+ created_at INTEGER NOT NULL,
+ last_used_at INTEGER,
+ revoked_at INTEGER,
+ UNIQUE (owner_user_id, sign_pub)
+);
+
+CREATE TABLE claims (
+ id TEXT PRIMARY KEY, -- clm_…
+ user_id TEXT NOT NULL REFERENCES accounts(user_id),
+ nonce TEXT NOT NULL,
+ expires_at INTEGER NOT NULL,
+ consumed_at INTEGER,
+ computer_id TEXT
+);
+
+CREATE TABLE access_requests (
+ id TEXT PRIMARY KEY, -- req_…
+ computer_id TEXT NOT NULL REFERENCES computers(id),
+ device_id TEXT NOT NULL REFERENCES devices(id),
+ user_id TEXT NOT NULL REFERENCES accounts(user_id),
+ status TEXT NOT NULL CHECK (status IN ('pending','approved','denied','expired','cancelled')),
+ commit_hash TEXT NOT NULL, -- SHA-256("codync/sascommit/v1" ‖ dk ‖ nD)
+ host_nonce TEXT, -- nH,host 設一次
+ device_nonce TEXT, -- nD,host_nonce 存在後裝置才可設
+ created_at INTEGER NOT NULL,
+ expires_at INTEGER NOT NULL, -- created_at + 10 min
+ decided_at INTEGER,
+ grant_id TEXT
+);
+CREATE INDEX access_requests_computer ON access_requests(computer_id, status);
+CREATE UNIQUE INDEX access_requests_one_pending ON access_requests(computer_id, device_id) WHERE status = 'pending';
+
+CREATE TABLE grants (
+ id TEXT PRIMARY KEY, -- grt_…
+ computer_id TEXT NOT NULL REFERENCES computers(id),
+ device_id TEXT NOT NULL REFERENCES devices(id),
+ scopes TEXT NOT NULL, -- JSON array
+ status TEXT NOT NULL CHECK (status IN ('active','revoked')),
+ created_at INTEGER NOT NULL,
+ revoked_at INTEGER,
+ revoked_reason TEXT -- owner|deviceRevoked|unclaimed|accountDeleted
+);
+CREATE UNIQUE INDEX grants_active ON grants(computer_id, device_id) WHERE status = 'active';
+
+CREATE TABLE sig_nonces (
+ kid TEXT NOT NULL,
+ nonce TEXT NOT NULL,
+ expires_at INTEGER NOT NULL,
+ PRIMARY KEY (kid, nonce)
+);
+
+CREATE TABLE processed_events (
+ provider TEXT NOT NULL,
+ event_id TEXT NOT NULL,
+ processed_at INTEGER NOT NULL,
+ PRIMARY KEY (provider, event_id)
+);
+
+CREATE TABLE audit_events (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ actor TEXT NOT NULL, -- user_id / computer:<id> / system
+ action TEXT NOT NULL,
+ target TEXT,
+ result TEXT NOT NULL,
+ created_at INTEGER NOT NULL
+);
+CREATE INDEX audit_time ON audit_events(created_at);
diff --git a/cloud/package-lock.json b/cloud/package-lock.json
new file mode 100644
index 00000000..d7d0ac57
--- /dev/null
+++ b/cloud/package-lock.json
@@ -0,0 +1,3777 @@
+{
+ "name": "codync-cloud",
+ "version": "3.0.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "codync-cloud",
+ "version": "3.0.0",
+ "license": "MIT",
+ "dependencies": {
+ "@clerk/backend": "^3.20.1",
+ "svix": "^2.5.0"
+ },
+ "devDependencies": {
+ "@cloudflare/vitest-pool-workers": "^0.22.0",
+ "@cloudflare/workers-types": "^5.20260925.1",
+ "@noble/ciphers": "^2.4.0",
+ "@noble/curves": "^2.4.0",
+ "@noble/hashes": "^2.4.0",
+ "@types/node": "^26.6.2",
+ "typescript": "^5.9.3",
+ "vitest": "~4.1.11",
+ "wrangler": "^4.140.0"
+ }
+ },
+ "node_modules/@clerk/backend": {
+ "version": "3.20.1",
+ "resolved": "https://registry.npmjs.org/@clerk/backend/-/backend-3.20.1.tgz",
+ "integrity": "sha512-s07oW5yoFtnMbIzzjX61E+s8p278IBNlbPH2obEqNKNVLVb3SNR+UWERBiT1LgTp2LL3cdJmdNCvIaVTaGKMEA==",
+ "license": "MIT",
+ "dependencies": {
+ "@clerk/shared": "^4.36.0",
+ "standardwebhooks": "^1.0.0",
+ "tslib": "2.8.1"
+ },
+ "engines": {
+ "node": ">=20.9.0"
+ }
+ },
+ "node_modules/@clerk/shared": {
+ "version": "4.36.0",
+ "resolved": "https://registry.npmjs.org/@clerk/shared/-/shared-4.36.0.tgz",
+ "integrity": "sha512-K0RAZxGe2otl5FDl6NkhmwI05deN/lO2KFqaObhCRvtw8L1DJMaXUQVfvsJ8D7eDu+0ORiYeC3FcY8cHgI/2Mg==",
+ "license": "MIT",
+ "dependencies": {
+ "@tanstack/query-core": "^5.101.4",
+ "dequal": "2.0.3",
+ "glob-to-regexp": "0.4.1",
+ "js-cookie": "3.0.8"
+ },
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "peerDependencies": {
+ "react": "^18.0.0 || ~19.0.3 || ~19.1.4 || ~19.2.3 || ~19.3.0-0",
+ "react-dom": "^18.0.0 || ~19.0.3 || ~19.1.4 || ~19.2.3 || ~19.3.0-0"
+ },
+ "peerDependenciesMeta": {
+ "react": {
+ "optional": true
+ },
+ "react-dom": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@cloudflare/kv-asset-handler": {
+ "version": "0.5.0",
+ "resolved": "https://registry.npmjs.org/@cloudflare/kv-asset-handler/-/kv-asset-handler-0.5.0.tgz",
+ "integrity": "sha512-jxQYkj8dSIzc0cD6cMMNdOc1UVjqSqu8BZdor5s8cGjW2I8BjODt/kWPVdY+u9zj3ms75Q5qaZgnxUad83+eAg==",
+ "dev": true,
+ "license": "MIT OR Apache-2.0",
+ "engines": {
+ "node": ">=22.0.0"
+ }
+ },
+ "node_modules/@cloudflare/unenv-preset": {
+ "version": "2.16.2",
+ "resolved": "https://registry.npmjs.org/@cloudflare/unenv-preset/-/unenv-preset-2.16.2.tgz",
+ "integrity": "sha512-JBP1+Z7ZSNG/d4mRP+y8VC5dka3tZVMLEZRvS+rzQ4DGV1EoxRFQckcJTTkXbHSQiTj0DtNI01Zwb/V2fX0mvQ==",
+ "dev": true,
+ "license": "MIT OR Apache-2.0",
+ "peerDependencies": {
+ "unenv": "2.0.0-rc.24",
+ "workerd": ">1.20260305.0 <2.0.0-0"
+ },
+ "peerDependenciesMeta": {
+ "workerd": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@cloudflare/vitest-pool-workers": {
+ "version": "0.22.0",
+ "resolved": "https://registry.npmjs.org/@cloudflare/vitest-pool-workers/-/vitest-pool-workers-0.22.0.tgz",
+ "integrity": "sha512-OJv/qikkOgxnKxJ5xrLS7zuOLZhc/6iziU+llqZm4tiQf2CJUYwlMuXN68VaWIQebORd1AUx4w6A0oy8XRbuaQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "cjs-module-lexer": "1.2.3",
+ "esbuild": "0.28.1",
+ "miniflare": "5.20260815.0-alpha",
+ "wrangler": "4.124.0",
+ "zod": "4.4.3"
+ },
+ "peerDependencies": {
+ "@vitest/runner": "^4.1.0",
+ "@vitest/snapshot": "^4.1.0",
+ "vitest": "^4.1.0"
+ }
+ },
+ "node_modules/@cloudflare/vitest-pool-workers/node_modules/@cloudflare/unenv-preset": {
+ "version": "2.16.1",
+ "resolved": "https://registry.npmjs.org/@cloudflare/unenv-preset/-/unenv-preset-2.16.1.tgz",
+ "integrity": "sha512-ECxObrMfyTl5bhQf/lZCXwo5G6xX9IAUo+nDMKK4SZ8m4Jvvxp52vilxyySSWh2YTZz8+HQ07qGH/2rEom1vDw==",
+ "dev": true,
+ "license": "MIT OR Apache-2.0",
+ "peerDependencies": {
+ "unenv": "2.0.0-rc.24",
+ "workerd": ">1.20260305.0 <2.0.0-0"
+ },
+ "peerDependenciesMeta": {
+ "workerd": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@cloudflare/vitest-pool-workers/node_modules/wrangler": {
+ "version": "4.124.0",
+ "resolved": "https://registry.npmjs.org/wrangler/-/wrangler-4.124.0.tgz",
+ "integrity": "sha512-75euoZKjVTJYFy+Xhctt/5JlZL4M6A4xmovZsUlep+6GHcCm14n9VtdGzNIybOW2t8wuNxRj5iMUwjT5E7Ctog==",
+ "dev": true,
+ "license": "MIT OR Apache-2.0",
+ "dependencies": {
+ "@cloudflare/kv-asset-handler": "0.5.0",
+ "@cloudflare/unenv-preset": "2.16.1",
+ "blake3-wasm": "2.1.5",
+ "esbuild": "0.28.1",
+ "miniflare": "5.20260815.0-alpha",
+ "path-to-regexp": "6.3.0",
+ "unenv": "2.0.0-rc.24",
+ "workerd": "1.20260815.1"
+ },
+ "bin": {
+ "cf-wrangler": "bin/cf-wrangler.js",
+ "wrangler": "bin/wrangler.js",
+ "wrangler2": "bin/wrangler.js"
+ },
+ "engines": {
+ "node": ">=22.0.0"
+ },
+ "optionalDependencies": {
+ "fsevents": "2.3.3"
+ },
+ "peerDependencies": {
+ "@cloudflare/workers-types": "^5.20260815.1"
+ },
+ "peerDependenciesMeta": {
+ "@cloudflare/workers-types": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@cloudflare/workerd-darwin-64": {
+ "version": "1.20260815.1",
+ "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-64/-/workerd-darwin-64-1.20260815.1.tgz",
+ "integrity": "sha512-7PsLdcz6pT9EMd1EJGZEgMyYRfs0CHxGs62PS2L1w3s6+xGmQcRXKm/zoMftmqZF45JBa4MzFeownRKbRt/x5g==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=16"
+ }
+ },
+ "node_modules/@cloudflare/workerd-darwin-arm64": {
+ "version": "1.20260815.1",
+ "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-arm64/-/workerd-darwin-arm64-1.20260815.1.tgz",
+ "integrity": "sha512-60wtg8ng7FVWeOg/UMbZ9Ye0sslpRRAKoftPbdtuH2volq676quxVr6Zm2EjVULH/JFZeCn72dbLlrnbh0Mpcw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=16"
+ }
+ },
+ "node_modules/@cloudflare/workerd-linux-64": {
+ "version": "1.20260815.1",
+ "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-64/-/workerd-linux-64-1.20260815.1.tgz",
+ "integrity": "sha512-MuqKIHPo0Qyo8MZMmy0lP2B5PeAL7f4T9Fu4Usk3QdbV4JIrKG/OoybN3Ign7m/Dff+L1Oo/ZHydB+hEg1ueFw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=16"
+ }
+ },
+ "node_modules/@cloudflare/workerd-linux-arm64": {
+ "version": "1.20260815.1",
+ "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-arm64/-/workerd-linux-arm64-1.20260815.1.tgz",
+ "integrity": "sha512-XNFtJ5rIqJxnY6ISjkfbhT/ODiWJ6LcBvNbntuPD6I/F2k7aZeKgPaXrvWvKde66LXyzFKzc8Hn+Ydx4shevQg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=16"
+ }
+ },
+ "node_modules/@cloudflare/workerd-windows-64": {
+ "version": "1.20260815.1",
+ "resolved": "https://registry.npmjs.org/@cloudflare/workerd-windows-64/-/workerd-windows-64-1.20260815.1.tgz",
+ "integrity": "sha512-PiIUWrhbMg3quolwjgMvPOd75vKESjT4aDm7nL6mSjL5IOgmpO/zKstXnYfnEH3pq7sC0UCvKlF8ZPcfsh8NMw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=16"
+ }
+ },
+ "node_modules/@cloudflare/workers-types": {
+ "version": "5.20260925.1",
+ "resolved": "https://registry.npmjs.org/@cloudflare/workers-types/-/workers-types-5.20260925.1.tgz",
+ "integrity": "sha512-E/Z3J8CzyNk0sinBu8g/1HjMCViSxG1kd/ARL8nzieSEdqtYZmgdnhlXbi95xyc3oetTwBR/r604/EuwuP6cnQ==",
+ "dev": true,
+ "license": "MIT OR Apache-2.0"
+ },
+ "node_modules/@cspotcode/source-map-support": {
+ "version": "0.8.1",
+ "resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz",
+ "integrity": "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/trace-mapping": "0.3.9"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@emnapi/runtime": {
+ "version": "1.11.3",
+ "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz",
+ "integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==",
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "tslib": "^2.4.0"
+ }
+ },
+ "node_modules/@esbuild/aix-ppc64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.1.tgz",
+ "integrity": "sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "aix"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-arm": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.1.tgz",
+ "integrity": "sha512-0k2F129Xdio1TdJfzJ8sy1Q47vUD2NnwdhiAf7drUN1EBTfPf4hsFCtmMgu/6m8JSzsBrlmVjudMBQqOfG8usQ==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-arm64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.1.tgz",
+ "integrity": "sha512-34EGEbCIAgosYz6goLcopX6Mo7NyGv9tfwEM2/7Ce2VcVRk568iSvniGWcUXIy7wEDR1wzolcxcriFVrWYcwBg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-x64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.1.tgz",
+ "integrity": "sha512-dbwY7ltSMDWsRatcRpCnES4F+im88OCUgGZjy52shC7GqHRE/cYlxNbB4Z4UpJswpcc4Qxd2oE/ufM0p61IKng==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/darwin-arm64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.1.tgz",
+ "integrity": "sha512-TZbWkQY7kvTAXbXUT7uVACR5cMHsDiSz9z7ZKAX/RTq/WJEk3QyRr0wZpNhBDX+/0CtdqUIJlOiodQcta6tY3Q==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/darwin-x64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.1.tgz",
+ "integrity": "sha512-zfdzgK9ACBNZLI/CyHTOx81SyNbM6YXn7rxSgX97VjyiPl9W1i4Ka4fgKECEoFCKGpvBj5qArWIGgQjOwkgskQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/freebsd-arm64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.1.tgz",
+ "integrity": "sha512-wG2EA8ENdEI0qhkSZMjfqrdY+ziCYCPMmtZjjIwOmXFjmyzEHn+UUxk5of+SYsjtfs3VpnlC7QLzSI5hY/rOAw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/freebsd-x64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.1.tgz",
+ "integrity": "sha512-i7dZ9vQgnvSCzi/rYCXNgtF/U+eKZNJBzu3eTQbRgHnM7tNSizLOkRFAl3qzVc/Op/u5YkHHa4pf/3DOYHthLQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-arm": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.1.tgz",
+ "integrity": "sha512-qVXBOHQS+d5Y722GwJzJUtOLlX7km3CraOaGormF1pDtPd2C/l1SHRPgjLunLGe51Sh5YYWKMFDyV4SxgMQYTQ==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-arm64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.1.tgz",
+ "integrity": "sha512-yHs+0uc8+nvEAfAfxrWQKK5peSNzBc4PegcMO0EJ2hT71uA7vB8Ihg2e77R2P7SG5uYjPbHlLLmve4LLLRCf0g==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-ia32": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.1.tgz",
+ "integrity": "sha512-d1z4ZuP0ajrfz/FhGT4vv278rX8KnPPJx8i5+AtK7TYbx9Le9F1hyzurZpkEyjkGa9dUGhQow4C1NmeGvqxN2w==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-loong64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.1.tgz",
+ "integrity": "sha512-M5sRjUVZrkm1OAPR3dlOYzNmN+loZKGVi1VUQGrwuqLcbR6qeAz+famMhjASeH3YVKvZz+zT1jlh/keC3Rj/lg==",
+ "cpu": [
+ "loong64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-mips64el": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.1.tgz",
+ "integrity": "sha512-mRObBZeHh2OxcBFPWE/FjylkRgZdYuiTR3vaTozquCGOH14iP9oN4x4Ge81CoIDYQrXmIxpFumJBu5MtZpnQJQ==",
+ "cpu": [
+ "mips64el"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-ppc64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.1.tgz",
+ "integrity": "sha512-slScBsMAb3GFDcdrCgLwZtPYRoH2H/youv10QiZyRjmsP48fznoveWytSgCI/R0ZcUgpc0ZhIUEx6LHts8yrfQ==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-riscv64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.1.tgz",
+ "integrity": "sha512-kw0owk1o0GFETUJyW0jc0G4Yzs0BHZn0JDZ8JRT088vjJYX777BAs1fDGxAC+q831qOs2DTC96mNsG2opdfyyQ==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-s390x": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.1.tgz",
+ "integrity": "sha512-/lAIjX8aYFRByhh6L5rYtPEDRqa9de/4V/juOXcta5frjvzXO4/sqEtyytse0g3zZFuWu5cDN0MkLz2qRDD2Ag==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-x64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.1.tgz",
+ "integrity": "sha512-u/anNYF2mmVOEDwLtnQ1wOr3EZ9sTNGLWrsYGYwHWzGA3Si84IOkHXlbWTD1NB+9/1lcnweYKO54uhxZydNzfA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/netbsd-arm64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.1.tgz",
+ "integrity": "sha512-oks0DYbLwWMmaakTsCb+zL4E+aHRVLom9IJZOAthMQEPiQmydXHkziYEsGYRx0uNV/IjEKGAV941JzH02pflqw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/netbsd-x64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.1.tgz",
+ "integrity": "sha512-aeL6lAnN89Hz43Mlh1G8ARasbuoYvSITDEx0tHh5b7jJnHcssqgjy9Yx430GDpmCa6OyrKoS0aNRjKundRizGg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openbsd-arm64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.1.tgz",
+ "integrity": "sha512-MEFJe5C3R8pwXdZ5Y21oo6m7ePiS0d9pWucn99O/wvyJZChoIQKrQDxKrGeW8F5+T0okTHesAmDeiHDTIq0V/Q==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openbsd-x64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.1.tgz",
+ "integrity": "sha512-i/ZLIOafE0Z8cI/XANJAixoJL/uRAoS2xOA3rb0xN+KK0K177cMAsQYkzHtBrtMXAKuAc7HGgcWiZ/sRC1Nxgw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openharmony-arm64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.1.tgz",
+ "integrity": "sha512-ge+Z7EXFNt2BO1oAMsVpiQ8EwndV9i1xXerAeTIK7AtPs3bKFXQM7nlRxDSIUIMeueR1CNXxqztLzdNeReKBJg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openharmony"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/sunos-x64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.1.tgz",
+ "integrity": "sha512-BEjgtECkL3vY+SaSQ6nzVfiALUeFxpawyp8Jmf5PtYhf1Ug40N1h/hxlhts+f1FvSvarEigdxS3BlSMI2PJLcQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "sunos"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-arm64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.1.tgz",
+ "integrity": "sha512-lCv9eK/H6ZJWbE7bh2nw54CZ9M2nupBxJcTsdk/QQnWkdSjKGuxmmH8/GWrlT1eMmZfn4dGcCjRte397WqfQXA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-ia32": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.1.tgz",
+ "integrity": "sha512-zvb/mB2bSCoJOpoCBgYKKpX6YM6mJBlBUVUtVj41DlZJVEB6/0CKlRYxP5wWl1C1ILiCoAU5wZZ4q1P3qeS6Eg==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-x64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.1.tgz",
+ "integrity": "sha512-bm4Mowrv+GXMlpWX++EcXw/iLyd1o3+bJkC2DkWXYVvgZCqD/bSj9ctZeAMC3cIxgjRVR2Dufaiu4YPxr5gW1A==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@img/colour": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz",
+ "integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@img/sharp-darwin-arm64": {
+ "version": "0.35.2",
+ "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.35.2.tgz",
+ "integrity": "sha512-eEieHsMksAW4IiO5NzauESRl2D2qz3J/kwUxUrSfV06A93eEaRfMpHXyUb1mAqrR7i8U9A0GRqE9pjn6u1Jjpg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-darwin-arm64": "1.3.1"
+ }
+ },
+ "node_modules/@img/sharp-darwin-x64": {
+ "version": "0.35.2",
+ "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.35.2.tgz",
+ "integrity": "sha512-BaktuGPCeHJMARpodR8jK4uKiZrPAy9WrfQW0sdI37clracq8Bp01AYS3SZgi5FS/y5twa9t4+LIuuxQjqRrWw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-darwin-x64": "1.3.1"
+ }
+ },
+ "node_modules/@img/sharp-freebsd-wasm32": {
+ "version": "0.35.2",
+ "resolved": "https://registry.npmjs.org/@img/sharp-freebsd-wasm32/-/sharp-freebsd-wasm32-0.35.2.tgz",
+ "integrity": "sha512-YoAxdnd8hPUkvLHd3bWY+YA8nw3xM/RyRopYucNsWHVSan8NLVM3X2volsfoRDcXdUJPg6tXahSd7HXPK7lRnw==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "dependencies": {
+ "@img/sharp-wasm32": "0.35.2"
+ },
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-darwin-arm64": {
+ "version": "1.3.1",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.3.1.tgz",
+ "integrity": "sha512-4V/M3roRMTYjiwZY9IOVQOE8OyeCxFAkYmyZDrZl51uOKjibm3oeEJ4WAmLxutAfzFbC9jqUiPs2gbnGflH+7g==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-darwin-x64": {
+ "version": "1.3.1",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.3.1.tgz",
+ "integrity": "sha512-c0/DxItpJv2+dGhgycJBBgotdqruGYDvA79drdh0MD1dFpy7JzJ/PlXwi1H4rFf0eTy8tgbI91aHDnZIceY3jQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linux-arm": {
+ "version": "1.3.1",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.3.1.tgz",
+ "integrity": "sha512-aGGy9aWzXgHBG7HNyQPWorZthlp7+x6fDRoPAQbGO3ThcttuTyKIx3NuSHb6zb4gBNq6/yNn9f1cy9nFKS/Vmg==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linux-arm64": {
+ "version": "1.3.1",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.3.1.tgz",
+ "integrity": "sha512-JznefmcK9j1JKPz8AkQDh89kjojubyfOasWBPKfzMIhPwsgDy9evpE/naJTXXXmghS1iFwR8u/kTwh/I2/+GCw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linux-ppc64": {
+ "version": "1.3.1",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.3.1.tgz",
+ "integrity": "sha512-1EkwGNCZk6iWNCMWqrvdJ+r1j0PT1zIz60CNPhYnJlK/zyeWqlsPZIe+ocBVqPF8k/Ssee/NCk+tE9Ryrko6ng==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linux-riscv64": {
+ "version": "1.3.1",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.3.1.tgz",
+ "integrity": "sha512-Ilays+w2bXdnxzxtQdmXR62u8o8GYa3eL4+Gr+1KiE4xperMZUslRaVPJwwPkzlHEjGfXAfRVAa/7CYCtSqsBw==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linux-s390x": {
+ "version": "1.3.1",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.3.1.tgz",
+ "integrity": "sha512-VfBwVHQTbRoj4XlpA/KLZ7ltgMpz+4WSejFzQ+GnoImjo1PtEJ59QB2qR1xQEeRPYIkNrPIm2L4cICMvz4C2ew==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linux-x64": {
+ "version": "1.3.1",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.3.1.tgz",
+ "integrity": "sha512-+c8ukgwU62DS54nCAjw7keOfHUkmr0B5QHEdcOqRnodF/MNXJbVI8Eopoj4B/0H8Asr65I+A4Amrn7a85/md6A==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linuxmusl-arm64": {
+ "version": "1.3.1",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.3.1.tgz",
+ "integrity": "sha512-qlKb/pwbkAi1WMsJrYHk7CuDrd12s27U2QnRhFYUoJNrRCmkosMTttuRFat/DDB3IlDm5qE1TJgZ4JDnHX8Ldw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linuxmusl-x64": {
+ "version": "1.3.1",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.3.1.tgz",
+ "integrity": "sha512-yO21HwoUVLN8Qa+/SBjQLMYwBWAVJjeGPNe+hc0OUeMeifEtJqu5a1c4HayE1nNpDih9y3/KkoltfkDodmKAlg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-linux-arm": {
+ "version": "0.35.2",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.35.2.tgz",
+ "integrity": "sha512-SE4kzF2mepn6z+6E7L6lsV8FzuLL6IPQdyX8ZiwROAG/G8td+hP/m7FsFPwidtrF19gvajuC9l6TxAVcsA4S7A==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linux-arm": "1.3.1"
+ }
+ },
+ "node_modules/@img/sharp-linux-arm64": {
+ "version": "0.35.2",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.35.2.tgz",
+ "integrity": "sha512-af12Pnd0ZGu2HfP8NayB0kk6eC/lrfbQE6HlR4jD+34wdJ1Vw9TF6TMn6ZvffT+WgqVsl0hRbmNvz2u/23VmwA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linux-arm64": "1.3.1"
+ }
+ },
+ "node_modules/@img/sharp-linux-ppc64": {
+ "version": "0.35.2",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.35.2.tgz",
+ "integrity": "sha512-hYSBm7zcNtDCozCxQHYZJiu63b/bXsgRZuOxCIBZsStMM9Vap47iFHdbX4kCvQsblPB/k+clhELpdQJHQLSHvg==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linux-ppc64": "1.3.1"
+ }
+ },
+ "node_modules/@img/sharp-linux-riscv64": {
+ "version": "0.35.2",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.35.2.tgz",
+ "integrity": "sha512-qQt0Kc13+Hoan/Awq/qMSQw3L+RI1NCRPgD5cUJ/1WSSmIoysLOc72jlRM3E0OHN9Yr313jgeQ2T+zW+F03QFA==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linux-riscv64": "1.3.1"
+ }
+ },
+ "node_modules/@img/sharp-linux-s390x": {
+ "version": "0.35.2",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.35.2.tgz",
+ "integrity": "sha512-E4fLLfRPzDLlEeDaTzI98OFLcv++WL5ChLLMwPoVd0CIoZQqupBSNbOisPL5am9XsbQ9T84+iiMpUvbFtkunbA==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linux-s390x": "1.3.1"
+ }
+ },
+ "node_modules/@img/sharp-linux-x64": {
+ "version": "0.35.2",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.35.2.tgz",
+ "integrity": "sha512-gi0zFJJRLswfCZmHtJdikXPOc5u7qamSOS3NHedLqLd4W8Q0NqjdBr6TTRIgsfFjqfTsHFgdfvJ9LwqSgcHiAA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linux-x64": "1.3.1"
+ }
+ },
+ "node_modules/@img/sharp-linuxmusl-arm64": {
+ "version": "0.35.2",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.35.2.tgz",
+ "integrity": "sha512-siWbOW1u6HFnFLrp0waKyW7VEf7jYvcDWdrXEFa8AkdAQgEvuu5Fz8/Y70w9EeqAdwDtfU012BhEHHaDqvQNzg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linuxmusl-arm64": "1.3.1"
+ }
+ },
+ "node_modules/@img/sharp-linuxmusl-x64": {
+ "version": "0.35.2",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.35.2.tgz",
+ "integrity": "sha512-YBqMMcjDi4QGYiSn4vNOYBhmlC4z5AXqkOUUqI2e0AFA4urNv4ESgOgwNl3K+4etQhha0twXlzeF20bbULm9Yg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linuxmusl-x64": "1.3.1"
+ }
+ },
+ "node_modules/@img/sharp-wasm32": {
+ "version": "0.35.2",
+ "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.35.2.tgz",
+ "integrity": "sha512-Mrv4JQNYVQ94xH+jzZ9r+gowleN8mv2FTgKT+PI6bx5C0G8TdNYndu161pg2i7uoBwxy2ImPMHrJOM2LZef7Bw==",
+ "dev": true,
+ "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT",
+ "optional": true,
+ "dependencies": {
+ "@emnapi/runtime": "^1.11.1"
+ },
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-webcontainers-wasm32": {
+ "version": "0.35.2",
+ "resolved": "https://registry.npmjs.org/@img/sharp-webcontainers-wasm32/-/sharp-webcontainers-wasm32-0.35.2.tgz",
+ "integrity": "sha512-QNV27pxs9wpApEiCfvHM1RDoP1w1+2KrUWWDPEhEwg+latvOrfuhWrHWZKwdSFwU6jh3myjw/yOCRsUIuOft3g==",
+ "cpu": [
+ "wasm32"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "dependencies": {
+ "@img/sharp-wasm32": "0.35.2"
+ },
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-win32-arm64": {
+ "version": "0.35.2",
+ "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.35.2.tgz",
+ "integrity": "sha512-BiVRYc/t6/Vl3e1hBx0hugG4oN9Pydf4fgMSpxTQJmwGUg/YoXTWHiFeRymHfCZzifxu4F4rpk/I67D0LQ20wQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0 AND LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-win32-ia32": {
+ "version": "0.35.2",
+ "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.35.2.tgz",
+ "integrity": "sha512-YYEhx9PImCC7T0tI8JDMi4DB9LwLCXCU5OWNYEXAxh5Q1ShKkyC6byxzoBJ3gEFDnH2lQckWuDe70G7mB2XJog==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "Apache-2.0 AND LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": "^20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-win32-x64": {
+ "version": "0.35.2",
+ "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.35.2.tgz",
+ "integrity": "sha512-imoOyBcoM/iiUr4J6VPpCNjPnjvP/Gks95898yB8YqoGGYmHYbOyCuNv9FMhFgtaiHFGbHW8bxKqRV6VjtXThQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0 AND LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@jridgewell/resolve-uri": {
+ "version": "3.1.2",
+ "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz",
+ "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.0.0"
+ }
+ },
+ "node_modules/@jridgewell/sourcemap-codec": {
+ "version": "1.6.0",
+ "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz",
+ "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@jridgewell/trace-mapping": {
+ "version": "0.3.9",
+ "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz",
+ "integrity": "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/resolve-uri": "^3.0.3",
+ "@jridgewell/sourcemap-codec": "^1.4.10"
+ }
+ },
+ "node_modules/@noble/ciphers": {
+ "version": "2.4.0",
+ "resolved": "https://registry.npmjs.org/@noble/ciphers/-/ciphers-2.4.0.tgz",
+ "integrity": "sha512-AnjFn0Jv92laAkvMrghlFZq4qQCIN/4DxFV/eooqtC2YTjB7kBeLMS2T9KJX4Dn+ZVXLOwK0lSgqDtx9gvxtiw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 20.19.0"
+ },
+ "funding": {
+ "url": "https://paulmillr.com/funding/"
+ }
+ },
+ "node_modules/@noble/curves": {
+ "version": "2.4.0",
+ "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-2.4.0.tgz",
+ "integrity": "sha512-P4/62zrgfH33CneE3Dn4WhJVA22YUU0eR51wKIan4NVRvwsA0YnPTwWGpNbpuacSujmSFLvyzpyuR30+fbq2Ew==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@noble/hashes": "2.4.0"
+ },
+ "engines": {
+ "node": ">= 20.19.0"
+ },
+ "funding": {
+ "url": "https://paulmillr.com/funding/"
+ }
+ },
+ "node_modules/@noble/hashes": {
+ "version": "2.4.0",
+ "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-2.4.0.tgz",
+ "integrity": "sha512-X5XaVWZIBCT7HHZGm5I7ZQXDwLG+bGXuSrMQAW+7Zvl87h1kmc1ZB1VSRJcpUfoUrGQp4Fkoxm5kZ+Ms+aW+eA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 20.19.0"
+ },
+ "funding": {
+ "url": "https://paulmillr.com/funding/"
+ }
+ },
+ "node_modules/@oxc-project/types": {
+ "version": "0.151.0",
+ "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.151.0.tgz",
+ "integrity": "sha512-J1yXrIlNDZVzE3ada310xeAw7nH8yCAyLPuUIsjKatFPmfn5bS1oW+cM+QsGOtVWd5nhSpbwZWx/rue+r5Z+PA==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/oxc-project"
+ }
+ },
+ "node_modules/@poppinss/colors": {
+ "version": "4.1.6",
+ "resolved": "https://registry.npmjs.org/@poppinss/colors/-/colors-4.1.6.tgz",
+ "integrity": "sha512-H9xkIdFswbS8n1d6vmRd8+c10t2Qe+rZITbbDHHkQixH5+2x1FDGmi/0K+WgWiqQFKPSlIYB7jlH6Kpfn6Fleg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "kleur": "^4.1.5"
+ }
+ },
+ "node_modules/@poppinss/dumper": {
+ "version": "0.6.5",
+ "resolved": "https://registry.npmjs.org/@poppinss/dumper/-/dumper-0.6.5.tgz",
+ "integrity": "sha512-NBdYIb90J7LfOI32dOewKI1r7wnkiH6m920puQ3qHUeZkxNkQiFnXVWoE6YtFSv6QOiPPf7ys6i+HWWecDz7sw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@poppinss/colors": "^4.1.5",
+ "@sindresorhus/is": "^7.0.2",
+ "supports-color": "^10.0.0"
+ }
+ },
+ "node_modules/@poppinss/exception": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/@poppinss/exception/-/exception-1.2.3.tgz",
+ "integrity": "sha512-dCED+QRChTVatE9ibtoaxc+WkdzOSjYTKi/+uacHWIsfodVfpsueo3+DKpgU5Px8qXjgmXkSvhXvSCz3fnP9lw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@rolldown/binding-android-arm-eabi": {
+ "version": "1.2.11",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.11.tgz",
+ "integrity": "sha512-A5kXfGKvKWWZE0TtPrfsvT+q4Y5d1QG8gGUzpYjGydM+fARM9MuX90PrXYXe0XbsDVgyxxNzHo6giCj90bsFNw==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-android-arm64": {
+ "version": "1.2.11",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.11.tgz",
+ "integrity": "sha512-z6cTycz+iJ4PVkuL4HHW4DfTfoeU/2nqYYuSOrTmH7yHK5Y0LCOnA03V4ZNxavyVaU1oOqUgIg2klN/s+USGOA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-darwin-arm64": {
+ "version": "1.2.11",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.11.tgz",
+ "integrity": "sha512-jShvqNtP6vDC6/A5JOAzbVV+DkgHqhl/ScVCJEbt+TUY6QYz7YnXcrg3sLtFBniro0f/Ld50ZwCWA6f7KYD1nQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-darwin-x64": {
+ "version": "1.2.11",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.11.tgz",
+ "integrity": "sha512-f2i2xiNWq1Z1l2++q2fuhZRdLAT3aqxD6vRNm1RAxpUoBcdqNB3C0s1Bt+K+PbEx2F5F4gQp6hqKkphCY/xF9w==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-freebsd-x64": {
+ "version": "1.2.11",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.11.tgz",
+ "integrity": "sha512-4Ir5FSOKIAMr4r0kExpt1s3bMgzJU3rA45AYOHtQpls0oNeqcYBKrWMlckrYH4KCfGLfkfn1tN1dmZPMVsdXow==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-arm-gnueabihf": {
+ "version": "1.2.11",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.11.tgz",
+ "integrity": "sha512-/gnRDM+39BROzAN/k1OZjDPnDMcZxB/0EUxKjONO5yVkNEvlsoMDrxGNKgZi/ttFriS2gwlDNzB65pvNbFOXIQ==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-arm64-gnu": {
+ "version": "1.2.11",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.11.tgz",
+ "integrity": "sha512-PFaK8HwvAHbaKbBcDNQihjMKYvFnA5hiENx/l5tphTDz1E0WFp32l0A7aq7lyUwGsRw/xSrNIy/gIK4thrSCrw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-arm64-musl": {
+ "version": "1.2.11",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.11.tgz",
+ "integrity": "sha512-AskzJUIKRLPxkruR1wLKewGbOw+EYfU/9lOrBFj4AFrEA8hPpKFnODWNu2WLaNs0QNkEb9QIJufmVZZIL/bJlg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-ppc64-gnu": {
+ "version": "1.2.11",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.11.tgz",
+ "integrity": "sha512-qlUGAheh2yh8afH7QBgx0PrRHN85hKnNd78x8MeMhXivuevgd8vgf6/CstOzmNKY/lLTHvNTrPy98cLnAugzJw==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-s390x-gnu": {
+ "version": "1.2.11",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.11.tgz",
+ "integrity": "sha512-secpEad+0vCbSfn8upFySkDskv+bGPk3THSDS9Y89yc4rb4kzqHp8Dmyd9BkQW4SnhNXBZCl/6CrO//hZahNJQ==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-x64-gnu": {
+ "version": "1.2.11",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.11.tgz",
+ "integrity": "sha512-mOVBT3dPpkWm8XBWPmU4bf+U6dYDLeMo/9ojUmis4N0L5uu10qra5vOyngZ7/PSdoE4G9KvRt4bloRxNjLas7A==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-x64-musl": {
+ "version": "1.2.11",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.11.tgz",
+ "integrity": "sha512-Is78i9A8Ui4SqcxUwFJ9uMmjDn58IbVTjFWYdQestFEgeuEmHMLGNriXnVJKkwG2YiZjw8cP0zCTyDMdDGtOOg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-openharmony-arm64": {
+ "version": "1.2.11",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.11.tgz",
+ "integrity": "sha512-dUCXneZ87INUMyQ0D+C0HrEBNUPNXHaPmU5GTjyKTJEiussw9Kaj5Ln8UztPe4epV/ffvgNBEadksdYhmW6xJA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openharmony"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-win32-arm64-msvc": {
+ "version": "1.2.11",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.11.tgz",
+ "integrity": "sha512-jByxb6qfd+bH1xUd0qnfFnb17i9sWBPY2tOavJ0l3tdr3OTu+Kvtm8cd/JV5nFt657b1VqGltxg9olOEfofXWw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-win32-x64-msvc": {
+ "version": "1.2.11",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.11.tgz",
+ "integrity": "sha512-/PzKqzAJ03i19oy2ItPvyvaVjOjBCNnfaJs8yvUdGBKmiESgnrJSQ2awd81QzFbbnAmu7YO9ZnJrDCb9VSJPRA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/pluginutils": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz",
+ "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@sindresorhus/is": {
+ "version": "7.2.0",
+ "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-7.2.0.tgz",
+ "integrity": "sha512-P1Cz1dWaFfR4IR+U13mqqiGsLFf1KbayybWwdd2vfctdV6hDpUkgCY0nKOLLTMSoRd/jJNjtbqzf13K8DCCXQw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "url": "https://github.com/sindresorhus/is?sponsor=1"
+ }
+ },
+ "node_modules/@speed-highlight/core": {
+ "version": "1.2.24",
+ "resolved": "https://registry.npmjs.org/@speed-highlight/core/-/core-1.2.24.tgz",
+ "integrity": "sha512-qeW2e1l78afw8VhRPfPQ1Gjj+KU5XFQ/OFV5ti6eTa9bruO7mJyZtA4vw0ofqmA3tKCkROE9xLk3VZoeRc98nw==",
+ "dev": true,
+ "license": "CC0-1.0"
+ },
+ "node_modules/@stablelib/base64": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/@stablelib/base64/-/base64-1.0.1.tgz",
+ "integrity": "sha512-1bnPQqSxSuc3Ii6MhBysoWCg58j97aUjuCSZrGSmDxNqtytIi0k8utUenAwTZN4V5mXXYGsVUI9zeBqy+jBOSQ==",
+ "license": "MIT"
+ },
+ "node_modules/@standard-schema/spec": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz",
+ "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@tanstack/query-core": {
+ "version": "5.103.2",
+ "resolved": "https://registry.npmjs.org/@tanstack/query-core/-/query-core-5.103.2.tgz",
+ "integrity": "sha512-I8DkFXls5jXLqtm8+QpOhEmG07hIblhSZFzafg9wHsMSEvMzULy9hK17wU1T/ahfhMbtITJhbxutwwCoihkR7A==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/tannerlinsley"
+ }
+ },
+ "node_modules/@types/chai": {
+ "version": "5.2.3",
+ "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz",
+ "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/deep-eql": "*",
+ "assertion-error": "^2.0.1"
+ }
+ },
+ "node_modules/@types/deep-eql": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz",
+ "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/estree": {
+ "version": "1.0.9",
+ "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",
+ "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/node": {
+ "version": "26.6.2",
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.2.tgz",
+ "integrity": "sha512-X1P21scMv4zGKLYqjdGjaKa7COa0RKVYYZZN/NfvLQ1JegxFhdhpZG/Lyn8AXx6CDUavKAd11v6BvfpkDByK8g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "undici-types": "~8.9.0"
+ }
+ },
+ "node_modules/@vitest/expect": {
+ "version": "4.1.11",
+ "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.11.tgz",
+ "integrity": "sha512-VX2x5vNJXET47KAFzwERI+KRMtTTCSWTfSMKsW7JsUsXV4psq++e3DvZpuTDOpHcxytiDs6p2nhVb2tVDiiUYw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@standard-schema/spec": "^1.1.0",
+ "@types/chai": "^5.2.2",
+ "@vitest/spy": "4.1.11",
+ "@vitest/utils": "4.1.11",
+ "chai": "^6.2.2",
+ "tinyrainbow": "^3.1.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/mocker": {
+ "version": "4.1.11",
+ "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.11.tgz",
+ "integrity": "sha512-2XJVD55d1o5AZous5CCGKS74g/riOj9odEt2bQpCVZeblHyHdnMeFl4jl0XjU21stf4mbjUkew2eXQZt65g5CQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/spy": "4.1.11",
+ "estree-walker": "^3.0.3",
+ "magic-string": "^0.30.21"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ },
+ "peerDependencies": {
+ "msw": "^2.4.9",
+ "vite": "^6.0.0 || ^7.0.0 || ^8.0.0"
+ },
+ "peerDependenciesMeta": {
+ "msw": {
+ "optional": true
+ },
+ "vite": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@vitest/pretty-format": {
+ "version": "4.1.11",
+ "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.11.tgz",
+ "integrity": "sha512-yiZzPbGTS9Sr/JpFl8zHrcIkAofNbFV6k21vIgQN/cY/oxZeXhJv5sc/MBJ5jFKWmWs+oJHw0UXLZjmf931+Vw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "tinyrainbow": "^3.1.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/runner": {
+ "version": "4.1.11",
+ "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.1.11.tgz",
+ "integrity": "sha512-LztvUgdwMNJMIkj3hQnnxiC2Xy1zNxq928W/xhjCLaNCzqTZOudjwbQf6v9IntZGPw132i2Lq2rgTRZHD3JHNw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/utils": "4.1.11",
+ "pathe": "^2.0.3"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/snapshot": {
+ "version": "4.1.11",
+ "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.1.11.tgz",
+ "integrity": "sha512-pN7ikn1ON7h8ee4gIAp4AzyK+zBtJPzVbqOgu5LCEh4VaJVbPQcgYQYJIMGQPXVeJJq1fnfazis7a5pFNPahog==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/pretty-format": "4.1.11",
+ "@vitest/utils": "4.1.11",
+ "magic-string": "^0.30.21",
+ "pathe": "^2.0.3"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/spy": {
+ "version": "4.1.11",
+ "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.11.tgz",
+ "integrity": "sha512-apNa/prQy2qCeywhnixOHPRCgGNhvg7T4Dapfl1GahLp/R+uhBm5cPyFoNVyqsNd2h1nJxL6BqqdIjiABL60YA==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/utils": {
+ "version": "4.1.11",
+ "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.11.tgz",
+ "integrity": "sha512-zTCVGpyFsGWBhllOyKlTw/vnr6D9qxsfSDyfbyZmTyjHw5N/VuvzHpHoQjm2ZJzn4RJgx5w4r7V0er69CmLgPQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/pretty-format": "4.1.11",
+ "convert-source-map": "^2.0.0",
+ "tinyrainbow": "^3.1.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/assertion-error": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz",
+ "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/blake3-wasm": {
+ "version": "2.1.5",
+ "resolved": "https://registry.npmjs.org/blake3-wasm/-/blake3-wasm-2.1.5.tgz",
+ "integrity": "sha512-F1+K8EbfOZE49dtoPtmxUQrpXaBIl3ICvasLh+nJta0xkz+9kF/7uet9fLnwKqhDrmj6g+6K3Tw9yQPUg2ka5g==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/chai": {
+ "version": "6.2.2",
+ "resolved": "https://registry.npmjs.org/chai/-/chai-6.2.2.tgz",
+ "integrity": "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/cjs-module-lexer": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/cjs-module-lexer/-/cjs-module-lexer-1.2.3.tgz",
+ "integrity": "sha512-0TNiGstbQmCFwt4akjjBg5pLRTSyj/PkWQ1ZoO2zntmg9yLqSRxwEa4iCfQLGjqhiqBfOJa7W/E8wfGrTDmlZQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/convert-source-map": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz",
+ "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/cookie": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/cookie/-/cookie-1.1.1.tgz",
+ "integrity": "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/dequal": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz",
+ "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/detect-libc": {
+ "version": "2.1.2",
+ "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
+ "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/error-stack-parser-es": {
+ "version": "1.0.5",
+ "resolved": "https://registry.npmjs.org/error-stack-parser-es/-/error-stack-parser-es-1.0.5.tgz",
+ "integrity": "sha512-5qucVt2XcuGMcEGgWI7i+yZpmpByQ8J1lHhcL7PwqCwu9FPP3VUXzT4ltHe5i2z9dePwEHcDVOAfSnHsOlCXRA==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/antfu"
+ }
+ },
+ "node_modules/es-module-lexer": {
+ "version": "2.3.2",
+ "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz",
+ "integrity": "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/esbuild": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.1.tgz",
+ "integrity": "sha512-HrJrvZv5ayxBzPfwphOoNzkzOIIlifzk0KJrGK2c8R4+LKpMtpYLQeUdjnwjWv/LZlkH2laZk+4w78pi99D4Vw==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "bin": {
+ "esbuild": "bin/esbuild"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "optionalDependencies": {
+ "@esbuild/aix-ppc64": "0.28.1",
+ "@esbuild/android-arm": "0.28.1",
+ "@esbuild/android-arm64": "0.28.1",
+ "@esbuild/android-x64": "0.28.1",
+ "@esbuild/darwin-arm64": "0.28.1",
+ "@esbuild/darwin-x64": "0.28.1",
+ "@esbuild/freebsd-arm64": "0.28.1",
+ "@esbuild/freebsd-x64": "0.28.1",
+ "@esbuild/linux-arm": "0.28.1",
+ "@esbuild/linux-arm64": "0.28.1",
+ "@esbuild/linux-ia32": "0.28.1",
+ "@esbuild/linux-loong64": "0.28.1",
+ "@esbuild/linux-mips64el": "0.28.1",
+ "@esbuild/linux-ppc64": "0.28.1",
+ "@esbuild/linux-riscv64": "0.28.1",
+ "@esbuild/linux-s390x": "0.28.1",
+ "@esbuild/linux-x64": "0.28.1",
+ "@esbuild/netbsd-arm64": "0.28.1",
+ "@esbuild/netbsd-x64": "0.28.1",
+ "@esbuild/openbsd-arm64": "0.28.1",
+ "@esbuild/openbsd-x64": "0.28.1",
+ "@esbuild/openharmony-arm64": "0.28.1",
+ "@esbuild/sunos-x64": "0.28.1",
+ "@esbuild/win32-arm64": "0.28.1",
+ "@esbuild/win32-ia32": "0.28.1",
+ "@esbuild/win32-x64": "0.28.1"
+ }
+ },
+ "node_modules/estree-walker": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz",
+ "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/estree": "^1.0.0"
+ }
+ },
+ "node_modules/expect-type": {
+ "version": "1.4.0",
+ "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz",
+ "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=12.0.0"
+ }
+ },
+ "node_modules/fast-sha256": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/fast-sha256/-/fast-sha256-1.3.0.tgz",
+ "integrity": "sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ==",
+ "license": "Unlicense"
+ },
+ "node_modules/fdir": {
+ "version": "6.5.0",
+ "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
+ "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12.0.0"
+ },
+ "peerDependencies": {
+ "picomatch": "^3 || ^4"
+ },
+ "peerDependenciesMeta": {
+ "picomatch": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/fsevents": {
+ "version": "2.3.3",
+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
+ "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"
+ }
+ },
+ "node_modules/glob-to-regexp": {
+ "version": "0.4.1",
+ "resolved": "https://registry.npmjs.org/glob-to-regexp/-/glob-to-regexp-0.4.1.tgz",
+ "integrity": "sha512-lkX1HJXwyMcprw/5YUZc2s7DrpAiHB21/V+E1rHUrVNokkvB6bqMzT0VfV6/86ZNabt1k14YOIaT7nDvOX3Iiw==",
+ "license": "BSD-2-Clause"
+ },
+ "node_modules/js-cookie": {
+ "version": "3.0.8",
+ "resolved": "https://registry.npmjs.org/js-cookie/-/js-cookie-3.0.8.tgz",
+ "integrity": "sha512-yeJd4aNAdYZQjaon2bpD/Gb0B/omw7HQOsynXXcOiWVCacbBcPlgn8S/d1X6blFSaHao7ozqtW7NZW19xpCtIw==",
+ "license": "MIT"
+ },
+ "node_modules/kleur": {
+ "version": "4.1.5",
+ "resolved": "https://registry.npmjs.org/kleur/-/kleur-4.1.5.tgz",
+ "integrity": "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/lightningcss": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz",
+ "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==",
+ "dev": true,
+ "license": "MPL-2.0",
+ "dependencies": {
+ "detect-libc": "^2.0.3"
+ },
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ },
+ "optionalDependencies": {
+ "lightningcss-android-arm64": "1.33.0",
+ "lightningcss-darwin-arm64": "1.33.0",
+ "lightningcss-darwin-x64": "1.33.0",
+ "lightningcss-freebsd-x64": "1.33.0",
+ "lightningcss-linux-arm-gnueabihf": "1.33.0",
+ "lightningcss-linux-arm64-gnu": "1.33.0",
+ "lightningcss-linux-arm64-musl": "1.33.0",
+ "lightningcss-linux-x64-gnu": "1.33.0",
+ "lightningcss-linux-x64-musl": "1.33.0",
+ "lightningcss-win32-arm64-msvc": "1.33.0",
+ "lightningcss-win32-x64-msvc": "1.33.0"
+ }
+ },
+ "node_modules/lightningcss-android-arm64": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz",
+ "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-darwin-arm64": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz",
+ "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-darwin-x64": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz",
+ "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-freebsd-x64": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz",
+ "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-linux-arm-gnueabihf": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz",
+ "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-linux-arm64-gnu": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz",
+ "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-linux-arm64-musl": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz",
+ "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-linux-x64-gnu": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz",
+ "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-linux-x64-musl": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz",
+ "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-win32-arm64-msvc": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz",
+ "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-win32-x64-msvc": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz",
+ "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/magic-string": {
+ "version": "0.30.21",
+ "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",
+ "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/sourcemap-codec": "^1.5.5"
+ }
+ },
+ "node_modules/miniflare": {
+ "version": "5.20260815.0-alpha",
+ "resolved": "https://registry.npmjs.org/miniflare/-/miniflare-5.20260815.0-alpha.tgz",
+ "integrity": "sha512-YAaGj4Sh5f4fqHKiMQ8zRHDOOM5IGUVtMhnLIeyjuQfU+9P6hcOTrHUVtbfj/ZPay9Kzik4pWELB39pGgefjiQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@cspotcode/source-map-support": "0.8.1",
+ "sharp": "0.35.2",
+ "undici": "7.29.0",
+ "workerd": "1.20260815.1",
+ "ws": "8.21.0",
+ "youch": "4.1.0-beta.10"
+ },
+ "engines": {
+ "node": ">=22.0.0"
+ }
+ },
+ "node_modules/nanoid": {
+ "version": "3.3.19",
+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.19.tgz",
+ "integrity": "sha512-Y2tUNy4ouw6tq5oDSKeQYGOyhkUBhNOcGV/02KC+6kd9eDGqdZd++mjMiIDilrBYvjEnCYvVtsuHCuP+okSfug==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "bin": {
+ "nanoid": "bin/nanoid.cjs"
+ },
+ "engines": {
+ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
+ }
+ },
+ "node_modules/obug": {
+ "version": "2.2.1",
+ "resolved": "https://registry.npmjs.org/obug/-/obug-2.2.1.tgz",
+ "integrity": "sha512-XrsrhT5sybtKI6wakr2SPOlGZWWYbUXZ7a0jT8/QOeAPau+1X/bSegNe5YR75oJmEZQbKningirmGOEJCIk61Q==",
+ "dev": true,
+ "funding": [
+ "https://github.com/sponsors/sxzz",
+ "https://opencollective.com/debug"
+ ],
+ "license": "MIT",
+ "engines": {
+ "node": ">=12.20.0"
+ }
+ },
+ "node_modules/path-to-regexp": {
+ "version": "6.3.0",
+ "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-6.3.0.tgz",
+ "integrity": "sha512-Yhpw4T9C6hPpgPeA28us07OJeqZ5EzQTkbfwuhsUg0c237RomFoETJgmp2sa3F/41gfLE6G5cqcYwznmeEeOlQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/pathe": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz",
+ "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/picocolors": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
+ "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
+ "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/picomatch": {
+ "version": "4.0.7",
+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz",
+ "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/jonschlinkert"
+ }
+ },
+ "node_modules/postcss": {
+ "version": "8.5.28",
+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.28.tgz",
+ "integrity": "sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/postcss/"
+ },
+ {
+ "type": "tidelift",
+ "url": "https://tidelift.com/funding/github/npm/postcss"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "nanoid": "^3.3.18",
+ "picocolors": "^1.1.1",
+ "source-map-js": "^1.2.1"
+ },
+ "engines": {
+ "node": "^10 || ^12 || >=14"
+ }
+ },
+ "node_modules/rolldown": {
+ "version": "1.2.11",
+ "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.11.tgz",
+ "integrity": "sha512-qpSwIyz0jHQq5qXBTNxFmE6664rJ7O+4TvPFOiOaBSrz8IOHc1koKKSqTM2H6u1UG1+TveuC6vaDHKXFOvb1Kw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@oxc-project/types": "=0.151.0",
+ "@rolldown/pluginutils": "^1.0.0"
+ },
+ "bin": {
+ "rolldown": "bin/cli.mjs"
+ },
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ },
+ "optionalDependencies": {
+ "@rolldown/binding-android-arm-eabi": "1.2.11",
+ "@rolldown/binding-android-arm64": "1.2.11",
+ "@rolldown/binding-darwin-arm64": "1.2.11",
+ "@rolldown/binding-darwin-x64": "1.2.11",
+ "@rolldown/binding-freebsd-x64": "1.2.11",
+ "@rolldown/binding-linux-arm-gnueabihf": "1.2.11",
+ "@rolldown/binding-linux-arm64-gnu": "1.2.11",
+ "@rolldown/binding-linux-arm64-musl": "1.2.11",
+ "@rolldown/binding-linux-ppc64-gnu": "1.2.11",
+ "@rolldown/binding-linux-s390x-gnu": "1.2.11",
+ "@rolldown/binding-linux-x64-gnu": "1.2.11",
+ "@rolldown/binding-linux-x64-musl": "1.2.11",
+ "@rolldown/binding-openharmony-arm64": "1.2.11",
+ "@rolldown/binding-win32-arm64-msvc": "1.2.11",
+ "@rolldown/binding-win32-x64-msvc": "1.2.11"
+ }
+ },
+ "node_modules/semver": {
+ "version": "7.8.5",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",
+ "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",
+ "dev": true,
+ "license": "ISC",
+ "bin": {
+ "semver": "bin/semver.js"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/sharp": {
+ "version": "0.35.2",
+ "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.2.tgz",
+ "integrity": "sha512-FVtFjtBCMiJS6yb5CX7Sop45WFMpeGw6oRKuJnXYgf/f1ms/D7LE/ZUSNxnW7rZ/dbslQWYkoqFHGPaDBtaK4w==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@img/colour": "^1.1.0",
+ "detect-libc": "^2.1.2",
+ "semver": "^7.8.4"
+ },
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-darwin-arm64": "0.35.2",
+ "@img/sharp-darwin-x64": "0.35.2",
+ "@img/sharp-freebsd-wasm32": "0.35.2",
+ "@img/sharp-libvips-darwin-arm64": "1.3.1",
+ "@img/sharp-libvips-darwin-x64": "1.3.1",
+ "@img/sharp-libvips-linux-arm": "1.3.1",
+ "@img/sharp-libvips-linux-arm64": "1.3.1",
+ "@img/sharp-libvips-linux-ppc64": "1.3.1",
+ "@img/sharp-libvips-linux-riscv64": "1.3.1",
+ "@img/sharp-libvips-linux-s390x": "1.3.1",
+ "@img/sharp-libvips-linux-x64": "1.3.1",
+ "@img/sharp-libvips-linuxmusl-arm64": "1.3.1",
+ "@img/sharp-libvips-linuxmusl-x64": "1.3.1",
+ "@img/sharp-linux-arm": "0.35.2",
+ "@img/sharp-linux-arm64": "0.35.2",
+ "@img/sharp-linux-ppc64": "0.35.2",
+ "@img/sharp-linux-riscv64": "0.35.2",
+ "@img/sharp-linux-s390x": "0.35.2",
+ "@img/sharp-linux-x64": "0.35.2",
+ "@img/sharp-linuxmusl-arm64": "0.35.2",
+ "@img/sharp-linuxmusl-x64": "0.35.2",
+ "@img/sharp-webcontainers-wasm32": "0.35.2",
+ "@img/sharp-win32-arm64": "0.35.2",
+ "@img/sharp-win32-ia32": "0.35.2",
+ "@img/sharp-win32-x64": "0.35.2"
+ }
+ },
+ "node_modules/siginfo": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz",
+ "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==",
+ "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/source-map-js": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
+ "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",
+ "dev": true,
+ "license": "BSD-3-Clause",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/stackback": {
+ "version": "0.0.2",
+ "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz",
+ "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/standardwebhooks": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/standardwebhooks/-/standardwebhooks-1.1.1.tgz",
+ "integrity": "sha512-bCbX9ZEyFkWPsRz7Bl3NuQUJohmwGSev/yhr7vhaGPlc4AfIrspIRa6cPTBuI1ItmrTDJ4d/S2hCsfe4+vQGnQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@stablelib/base64": "^1.0.0",
+ "fast-sha256": "^1.3.0"
+ }
+ },
+ "node_modules/std-env": {
+ "version": "4.2.0",
+ "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.2.0.tgz",
+ "integrity": "sha512-oCUKSupKTHX53EyjDtuZQ64pjLJ6yYCtpmEw0goYxtjG9KpbRe8KAsl2tBUGU9DyMcJ0RwJ8GqJAFzMXcXW1Rw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/supports-color": {
+ "version": "10.2.2",
+ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-10.2.2.tgz",
+ "integrity": "sha512-SS+jx45GF1QjgEXQx4NJZV9ImqmO2NPz5FNsIHrsDjh2YsHnawpan7SNQ1o8NuhrbHZy9AZhIoCUiCeaW/C80g==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "url": "https://github.com/chalk/supports-color?sponsor=1"
+ }
+ },
+ "node_modules/svix": {
+ "version": "2.5.0",
+ "resolved": "https://registry.npmjs.org/svix/-/svix-2.5.0.tgz",
+ "integrity": "sha512-mqcwCPKL6J5yqC2EQy5ZqE5XEJriCZffy49EGBDCsnrQ7RAYF4kZLJhKfXrB0n21S+3M9qYmQ9YjzrNjRlIuCw==",
+ "license": "MIT",
+ "dependencies": {
+ "standardwebhooks": "^1.1.1"
+ },
+ "engines": {
+ "node": ">=22"
+ }
+ },
+ "node_modules/tinybench": {
+ "version": "2.9.0",
+ "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz",
+ "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/tinyexec": {
+ "version": "1.3.1",
+ "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.3.1.tgz",
+ "integrity": "sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tinyglobby": {
+ "version": "0.2.17",
+ "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",
+ "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "fdir": "^6.5.0",
+ "picomatch": "^4.0.4"
+ },
+ "engines": {
+ "node": ">=12.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/SuperchupuDev"
+ }
+ },
+ "node_modules/tinyrainbow": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.1.1.tgz",
+ "integrity": "sha512-yau8yJdTt989Mm0Bd/236QnzEiPf2xLLTqUZRUJOo/3CB078LSwzei343DgtJVmfJKJE3TMINY1u42SQsP6mXw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=14.0.0"
+ }
+ },
+ "node_modules/tslib": {
+ "version": "2.8.1",
+ "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
+ "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
+ "license": "0BSD"
+ },
+ "node_modules/typescript": {
+ "version": "5.9.3",
+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
+ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "bin": {
+ "tsc": "bin/tsc",
+ "tsserver": "bin/tsserver"
+ },
+ "engines": {
+ "node": ">=14.17"
+ }
+ },
+ "node_modules/undici": {
+ "version": "7.29.0",
+ "resolved": "https://registry.npmjs.org/undici/-/undici-7.29.0.tgz",
+ "integrity": "sha512-IDxfleLmmbSskfWSUATiN1nfn2rDuvnMOqb5CWR92iIfojA0Ud+ulOAAEQ57LPr9rWmsreUyf5lwyao+7GNNVw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=20.18.1"
+ }
+ },
+ "node_modules/undici-types": {
+ "version": "8.9.0",
+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz",
+ "integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/unenv": {
+ "version": "2.0.0-rc.24",
+ "resolved": "https://registry.npmjs.org/unenv/-/unenv-2.0.0-rc.24.tgz",
+ "integrity": "sha512-i7qRCmY42zmCwnYlh9H2SvLEypEFGye5iRmEMKjcGi7zk9UquigRjFtTLz0TYqr0ZGLZhaMHl/foy1bZR+Cwlw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "pathe": "^2.0.3"
+ }
+ },
+ "node_modules/vite": {
+ "version": "8.3.1",
+ "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.1.tgz",
+ "integrity": "sha512-/bvH9E9tmCXRGp2uXY3WbOldqpTwFkbha/8ANaEQ6VkxhH60KyqLwgZq6lG2y+4uT55x9+9eUHMpQ7uGnOCKjA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "lightningcss": "^1.33.0",
+ "picomatch": "^4.0.7",
+ "postcss": "^8.5.28",
+ "rolldown": "~1.2.9",
+ "tinyglobby": "^0.2.17"
+ },
+ "bin": {
+ "vite": "bin/vite.js"
+ },
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ },
+ "funding": {
+ "url": "https://github.com/vitejs/vite?sponsor=1"
+ },
+ "optionalDependencies": {
+ "fsevents": "~2.3.3"
+ },
+ "peerDependencies": {
+ "@types/node": "^20.19.0 || >=22.12.0",
+ "@vitejs/devtools": "^0.7.1",
+ "esbuild": "^0.27.0 || ^0.28.0",
+ "jiti": ">=1.21.0",
+ "less": "^4.0.0",
+ "sass": "^1.70.0",
+ "sass-embedded": "^1.70.0",
+ "stylus": ">=0.54.8",
+ "sugarss": "^5.0.0",
+ "terser": "^5.16.0",
+ "tsx": "^4.8.1",
+ "yaml": "^2.4.2"
+ },
+ "peerDependenciesMeta": {
+ "@types/node": {
+ "optional": true
+ },
+ "@vitejs/devtools": {
+ "optional": true
+ },
+ "esbuild": {
+ "optional": true
+ },
+ "jiti": {
+ "optional": true
+ },
+ "less": {
+ "optional": true
+ },
+ "sass": {
+ "optional": true
+ },
+ "sass-embedded": {
+ "optional": true
+ },
+ "stylus": {
+ "optional": true
+ },
+ "sugarss": {
+ "optional": true
+ },
+ "terser": {
+ "optional": true
+ },
+ "tsx": {
+ "optional": true
+ },
+ "yaml": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/vitest": {
+ "version": "4.1.11",
+ "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.11.tgz",
+ "integrity": "sha512-fhACrNXUidIbGSBr5FlbuBkO7VWC1ZyLl0DO4CU2DrQoAPxX84Ysxs+HeGQpii5lZWV1Q4gBZTTu49mF+A6Edw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/expect": "4.1.11",
+ "@vitest/mocker": "4.1.11",
+ "@vitest/pretty-format": "4.1.11",
+ "@vitest/runner": "4.1.11",
+ "@vitest/snapshot": "4.1.11",
+ "@vitest/spy": "4.1.11",
+ "@vitest/utils": "4.1.11",
+ "es-module-lexer": "^2.0.0",
+ "expect-type": "^1.3.0",
+ "magic-string": "^0.30.21",
+ "obug": "^2.1.1",
+ "pathe": "^2.0.3",
+ "picomatch": "^4.0.3",
+ "std-env": "^4.0.0-rc.1",
+ "tinybench": "^2.9.0",
+ "tinyexec": "^1.0.2",
+ "tinyglobby": "^0.2.15",
+ "tinyrainbow": "^3.1.0",
+ "vite": "^6.0.0 || ^7.0.0 || ^8.0.0",
+ "why-is-node-running": "^2.3.0"
+ },
+ "bin": {
+ "vitest": "vitest.mjs"
+ },
+ "engines": {
+ "node": "^20.0.0 || ^22.0.0 || >=24.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ },
+ "peerDependencies": {
+ "@edge-runtime/vm": "*",
+ "@opentelemetry/api": "^1.9.0",
+ "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0",
+ "@vitest/browser-playwright": "4.1.11",
+ "@vitest/browser-preview": "4.1.11",
+ "@vitest/browser-webdriverio": "4.1.11",
+ "@vitest/coverage-istanbul": "4.1.11",
+ "@vitest/coverage-v8": "4.1.11",
+ "@vitest/ui": "4.1.11",
+ "happy-dom": "*",
+ "jsdom": "*",
+ "vite": "^6.0.0 || ^7.0.0 || ^8.0.0"
+ },
+ "peerDependenciesMeta": {
+ "@edge-runtime/vm": {
+ "optional": true
+ },
+ "@opentelemetry/api": {
+ "optional": true
+ },
+ "@types/node": {
+ "optional": true
+ },
+ "@vitest/browser-playwright": {
+ "optional": true
+ },
+ "@vitest/browser-preview": {
+ "optional": true
+ },
+ "@vitest/browser-webdriverio": {
+ "optional": true
+ },
+ "@vitest/coverage-istanbul": {
+ "optional": true
+ },
+ "@vitest/coverage-v8": {
+ "optional": true
+ },
+ "@vitest/ui": {
+ "optional": true
+ },
+ "happy-dom": {
+ "optional": true
+ },
+ "jsdom": {
+ "optional": true
+ },
+ "vite": {
+ "optional": false
+ }
+ }
+ },
+ "node_modules/why-is-node-running": {
+ "version": "2.3.0",
+ "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz",
+ "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "siginfo": "^2.0.0",
+ "stackback": "0.0.2"
+ },
+ "bin": {
+ "why-is-node-running": "cli.js"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/workerd": {
+ "version": "1.20260815.1",
+ "resolved": "https://registry.npmjs.org/workerd/-/workerd-1.20260815.1.tgz",
+ "integrity": "sha512-8bArFkHmlp7qFEKVPyNzDzHzS35gc2fg0PYBcDtaNLF7UCDryCX2BQnpkUkTHYIy824IRrHOTwOEoTj0sUO2Fg==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "Apache-2.0",
+ "bin": {
+ "workerd": "bin/workerd"
+ },
+ "engines": {
+ "node": ">=16"
+ },
+ "optionalDependencies": {
+ "@cloudflare/workerd-darwin-64": "1.20260815.1",
+ "@cloudflare/workerd-darwin-arm64": "1.20260815.1",
+ "@cloudflare/workerd-linux-64": "1.20260815.1",
+ "@cloudflare/workerd-linux-arm64": "1.20260815.1",
+ "@cloudflare/workerd-windows-64": "1.20260815.1"
+ }
+ },
+ "node_modules/wrangler": {
+ "version": "4.140.0",
+ "resolved": "https://registry.npmjs.org/wrangler/-/wrangler-4.140.0.tgz",
+ "integrity": "sha512-XeKeC33B4Nglg0RAJ8F8ecGHOW+cPFeE5+fp4WBzn1c0u+H/96cVQYjto3/0ahilfPurnnGcUslJ1xaZXy+NGQ==",
+ "dev": true,
+ "license": "MIT OR Apache-2.0",
+ "dependencies": {
+ "@cloudflare/kv-asset-handler": "0.5.0",
+ "@cloudflare/unenv-preset": "2.16.2",
+ "blake3-wasm": "2.1.5",
+ "esbuild": "0.28.1",
+ "miniflare": "5.20260923.0-alpha",
+ "path-to-regexp": "6.3.0",
+ "unenv": "2.0.0-rc.24",
+ "workerd": "1.20260923.1"
+ },
+ "bin": {
+ "cf-wrangler": "bin/cf-wrangler.js",
+ "wrangler": "bin/wrangler.js",
+ "wrangler2": "bin/wrangler.js"
+ },
+ "engines": {
+ "node": ">=22.0.0"
+ },
+ "optionalDependencies": {
+ "fsevents": "2.3.3"
+ },
+ "peerDependencies": {
+ "@cloudflare/workers-types": "^5.20260923.1"
+ },
+ "peerDependenciesMeta": {
+ "@cloudflare/workers-types": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/wrangler/node_modules/@cloudflare/workerd-darwin-64": {
+ "version": "1.20260923.1",
+ "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-64/-/workerd-darwin-64-1.20260923.1.tgz",
+ "integrity": "sha512-sFMyHjABspfVxAf9bmcRdYWm3rO5Vrmhb3fLboMB5Lt+Eo+X1Fj4n/3hgMYmXb6P+zW+cjWjZdH1ilE+Ad5kDw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=16"
+ }
+ },
+ "node_modules/wrangler/node_modules/@cloudflare/workerd-darwin-arm64": {
+ "version": "1.20260923.1",
+ "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-arm64/-/workerd-darwin-arm64-1.20260923.1.tgz",
+ "integrity": "sha512-t/O1jcuag+JO5VnFblf20B960FU/WSmn/n2Lcy021cBUhWnhApO9yx1VjJ7I4KhS09yXLgC2shHTzB9EnbSQpg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=16"
+ }
+ },
+ "node_modules/wrangler/node_modules/@cloudflare/workerd-linux-64": {
+ "version": "1.20260923.1",
+ "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-64/-/workerd-linux-64-1.20260923.1.tgz",
+ "integrity": "sha512-6X9fp5vFBJG0BXrjOcB4yqyqZRtZ/Jx4KRAmEp5FPxuNUbf3n6ogzZvD2s0YS+DC2zNKb0gd1lIiOye7AaGnvA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=16"
+ }
+ },
+ "node_modules/wrangler/node_modules/@cloudflare/workerd-linux-arm64": {
+ "version": "1.20260923.1",
+ "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-arm64/-/workerd-linux-arm64-1.20260923.1.tgz",
+ "integrity": "sha512-esOXfxhDp2YPjZmMrO3OLa/9qAfa/uXQGwFGDyUWNF3aXkwE8fc6oauZS01UDk8YwuYlxsyjLQIKjJOrzJ2N+g==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=16"
+ }
+ },
+ "node_modules/wrangler/node_modules/@cloudflare/workerd-windows-64": {
+ "version": "1.20260923.1",
+ "resolved": "https://registry.npmjs.org/@cloudflare/workerd-windows-64/-/workerd-windows-64-1.20260923.1.tgz",
+ "integrity": "sha512-Hlda2apkBcRtPQD4NnEZiEqKLIhR7au+8skF+tBHBa1jsX1/GfuYEdIR0HJ6He1qkSNkxD/Y0VXo+TNgUc1EUg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=16"
+ }
+ },
+ "node_modules/wrangler/node_modules/@img/sharp-darwin-arm64": {
+ "version": "0.35.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.35.4.tgz",
+ "integrity": "sha512-Uhfl4V4lhP2nbUVF9+hyH1+luj86f1gUFeo8ALYxFoULoU+G87D43BfeMP8XHsk9boxAnCY/bf2EHwhA7MuGsA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-darwin-arm64": "1.3.3"
+ }
+ },
+ "node_modules/wrangler/node_modules/@img/sharp-darwin-x64": {
+ "version": "0.35.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.35.4.tgz",
+ "integrity": "sha512-hWniXY3bG5qKpkKrAwPe4y+VTPmf086YQAnkxWh7uA1YrlRouWGa0M0Mxj3ZjnXFkv7/TD1bTy9lGUK26vRvWw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-darwin-x64": "1.3.3"
+ }
+ },
+ "node_modules/wrangler/node_modules/@img/sharp-freebsd-wasm32": {
+ "version": "0.35.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-freebsd-wasm32/-/sharp-freebsd-wasm32-0.35.4.tgz",
+ "integrity": "sha512-lIsKw/BU+kjB4eZjxrYrZmwOJYi3Ajrv66iAlBmUPyKc3HpnloevB1g3wxGD9P/5BbQ1brBGl65VRRrCvQDEqA==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "dependencies": {
+ "@img/sharp-wasm32": "0.35.4"
+ },
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/wrangler/node_modules/@img/sharp-libvips-darwin-arm64": {
+ "version": "1.3.3",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.3.3.tgz",
+ "integrity": "sha512-suTBPTDGrI9WodccaDdwZItTSaBYASlBk1NSfElSHrUfzu3szG6lvIF58+WiFvnfzuK8ZBFS5zE00PxqxnRiPg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/wrangler/node_modules/@img/sharp-libvips-darwin-x64": {
+ "version": "1.3.3",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.3.3.tgz",
+ "integrity": "sha512-FVJZ5mITMobmXIz/hPDTw0EintTW5H3WfrxwLqEqjiIihlu+hVRyGrFQ60xl0Lxn7Bt3zdpevPaQi0HEzqz9fw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/wrangler/node_modules/@img/sharp-libvips-linux-arm": {
+ "version": "1.3.3",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.3.3.tgz",
+ "integrity": "sha512-3rbU4vqXXc3hY/OiXdl52xZvT0F1yEngWfvqudtPJg/KkyiaQw2DRsFrNzpmLvfavbwOq3qXn36GP8obHRULQA==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/wrangler/node_modules/@img/sharp-libvips-linux-arm64": {
+ "version": "1.3.3",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.3.3.tgz",
+ "integrity": "sha512-0DaL0A6Xu6sQSQFwe4iVCrKWU2cCTItnRsYsCdxAMm9NF6twAA9BKnoqy4hqz4+azQ0JHuA26qiUKsf1XJ/v5A==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/wrangler/node_modules/@img/sharp-libvips-linux-ppc64": {
+ "version": "1.3.3",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.3.3.tgz",
+ "integrity": "sha512-cdn1OvUBwsXhbC0zSzJnNzf5MZ/mTrobawDvNXBTxe8VtqKAm0sRuEY2Evzovb/w9JMk4TvRxqt1mekSuJz64w==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/wrangler/node_modules/@img/sharp-libvips-linux-riscv64": {
+ "version": "1.3.3",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.3.3.tgz",
+ "integrity": "sha512-HjPVx7yKz+0lqdhDlTw1tt90wamBoxhiXpvl1XZpJLiHH4RCJ5yDTqH+VlYPv2fwFs89JFw4c1IexYOcQUi4IQ==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/wrangler/node_modules/@img/sharp-libvips-linux-s390x": {
+ "version": "1.3.3",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.3.3.tgz",
+ "integrity": "sha512-neWLh+3yCNThxnfy3c4BbVBeGgt9aftno+XbT56iK28RgeDs3UOFWviLWlUu0bArYVYJaFDK+RRohbicUNCm8Q==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/wrangler/node_modules/@img/sharp-libvips-linux-x64": {
+ "version": "1.3.3",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.3.3.tgz",
+ "integrity": "sha512-4vKmvAst9nrowcqquKFAyZJUDolUaIp8uRiN0mWFguJ1IplC9/pitXtlnnlU4aa/eJw3J7i67V+pwUL+wZGdsA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/wrangler/node_modules/@img/sharp-libvips-linuxmusl-arm64": {
+ "version": "1.3.3",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.3.3.tgz",
+ "integrity": "sha512-Y9kQaLMuNoB0bPYOOdcZMaseNrFpPodIWWMrx+CZyydf2xn68j9WYc6sWWRrDwNkzCQjKYfc68L7jKjGlHMibw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/wrangler/node_modules/@img/sharp-libvips-linuxmusl-x64": {
+ "version": "1.3.3",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.3.3.tgz",
+ "integrity": "sha512-fj8Mv0HHfD1Rr+4I68+3agJynxDWtBFgicTbSOb9Bke6pIwzGcJ+RX/yHjmiEGFMCavY/dxvem7MyNaJF+wDiw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/wrangler/node_modules/@img/sharp-linux-arm": {
+ "version": "0.35.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.35.4.tgz",
+ "integrity": "sha512-7OAS8gI0EReKGVN2HssHlM6umJgxF5VI3xN0p9FA91p/YO+ou5hiNghLdZ5BEHztwaaK5+bLKRf8x/o2L2nk9A==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linux-arm": "1.3.3"
+ }
+ },
+ "node_modules/wrangler/node_modules/@img/sharp-linux-arm64": {
+ "version": "0.35.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.35.4.tgz",
+ "integrity": "sha512-De4jpEnAU8Hd5oT0j1G3uL4ZvTuipVMn7YC6vPaJhy6/7EwEae0SVAoBrUMYQbkLGDm85taVWwuPc1a44LTzCQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linux-arm64": "1.3.3"
+ }
+ },
+ "node_modules/wrangler/node_modules/@img/sharp-linux-ppc64": {
+ "version": "0.35.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.35.4.tgz",
+ "integrity": "sha512-2oYZJeIl4kCcMGk4ouZVjnkCtFrpQFlNEtJ6GbxzhHQchwH0NH/qEb9ykmOl29dqwMq+JhFdZn+1ak2FKhI9fQ==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linux-ppc64": "1.3.3"
+ }
+ },
+ "node_modules/wrangler/node_modules/@img/sharp-linux-riscv64": {
+ "version": "0.35.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.35.4.tgz",
+ "integrity": "sha512-cPbNChoRURAWdebDIHSenxRpgEdy7JkPydSnUxRm9VvKD7m0/xVaR/8Fzlu81pk5nHEvHH87UZUA7cTtwnbJSA==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linux-riscv64": "1.3.3"
+ }
+ },
+ "node_modules/wrangler/node_modules/@img/sharp-linux-s390x": {
+ "version": "0.35.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.35.4.tgz",
+ "integrity": "sha512-RY0JFY8Fd6RonCBtHz+DvadaPkXDSI1AUn6yWL9TipqkZ1vY8w8evqdgyDFnkm4/K1ve1TvZiaePP5oSd4+WVQ==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linux-s390x": "1.3.3"
+ }
+ },
+ "node_modules/wrangler/node_modules/@img/sharp-linux-x64": {
+ "version": "0.35.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.35.4.tgz",
+ "integrity": "sha512-9qvvEAuk8k89TfWUoX2htWjbAMX8p+NxCppjpcg5k6xMsjhBQPTsoIh36h9Qde4WRuGpJeYnOjdosDn/cnv+OA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linux-x64": "1.3.3"
+ }
+ },
+ "node_modules/wrangler/node_modules/@img/sharp-linuxmusl-arm64": {
+ "version": "0.35.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.35.4.tgz",
+ "integrity": "sha512-KB5jxpfWQTr0nc3xdHtWChdbifHrBGsd2SM62Eyxrl8afikm+f5qGBU75SJIZBT/S1MC8XyacdlXBMSWq6OURA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linuxmusl-arm64": "1.3.3"
+ }
+ },
+ "node_modules/wrangler/node_modules/@img/sharp-linuxmusl-x64": {
+ "version": "0.35.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.35.4.tgz",
+ "integrity": "sha512-f+eZJZIQNEEd26RPSW+76chwOf1XtA2Y/O+5ocVyLliHkeih3e+jhLVBdNTd2rS3IbNXK8+ug93Vf5ZXtF5Lxg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linuxmusl-x64": "1.3.3"
+ }
+ },
+ "node_modules/wrangler/node_modules/@img/sharp-wasm32": {
+ "version": "0.35.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.35.4.tgz",
+ "integrity": "sha512-zQnl4Kwp7Q6NHsENtU2T/00Zi+w3AQNwz3+UaTyVBy2FpXrzXzGjndpK61onhZjRtRpQXxCTeqw19bVyXOh7jA==",
+ "dev": true,
+ "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT",
+ "optional": true,
+ "dependencies": {
+ "@emnapi/runtime": "^1.11.3"
+ },
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/wrangler/node_modules/@img/sharp-webcontainers-wasm32": {
+ "version": "0.35.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-webcontainers-wasm32/-/sharp-webcontainers-wasm32-0.35.4.tgz",
+ "integrity": "sha512-ESfNkywmCfPNyaZjxooddJQiQ+l/nTpGEOGthxiLnIHXC/CmcBixnfwUleX9mCz9ovrUUvKMap/pm8RYbzfwaA==",
+ "cpu": [
+ "wasm32"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "dependencies": {
+ "@img/sharp-wasm32": "0.35.4"
+ },
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/wrangler/node_modules/@img/sharp-win32-arm64": {
+ "version": "0.35.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.35.4.tgz",
+ "integrity": "sha512-iNdlBX9gLVvqe2I3uIJSIKTq6wckP/DYxZtcqxm09x5Gi24DnFBmPAWZmr60ZyYMG0xlzo6goG3670ar+RXvRw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0 AND LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/wrangler/node_modules/@img/sharp-win32-ia32": {
+ "version": "0.35.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.35.4.tgz",
+ "integrity": "sha512-kqRsbaa5CS6KHlpxnN7WhE6vAAugXyZButpRdvDWetlv6Qv4N9WTcrWzF7tXfB9T7MsoadqdI8hmwLq6UlLvtw==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "Apache-2.0 AND LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": "^20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/wrangler/node_modules/@img/sharp-win32-x64": {
+ "version": "0.35.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.35.4.tgz",
+ "integrity": "sha512-XtmnYhBcrORsJ4XJngyzr/EWP0hRZLAZRFaApdKuviyqF78+ylxh2y06ZmtULAMOnObJ3ucpN0AcwSWnMowTRg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0 AND LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/wrangler/node_modules/miniflare": {
+ "version": "5.20260923.0-alpha",
+ "resolved": "https://registry.npmjs.org/miniflare/-/miniflare-5.20260923.0-alpha.tgz",
+ "integrity": "sha512-tmICPUd2P+/4WNa2A9kE22SPZexlu+Dw8nZIvaXCzRj2OVu62hc751Xq4S1P4HEscT5viDle3zxyHyxT2XY3Fw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@cspotcode/source-map-support": "0.8.1",
+ "sharp": "0.35.4",
+ "undici": "7.29.0",
+ "workerd": "1.20260923.1",
+ "ws": "8.21.0",
+ "youch": "4.1.0-beta.10"
+ },
+ "engines": {
+ "node": ">=22.0.0"
+ }
+ },
+ "node_modules/wrangler/node_modules/sharp": {
+ "version": "0.35.4",
+ "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.4.tgz",
+ "integrity": "sha512-n++8XWcj+jCOr2IOl7h8LbKnGBDY4aPbmprMONBNFdn0ImXqpGVv5zliDs0V9HbmbCQLpbuo2ej9rAoOQTvMDA==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@img/colour": "^1.1.0",
+ "detect-libc": "^2.1.2",
+ "semver": "^7.8.5"
+ },
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-darwin-arm64": "0.35.4",
+ "@img/sharp-darwin-x64": "0.35.4",
+ "@img/sharp-freebsd-wasm32": "0.35.4",
+ "@img/sharp-libvips-darwin-arm64": "1.3.3",
+ "@img/sharp-libvips-darwin-x64": "1.3.3",
+ "@img/sharp-libvips-linux-arm": "1.3.3",
+ "@img/sharp-libvips-linux-arm64": "1.3.3",
+ "@img/sharp-libvips-linux-ppc64": "1.3.3",
+ "@img/sharp-libvips-linux-riscv64": "1.3.3",
+ "@img/sharp-libvips-linux-s390x": "1.3.3",
+ "@img/sharp-libvips-linux-x64": "1.3.3",
+ "@img/sharp-libvips-linuxmusl-arm64": "1.3.3",
+ "@img/sharp-libvips-linuxmusl-x64": "1.3.3",
+ "@img/sharp-linux-arm": "0.35.4",
+ "@img/sharp-linux-arm64": "0.35.4",
+ "@img/sharp-linux-ppc64": "0.35.4",
+ "@img/sharp-linux-riscv64": "0.35.4",
+ "@img/sharp-linux-s390x": "0.35.4",
+ "@img/sharp-linux-x64": "0.35.4",
+ "@img/sharp-linuxmusl-arm64": "0.35.4",
+ "@img/sharp-linuxmusl-x64": "0.35.4",
+ "@img/sharp-webcontainers-wasm32": "0.35.4",
+ "@img/sharp-win32-arm64": "0.35.4",
+ "@img/sharp-win32-ia32": "0.35.4",
+ "@img/sharp-win32-x64": "0.35.4"
+ },
+ "peerDependenciesMeta": {
+ "@types/node": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/wrangler/node_modules/workerd": {
+ "version": "1.20260923.1",
+ "resolved": "https://registry.npmjs.org/workerd/-/workerd-1.20260923.1.tgz",
+ "integrity": "sha512-1xynegnJJqkgk/zuhNVcOFzAJXzsJ4UxazfThUe0K80eZXKpsRIXI2sHcT4trswLfeHCc+3uWTBvtSWLFRozbQ==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "Apache-2.0",
+ "bin": {
+ "workerd": "bin/workerd"
+ },
+ "engines": {
+ "node": ">=16"
+ },
+ "optionalDependencies": {
+ "@cloudflare/workerd-darwin-64": "1.20260923.1",
+ "@cloudflare/workerd-darwin-arm64": "1.20260923.1",
+ "@cloudflare/workerd-linux-64": "1.20260923.1",
+ "@cloudflare/workerd-linux-arm64": "1.20260923.1",
+ "@cloudflare/workerd-windows-64": "1.20260923.1"
+ }
+ },
+ "node_modules/ws": {
+ "version": "8.21.0",
+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz",
+ "integrity": "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=10.0.0"
+ },
+ "peerDependencies": {
+ "bufferutil": "^4.0.1",
+ "utf-8-validate": ">=5.0.2"
+ },
+ "peerDependenciesMeta": {
+ "bufferutil": {
+ "optional": true
+ },
+ "utf-8-validate": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/youch": {
+ "version": "4.1.0-beta.10",
+ "resolved": "https://registry.npmjs.org/youch/-/youch-4.1.0-beta.10.tgz",
+ "integrity": "sha512-rLfVLB4FgQneDr0dv1oddCVZmKjcJ6yX6mS4pU82Mq/Dt9a3cLZQ62pDBL4AUO+uVrCvtWz3ZFUL2HFAFJ/BXQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@poppinss/colors": "^4.1.5",
+ "@poppinss/dumper": "^0.6.4",
+ "@speed-highlight/core": "^1.2.7",
+ "cookie": "^1.0.2",
+ "youch-core": "^0.3.3"
+ }
+ },
+ "node_modules/youch-core": {
+ "version": "0.3.3",
+ "resolved": "https://registry.npmjs.org/youch-core/-/youch-core-0.3.3.tgz",
+ "integrity": "sha512-ho7XuGjLaJ2hWHoK8yFnsUGy2Y5uDpqSTq1FkHLK4/oqKtyUU1AFbOOxY4IpC9f0fTLjwYbslUz0Po5BpD1wrA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@poppinss/exception": "^1.2.2",
+ "error-stack-parser-es": "^1.0.5"
+ }
+ },
+ "node_modules/zod": {
+ "version": "4.4.3",
+ "resolved": "https://registry.npmjs.org/zod/-/zod-4.4.3.tgz",
+ "integrity": "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/colinhacks"
+ }
+ }
+ }
+}
diff --git a/cloud/package.json b/cloud/package.json
new file mode 100644
index 00000000..18c72e83
--- /dev/null
+++ b/cloud/package.json
@@ -0,0 +1,30 @@
+{
+ "name": "codync-cloud",
+ "version": "3.0.0",
+ "description": "Codync cloud: accounts, computers and the end-to-end encrypted relay (Cloudflare Worker + Durable Object)",
+ "private": true,
+ "license": "MIT",
+ "type": "module",
+ "scripts": {
+ "dev": "wrangler dev --env dev",
+ "deploy:staging": "wrangler deploy --env staging",
+ "typecheck": "tsc && tsc -p test/e2e",
+ "test": "vitest run",
+ "e2e": "node --experimental-strip-types --no-warnings test/e2e/relay.e2e.ts"
+ },
+ "dependencies": {
+ "@clerk/backend": "^3.20.1",
+ "svix": "^2.5.0"
+ },
+ "devDependencies": {
+ "@cloudflare/workers-types": "^5.20260925.1",
+ "@noble/ciphers": "^2.4.0",
+ "@noble/curves": "^2.4.0",
+ "@noble/hashes": "^2.4.0",
+ "@types/node": "^26.6.2",
+ "typescript": "^5.9.3",
+ "wrangler": "^4.140.0",
+ "vitest": "~4.1.11",
+ "@cloudflare/vitest-pool-workers": "^0.22.0"
+ }
+}
diff --git a/cloud/src/api.ts b/cloud/src/api.ts
new file mode 100644
index 00000000..e2dec2b6
--- /dev/null
+++ b/cloud/src/api.ts
@@ -0,0 +1,913 @@
+// /v1 HTTP handlers (spec §8.4) and the relay upgrade routes (§7.1).
+
+import { Webhook } from "svix";
+import {
+ COMPUTER_ID,
+ computerIdFor,
+ fromB64url,
+ NONCE_TTL_MS,
+ randomId,
+ utf8,
+ verifyClerk,
+ verifyEd25519,
+ verifySig,
+ type SignedRequest,
+} from "./auth";
+import type { Env } from "./index";
+
+export const VERSION = "3.0.0";
+
+const CLAIM_TTL_MS = 5 * 60_000;
+const REQUEST_TTL_MS = 10 * 60_000;
+const REQUESTS_PER_HOUR = 20;
+const MAX_BODY = 64 * 1024;
+const SCOPES = '["control","screen"]';
+
+// ---- errors ----
+
+const STATUS: Record<string, number> = {
+ badRequest: 400,
+ unauthenticated: 401,
+ badSignature: 401,
+ forbidden: 403,
+ accountDeleted: 403,
+ notFound: 404,
+ unknownComputer: 404,
+ alreadyClaimed: 409,
+ conflict: 409,
+ claimExpired: 410,
+ requestExpired: 410,
+ upgradeRequired: 426,
+ rateLimited: 429,
+ internal: 500,
+};
+
+export class ApiError extends Error {
+ readonly status: number;
+ constructor(
+ readonly code: string,
+ message?: string,
+ status?: number,
+ ) {
+ super(message ?? code);
+ this.status = status ?? STATUS[code] ?? 500;
+ }
+}
+
+// ---- request context ----
+
+export interface Ctx {
+ req: Request;
+ env: Env;
+ exec: ExecutionContext;
+ url: URL;
+ /** Raw body bytes: Codync-Sig hashes exactly these. */
+ raw: Uint8Array;
+ now: number;
+}
+
+type Body = Record<string, unknown>;
+
+function body(c: Ctx): Body {
+ if (c.raw.length > MAX_BODY) throw new ApiError("badRequest", "Body too large");
+ if (!c.raw.length) return {};
+ let v: unknown;
+ try {
+ v = JSON.parse(new TextDecoder().decode(c.raw));
+ } catch {
+ throw new ApiError("badRequest", "Body is not JSON");
+ }
+ if (!v || typeof v !== "object" || Array.isArray(v)) throw new ApiError("badRequest", "Body must be an object");
+ return v as Body;
+}
+
+function str(b: Body, key: string, max = 100): string {
+ const v = b[key];
+ if (typeof v !== "string" || !v.trim() || v.length > max) throw new ApiError("badRequest", `Invalid ${key}`);
+ return v;
+}
+
+function optStr(b: Body, key: string, max = 100): string | null {
+ return b[key] === undefined || b[key] === null ? null : str(b, key, max);
+}
+
+function oneOf<T extends string>(b: Body, key: string, allowed: readonly T[]): T {
+ const v = b[key];
+ if (!allowed.includes(v as T)) throw new ApiError("badRequest", `Invalid ${key}`);
+ return v as T;
+}
+
+/** A base64url field of exactly `len` bytes; returns the original string. */
+function key(b: Body, name: string, len: number): string {
+ if (!fromB64url(b[name], len)) throw new ApiError("badRequest", `Invalid ${name}`);
+ return b[name] as string;
+}
+
+// ---- auth ----
+
+interface User {
+ userId: string;
+ email: string | null;
+ createdAt: number;
+}
+
+async function user(c: Ctx): Promise<User> {
+ const clerk = await verifyClerk(c.req, c.env);
+ if (!clerk) throw new ApiError("unauthenticated");
+ const row = await c.env.DB.prepare(
+ `INSERT INTO accounts(user_id, email, created_at) VALUES (?1, ?2, ?3)
+ ON CONFLICT(user_id) DO UPDATE SET email = COALESCE(excluded.email, accounts.email)
+ RETURNING status, email, created_at`,
+ )
+ .bind(clerk.userId, clerk.email, c.now)
+ .first<{ status: string; email: string | null; created_at: number }>();
+ if (!row || row.status === "deleted") throw new ApiError("accountDeleted");
+ return { userId: clerk.userId, email: row.email, createdAt: row.created_at };
+}
+
+/** Codync-Sig with D1 replay protection (§5). */
+async function signed(c: Ctx): Promise<SignedRequest> {
+ const s = await verifySig(c.req, c.raw, c.now);
+ if (!s) throw new ApiError("badSignature");
+ const r = await c.env.DB.prepare("INSERT OR IGNORE INTO sig_nonces(kid, nonce, expires_at) VALUES (?, ?, ?)")
+ .bind(s.kid, s.nonce, c.now + NONCE_TTL_MS)
+ .run();
+ if (r.meta.changes !== 1) throw new ApiError("badSignature");
+ return s;
+}
+
+interface ComputerRow {
+ id: string;
+ sign_pub: string;
+ box_pub: string;
+ owner_user_id: string | null;
+ name: string;
+ platform: string;
+ device: string | null;
+ version: string;
+ status: string;
+ online: number;
+ last_seen_at: number | null;
+ claimed_at: number | null;
+}
+
+/** Sig(host): the signing key names the computer; it must be registered and not blocked. */
+async function host(c: Ctx): Promise<ComputerRow> {
+ const s = await signed(c);
+ const id = await computerIdFor(fromB64url(s.kid, 32)!);
+ const row = await c.env.DB.prepare("SELECT * FROM computers WHERE id = ?").bind(id).first<ComputerRow>();
+ if (!row) throw new ApiError("unknownComputer");
+ if (row.status !== "active") throw new ApiError("forbidden");
+ return row;
+}
+
+/** Sig(dev) for a device registered (and not revoked) under `userId`. */
+async function device(c: Ctx, userId: string): Promise<{ id: string; dk: string }> {
+ const s = await signed(c);
+ const row = await c.env.DB.prepare(
+ "SELECT id FROM devices WHERE owner_user_id = ? AND sign_pub = ? AND revoked_at IS NULL",
+ )
+ .bind(userId, s.kid)
+ .first<{ id: string }>();
+ if (!row) throw new ApiError("notFound");
+ return { id: row.id, dk: s.kid };
+}
+
+async function ownedComputer(c: Ctx, id: string, userId: string): Promise<ComputerRow> {
+ const row = await c.env.DB.prepare("SELECT * FROM computers WHERE id = ? AND owner_user_id = ?")
+ .bind(id, userId)
+ .first<ComputerRow>();
+ if (!row) throw new ApiError("notFound");
+ return row;
+}
+
+// ---- shared pieces ----
+
+function computerView(r: ComputerRow & { access?: string | null }) {
+ return {
+ computerId: r.id,
+ name: r.name,
+ platform: r.platform,
+ device: r.device,
+ signKey: r.sign_pub,
+ boxKey: r.box_pub,
+ version: r.version,
+ online: r.online === 1,
+ lastSeenAt: r.last_seen_at,
+ claimedAt: r.claimed_at,
+ access: r.access ?? null,
+ };
+}
+
+const audit = (env: Env, actor: string, action: string, target: string | null, result: string, now: number) =>
+ env.DB.prepare("INSERT INTO audit_events(actor, action, target, result, created_at) VALUES (?, ?, ?, ?, ?)").bind(
+ actor,
+ action,
+ target,
+ result,
+ now,
+ );
+
+interface Blocked {
+ dk: string;
+ grantId: string;
+}
+
+/** Statements revoking every active grant matching `filter`, and the DO blocks they imply, per computer. */
+async function revokeGrants(
+ env: Env,
+ filter: string,
+ binds: unknown[],
+ reason: string,
+ now: number,
+): Promise<{ stmts: D1PreparedStatement[]; blocks: Map<string, Blocked[]> }> {
+ const { results } = await env.DB.prepare(
+ `SELECT g.id, g.computer_id, d.sign_pub FROM grants g JOIN devices d ON d.id = g.device_id
+ WHERE g.status = 'active' AND (${filter})`,
+ )
+ .bind(...binds)
+ .all<{ id: string; computer_id: string; sign_pub: string }>();
+ const blocks = new Map<string, Blocked[]>();
+ const stmts = results.map((g) => {
+ blocks.set(g.computer_id, [...(blocks.get(g.computer_id) ?? []), { dk: g.sign_pub, grantId: g.id }]);
+ return env.DB.prepare(
+ "UPDATE grants SET status = 'revoked', revoked_at = ?, revoked_reason = ? WHERE id = ? AND status = 'active'",
+ ).bind(now, reason, g.id);
+ });
+ return { stmts, blocks };
+}
+
+/** Tells a computer's DO: block these devices (closing their sockets), then `cloud.changed` to the host. */
+async function notify(env: Env, computerId: string, blocked: Blocked[] = []): Promise<void> {
+ const path = blocked.length ? "/internal/block" : "/internal/changed";
+ try {
+ const res = await env.RELAY.get(env.RELAY.idFromName(computerId)).fetch(`https://do${path}`, {
+ method: "POST",
+ headers: { "X-Codync-Internal": "1", "Content-Type": "application/json" },
+ body: JSON.stringify(blocked.length ? { devices: blocked } : {}),
+ });
+ if (!res.ok) console.error("relay notify failed", { computerId, path, status: res.status });
+ } catch (e) {
+ console.error("relay notify failed", { computerId, path, error: String(e) });
+ }
+}
+
+/** Removes a computer from its account: grants revoked, pending requests cancelled, sockets closed. */
+async function unclaim(env: Env, id: string, actor: string, now: number): Promise<void> {
+ const { stmts, blocks } = await revokeGrants(env, "g.computer_id = ?", [id], "unclaimed", now);
+ await env.DB.batch([
+ ...stmts,
+ env.DB.prepare("UPDATE computers SET owner_user_id = NULL, claimed_at = NULL, updated_at = ? WHERE id = ?").bind(now, id),
+ env.DB.prepare(
+ "UPDATE access_requests SET status = 'cancelled', decided_at = ? WHERE computer_id = ? AND status = 'pending'",
+ ).bind(now, id),
+ audit(env, actor, "computer.unclaim", id, "ok", now),
+ ]);
+ await notify(env, id, blocks.get(id));
+}
+
+export const claimCanonical = (claimId: string, nonce: string, userId: string, computerId: string, boxKey: string) =>
+ ["codync/claim/v1", claimId, nonce, userId, computerId, boxKey].join("\n");
+
+// ---- public ----
+
+export const health = async () => ({ ok: true, version: VERSION });
+
+// ---- Clerk (users) ----
+
+export async function me(c: Ctx) {
+ const u = await user(c);
+ return { userId: u.userId, email: u.email, createdAt: u.createdAt };
+}
+
+interface DeviceRow {
+ id: string;
+ sign_pub: string;
+ name: string;
+ platform: string;
+ created_at: number;
+ last_used_at: number | null;
+ revoked_at: number | null;
+}
+
+const deviceView = (d: DeviceRow) => ({
+ deviceId: d.id,
+ deviceKey: d.sign_pub,
+ name: d.name,
+ platform: d.platform,
+ createdAt: d.created_at,
+});
+
+export async function registerDevice(c: Ctx) {
+ const u = await user(c);
+ const s = await signed(c);
+ const b = body(c);
+ const name = str(b, "name");
+ const platform = oneOf(b, "platform", ["ios", "macos"] as const);
+ const existing = await c.env.DB.prepare("SELECT * FROM devices WHERE owner_user_id = ? AND sign_pub = ?")
+ .bind(u.userId, s.kid)
+ .first<DeviceRow>();
+ if (existing?.revoked_at) throw new ApiError("forbidden", "This device key was revoked; create a new one");
+ if (existing) {
+ await c.env.DB.prepare("UPDATE devices SET name = ?, platform = ?, last_used_at = ? WHERE id = ?")
+ .bind(name, platform, c.now, existing.id)
+ .run();
+ return { device: deviceView({ ...existing, name, platform }) };
+ }
+ const row: DeviceRow = {
+ id: randomId("dev_"),
+ sign_pub: s.kid,
+ name,
+ platform,
+ created_at: c.now,
+ last_used_at: c.now,
+ revoked_at: null,
+ };
+ await c.env.DB.prepare(
+ `INSERT INTO devices(id, owner_user_id, sign_pub, name, platform, created_at, last_used_at) VALUES (?, ?, ?, ?, ?, ?, ?)
+ ON CONFLICT(owner_user_id, sign_pub) DO NOTHING`,
+ )
+ .bind(row.id, u.userId, row.sign_pub, name, platform, c.now, c.now)
+ .run();
+ // A concurrent registration of the same key wins the insert; report whichever row exists.
+ const saved = await c.env.DB.prepare("SELECT * FROM devices WHERE owner_user_id = ? AND sign_pub = ?")
+ .bind(u.userId, s.kid)
+ .first<DeviceRow>();
+ return { device: deviceView(saved ?? row) };
+}
+
+export async function listDevices(c: Ctx) {
+ const u = await user(c);
+ const { results } = await c.env.DB.prepare("SELECT * FROM devices WHERE owner_user_id = ? ORDER BY created_at")
+ .bind(u.userId)
+ .all<DeviceRow>();
+ return {
+ devices: results.map((d) => ({ ...deviceView(d), lastUsedAt: d.last_used_at, revoked: d.revoked_at !== null })),
+ };
+}
+
+export async function revokeDevice(c: Ctx, [deviceId]: string[]) {
+ const u = await user(c);
+ const d = await c.env.DB.prepare("SELECT id, revoked_at FROM devices WHERE id = ? AND owner_user_id = ?")
+ .bind(deviceId, u.userId)
+ .first<{ id: string; revoked_at: number | null }>();
+ if (!d) throw new ApiError("notFound");
+ if (d.revoked_at) return {};
+ const { stmts, blocks } = await revokeGrants(c.env, "g.device_id = ?", [deviceId], "deviceRevoked", c.now);
+ const pending = await c.env.DB.prepare(
+ "SELECT DISTINCT computer_id FROM access_requests WHERE device_id = ? AND status = 'pending'",
+ )
+ .bind(deviceId)
+ .all<{ computer_id: string }>();
+ await c.env.DB.batch([
+ ...stmts,
+ c.env.DB.prepare("UPDATE devices SET revoked_at = ? WHERE id = ?").bind(c.now, deviceId),
+ c.env.DB.prepare(
+ "UPDATE access_requests SET status = 'cancelled', decided_at = ? WHERE device_id = ? AND status = 'pending'",
+ ).bind(c.now, deviceId),
+ audit(c.env, u.userId, "device.revoke", deviceId, "ok", c.now),
+ ]);
+ const computers = new Set([...blocks.keys(), ...pending.results.map((r) => r.computer_id)]);
+ await Promise.all([...computers].map((id) => notify(c.env, id, blocks.get(id))));
+ return {};
+}
+
+export async function createClaim(c: Ctx) {
+ const u = await user(c);
+ const claimId = randomId("clm_");
+ const nonce = randomId();
+ const expiresAt = c.now + CLAIM_TTL_MS;
+ await c.env.DB.prepare("INSERT INTO claims(id, user_id, nonce, expires_at) VALUES (?, ?, ?, ?)")
+ .bind(claimId, u.userId, nonce, expiresAt)
+ .run();
+ return { claimId, nonce, expiresAt };
+}
+
+export async function completeClaim(c: Ctx, [claimId]: string[]) {
+ const u = await user(c);
+ const b = body(c);
+ const signKey = key(b, "signKey", 32);
+ const boxKey = key(b, "boxKey", 32);
+ const sig = fromB64url(b.sig, 64);
+ const computerId = str(b, "computerId", 22);
+ const name = str(b, "name");
+ const platform = oneOf(b, "platform", ["macos", "linux"] as const);
+ const device = optStr(b, "device", 32);
+ const version = str(b, "version", 32);
+ if (!sig) throw new ApiError("badRequest", "Invalid sig");
+ if (computerId !== (await computerIdFor(fromB64url(signKey, 32)!))) throw new ApiError("badRequest", "computerId doesn't match signKey");
+ const claim = await c.env.DB.prepare("SELECT nonce FROM claims WHERE id = ? AND user_id = ?")
+ .bind(claimId, u.userId)
+ .first<{ nonce: string }>();
+ if (!claim) throw new ApiError("notFound");
+ const canonical = claimCanonical(claimId, claim.nonce, u.userId, computerId, boxKey);
+ if (!(await verifyEd25519(fromB64url(signKey, 32)!, sig, utf8(canonical)))) throw new ApiError("badSignature");
+ const existing = await c.env.DB.prepare("SELECT status FROM computers WHERE id = ?").bind(computerId).first<{ status: string }>();
+ if (existing && existing.status !== "active") throw new ApiError("forbidden");
+
+ const t = c.now;
+ const [consumed, , owned] = await c.env.DB.batch([
+ c.env.DB.prepare(
+ `UPDATE claims SET consumed_at = ?1, computer_id = ?2
+ WHERE id = ?3 AND user_id = ?4 AND consumed_at IS NULL AND expires_at > ?1`,
+ ).bind(t, computerId, claimId, u.userId),
+ // box_pub always comes from the signed boxKey; the row is created only for a valid claim.
+ c.env.DB.prepare(
+ `INSERT INTO computers(id, sign_pub, box_pub, name, platform, device, version, created_at, updated_at)
+ SELECT ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?8 WHERE EXISTS(SELECT 1 FROM claims WHERE id = ?9 AND consumed_at = ?8)
+ ON CONFLICT(id) DO UPDATE SET box_pub = excluded.box_pub, updated_at = excluded.updated_at`,
+ ).bind(computerId, signKey, boxKey, name, platform, device, version, t, claimId),
+ c.env.DB.prepare(
+ `UPDATE computers SET owner_user_id = ?1, claimed_at = ?2, updated_at = ?2
+ WHERE id = ?3 AND owner_user_id IS NULL AND EXISTS(SELECT 1 FROM claims WHERE id = ?4 AND consumed_at = ?2)`,
+ ).bind(u.userId, t, computerId, claimId),
+ ]);
+ if (consumed!.meta.changes === 0) throw new ApiError("claimExpired");
+ const row = await c.env.DB.prepare("SELECT * FROM computers WHERE id = ?").bind(computerId).first<ComputerRow>();
+ if (owned!.meta.changes === 0 && row?.owner_user_id !== u.userId) {
+ await audit(c.env, u.userId, "computer.claim", computerId, "alreadyClaimed", t).run();
+ throw new ApiError("alreadyClaimed");
+ }
+ await audit(c.env, u.userId, "computer.claim", computerId, "ok", t).run();
+ await notify(c.env, computerId);
+ return { computer: computerView(row!) };
+}
+
+export async function listComputers(c: Ctx) {
+ const u = await user(c);
+ let deviceId: string | null = null;
+ if (c.req.headers.has("Codync-Sig")) {
+ const s = await signed(c);
+ const d = await c.env.DB.prepare(
+ "UPDATE devices SET last_used_at = ? WHERE owner_user_id = ? AND sign_pub = ? AND revoked_at IS NULL RETURNING id",
+ )
+ .bind(c.now, u.userId, s.kid)
+ .first<{ id: string }>();
+ deviceId = d?.id ?? null;
+ }
+ const { results } = await c.env.DB.prepare(
+ `SELECT c.*, CASE
+ WHEN ?1 IS NULL THEN NULL
+ WHEN EXISTS(SELECT 1 FROM grants g WHERE g.computer_id = c.id AND g.device_id = ?1 AND g.status = 'active') THEN 'granted'
+ WHEN EXISTS(SELECT 1 FROM access_requests r WHERE r.computer_id = c.id AND r.device_id = ?1
+ AND r.status = 'pending' AND r.expires_at > ?3) THEN 'pending'
+ ELSE 'none' END AS access
+ FROM computers c WHERE c.owner_user_id = ?2 ORDER BY c.claimed_at`,
+ )
+ .bind(deviceId, u.userId, c.now)
+ .all<ComputerRow & { access: string | null }>();
+ return { computers: results.map(computerView) };
+}
+
+export async function renameComputer(c: Ctx, [id]: string[]) {
+ const u = await user(c);
+ const name = str(body(c), "name");
+ await ownedComputer(c, id!, u.userId);
+ await c.env.DB.prepare("UPDATE computers SET name = ?, updated_at = ? WHERE id = ?").bind(name, c.now, id).run();
+ return { computer: computerView(await ownedComputer(c, id!, u.userId)) };
+}
+
+export async function removeComputer(c: Ctx, [id]: string[]) {
+ const u = await user(c);
+ await ownedComputer(c, id!, u.userId);
+ await unclaim(c.env, id!, u.userId, c.now);
+ return {};
+}
+
+export async function createAccessRequest(c: Ctx, [computerId]: string[]) {
+ const u = await user(c);
+ const dev = await device(c, u.userId);
+ const commit = key(body(c), "commit", 32);
+ await ownedComputer(c, computerId!, u.userId);
+ const recent = await c.env.DB.prepare("SELECT COUNT(*) AS n FROM access_requests WHERE user_id = ? AND created_at > ?")
+ .bind(u.userId, c.now - 3600_000)
+ .first<{ n: number }>();
+ if ((recent?.n ?? 0) >= REQUESTS_PER_HOUR) throw new ApiError("rateLimited");
+ const granted = await c.env.DB.prepare(
+ "SELECT 1 FROM grants WHERE computer_id = ? AND device_id = ? AND status = 'active'",
+ )
+ .bind(computerId, dev.id)
+ .first();
+ if (granted) throw new ApiError("conflict", "This device already has access");
+ const requestId = randomId("req_");
+ const expiresAt = c.now + REQUEST_TTL_MS;
+ // A commit is never reused: an earlier pending request is cancelled, not refreshed.
+ await c.env.DB.batch([
+ c.env.DB.prepare(
+ "UPDATE access_requests SET status = 'cancelled', decided_at = ? WHERE computer_id = ? AND device_id = ? AND status = 'pending'",
+ ).bind(c.now, computerId, dev.id),
+ c.env.DB.prepare(
+ `INSERT INTO access_requests(id, computer_id, device_id, user_id, status, commit_hash, created_at, expires_at)
+ VALUES (?, ?, ?, ?, 'pending', ?, ?, ?)`,
+ ).bind(requestId, computerId, dev.id, u.userId, commit, c.now, expiresAt),
+ ]);
+ await notify(c.env, computerId!);
+ return { requestId, expiresAt };
+}
+
+interface RequestRow {
+ id: string;
+ computer_id: string;
+ device_id: string;
+ status: string;
+ host_nonce: string | null;
+ device_nonce: string | null;
+ expires_at: number;
+ grant_id: string | null;
+}
+
+const effectiveStatus = (r: RequestRow, now: number) => (r.status === "pending" && r.expires_at <= now ? "expired" : r.status);
+
+export async function getAccessRequest(c: Ctx, [id]: string[]) {
+ const u = await user(c);
+ const r = await c.env.DB.prepare("SELECT * FROM access_requests WHERE id = ? AND user_id = ?")
+ .bind(id, u.userId)
+ .first<RequestRow>();
+ if (!r) throw new ApiError("notFound");
+ return {
+ requestId: r.id,
+ computerId: r.computer_id,
+ status: effectiveStatus(r, c.now),
+ expiresAt: r.expires_at,
+ ...(r.host_nonce ? { hostNonce: r.host_nonce } : {}),
+ ...(r.grant_id && r.status === "approved" ? { grantId: r.grant_id } : {}),
+ };
+}
+
+export async function revealAccessRequest(c: Ctx, [id]: string[]) {
+ const u = await user(c);
+ const dev = await device(c, u.userId);
+ const nonce = key(body(c), "nonce", 32);
+ const r = await c.env.DB.prepare(
+ `UPDATE access_requests SET device_nonce = ?1
+ WHERE id = ?2 AND user_id = ?3 AND device_id = ?4 AND status = 'pending' AND expires_at > ?5
+ AND host_nonce IS NOT NULL AND device_nonce IS NULL`,
+ )
+ .bind(nonce, id, u.userId, dev.id, c.now)
+ .run();
+ if (r.meta.changes === 0) {
+ const row = await c.env.DB.prepare("SELECT * FROM access_requests WHERE id = ? AND user_id = ? AND device_id = ?")
+ .bind(id, u.userId, dev.id)
+ .first<RequestRow>();
+ if (!row) throw new ApiError("notFound");
+ if (effectiveStatus(row, c.now) === "expired") throw new ApiError("requestExpired");
+ throw new ApiError("conflict", row.host_nonce ? "Already revealed" : "The computer hasn't answered yet");
+ }
+ const row = await c.env.DB.prepare("SELECT computer_id FROM access_requests WHERE id = ?").bind(id).first<{ computer_id: string }>();
+ await notify(c.env, row!.computer_id);
+ return {};
+}
+
+export async function cancelAccessRequest(c: Ctx, [id]: string[]) {
+ const u = await user(c);
+ const row = await c.env.DB.prepare("SELECT * FROM access_requests WHERE id = ? AND user_id = ?")
+ .bind(id, u.userId)
+ .first<RequestRow>();
+ if (!row) throw new ApiError("notFound");
+ const r = await c.env.DB.prepare(
+ "UPDATE access_requests SET status = 'cancelled', decided_at = ? WHERE id = ? AND status = 'pending'",
+ )
+ .bind(c.now, id)
+ .run();
+ if (r.meta.changes) await notify(c.env, row.computer_id);
+ return {};
+}
+
+export async function listGrants(c: Ctx, [id]: string[]) {
+ const u = await user(c);
+ await ownedComputer(c, id!, u.userId);
+ const { results } = await c.env.DB.prepare(
+ `SELECT g.id, g.device_id, d.name, d.platform, g.scopes, g.created_at FROM grants g JOIN devices d ON d.id = g.device_id
+ WHERE g.computer_id = ? AND g.status = 'active' ORDER BY g.created_at`,
+ )
+ .bind(id)
+ .all<{ id: string; device_id: string; name: string; platform: string; scopes: string; created_at: number }>();
+ return {
+ grants: results.map((g) => ({
+ grantId: g.id,
+ deviceId: g.device_id,
+ deviceName: g.name,
+ platform: g.platform,
+ scopes: JSON.parse(g.scopes) as string[],
+ createdAt: g.created_at,
+ })),
+ };
+}
+
+export async function revokeGrant(c: Ctx, [id, grantId]: string[]) {
+ const u = await user(c);
+ await ownedComputer(c, id!, u.userId);
+ const exists = await c.env.DB.prepare("SELECT 1 FROM grants WHERE id = ? AND computer_id = ?").bind(grantId, id).first();
+ if (!exists) throw new ApiError("notFound");
+ const { stmts, blocks } = await revokeGrants(c.env, "g.id = ? AND g.computer_id = ?", [grantId, id], "owner", c.now);
+ if (!stmts.length) return {};
+ await c.env.DB.batch([...stmts, audit(c.env, u.userId, "grant.revoke", grantId!, "ok", c.now)]);
+ await notify(c.env, id!, blocks.get(id!));
+ return {};
+}
+
+// ---- Sig(host) ----
+
+export async function hostRegister(c: Ctx) {
+ const s = await signed(c);
+ const b = body(c);
+ const boxKey = key(b, "boxKey", 32);
+ const name = str(b, "name");
+ const platform = oneOf(b, "platform", ["macos", "linux"] as const);
+ const device = optStr(b, "device", 32);
+ const version = str(b, "version", 32);
+ const id = await computerIdFor(fromB64url(s.kid, 32)!);
+ const existing = await c.env.DB.prepare("SELECT status, owner_user_id FROM computers WHERE id = ?")
+ .bind(id)
+ .first<{ status: string; owner_user_id: string | null }>();
+ if (existing && existing.status !== "active") throw new ApiError("forbidden");
+ if (!existing && c.env.REGISTER_LIMITER) {
+ const ip = c.req.headers.get("CF-Connecting-IP") ?? "unknown";
+ if (!(await c.env.REGISTER_LIMITER.limit({ key: ip })).success) throw new ApiError("rateLimited");
+ }
+ await c.env.DB.prepare(
+ `INSERT INTO computers(id, sign_pub, box_pub, name, platform, device, version, created_at, updated_at)
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?8)
+ ON CONFLICT(id) DO UPDATE SET name = excluded.name, device = excluded.device, version = excluded.version,
+ box_pub = excluded.box_pub, updated_at = excluded.updated_at`,
+ )
+ .bind(id, s.kid, boxKey, name, platform, device, version, c.now)
+ .run();
+ return { computerId: id, owned: !!existing?.owner_user_id };
+}
+
+export async function hostState(c: Ctx) {
+ const comp = await host(c);
+ const owner = comp.owner_user_id
+ ? await c.env.DB.prepare("SELECT user_id, email FROM accounts WHERE user_id = ? AND status = 'active'")
+ .bind(comp.owner_user_id)
+ .first<{ user_id: string; email: string | null }>()
+ : null;
+ const grants = await c.env.DB.prepare(
+ `SELECT g.id, d.sign_pub, d.name, d.platform, g.scopes FROM grants g
+ JOIN devices d ON d.id = g.device_id JOIN computers c ON c.id = g.computer_id
+ WHERE g.computer_id = ? AND g.status = 'active' AND d.revoked_at IS NULL AND d.owner_user_id = c.owner_user_id
+ ORDER BY g.created_at`,
+ )
+ .bind(comp.id)
+ .all<{ id: string; sign_pub: string; name: string; platform: string; scopes: string }>();
+ const requests = await c.env.DB.prepare(
+ `SELECT r.id, d.sign_pub, d.name, d.platform, a.email, r.commit_hash, r.host_nonce, r.device_nonce, r.created_at, r.expires_at
+ FROM access_requests r JOIN devices d ON d.id = r.device_id JOIN accounts a ON a.user_id = r.user_id
+ JOIN computers c ON c.id = r.computer_id
+ WHERE r.computer_id = ? AND r.status = 'pending' AND r.expires_at > ? AND d.revoked_at IS NULL
+ AND r.user_id = c.owner_user_id
+ ORDER BY r.created_at`,
+ )
+ .bind(comp.id, c.now)
+ .all<{
+ id: string;
+ sign_pub: string;
+ name: string;
+ platform: string;
+ email: string | null;
+ commit_hash: string;
+ host_nonce: string | null;
+ device_nonce: string | null;
+ created_at: number;
+ expires_at: number;
+ }>();
+ return {
+ owner: owner ? { userId: owner.user_id, email: owner.email } : null,
+ grants: grants.results.map((g) => ({
+ grantId: g.id,
+ deviceKey: g.sign_pub,
+ deviceName: g.name,
+ platform: g.platform,
+ scopes: JSON.parse(g.scopes) as string[],
+ })),
+ requests: requests.results.map((r) => ({
+ requestId: r.id,
+ deviceKey: r.sign_pub,
+ deviceName: r.name,
+ platform: r.platform,
+ email: r.email,
+ commit: r.commit_hash,
+ ...(r.host_nonce ? { hostNonce: r.host_nonce } : {}),
+ ...(r.device_nonce ? { deviceNonce: r.device_nonce } : {}),
+ createdAt: r.created_at,
+ expiresAt: r.expires_at,
+ })),
+ };
+}
+
+async function hostRequest(c: Ctx, computerId: string, id: string): Promise<RequestRow> {
+ const r = await c.env.DB.prepare("SELECT * FROM access_requests WHERE id = ? AND computer_id = ?")
+ .bind(id, computerId)
+ .first<RequestRow>();
+ if (!r) throw new ApiError("notFound");
+ return r;
+}
+
+export async function hostNonce(c: Ctx, [id]: string[]) {
+ const comp = await host(c);
+ const nonce = key(body(c), "nonce", 32);
+ const r = await c.env.DB.prepare(
+ `UPDATE access_requests SET host_nonce = ?
+ WHERE id = ? AND computer_id = ? AND status = 'pending' AND expires_at > ? AND host_nonce IS NULL`,
+ )
+ .bind(nonce, id, comp.id, c.now)
+ .run();
+ if (r.meta.changes === 0) {
+ const row = await hostRequest(c, comp.id, id!);
+ if (effectiveStatus(row, c.now) === "expired") throw new ApiError("requestExpired");
+ throw new ApiError("conflict");
+ }
+ return {};
+}
+
+export async function hostDecision(c: Ctx, [id]: string[]) {
+ const comp = await host(c);
+ const decision = oneOf(body(c), "decision", ["approve", "deny"] as const);
+ const row = await hostRequest(c, comp.id, id!);
+ if (effectiveStatus(row, c.now) === "expired") throw new ApiError("requestExpired");
+ if (decision === "deny") {
+ const r = await c.env.DB.prepare(
+ "UPDATE access_requests SET status = 'denied', decided_at = ? WHERE id = ? AND status = 'pending'",
+ )
+ .bind(c.now, id)
+ .run();
+ if (r.meta.changes === 0 && row.status !== "denied") throw new ApiError("conflict");
+ await audit(c.env, `computer:${comp.id}`, "access.deny", id!, "ok", c.now).run();
+ return { status: "denied" };
+ }
+ const g = randomId("grt_");
+ // The device must still be live and belong to the computer's owner at the moment of approval.
+ const [approved, inserted] = await c.env.DB.batch([
+ c.env.DB.prepare(
+ `UPDATE access_requests SET status = 'approved', decided_at = ?1, grant_id = ?2
+ WHERE id = ?3 AND computer_id = ?4 AND status = 'pending' AND expires_at > ?1 AND device_nonce IS NOT NULL
+ AND EXISTS(SELECT 1 FROM devices d JOIN computers c ON c.id = ?4
+ WHERE d.id = access_requests.device_id AND d.revoked_at IS NULL AND d.owner_user_id = c.owner_user_id)`,
+ ).bind(c.now, g, id, comp.id),
+ c.env.DB.prepare(
+ `INSERT INTO grants(id, computer_id, device_id, scopes, status, created_at)
+ SELECT ?1, computer_id, device_id, ?2, 'active', ?3 FROM access_requests WHERE id = ?4 AND grant_id = ?1
+ ON CONFLICT DO NOTHING`,
+ ).bind(g, SCOPES, c.now, id),
+ ]);
+ if (approved!.meta.changes === 0) {
+ const latest = await hostRequest(c, comp.id, id!);
+ // A double-click: the first approval already stands.
+ if (latest.status === "approved") return { status: "approved", grantId: latest.grant_id };
+ if (effectiveStatus(latest, c.now) === "expired") throw new ApiError("requestExpired");
+ throw new ApiError("conflict", latest.device_nonce ? "The request can't be approved" : "The device hasn't revealed its code yet");
+ }
+ let grantId = g;
+ if (inserted!.meta.changes === 0) {
+ // grants_active: this device already holds an active grant on this computer; hand that one back.
+ const existing = await c.env.DB.prepare(
+ "SELECT id FROM grants WHERE computer_id = ? AND device_id = ? AND status = 'active'",
+ )
+ .bind(comp.id, row.device_id)
+ .first<{ id: string }>();
+ grantId = existing!.id;
+ await c.env.DB.prepare("UPDATE access_requests SET grant_id = ? WHERE id = ?").bind(grantId, id).run();
+ }
+ await audit(c.env, `computer:${comp.id}`, "access.approve", id!, grantId, c.now).run();
+ return { status: "approved", grantId };
+}
+
+export async function hostRevokeGrant(c: Ctx, [grantId]: string[]) {
+ const comp = await host(c);
+ const exists = await c.env.DB.prepare("SELECT 1 FROM grants WHERE id = ? AND computer_id = ?").bind(grantId, comp.id).first();
+ if (!exists) throw new ApiError("notFound");
+ const { stmts } = await revokeGrants(c.env, "g.id = ? AND g.computer_id = ?", [grantId, comp.id], "owner", c.now);
+ if (stmts.length) await c.env.DB.batch([...stmts, audit(c.env, `computer:${comp.id}`, "grant.revoke", grantId!, "ok", c.now)]);
+ return {};
+}
+
+export async function hostUnclaim(c: Ctx) {
+ const comp = await host(c);
+ if (comp.owner_user_id) await unclaim(c.env, comp.id, `computer:${comp.id}`, c.now);
+ return {};
+}
+
+// ---- relay upgrades (§7.1) ----
+
+function checkUpgrade(c: Ctx): void {
+ if (c.url.searchParams.get("v") !== "1") throw new ApiError("upgradeRequired");
+ if (c.req.headers.get("Upgrade")?.toLowerCase() !== "websocket") throw new ApiError("badRequest", "Expected a WebSocket upgrade");
+}
+
+/** Forwards the upgrade to the computer's DO in a request the Worker builds itself; the client's URL never reaches it. */
+async function forward(c: Ctx, computerId: string, role: "host" | "device", s: SignedRequest, pair: string): Promise<Response> {
+ const headers = new Headers({
+ "X-Codync-Internal": "1",
+ "X-Codync-Role": role,
+ "X-Codync-Key": s.kid,
+ "X-Codync-Nonce": s.nonce,
+ "X-Codync-Ts": String(s.ts),
+ "X-Codync-Pair": pair,
+ "X-Codync-Computer": computerId,
+ });
+ for (const [name, value] of c.req.headers) {
+ if (name === "upgrade" || name.startsWith("sec-websocket-")) headers.set(name, value);
+ }
+ const res = await c.env.RELAY.get(c.env.RELAY.idFromName(computerId)).fetch(new Request("https://do/relay", { headers }));
+ if (res.status === 101) return res;
+ const err = (await res.json().catch(() => null)) as { error?: { code?: string } } | null;
+ throw new ApiError(err?.error?.code ?? "internal", undefined, res.status);
+}
+
+export async function relayHost(c: Ctx): Promise<Response> {
+ checkUpgrade(c);
+ const s = await verifySig(c.req, c.raw, c.now);
+ if (!s) throw new ApiError("badSignature");
+ const id = await computerIdFor(fromB64url(s.kid, 32)!);
+ const row = await c.env.DB.prepare("SELECT status FROM computers WHERE id = ?").bind(id).first<{ status: string }>();
+ if (!row) throw new ApiError("unknownComputer", "Register first (POST /v1/host/register)");
+ if (row.status !== "active") throw new ApiError("forbidden");
+ return forward(c, id, "host", s, "");
+}
+
+export async function relayDevice(c: Ctx, [computerId]: string[]): Promise<Response> {
+ checkUpgrade(c);
+ if (!COMPUTER_ID.test(computerId!)) throw new ApiError("badRequest", "Invalid computerId");
+ const pair = c.url.searchParams.get("pair") ?? "";
+ if (pair && !fromB64url(pair, 16)) throw new ApiError("badRequest", "Invalid pair");
+ const s = await verifySig(c.req, c.raw, c.now);
+ if (!s) throw new ApiError("badSignature");
+ // Only registered computers get a DO; random IDs never create one.
+ const row = await c.env.DB.prepare("SELECT status FROM computers WHERE id = ?").bind(computerId).first<{ status: string }>();
+ if (!row || row.status !== "active") throw new ApiError("unknownComputer");
+ return forward(c, computerId!, "device", s, pair);
+}
+
+// ---- webhooks ----
+
+export async function clerkWebhook(c: Ctx) {
+ if (!c.env.CLERK_WEBHOOK_SECRET) throw new ApiError("internal", "Webhook secret not configured");
+ const payload = new TextDecoder().decode(c.raw);
+ const h = (name: string) => c.req.headers.get(name) ?? "";
+ let event: { type?: string; data?: { id?: unknown } } | null;
+ try {
+ // Throws unless the signature and timestamp check out; returns nothing.
+ new Webhook(c.env.CLERK_WEBHOOK_SECRET).verify(payload, {
+ "svix-id": h("svix-id"),
+ "svix-timestamp": h("svix-timestamp"),
+ "svix-signature": h("svix-signature"),
+ });
+ event = JSON.parse(payload);
+ } catch {
+ throw new ApiError("badSignature");
+ }
+ const seen = await c.env.DB.prepare("SELECT 1 FROM processed_events WHERE provider = 'clerk' AND event_id = ?")
+ .bind(h("svix-id"))
+ .first();
+ if (seen) return {};
+ if (event?.type === "user.deleted" && typeof event.data?.id === "string") await deleteAccount(c.env, event.data.id, c.now);
+ await c.env.DB.prepare("INSERT OR IGNORE INTO processed_events(provider, event_id, processed_at) VALUES ('clerk', ?, ?)")
+ .bind(h("svix-id"), c.now)
+ .run();
+ return {};
+}
+
+async function deleteAccount(env: Env, userId: string, now: number): Promise<void> {
+ const { stmts, blocks } = await revokeGrants(
+ env,
+ "d.owner_user_id = ?1 OR g.computer_id IN (SELECT id FROM computers WHERE owner_user_id = ?1)",
+ [userId],
+ "accountDeleted",
+ now,
+ );
+ const owned = await env.DB.prepare("SELECT id FROM computers WHERE owner_user_id = ?").bind(userId).all<{ id: string }>();
+ await env.DB.batch([
+ ...stmts,
+ env.DB.prepare(
+ `INSERT INTO accounts(user_id, status, created_at, deleted_at) VALUES (?1, 'deleted', ?2, ?2)
+ ON CONFLICT(user_id) DO UPDATE SET status = 'deleted', deleted_at = ?2`,
+ ).bind(userId, now),
+ env.DB.prepare("UPDATE devices SET revoked_at = ? WHERE owner_user_id = ? AND revoked_at IS NULL").bind(now, userId),
+ env.DB.prepare(
+ `UPDATE access_requests SET status = 'cancelled', decided_at = ?1
+ WHERE status = 'pending' AND (user_id = ?2 OR computer_id IN (SELECT id FROM computers WHERE owner_user_id = ?2))`,
+ ).bind(now, userId),
+ env.DB.prepare("UPDATE computers SET owner_user_id = NULL, claimed_at = NULL, updated_at = ? WHERE owner_user_id = ?").bind(
+ now,
+ userId,
+ ),
+ audit(env, "system", "account.delete", userId, "ok", now),
+ ]);
+ const computers = new Set([...blocks.keys(), ...owned.results.map((r) => r.id)]);
+ await Promise.all([...computers].map((id) => notify(env, id, blocks.get(id))));
+}
+
+// ---- cron (every 15 minutes) ----
+
+export async function sweep(env: Env, now: number): Promise<void> {
+ await env.DB.batch([
+ env.DB.prepare("DELETE FROM sig_nonces WHERE expires_at <= ?").bind(now),
+ env.DB.prepare("DELETE FROM claims WHERE expires_at <= ?").bind(now - 86_400_000),
+ env.DB.prepare(
+ `UPDATE access_requests SET status = 'expired', host_nonce = NULL, device_nonce = NULL
+ WHERE status = 'pending' AND expires_at <= ?`,
+ ).bind(now),
+ env.DB.prepare("DELETE FROM audit_events WHERE created_at <= ?").bind(now - 30 * 86_400_000),
+ ]);
+}
diff --git a/cloud/src/auth.ts b/cloud/src/auth.ts
new file mode 100644
index 00000000..e577ed7f
--- /dev/null
+++ b/cloud/src/auth.ts
@@ -0,0 +1,133 @@
+// Authentication: Clerk session JWTs (users) and Codync-Sig (host and device keys, spec §5).
+
+import { verifyToken } from "@clerk/backend";
+import type { Env } from "./index";
+
+// ---- encoding ----
+
+export const b64url = (bytes: Uint8Array): string => {
+ let s = "";
+ for (let i = 0; i < bytes.length; i += 0x8000) s += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
+ return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
+};
+
+/** Strict base64url (no padding); `null` when malformed or not `len` bytes long. */
+export function fromB64url(s: unknown, len?: number): Uint8Array | null {
+ if (typeof s !== "string" || !/^[A-Za-z0-9_-]*$/.test(s) || s.length % 4 === 1) return null;
+ const bytes = Uint8Array.from(atob(s.replace(/-/g, "+").replace(/_/g, "/")), (c) => c.charCodeAt(0));
+ if (len !== undefined && bytes.length !== len) return null;
+ // Reject non-canonical encodings (stray low bits in the last character).
+ return b64url(bytes) === s ? bytes : null;
+}
+
+export const utf8 = (s: string) => new TextEncoder().encode(s);
+
+export const concat = (...parts: Uint8Array[]): Uint8Array => {
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
+ let at = 0;
+ for (const p of parts) {
+ out.set(p, at);
+ at += p.length;
+ }
+ return out;
+};
+
+export const sha256 = async (bytes: Uint8Array) => new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));
+
+export const randomId = (prefix = "", n = 16) => prefix + b64url(crypto.getRandomValues(new Uint8Array(n)));
+
+/** `computerId = b64url(SHA-256(hostSignPub)[0..16])` (§1). */
+export const computerIdFor = async (signPub: Uint8Array) => b64url((await sha256(signPub)).subarray(0, 16));
+
+export const COMPUTER_ID = /^[A-Za-z0-9_-]{22}$/;
+
+// ---- Ed25519 (WebCrypto) ----
+
+export async function verifyEd25519(pub: Uint8Array, sig: Uint8Array, msg: Uint8Array): Promise<boolean> {
+ if (pub.length !== 32 || sig.length !== 64) return false;
+ try {
+ const key = await crypto.subtle.importKey("raw", pub, { name: "Ed25519" }, false, ["verify"]);
+ return await crypto.subtle.verify({ name: "Ed25519" }, key, sig, msg);
+ } catch {
+ return false;
+ }
+}
+
+// ---- Codync-Sig (§5) ----
+
+export const SIG_WINDOW_MS = 300_000;
+export const NONCE_TTL_MS = 600_000;
+
+export interface SignedRequest {
+ kid: string;
+ ts: number;
+ nonce: string;
+}
+
+/** The exact bytes a Codync-Sig signs. */
+export async function sigCanonical(
+ method: string,
+ authority: string,
+ pathAndQuery: string,
+ ts: number,
+ nonce: string,
+ body: Uint8Array,
+): Promise<string> {
+ return ["codync-sig-v1", method.toUpperCase(), authority.toLowerCase(), pathAndQuery, String(ts), nonce, b64url(await sha256(body))].join("\n");
+}
+
+/**
+ * Checks the header's signature and time window. Replay (the `(kid, nonce)` pair) is the caller's job:
+ * D1 `sig_nonces` for HTTP, the DO's `nonces` table for relay sockets. `null` = reject.
+ */
+export async function verifySig(req: Request, body: Uint8Array, now = Date.now()): Promise<SignedRequest | null> {
+ const header = req.headers.get("Codync-Sig");
+ if (!header) return null;
+ const f = new Map<string, string>();
+ for (const part of header.split(",")) {
+ const i = part.indexOf("=");
+ if (i <= 0) return null;
+ f.set(part.slice(0, i).trim(), part.slice(i + 1).trim());
+ }
+ const pub = fromB64url(f.get("kid"), 32);
+ const sig = fromB64url(f.get("sig"), 64);
+ const nonce = f.get("nonce") ?? "";
+ const tsText = f.get("ts") ?? "";
+ if (f.get("v") !== "1" || !pub || !sig || !fromB64url(nonce, 16) || !/^\d{1,16}$/.test(tsText)) return null;
+ const ts = Number(tsText);
+ if (Math.abs(now - ts) > SIG_WINDOW_MS) return null;
+ const url = new URL(req.url);
+ const canonical = await sigCanonical(req.method, url.host, url.pathname + url.search, ts, nonce, body);
+ if (!(await verifyEd25519(pub, sig, utf8(canonical)))) return null;
+ return { kid: f.get("kid")!, ts, nonce };
+}
+
+// ---- Clerk (§8.3) ----
+
+export interface ClerkUser {
+ userId: string;
+ email: string | null;
+}
+
+/** `null` when the bearer token is missing or doesn't verify. */
+export async function verifyClerk(req: Request, env: Env): Promise<ClerkUser | null> {
+ const auth = req.headers.get("Authorization") ?? "";
+ if (!auth.startsWith("Bearer ")) return null;
+ const token = auth.slice(7).trim();
+ const authorizedParties = (env.CLERK_AUTHORIZED_PARTIES ?? "")
+ .split(",")
+ .map((s) => s.trim())
+ .filter(Boolean);
+ try {
+ // With a secret key, @clerk/backend fetches the JWKS and caches it per isolate (rotation-aware).
+ const claims = await verifyToken(token, {
+ ...(env.CLERK_JWT_KEY ? { jwtKey: env.CLERK_JWT_KEY } : { secretKey: env.CLERK_SECRET_KEY }),
+ ...(authorizedParties.length ? { authorizedParties } : {}),
+ });
+ if (claims.iss !== env.CLERK_ISSUER || typeof claims.sub !== "string" || !claims.sub || !claims.sid) return null;
+ const email = (claims as { email?: unknown }).email;
+ return { userId: claims.sub, email: typeof email === "string" && email ? email : null };
+ } catch {
+ return null;
+ }
+}
diff --git a/cloud/src/index.ts b/cloud/src/index.ts
new file mode 100644
index 00000000..c93e1698
--- /dev/null
+++ b/cloud/src/index.ts
@@ -0,0 +1,79 @@
+// Codync cloud: accounts (Clerk), computers, access grants (D1) and the end-to-end encrypted relay
+// (one ComputerRelay Durable Object per computer). The cloud only ever sees ciphertext and routing
+// metadata; the host stays the sole authority on which devices may decrypt (docs/remote-relay-spec.md).
+
+import * as api from "./api";
+import { ApiError, type Ctx } from "./api";
+import type { ComputerRelay } from "./relay";
+
+export { ComputerRelay } from "./relay";
+
+export interface Env {
+ DB: D1Database;
+ RELAY: DurableObjectNamespace<ComputerRelay>;
+ /** Workers Rate Limiting binding for new computer registrations. */
+ REGISTER_LIMITER?: RateLimit;
+ CLERK_ISSUER: string;
+ CLERK_SECRET_KEY?: string;
+ /** dev / e2e only: networkless verification with this public key. */
+ CLERK_JWT_KEY?: string;
+ CLERK_AUTHORIZED_PARTIES?: string;
+ CLERK_WEBHOOK_SECRET?: string;
+}
+
+type Handler = (c: Ctx, params: string[]) => Promise<unknown>;
+
+const ID = "([A-Za-z0-9_-]{1,64})";
+const routes: [string, RegExp, Handler][] = [
+ ["GET", /^\/v1\/health$/, api.health],
+ ["GET", /^\/v1\/me$/, api.me],
+ ["POST", /^\/v1\/devices$/, api.registerDevice],
+ ["GET", /^\/v1\/devices$/, api.listDevices],
+ ["DELETE", new RegExp(`^/v1/devices/${ID}$`), api.revokeDevice],
+ ["POST", /^\/v1\/claims$/, api.createClaim],
+ ["POST", new RegExp(`^/v1/claims/${ID}/complete$`), api.completeClaim],
+ ["GET", /^\/v1\/computers$/, api.listComputers],
+ ["PATCH", new RegExp(`^/v1/computers/${ID}$`), api.renameComputer],
+ ["DELETE", new RegExp(`^/v1/computers/${ID}$`), api.removeComputer],
+ ["POST", new RegExp(`^/v1/computers/${ID}/access-requests$`), api.createAccessRequest],
+ ["GET", new RegExp(`^/v1/computers/${ID}/grants$`), api.listGrants],
+ ["DELETE", new RegExp(`^/v1/computers/${ID}/grants/${ID}$`), api.revokeGrant],
+ ["GET", new RegExp(`^/v1/access-requests/${ID}$`), api.getAccessRequest],
+ ["POST", new RegExp(`^/v1/access-requests/${ID}/reveal$`), api.revealAccessRequest],
+ ["DELETE", new RegExp(`^/v1/access-requests/${ID}$`), api.cancelAccessRequest],
+ ["POST", /^\/v1\/host\/register$/, api.hostRegister],
+ ["GET", /^\/v1\/host\/state$/, api.hostState],
+ ["POST", new RegExp(`^/v1/host/access-requests/${ID}/nonce$`), api.hostNonce],
+ ["POST", new RegExp(`^/v1/host/access-requests/${ID}/decision$`), api.hostDecision],
+ ["POST", new RegExp(`^/v1/host/grants/${ID}/revoke$`), api.hostRevokeGrant],
+ ["POST", /^\/v1\/host\/unclaim$/, api.hostUnclaim],
+ ["GET", /^\/v1\/relay\/host$/, api.relayHost],
+ // Any segment reaches the handler so a malformed computerId gets its 400 (§7.1).
+ ["GET", /^\/v1\/relay\/device\/([^/]+)$/, api.relayDevice],
+ ["POST", /^\/v1\/webhooks\/clerk$/, api.clerkWebhook],
+];
+
+export default {
+ async fetch(req: Request, env: Env, exec: ExecutionContext): Promise<Response> {
+ const requestId = req.headers.get("cf-ray") ?? crypto.randomUUID();
+ try {
+ const url = new URL(req.url);
+ for (const [method, pattern, handler] of routes) {
+ const m = pattern.exec(url.pathname);
+ if (!m || req.method !== method) continue;
+ const raw = new Uint8Array(await req.arrayBuffer());
+ const out = await handler({ req, env, exec, url, raw, now: Date.now() }, m.slice(1));
+ return out instanceof Response ? out : Response.json(out);
+ }
+ throw new ApiError("notFound");
+ } catch (e) {
+ const err = e instanceof ApiError ? e : new ApiError("internal");
+ if (!(e instanceof ApiError)) console.error("unhandled", { requestId, error: e instanceof Error ? e.stack : String(e) });
+ return Response.json({ error: { code: err.code, message: err.message }, requestId }, { status: err.status });
+ }
+ },
+
+ async scheduled(_controller: ScheduledController, env: Env): Promise<void> {
+ await api.sweep(env, Date.now());
+ },
+} satisfies ExportedHandler<Env>;
diff --git a/cloud/src/relay.ts b/cloud/src/relay.ts
new file mode 100644
index 00000000..4b6edee1
--- /dev/null
+++ b/cloud/src/relay.ts
@@ -0,0 +1,567 @@
+// ComputerRelay: one Durable Object per computer (spec §7, §8.5).
+//
+// Presence, ciphertext forwarding between the host socket and device sockets, ACL admission, and the
+// offline mailbox (device → host). It never parses channel frames and never stores chat. Reached only
+// through requests the Worker builds itself (`X-Codync-Internal: 1`), never a client's own request.
+
+import { DurableObject } from "cloudflare:workers";
+import { b64url, fromB64url, NONCE_TTL_MS, randomId, utf8, verifyEd25519 } from "./auth";
+import type { Env } from "./index";
+
+const MAX_DEVICE_SOCKETS = 16;
+const MAX_PAIRING_SOCKETS = 2;
+const PAIRING_TTL_MS = 120_000;
+const PAIRING_MAX_MESSAGES = 16;
+const RATE_WINDOW_MS = 10_000;
+const RATE_MAX_MESSAGES = 200;
+const RATE_MAX_BYTES = 8 * 1024 * 1024;
+const MBOX_MAX_BLOB = 64 * 1024;
+const MBOX_PER_DEVICE = 50;
+const MBOX_PER_COMPUTER = 500;
+const MBOX_MAX_BYTES = 8 * 1024 * 1024;
+const MBOX_TTL_MS = 24 * 3600_000;
+const HOST_TIMEOUT_MS = 90_000;
+const ALARM_MS = 60_000;
+/** epk(32) ‖ sig(64) ‖ ciphertext with at least its 16-byte tag (§6.4). */
+const MBOX_MIN_BLOB = 32 + 64 + 16;
+const FAIL_CODES = new Set(["unauthorized", "unknownBot", "invalid"]);
+
+export const PING = '{"t":"ping"}';
+export const PONG = '{"t":"pong"}';
+
+interface HostAttachment {
+ role: "host";
+ kid: string;
+ ready: boolean;
+ at: number;
+}
+interface DeviceAttachment {
+ role: "device";
+ dk: string;
+ link: string;
+ pair: boolean;
+ offer?: string;
+ at: number;
+ msgs: number;
+}
+type Attachment = HostAttachment | DeviceAttachment;
+
+export interface Acl {
+ v: 1;
+ computerId: string;
+ ver: number;
+ devices: { dk: string; grant: string | null }[];
+ offers: { id: string; exp: number }[];
+}
+
+type Msg = Record<string, unknown> & { t: string };
+
+const errorResponse = (status: number, code: string) => Response.json({ error: { code } }, { status });
+
+/** Parses and shape-checks a signed ACL's JSON; `null` when malformed. */
+export function parseAcl(bytes: Uint8Array): Acl | null {
+ let acl: unknown;
+ try {
+ acl = JSON.parse(new TextDecoder("utf-8", { fatal: true, ignoreBOM: false }).decode(bytes));
+ } catch {
+ return null;
+ }
+ const a = acl as Partial<Acl> | null;
+ const ok =
+ !!a &&
+ a.v === 1 &&
+ typeof a.computerId === "string" &&
+ Number.isSafeInteger(a.ver) &&
+ (a.ver ?? 0) >= 1 &&
+ Array.isArray(a.devices) &&
+ a.devices.every(
+ (d) => d && fromB64url(d.dk, 32) !== null && (d.grant === null || (typeof d.grant === "string" && d.grant.length <= 64)),
+ ) &&
+ Array.isArray(a.offers) &&
+ a.offers.every((o) => o && fromB64url(o.id, 16) !== null && Number.isSafeInteger(o.exp));
+ return ok ? (a as Acl) : null;
+}
+
+/** Sends unless the socket is gone; a socket can be closing while it's still listed. */
+function send(ws: WebSocket | undefined, text: string): void {
+ try {
+ ws?.send(text);
+ } catch {
+ // Closed underneath us; its close handler does the bookkeeping.
+ }
+}
+
+const validCloseCode = (c: unknown): c is number =>
+ typeof c === "number" && Number.isInteger(c) && (c === 1000 || (c >= 3000 && c <= 4999));
+
+export class ComputerRelay extends DurableObject<Env> {
+ private readonly sql: SqlStorage;
+ /** Per-link rate windows (device → DO only). Lost on hibernation, which is acceptable (§7.6). */
+ private readonly rates = new Map<string, { start: number; msgs: number; bytes: number }>();
+
+ constructor(ctx: DurableObjectState, env: Env) {
+ super(ctx, env);
+ this.sql = ctx.storage.sql;
+ this.sql.exec(`
+ CREATE TABLE IF NOT EXISTS meta(k TEXT PRIMARY KEY, v TEXT);
+ CREATE TABLE IF NOT EXISTS mailbox(seq INTEGER PRIMARY KEY AUTOINCREMENT, dk TEXT, nonce TEXT, blob BLOB,
+ size INTEGER, exp INTEGER, state TEXT, UNIQUE(dk, nonce));
+ CREATE TABLE IF NOT EXISTS nonces(kid TEXT, nonce TEXT, exp INTEGER, PRIMARY KEY(kid, nonce));
+ CREATE TABLE IF NOT EXISTS blocked(dk TEXT PRIMARY KEY, grant_id TEXT, blocked_at INTEGER);
+ `);
+ ctx.setWebSocketAutoResponse(new WebSocketRequestResponsePair(PING, PONG));
+ }
+
+ // ---- entry points ----
+
+ override async fetch(req: Request): Promise<Response> {
+ if (req.headers.get("X-Codync-Internal") !== "1") return errorResponse(404, "notFound");
+ const { pathname } = new URL(req.url);
+ if (pathname === "/relay") return this.relay(req);
+ if (pathname === "/internal/block" && req.method === "POST") return this.block(req);
+ if (pathname === "/internal/changed" && req.method === "POST") {
+ this.toHosts({ t: "cloud.changed" });
+ return Response.json({});
+ }
+ return errorResponse(404, "notFound");
+ }
+
+ private async relay(req: Request): Promise<Response> {
+ const h = (name: string) => req.headers.get(name) ?? "";
+ if (h("Upgrade").toLowerCase() !== "websocket") return errorResponse(426, "upgradeRequired");
+ const role = h("X-Codync-Role");
+ const key = h("X-Codync-Key");
+ const nonce = h("X-Codync-Nonce");
+ if (!fromB64url(key, 32) || !fromB64url(nonce, 16)) return errorResponse(400, "badRequest");
+ const now = Date.now();
+ if (this.sql.exec("SELECT 1 FROM nonces WHERE kid = ? AND nonce = ?", key, nonce).toArray().length) {
+ return errorResponse(401, "badSignature");
+ }
+ this.sql.exec("INSERT INTO nonces(kid, nonce, exp) VALUES (?, ?, ?)", key, nonce, now + NONCE_TTL_MS);
+ if (role === "host") return this.acceptHost(key, h("X-Codync-Computer"), now);
+ if (role === "device") return this.acceptDevice(key, h("X-Codync-Pair"), now);
+ return errorResponse(400, "badRequest");
+ }
+
+ private async acceptHost(kid: string, computerId: string, now: number): Promise<Response> {
+ const signKey = this.meta("signKey");
+ if (signKey === null) {
+ this.setMeta("signKey", kid);
+ this.setMeta("computerId", computerId);
+ } else if (signKey !== kid) {
+ return errorResponse(403, "forbidden");
+ }
+ // A new host connection replaces the old one (§7.2).
+ let wasOnline = false;
+ for (const old of this.ctx.getWebSockets("host")) {
+ const a = old.deserializeAttachment() as HostAttachment;
+ wasOnline ||= a.ready;
+ old.serializeAttachment({ ...a, ready: false });
+ this.safeClose(old, 4009, "replaced");
+ }
+ if (wasOnline) await this.hostOffline(now);
+ const { 0: client, 1: server } = new WebSocketPair();
+ this.ctx.acceptWebSocket(server, ["host"]);
+ server.serializeAttachment({ role: "host", kid, ready: false, at: now } satisfies HostAttachment);
+ await this.ensureAlarm(now + ALARM_MS);
+ return new Response(null, { status: 101, webSocket: client });
+ }
+
+ private async acceptDevice(dk: string, offer: string, now: number): Promise<Response> {
+ const acl = this.acl();
+ if (!acl) return errorResponse(404, "unknownComputer");
+ // A pairing needs the host's one-time code, so the host decides; a block only stops ACL access.
+ if (!offer && this.sql.exec("SELECT 1 FROM blocked WHERE dk = ?", dk).toArray().length) return errorResponse(403, "forbidden");
+ const sockets = this.devices();
+ if (sockets.length >= MAX_DEVICE_SOCKETS) return errorResponse(429, "rateLimited");
+ let deadline = now + ALARM_MS;
+ if (offer) {
+ const o = acl.offers.find((o) => o.id === offer && o.exp > now);
+ if (!o) return errorResponse(403, "forbidden");
+ if (sockets.filter(([, a]) => a.pair).length >= MAX_PAIRING_SOCKETS) return errorResponse(429, "rateLimited");
+ deadline = Math.min(deadline, now + PAIRING_TTL_MS, o.exp);
+ } else if (!acl.devices.some((d) => d.dk === dk)) {
+ return errorResponse(403, "forbidden");
+ }
+ const { 0: client, 1: server } = new WebSocketPair();
+ this.ctx.acceptWebSocket(server, ["device"]);
+ const a: DeviceAttachment = { role: "device", dk, link: randomId("", 12), pair: !!offer, at: now, msgs: 0 };
+ if (offer) a.offer = offer;
+ server.serializeAttachment(a);
+ send(server, JSON.stringify(this.presence()));
+ send(this.readyHost(), JSON.stringify({ t: "open", link: a.link, dk, pair: a.pair }));
+ await this.ensureAlarm(deadline);
+ return new Response(null, { status: 101, webSocket: client });
+ }
+
+ /** `POST /internal/block {"devices":[{dk, grantId}]}` (§3.4). */
+ private async block(req: Request): Promise<Response> {
+ const body = (await req.json().catch(() => null)) as { devices?: { dk?: unknown; grantId?: unknown }[] } | null;
+ if (!Array.isArray(body?.devices)) return errorResponse(400, "badRequest");
+ const now = Date.now();
+ const dks = new Set<string>();
+ for (const d of body.devices) {
+ if (typeof d?.dk !== "string" || !fromB64url(d.dk, 32)) continue;
+ const grant = typeof d.grantId === "string" ? d.grantId : null;
+ this.sql.exec(
+ `INSERT INTO blocked(dk, grant_id, blocked_at) VALUES (?, ?, ?)
+ ON CONFLICT(dk) DO UPDATE SET grant_id = excluded.grant_id, blocked_at = excluded.blocked_at`,
+ d.dk,
+ grant,
+ now,
+ );
+ // Nothing it queued should reach the host any more.
+ this.sql.exec("DELETE FROM mailbox WHERE dk = ? AND state = 'queued'", d.dk);
+ dks.add(d.dk);
+ }
+ for (const [ws, a] of this.devices()) if (dks.has(a.dk)) this.safeClose(ws, 4003, "revoked");
+ this.toHosts({ t: "cloud.changed" });
+ return Response.json({});
+ }
+
+ // ---- messages ----
+
+ override async webSocketMessage(ws: WebSocket, message: string | ArrayBuffer): Promise<void> {
+ const a = ws.deserializeAttachment() as Attachment;
+ if (typeof message !== "string") return this.safeClose(ws, 4002, "protocolError");
+ let msg: Msg;
+ try {
+ msg = JSON.parse(message);
+ } catch {
+ return this.safeClose(ws, 4002, "protocolError");
+ }
+ if (!msg || typeof msg !== "object" || typeof msg.t !== "string") return this.safeClose(ws, 4002, "protocolError");
+ if (a.role === "host") return this.onHost(ws, a, msg);
+ return this.onDevice(ws, a, msg, message);
+ }
+
+ private async onHost(ws: WebSocket, a: HostAttachment, msg: Msg): Promise<void> {
+ const now = Date.now();
+ switch (msg.t) {
+ case "acl":
+ return this.onAcl(ws, a, msg, now);
+ case "ready": {
+ if (a.ready) return;
+ if (!this.acl()) return send(ws, JSON.stringify({ t: "error", code: "badAcl", ver: 0 }));
+ ws.serializeAttachment({ ...a, ready: true });
+ this.setMeta("lastSeenAt", String(now));
+ await this.recordPresence(true, now);
+ const presence = JSON.stringify(this.presence());
+ for (const [dws, d] of this.devices()) {
+ send(dws, presence);
+ send(ws, JSON.stringify({ t: "open", link: d.link, dk: d.dk, pair: d.pair }));
+ }
+ this.deliverNext(ws, now);
+ return;
+ }
+ case "data": {
+ if (!a.ready || !msg.m || typeof msg.m !== "object") return;
+ send(this.deviceByLink(msg.link), JSON.stringify(msg.m));
+ return;
+ }
+ case "close": {
+ if (!a.ready) return;
+ const d = this.deviceByLink(msg.link);
+ if (d) this.safeClose(d, validCloseCode(msg.code) ? msg.code : 1000, typeof msg.reason === "string" ? msg.reason : "");
+ return;
+ }
+ case "mbox.ack":
+ return this.onAck(ws, msg, now);
+ case "ping":
+ return send(ws, PONG);
+ default:
+ return;
+ }
+ }
+
+ private async onAcl(ws: WebSocket, a: HostAttachment, msg: Msg, now: number): Promise<void> {
+ const stored = Number(this.meta("aclVer") ?? 0);
+ const d = fromB64url(msg.d);
+ const sig = fromB64url(msg.sig, 64);
+ const pub = fromB64url(a.kid, 32);
+ const acl = d && sig && pub && (await verifyEd25519(pub, sig, d)) ? parseAcl(d) : null;
+ if (!acl || acl.computerId !== this.meta("computerId")) {
+ return send(ws, JSON.stringify({ t: "error", code: "badAcl", ver: stored }));
+ }
+ // Re-read after the await: another ACL may have been stored meanwhile.
+ const current = Number(this.meta("aclVer") ?? 0);
+ if (acl.ver <= current) return send(ws, JSON.stringify({ t: "error", code: "staleVersion", ver: current }));
+ this.setMeta("aclVer", String(acl.ver));
+ this.setMeta("aclD", msg.d as string);
+ this.setMeta("aclSig", msg.sig as string);
+ // Unblock only when the host authorized the dk anew: a different grant (a new approval) or
+ // none (a QR pairing). Still listed with the revoked grant = the host hasn't caught up (§7.3).
+ for (const row of this.sql.exec<{ dk: string; grant_id: string | null }>("SELECT dk, grant_id FROM blocked").toArray()) {
+ if (acl.devices.some((x) => x.dk === row.dk && x.grant !== row.grant_id)) {
+ this.sql.exec("DELETE FROM blocked WHERE dk = ?", row.dk);
+ }
+ }
+ for (const [dws, dev] of this.devices()) {
+ if (dev.pair) {
+ if (!acl.offers.some((o) => o.id === dev.offer && o.exp > now)) this.safeClose(dws, 4410, "pairingExpired");
+ } else if (!acl.devices.some((x) => x.dk === dev.dk)) {
+ this.safeClose(dws, 4003, "revoked");
+ }
+ }
+ send(ws, JSON.stringify({ t: "acl.ok", ver: acl.ver }));
+ }
+
+ private onAck(ws: WebSocket, msg: Msg, now: number): void {
+ const row = this.sql
+ .exec<{ dk: string; nonce: string }>("SELECT dk, nonce FROM mailbox WHERE seq = ? AND state = 'delivering'", Number(msg.seq))
+ .toArray()[0];
+ if (row) {
+ this.sql.exec("DELETE FROM mailbox WHERE seq = ?", Number(msg.seq));
+ const note =
+ msg.ok === true
+ ? { t: "mbox.delivered", nonce: row.nonce }
+ : { t: "mbox.failed", nonce: row.nonce, code: FAIL_CODES.has(msg.code as string) ? msg.code : "invalid" };
+ this.toDevice(row.dk, note);
+ }
+ this.deliverNext(ws, now);
+ }
+
+ private async onDevice(ws: WebSocket, a: DeviceAttachment, msg: Msg, raw: string): Promise<void> {
+ const now = Date.now();
+ if (!this.charge(a.link, utf8(raw).length, now)) return this.safeClose(ws, 4008, "rateLimited");
+ if (a.pair) {
+ a.msgs += 1;
+ if (a.msgs > PAIRING_MAX_MESSAGES) return this.safeClose(ws, 4008, "rateLimited");
+ ws.serializeAttachment(a);
+ }
+ switch (msg.t) {
+ case "hello":
+ case "f": {
+ const host = this.readyHost();
+ if (host) send(host, JSON.stringify({ t: "data", link: a.link, m: msg }));
+ else send(ws, JSON.stringify(this.presence()));
+ return;
+ }
+ case "ping":
+ return send(ws, PONG);
+ case "mbox.put":
+ case "mbox.cancel":
+ case "mbox.list":
+ if (a.pair) return send(ws, JSON.stringify({ t: "mbox.err", nonce: msg.nonce ?? null, code: "pairing" }));
+ if (msg.t === "mbox.put") return this.mboxPut(ws, a, msg, now);
+ if (msg.t === "mbox.cancel") return this.mboxCancel(ws, a, msg);
+ return this.mboxList(ws, a);
+ default:
+ return this.safeClose(ws, 4002, "protocolError");
+ }
+ }
+
+ /** Fixed 10 s window per device link: ≤ 200 messages and ≤ 8 MiB (§7.6). */
+ private charge(link: string, bytes: number, now: number): boolean {
+ let r = this.rates.get(link);
+ if (!r || now - r.start >= RATE_WINDOW_MS) {
+ r = { start: now, msgs: 0, bytes: 0 };
+ this.rates.set(link, r);
+ }
+ r.msgs += 1;
+ r.bytes += bytes;
+ return r.msgs <= RATE_MAX_MESSAGES && r.bytes <= RATE_MAX_BYTES;
+ }
+
+ // ---- mailbox (§7.7) ----
+
+ private async mboxPut(ws: WebSocket, a: DeviceAttachment, msg: Msg, now: number): Promise<void> {
+ const nonce = msg.nonce;
+ const err = (code: string) => send(ws, JSON.stringify({ t: "mbox.err", nonce: nonce ?? null, code }));
+ if (typeof nonce !== "string" || !nonce || nonce.length > 128) return err("invalid");
+ const existing = this.sql
+ .exec<{ state: string }>("SELECT state FROM mailbox WHERE dk = ? AND nonce = ?", a.dk, nonce)
+ .toArray()[0];
+ if (existing) return send(ws, JSON.stringify({ t: "mbox.ok", nonce, state: existing.state }));
+ if (this.readyHost()) return err("hostOnline");
+ if (typeof msg.d === "string" && msg.d.length > Math.ceil((MBOX_MAX_BLOB * 4) / 3)) return err("tooLarge");
+ const blob = fromB64url(msg.d);
+ if (!blob || blob.length < MBOX_MIN_BLOB) return err("invalid");
+ if (blob.length > MBOX_MAX_BLOB) return err("tooLarge");
+ const exp = msg.exp === undefined ? now + MBOX_TTL_MS : msg.exp;
+ if (typeof exp !== "number" || !Number.isSafeInteger(exp) || exp <= now || exp > now + MBOX_TTL_MS) return err("invalid");
+ const mine = this.sql.exec<{ n: number }>("SELECT COUNT(*) AS n FROM mailbox WHERE dk = ?", a.dk).one().n;
+ const all = this.sql.exec<{ n: number; b: number }>("SELECT COUNT(*) AS n, COALESCE(SUM(size), 0) AS b FROM mailbox").one();
+ if (mine >= MBOX_PER_DEVICE || all.n >= MBOX_PER_COMPUTER || all.b + blob.length > MBOX_MAX_BYTES) return err("full");
+ this.sql.exec(
+ "INSERT INTO mailbox(dk, nonce, blob, size, exp, state) VALUES (?, ?, ?, ?, ?, 'queued')",
+ a.dk,
+ nonce,
+ blob.slice().buffer,
+ blob.length,
+ exp,
+ );
+ send(ws, JSON.stringify({ t: "mbox.ok", nonce, state: "queued" }));
+ await this.ensureAlarm(now + ALARM_MS);
+ }
+
+ private mboxCancel(ws: WebSocket, a: DeviceAttachment, msg: Msg): void {
+ const nonce = typeof msg.nonce === "string" ? msg.nonce : "";
+ const row = this.sql
+ .exec<{ state: string }>("SELECT state FROM mailbox WHERE dk = ? AND nonce = ?", a.dk, nonce)
+ .toArray()[0];
+ if (row?.state === "queued") {
+ this.sql.exec("DELETE FROM mailbox WHERE dk = ? AND nonce = ?", a.dk, nonce);
+ return send(ws, JSON.stringify({ t: "mbox.cancelled", nonce }));
+ }
+ send(ws, JSON.stringify({ t: "mbox.gone", nonce, state: row ? "delivering" : "unknown" }));
+ }
+
+ private mboxList(ws: WebSocket, a: DeviceAttachment): void {
+ const items = this.sql
+ .exec<{ nonce: string; exp: number; state: string }>("SELECT nonce, exp, state FROM mailbox WHERE dk = ? ORDER BY seq", a.dk)
+ .toArray();
+ send(ws, JSON.stringify({ t: "mbox.items", items }));
+ }
+
+ /** One item in flight at a time, in `seq` order; the next goes out after the host's ack. */
+ private deliverNext(host: WebSocket, now: number): void {
+ const a = host.deserializeAttachment() as HostAttachment;
+ if (!a.ready) return;
+ if (this.sql.exec("SELECT 1 FROM mailbox WHERE state = 'delivering'").toArray().length) return;
+ const row = this.sql
+ .exec<{ seq: number; dk: string; nonce: string; blob: ArrayBuffer; exp: number }>(
+ "SELECT seq, dk, nonce, blob, exp FROM mailbox WHERE state = 'queued' AND exp > ? ORDER BY seq LIMIT 1",
+ now,
+ )
+ .toArray()[0];
+ if (!row) return;
+ this.sql.exec("UPDATE mailbox SET state = 'delivering' WHERE seq = ?", row.seq);
+ send(host,
+ JSON.stringify({ t: "mbox.item", seq: row.seq, from: row.dk, nonce: row.nonce, d: b64url(new Uint8Array(row.blob)), exp: row.exp }),
+ );
+ }
+
+ // ---- lifecycle ----
+
+ override async webSocketClose(ws: WebSocket): Promise<void> {
+ await this.closed(ws);
+ }
+
+ override async webSocketError(ws: WebSocket): Promise<void> {
+ await this.closed(ws);
+ }
+
+ private async closed(ws: WebSocket): Promise<void> {
+ const a = ws.deserializeAttachment() as Attachment;
+ this.safeClose(ws, 1000, "");
+ if (a.role === "host") {
+ if (a.ready) await this.hostOffline(Date.now(), ws);
+ } else {
+ this.rates.delete(a.link);
+ send(this.readyHost(ws), JSON.stringify({ t: "close", link: a.link }));
+ }
+ }
+
+ override async alarm(): Promise<void> {
+ const now = Date.now();
+ for (const ws of this.ctx.getWebSockets("host")) {
+ const a = ws.deserializeAttachment() as HostAttachment;
+ const last = Math.max(a.at, this.ctx.getWebSocketAutoResponseTimestamp(ws)?.getTime() ?? 0);
+ if (now - last > HOST_TIMEOUT_MS) {
+ ws.serializeAttachment({ ...a, ready: false });
+ this.safeClose(ws, 1011, "timeout");
+ if (a.ready) await this.hostOffline(now, ws);
+ }
+ }
+ for (const row of this.sql
+ .exec<{ dk: string; nonce: string }>("SELECT dk, nonce FROM mailbox WHERE exp <= ?", now)
+ .toArray()) {
+ this.toDevice(row.dk, { t: "mbox.expired", nonce: row.nonce });
+ }
+ this.sql.exec("DELETE FROM mailbox WHERE exp <= ?", now);
+ this.sql.exec("DELETE FROM nonces WHERE exp <= ?", now);
+
+ const acl = this.acl();
+ let next = now + ALARM_MS;
+ for (const [ws, d] of this.devices()) {
+ if (!d.pair) continue;
+ const exp = Math.min(d.at + PAIRING_TTL_MS, acl?.offers.find((o) => o.id === d.offer)?.exp ?? 0);
+ if (exp <= now) this.safeClose(ws, 4410, "pairingExpired");
+ else next = Math.min(next, exp);
+ }
+ const busy =
+ this.ctx.getWebSockets().length > 0 || this.sql.exec("SELECT 1 FROM mailbox LIMIT 1").toArray().length > 0;
+ if (busy) await this.ctx.storage.setAlarm(next);
+ }
+
+ /** The host went away: devices see it offline, in-flight mail goes back to the queue. */
+ private async hostOffline(now: number, exclude?: WebSocket): Promise<void> {
+ this.setMeta("lastSeenAt", String(now));
+ this.sql.exec("UPDATE mailbox SET state = 'queued' WHERE state = 'delivering'");
+ if (!this.readyHost(exclude)) {
+ const presence = JSON.stringify(this.presence(exclude));
+ for (const [ws] of this.devices()) send(ws, presence);
+ }
+ await this.recordPresence(false, now);
+ }
+
+ private async recordPresence(online: boolean, now: number): Promise<void> {
+ const id = this.meta("computerId");
+ if (!id) return;
+ try {
+ await this.env.DB.prepare("UPDATE computers SET online = ?, last_seen_at = ? WHERE id = ?").bind(online ? 1 : 0, now, id).run();
+ } catch (e) {
+ console.error("presence write failed", { computerId: id, error: String(e) });
+ }
+ }
+
+ private async ensureAlarm(at: number): Promise<void> {
+ const current = await this.ctx.storage.getAlarm();
+ if (current === null || current > at) await this.ctx.storage.setAlarm(at);
+ }
+
+ // ---- helpers ----
+
+ /** The single definition of "host online" (§7.2): a host socket whose attachment is `ready`. */
+ private readyHost(exclude?: WebSocket): WebSocket | undefined {
+ return this.ctx
+ .getWebSockets("host")
+ .find((ws) => ws !== exclude && (ws.deserializeAttachment() as HostAttachment).ready);
+ }
+
+ private presence(exclude?: WebSocket) {
+ const last = this.meta("lastSeenAt");
+ return { t: "presence", online: !!this.readyHost(exclude), lastSeenAt: last === null ? null : Number(last) };
+ }
+
+ private devices(): [WebSocket, DeviceAttachment][] {
+ return this.ctx.getWebSockets("device").map((ws) => [ws, ws.deserializeAttachment() as DeviceAttachment]);
+ }
+
+ private deviceByLink(link: unknown): WebSocket | undefined {
+ return this.devices().find(([, a]) => a.link === link)?.[0];
+ }
+
+ private toDevice(dk: string, msg: object): void {
+ const text = JSON.stringify(msg);
+ for (const [ws, a] of this.devices()) if (a.dk === dk && !a.pair) send(ws, text);
+ }
+
+ private toHosts(msg: object): void {
+ const text = JSON.stringify(msg);
+ for (const ws of this.ctx.getWebSockets("host")) send(ws, text);
+ }
+
+ private acl(): Acl | null {
+ const d = this.meta("aclD");
+ const bytes = d === null ? null : fromB64url(d);
+ return bytes ? parseAcl(bytes) : null;
+ }
+
+ private meta(k: string): string | null {
+ return this.sql.exec<{ v: string }>("SELECT v FROM meta WHERE k = ?", k).toArray()[0]?.v ?? null;
+ }
+
+ private setMeta(k: string, v: string): void {
+ this.sql.exec("INSERT INTO meta(k, v) VALUES (?, ?) ON CONFLICT(k) DO UPDATE SET v = excluded.v", k, v);
+ }
+
+ private safeClose(ws: WebSocket, code: number, reason: string): void {
+ try {
+ ws.close(code, reason.slice(0, 40));
+ } catch {
+ // Already closing or closed.
+ }
+ }
+}
diff --git a/cloud/test/api.test.ts b/cloud/test/api.test.ts
new file mode 100644
index 00000000..254bb8d1
--- /dev/null
+++ b/cloud/test/api.test.ts
@@ -0,0 +1,500 @@
+// /v1 HTTP API: auth, claims, access requests, grants, webhooks, cron.
+
+import { createScheduledController } from "cloudflare:test";
+import { Webhook } from "svix";
+import { describe, expect, it } from "vitest";
+import worker from "../src/index";
+import {
+ AUTHORITY,
+ call,
+ clerkToken,
+ devicePath,
+ env,
+ hostSocket,
+ newHost,
+ upgrade,
+ type Json,
+ type TestHost,
+} from "./helpers";
+import * as ref from "./ref";
+
+let seq = 0;
+const uid = (name: string) => `user_${name}_${++seq}_${ref.b64url(ref.random(4))}`;
+
+/** A signed-in user with one registered device key. */
+async function newUser(name = "a") {
+ const userId = uid(name);
+ const token = await clerkToken(userId);
+ const key = ref.signKey();
+ const r = await call("POST", "/v1/devices", { token, key, body: { name: "iPhone", platform: "ios" } });
+ expect(r.status).toBe(200);
+ return { userId, token, key, deviceId: r.body.device.deviceId as string, dk: ref.b64url(key.pub) };
+}
+
+type User = Awaited<ReturnType<typeof newUser>>;
+
+/** Claims `host` into `user`'s account the way the Mac app does (§4.2 A). */
+async function claim(user: User, host: TestHost) {
+ const c = await call("POST", "/v1/claims", { token: user.token });
+ expect(c.status).toBe(200);
+ return call("POST", `/v1/claims/${c.body.claimId}/complete`, { token: user.token, body: claimBody(c.body, user.userId, host) });
+}
+
+function claimBody(c: Json, userId: string, host: TestHost) {
+ const boxKey = ref.b64url(host.box.pub);
+ const canonical = ref.claimCanonical(c.claimId, c.nonce, userId, host.cid, boxKey);
+ return {
+ computerId: host.cid,
+ signKey: ref.b64url(host.sign.pub),
+ boxKey,
+ name: "Studio",
+ platform: "macos",
+ device: "macmini",
+ version: "3.0.0",
+ sig: ref.b64url(ref.sign(host.sign, ref.enc.encode(canonical))),
+ };
+}
+
+/** Runs §4.2 B up to an approved grant; returns the grant and the SAS both sides computed. */
+async function grantAccess(user: User, host: TestHost) {
+ const nD = ref.random(32);
+ const req = await call("POST", `/v1/computers/${host.cid}/access-requests`, {
+ token: user.token,
+ key: user.key,
+ body: { commit: ref.b64url(ref.sasCommit(user.key.pub, nD)) },
+ });
+ expect(req.status).toBe(200);
+ const id = req.body.requestId as string;
+ const nH = ref.random(32);
+ expect((await call("POST", `/v1/host/access-requests/${id}/nonce`, { key: host.sign, body: { nonce: ref.b64url(nH) } })).status).toBe(200);
+ const seen = await call("GET", `/v1/access-requests/${id}`, { token: user.token });
+ expect(seen.body.hostNonce).toBe(ref.b64url(nH));
+ expect((await call("POST", `/v1/access-requests/${id}/reveal`, { token: user.token, key: user.key, body: { nonce: ref.b64url(nD) } })).status).toBe(200);
+ const state = await call("GET", "/v1/host/state", { key: host.sign });
+ const r = state.body.requests.find((x: Json) => x.requestId === id);
+ expect(ref.b64url(ref.sasCommit(ref.unb64url(r.deviceKey), ref.unb64url(r.deviceNonce)))).toBe(r.commit);
+ const decision = await call("POST", `/v1/host/access-requests/${id}/decision`, { key: host.sign, body: { decision: "approve" } });
+ expect(decision.status).toBe(200);
+ return {
+ requestId: id,
+ grantId: decision.body.grantId as string,
+ sas: ref.sasCode(host.sign.pub, user.key.pub, nD, nH),
+ };
+}
+
+describe("basics", () => {
+ it("health", async () => {
+ expect(await call("GET", "/v1/health")).toEqual({ status: 200, body: { ok: true, version: "3.0.0" } });
+ });
+
+ it("errors carry a code and a requestId", async () => {
+ const r = await call("GET", "/v1/nope");
+ expect(r.status).toBe(404);
+ expect(r.body.error.code).toBe("notFound");
+ expect(typeof r.body.requestId).toBe("string");
+ });
+});
+
+describe("Clerk", () => {
+ it("accepts a valid session token and records the account", async () => {
+ const userId = uid("me");
+ const r = await call("GET", "/v1/me", { token: await clerkToken(userId, { email: "[email protected]" }) });
+ expect(r.status).toBe(200);
+ expect(r.body).toMatchObject({ userId, email: "[email protected]" });
+ });
+
+ it("rejects missing, foreign-issuer, session-less and tampered tokens", async () => {
+ const userId = uid("bad");
+ expect((await call("GET", "/v1/me")).body.error.code).toBe("unauthenticated");
+ expect((await call("GET", "/v1/me", { token: await clerkToken(userId, { iss: "https://evil.example" }) })).status).toBe(401);
+ expect((await call("GET", "/v1/me", { token: await clerkToken(userId, { sid: undefined }) })).status).toBe(401);
+ expect((await call("GET", "/v1/me", { token: await clerkToken(userId, { exp: Math.floor(Date.now() / 1000) - 60 }) })).status).toBe(401);
+ const good = await clerkToken(userId);
+ const [h, p, s] = good.split(".");
+ const forged = ref.b64url(ref.enc.encode(JSON.stringify({ ...JSON.parse(ref.dec.decode(ref.unb64url(p!))), sub: "user_victim" })));
+ expect((await call("GET", "/v1/me", { token: `${h}.${forged}.${s}` })).status).toBe(401);
+ });
+});
+
+describe("Codync-Sig over HTTP", () => {
+ const register = (key: ref.SignKey, o: { nonce?: string; ts?: number; authority?: string } = {}) =>
+ call("POST", "/v1/host/register", {
+ key,
+ ...o,
+ body: { boxKey: ref.b64url(ref.boxKey().pub), name: "Mac", platform: "macos", version: "3.0.0" },
+ });
+
+ it("rejects a replayed nonce", async () => {
+ const key = ref.signKey();
+ const nonce = ref.b64url(ref.random(16));
+ expect((await register(key, { nonce })).status).toBe(200);
+ const again = await register(key, { nonce });
+ expect(again.status).toBe(401);
+ expect(again.body.error.code).toBe("badSignature");
+ });
+
+ it("rejects timestamps outside ±5 minutes and other authorities", async () => {
+ const key = ref.signKey();
+ expect((await register(key, { ts: Date.now() - 301_000 })).status).toBe(401);
+ expect((await register(key, { ts: Date.now() + 301_000 })).status).toBe(401);
+ expect((await register(key, { authority: "codync-cloud.example.workers.dev" })).status).toBe(401);
+ expect((await register(key, { authority: AUTHORITY.toUpperCase() })).status).toBe(200);
+ });
+
+ it("limits new computers per IP", async () => {
+ const ip = { "CF-Connecting-IP": "192.0.2.7" };
+ const statuses = [];
+ for (let i = 0; i < 11; i++) {
+ const r = await call("POST", "/v1/host/register", {
+ key: ref.signKey(),
+ headers: ip,
+ body: { boxKey: ref.b64url(ref.boxKey().pub), name: "Mac", platform: "macos", version: "3.0.0" },
+ });
+ statuses.push(r.status);
+ }
+ expect(statuses.slice(0, 10).every((s) => s === 200)).toBe(true);
+ expect(statuses[10]).toBe(429);
+ });
+
+ it("binds the body", async () => {
+ const key = ref.signKey();
+ const body = ref.enc.encode(JSON.stringify({ boxKey: ref.b64url(ref.boxKey().pub), name: "Mac", platform: "macos", version: "3.0.0" }));
+ const sig = ref.signRequest(key, { method: "POST", authority: AUTHORITY, pathAndQuery: "/v1/host/register", body });
+ const res = await worker.fetch(
+ new Request(`https://${AUTHORITY}/v1/host/register`, {
+ method: "POST",
+ headers: { "Codync-Sig": sig },
+ body: ref.enc.encode(ref.dec.decode(body).replace("Mac", "Evil")),
+ }),
+ env,
+ {} as ExecutionContext,
+ );
+ expect(res.status).toBe(401);
+ });
+});
+
+describe("devices", () => {
+ it("registers idempotently, lists, and refuses a revoked key", async () => {
+ const u = await newUser();
+ const again = await call("POST", "/v1/devices", { token: u.token, key: u.key, body: { name: "Kevin's iPhone", platform: "ios" } });
+ expect(again.body.device).toMatchObject({ deviceId: u.deviceId, deviceKey: u.dk, name: "Kevin's iPhone" });
+ const list = await call("GET", "/v1/devices", { token: u.token });
+ expect(list.body.devices).toHaveLength(1);
+ expect(list.body.devices[0].revoked).toBe(false);
+ expect((await call("DELETE", `/v1/devices/${u.deviceId}`, { token: u.token })).status).toBe(200);
+ const revoked = await call("POST", "/v1/devices", { token: u.token, key: u.key, body: { name: "x", platform: "ios" } });
+ expect(revoked.status).toBe(403);
+ });
+
+ it("requires the device key's signature", async () => {
+ const userId = uid("nosig");
+ const r = await call("POST", "/v1/devices", { token: await clerkToken(userId), body: { name: "x", platform: "ios" } });
+ expect(r.status).toBe(401);
+ });
+
+ it("hides other accounts' devices", async () => {
+ const a = await newUser();
+ const b = await newUser("b");
+ expect((await call("DELETE", `/v1/devices/${a.deviceId}`, { token: b.token })).status).toBe(404);
+ });
+});
+
+describe("claims", () => {
+ it("claims a computer with the host's signature and reports ownership to the host", async () => {
+ const u = await newUser();
+ const host = await newHost();
+ const r = await claim(u, host);
+ expect(r.status).toBe(200);
+ expect(r.body.computer).toMatchObject({ computerId: host.cid, signKey: ref.b64url(host.sign.pub), boxKey: ref.b64url(host.box.pub) });
+ const state = await call("GET", "/v1/host/state", { key: host.sign });
+ expect(state.body.owner).toEqual({ userId: u.userId, email: `${u.userId}@example.com` });
+ const list = await call("GET", "/v1/computers", { token: u.token });
+ expect(list.body.computers.map((c: Json) => c.computerId)).toEqual([host.cid]);
+ expect(list.body.computers[0].access).toBeNull();
+ });
+
+ it("creates the computer row from the signed boxKey when the host never registered", async () => {
+ const u = await newUser();
+ const host: TestHost = { sign: ref.signKey(), box: ref.boxKey(), cid: "", ver: 0 };
+ host.cid = ref.computerId(host.sign.pub);
+ const r = await claim(u, host);
+ expect(r.status).toBe(200);
+ expect(r.body.computer.boxKey).toBe(ref.b64url(host.box.pub));
+ });
+
+ it("rejects a bad signature, a wrong computerId, someone else's claim and a used claim", async () => {
+ const u = await newUser();
+ const other = await newUser("o");
+ const host = await newHost();
+ const c = (await call("POST", "/v1/claims", { token: u.token })).body;
+ const body = claimBody(c, u.userId, host);
+ const path = `/v1/claims/${c.claimId}/complete`;
+ expect((await call("POST", path, { token: u.token, body: { ...body, boxKey: ref.b64url(ref.boxKey().pub) } })).status).toBe(401);
+ expect((await call("POST", path, { token: u.token, body: { ...body, computerId: "A".repeat(22) } })).status).toBe(400);
+ expect((await call("POST", path, { token: other.token, body })).status).toBe(404);
+ expect((await call("POST", path, { token: u.token, body })).status).toBe(200);
+ const reused = await call("POST", path, { token: u.token, body });
+ expect(reused.status).toBe(410);
+ expect(reused.body.error.code).toBe("claimExpired");
+ });
+
+ it("lets exactly one of two accounts win a race", async () => {
+ const a = await newUser();
+ const b = await newUser("b");
+ const host = await newHost();
+ const [ca, cb] = await Promise.all([a, b].map(async (u) => (await call("POST", "/v1/claims", { token: u.token })).body));
+ const results = await Promise.all([
+ call("POST", `/v1/claims/${ca.claimId}/complete`, { token: a.token, body: claimBody(ca, a.userId, host) }),
+ call("POST", `/v1/claims/${cb.claimId}/complete`, { token: b.token, body: claimBody(cb, b.userId, host) }),
+ ]);
+ expect(results.map((r) => r.status).sort()).toEqual([200, 409]);
+ expect(results.find((r) => r.status === 409)!.body.error.code).toBe("alreadyClaimed");
+ });
+});
+
+describe("access requests", () => {
+ it("runs commit → host nonce → reveal → approve, and both sides get the same SAS", async () => {
+ const u = await newUser();
+ const host = await newHost();
+ await claim(u, host);
+ const { grantId, sas } = await grantAccess(u, host);
+ expect(grantId).toMatch(/^grt_/);
+ expect(sas).toMatch(/^\d{6}$/);
+ const state = await call("GET", "/v1/host/state", { key: host.sign });
+ expect(state.body.grants).toEqual([{ grantId, deviceKey: u.dk, deviceName: "iPhone", platform: "ios", scopes: ["control", "screen"] }]);
+ const list = await call("GET", "/v1/computers", { token: u.token, key: u.key });
+ expect(list.body.computers[0].access).toBe("granted");
+ const grants = await call("GET", `/v1/computers/${host.cid}/grants`, { token: u.token });
+ expect(grants.body.grants[0]).toMatchObject({ grantId, deviceId: u.deviceId, scopes: ["control", "screen"] });
+ const again = await call("POST", `/v1/computers/${host.cid}/access-requests`, {
+ token: u.token,
+ key: u.key,
+ body: { commit: ref.b64url(ref.random(32)) },
+ });
+ expect(again.status).toBe(409);
+ });
+
+ it("enforces order: no reveal before the host nonce, no approve before the reveal, one host nonce", async () => {
+ const u = await newUser();
+ const host = await newHost();
+ await claim(u, host);
+ const nD = ref.random(32);
+ const req = await call("POST", `/v1/computers/${host.cid}/access-requests`, {
+ token: u.token,
+ key: u.key,
+ body: { commit: ref.b64url(ref.sasCommit(u.key.pub, nD)) },
+ });
+ const id = req.body.requestId;
+ expect((await call("GET", "/v1/computers", { token: u.token, key: u.key })).body.computers[0].access).toBe("pending");
+ const early = await call("POST", `/v1/access-requests/${id}/reveal`, { token: u.token, key: u.key, body: { nonce: ref.b64url(nD) } });
+ expect(early.status).toBe(409);
+ const nonce = (n = ref.random(32)) => call("POST", `/v1/host/access-requests/${id}/nonce`, { key: host.sign, body: { nonce: ref.b64url(n) } });
+ expect((await nonce()).status).toBe(200);
+ expect((await nonce()).status).toBe(409);
+ const approve = () => call("POST", `/v1/host/access-requests/${id}/decision`, { key: host.sign, body: { decision: "approve" } });
+ expect((await approve()).status).toBe(409);
+ expect((await call("POST", `/v1/access-requests/${id}/reveal`, { token: u.token, key: u.key, body: { nonce: ref.b64url(nD) } })).status).toBe(200);
+ expect((await call("POST", `/v1/access-requests/${id}/reveal`, { token: u.token, key: u.key, body: { nonce: ref.b64url(nD) } })).status).toBe(409);
+ // A double-click on approve returns the same grant.
+ const [first, second] = [await approve(), await approve()];
+ expect(first.status).toBe(200);
+ expect(second.body).toEqual(first.body);
+ expect((await call("GET", `/v1/access-requests/${id}`, { token: u.token })).body).toMatchObject({ status: "approved", grantId: first.body.grantId });
+ });
+
+ it("returns 404 for anything belonging to another account", async () => {
+ const a = await newUser();
+ const b = await newUser("b");
+ const host = await newHost();
+ await claim(a, host);
+ const commit = { commit: ref.b64url(ref.random(32)) };
+ const cross = await call("POST", `/v1/computers/${host.cid}/access-requests`, { token: b.token, key: b.key, body: commit });
+ expect(cross.status).toBe(404);
+ // a's token with b's device key: the device doesn't belong to a.
+ expect((await call("POST", `/v1/computers/${host.cid}/access-requests`, { token: a.token, key: b.key, body: commit })).status).toBe(404);
+ const own = await call("POST", `/v1/computers/${host.cid}/access-requests`, { token: a.token, key: a.key, body: commit });
+ const id = own.body.requestId;
+ expect((await call("GET", `/v1/access-requests/${id}`, { token: b.token })).status).toBe(404);
+ expect((await call("DELETE", `/v1/access-requests/${id}`, { token: b.token })).status).toBe(404);
+ expect((await call("GET", `/v1/computers/${host.cid}/grants`, { token: b.token })).status).toBe(404);
+ expect((await call("PATCH", `/v1/computers/${host.cid}`, { token: b.token, body: { name: "mine" } })).status).toBe(404);
+ expect((await call("DELETE", `/v1/computers/${host.cid}`, { token: b.token })).status).toBe(404);
+ // Another host can't touch this computer's requests either.
+ const other = await newHost();
+ expect((await call("POST", `/v1/host/access-requests/${id}/nonce`, { key: other.sign, body: { nonce: ref.b64url(ref.random(32)) } })).status).toBe(404);
+ });
+
+ it("cancels an earlier pending request instead of reusing its commit", async () => {
+ const u = await newUser();
+ const host = await newHost();
+ await claim(u, host);
+ const make = () =>
+ call("POST", `/v1/computers/${host.cid}/access-requests`, { token: u.token, key: u.key, body: { commit: ref.b64url(ref.random(32)) } });
+ const first = (await make()).body.requestId;
+ const second = (await make()).body.requestId;
+ expect((await call("GET", `/v1/access-requests/${first}`, { token: u.token })).body.status).toBe("cancelled");
+ expect((await call("GET", `/v1/access-requests/${second}`, { token: u.token })).body.status).toBe("pending");
+ expect((await call("DELETE", `/v1/access-requests/${second}`, { token: u.token })).status).toBe(200);
+ expect((await call("GET", "/v1/host/state", { key: host.sign })).body.requests).toEqual([]);
+ });
+
+ it("limits each account to 20 requests an hour", async () => {
+ const u = await newUser();
+ const host = await newHost();
+ await claim(u, host);
+ let last = 0;
+ for (let i = 0; i < 21; i++) {
+ last = (await call("POST", `/v1/computers/${host.cid}/access-requests`, { token: u.token, key: u.key, body: { commit: ref.b64url(ref.random(32)) } })).status;
+ }
+ expect(last).toBe(429);
+ });
+
+ it("denies", async () => {
+ const u = await newUser();
+ const host = await newHost();
+ await claim(u, host);
+ const id = (await call("POST", `/v1/computers/${host.cid}/access-requests`, { token: u.token, key: u.key, body: { commit: ref.b64url(ref.random(32)) } })).body.requestId;
+ const r = await call("POST", `/v1/host/access-requests/${id}/decision`, { key: host.sign, body: { decision: "deny" } });
+ expect(r.body).toEqual({ status: "denied" });
+ expect((await call("GET", `/v1/access-requests/${id}`, { token: u.token })).body.status).toBe("denied");
+ });
+});
+
+describe("revocation reaches the relay", () => {
+ it("closes the device socket with 4003, blocks it, and only a new grant unblocks it", async () => {
+ const u = await newUser();
+ const host = await newHost();
+ await claim(u, host);
+ const { grantId } = await grantAccess(u, host);
+ const hostWs = await hostSocket(host, [{ dk: u.dk, grant: grantId }]);
+ const device = (await upgrade(devicePath(host), u.key)).sock!;
+ await device.nextT("presence");
+
+ const started = Date.now();
+ expect((await call("DELETE", `/v1/computers/${host.cid}/grants/${grantId}`, { token: u.token })).status).toBe(200);
+ expect(await device.closed(1000)).toBe(4003);
+ expect(Date.now() - started).toBeLessThan(1000);
+ await hostWs.nextT("cloud.changed");
+ expect((await call("GET", "/v1/host/state", { key: host.sign })).body.grants).toEqual([]);
+
+ // Still listed with the same grant (host hasn't pulled state yet): stays blocked.
+ hostWs.send(ref.aclMessage(host.sign, { v: 1, computerId: host.cid, ver: ++host.ver, devices: [{ dk: u.dk, grant: grantId }], offers: [] }));
+ await hostWs.nextT("acl.ok");
+ expect((await upgrade(devicePath(host), u.key)).status).toBe(403);
+
+ // A new approval → a different grant → unblocked.
+ const again = await grantAccess(u, host);
+ expect(again.grantId).not.toBe(grantId);
+ hostWs.send(ref.aclMessage(host.sign, { v: 1, computerId: host.cid, ver: ++host.ver, devices: [{ dk: u.dk, grant: again.grantId }], offers: [] }));
+ await hostWs.nextT("acl.ok");
+ expect((await upgrade(devicePath(host), u.key)).status).toBe(101);
+ });
+
+ it("a QR pairing of a revoked device unblocks it", async () => {
+ const u = await newUser();
+ const host = await newHost();
+ await claim(u, host);
+ const { grantId } = await grantAccess(u, host);
+ const hostWs = await hostSocket(host, [{ dk: u.dk, grant: grantId }]);
+ expect((await call("DELETE", `/v1/computers/${host.cid}/grants/${grantId}`, { token: u.token })).status).toBe(200);
+ await hostWs.nextT("cloud.changed");
+ hostWs.send(ref.aclMessage(host.sign, { v: 1, computerId: host.cid, ver: ++host.ver, devices: [], offers: [] }));
+ await hostWs.nextT("acl.ok");
+ expect((await upgrade(devicePath(host), u.key)).status).toBe(403);
+
+ // The host paired it again locally (grant null): the host is the authority.
+ hostWs.send(ref.aclMessage(host.sign, { v: 1, computerId: host.cid, ver: ++host.ver, devices: [{ dk: u.dk, grant: null }], offers: [] }));
+ await hostWs.nextT("acl.ok");
+ expect((await upgrade(devicePath(host), u.key)).status).toBe(101);
+ });
+
+ it("revoking the device revokes its grants everywhere", async () => {
+ const u = await newUser();
+ const host = await newHost();
+ await claim(u, host);
+ const { grantId } = await grantAccess(u, host);
+ const hostWs = await hostSocket(host, [{ dk: u.dk, grant: grantId }]);
+ const device = (await upgrade(devicePath(host), u.key)).sock!;
+ expect((await call("DELETE", `/v1/devices/${u.deviceId}`, { token: u.token })).status).toBe(200);
+ expect(await device.closed()).toBe(4003);
+ await hostWs.nextT("cloud.changed");
+ expect((await call("GET", "/v1/host/state", { key: host.sign })).body.grants).toEqual([]);
+ });
+
+ it("unclaiming clears the owner and grants", async () => {
+ const u = await newUser();
+ const host = await newHost();
+ await claim(u, host);
+ await grantAccess(u, host);
+ expect((await call("POST", "/v1/host/unclaim", { key: host.sign, body: {} })).status).toBe(200);
+ const state = await call("GET", "/v1/host/state", { key: host.sign });
+ expect(state.body).toEqual({ owner: null, grants: [], requests: [] });
+ expect((await call("GET", "/v1/computers", { token: u.token })).body.computers).toEqual([]);
+ });
+
+ it("the host's own revoke marks the grant revoked", async () => {
+ const u = await newUser();
+ const host = await newHost();
+ await claim(u, host);
+ const { grantId } = await grantAccess(u, host);
+ expect((await call("POST", `/v1/host/grants/${grantId}/revoke`, { key: host.sign, body: {} })).status).toBe(200);
+ expect((await call("GET", `/v1/computers/${host.cid}/grants`, { token: u.token })).body.grants).toEqual([]);
+ const other = await newHost();
+ expect((await call("POST", `/v1/host/grants/${grantId}/revoke`, { key: other.sign, body: {} })).status).toBe(404);
+ });
+});
+
+describe("Clerk webhook", () => {
+ const deliver = (id: string, payload: unknown, secret = env.CLERK_WEBHOOK_SECRET!) => {
+ const body = JSON.stringify(payload);
+ const now = new Date();
+ return call("POST", "/v1/webhooks/clerk", {
+ body: payload,
+ headers: {
+ "svix-id": id,
+ "svix-timestamp": String(Math.floor(now.getTime() / 1000)),
+ "svix-signature": new Webhook(secret).sign(id, now, body),
+ },
+ });
+ };
+
+ it("rejects bad signatures", async () => {
+ const r = await deliver("msg_bad", { type: "user.deleted", data: { id: "x" } }, `whsec_${btoa("0".repeat(24))}`);
+ expect(r.status).toBe(401);
+ });
+
+ it("deletes the account, revokes everything, and processes each event once", async () => {
+ const u = await newUser();
+ const host = await newHost();
+ await claim(u, host);
+ await grantAccess(u, host);
+ const id = `msg_${ref.b64url(ref.random(8))}`;
+ expect((await deliver(id, { type: "user.deleted", data: { id: u.userId } })).status).toBe(200);
+ expect((await call("GET", "/v1/me", { token: u.token })).body.error.code).toBe("accountDeleted");
+ expect((await call("GET", "/v1/host/state", { key: host.sign })).body).toEqual({ owner: null, grants: [], requests: [] });
+ expect((await deliver(id, { type: "user.deleted", data: { id: u.userId } })).status).toBe(200);
+ const n = await env.DB.prepare("SELECT COUNT(*) AS n FROM processed_events WHERE event_id = ?").bind(id).first<{ n: number }>();
+ expect(n?.n).toBe(1);
+ const audits = await env.DB.prepare("SELECT COUNT(*) AS n FROM audit_events WHERE action = 'account.delete' AND target = ?")
+ .bind(u.userId)
+ .first<{ n: number }>();
+ expect(audits?.n).toBe(1);
+ });
+});
+
+describe("cron", () => {
+ it("expires pending requests and clears their nonces", async () => {
+ const u = await newUser();
+ const host = await newHost();
+ await claim(u, host);
+ const id = (await call("POST", `/v1/computers/${host.cid}/access-requests`, { token: u.token, key: u.key, body: { commit: ref.b64url(ref.random(32)) } })).body.requestId;
+ await call("POST", `/v1/host/access-requests/${id}/nonce`, { key: host.sign, body: { nonce: ref.b64url(ref.random(32)) } });
+ await env.DB.prepare("UPDATE access_requests SET expires_at = ? WHERE id = ?").bind(Date.now() - 1, id).run();
+ expect((await call("GET", `/v1/access-requests/${id}`, { token: u.token })).body.status).toBe("expired");
+ const decision = await call("POST", `/v1/host/access-requests/${id}/decision`, { key: host.sign, body: { decision: "approve" } });
+ expect(decision.body.error.code).toBe("requestExpired");
+ await worker.scheduled(createScheduledController(), env);
+ const row = await env.DB.prepare("SELECT status, host_nonce FROM access_requests WHERE id = ?").bind(id).first();
+ expect(row).toEqual({ status: "expired", host_nonce: null });
+ });
+});
diff --git a/cloud/test/e2e/phone.ts b/cloud/test/e2e/phone.ts
new file mode 100644
index 00000000..f50aa0a4
--- /dev/null
+++ b/cloud/test/e2e/phone.ts
@@ -0,0 +1,223 @@
+// A fake phone for the cross-track e2e test (spec §12.1): a device key, the E2E channel over the relay
+// or a direct `/channel` socket, inner RPC, subscriptions and the mailbox. Node only (global WebSocket).
+
+import * as ref from "../ref.ts";
+
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+export type Json = any;
+
+export async function waitFor<T>(what: string, check: () => T | undefined | Promise<T | undefined>, ms = 15_000): Promise<T> {
+ const deadline = Date.now() + ms;
+ for (;;) {
+ const v = await check();
+ if (v !== undefined && v !== false) return v as T;
+ if (Date.now() > deadline) throw new Error(`timed out waiting for ${what}`);
+ await new Promise((r) => setTimeout(r, 100));
+ }
+}
+
+/** A WebSocket with a queue of parsed messages and the close code. */
+export class Wire {
+ readonly msgs: Json[] = [];
+ close?: { code: number; reason: string };
+ onMessage?: (m: Json) => boolean; // true = consumed
+ readonly opened: Promise<void>;
+
+ readonly ws: WebSocket;
+
+ constructor(ws: WebSocket) {
+ this.ws = ws;
+ this.opened = new Promise((resolve, reject) => {
+ ws.addEventListener("open", () => resolve());
+ ws.addEventListener("error", () => reject(new Error(`WebSocket to ${ws.url} failed`)));
+ });
+ ws.addEventListener("message", (e) => {
+ const m = JSON.parse(String(e.data));
+ if (!this.onMessage?.(m)) this.msgs.push(m);
+ });
+ ws.addEventListener("close", (e) => {
+ this.close = { code: e.code, reason: e.reason };
+ });
+ }
+
+ static connect(url: string, key?: ref.SignKey): Wire {
+ const u = new URL(url);
+ const headers: Record<string, string> = {};
+ if (key) headers["Codync-Sig"] = ref.signRequest(key, { method: "GET", authority: u.host, pathAndQuery: u.pathname + u.search });
+ // undici's WebSocket takes headers in its init object (not in the DOM typings).
+ return new Wire(new WebSocket(url, { headers } as unknown as string[]));
+ }
+
+ send(m: unknown) {
+ this.ws.send(typeof m === "string" ? m : JSON.stringify(m));
+ }
+
+ next(pred: (m: Json) => boolean, what: string, ms = 15_000): Promise<Json> {
+ return waitFor(what, () => {
+ const i = this.msgs.findIndex(pred);
+ if (i >= 0) return this.msgs.splice(i, 1)[0];
+ if (this.close) throw new Error(`socket closed (${this.close.code} ${this.close.reason}) while waiting for ${what}`);
+ return undefined;
+ }, ms);
+ }
+
+ closed(ms = 15_000): Promise<number> {
+ return waitFor("close", () => this.close?.code, ms);
+ }
+}
+
+export interface PairingInfo {
+ computerId: string;
+ signKey: Uint8Array;
+ boxKey: Uint8Array;
+ code: string;
+ urls: string[];
+ cloud: string | null;
+}
+
+/** Parses a v3 `codync://pair?…` link (§4.1), refusing a mismatched computerId. */
+export function parsePairing(link: string): PairingInfo {
+ const u = new URL(link);
+ const q = u.searchParams;
+ if (u.protocol !== "codync:" || q.get("v") !== "3") throw new Error(`not a v3 pairing link: ${link}`);
+ const signKey = ref.unb64url(q.get("sk") ?? "");
+ if (ref.computerId(signKey) !== q.get("id")) throw new Error("pairing link id doesn't match sk");
+ return {
+ computerId: q.get("id")!,
+ signKey,
+ boxKey: ref.unb64url(q.get("bk") ?? ""),
+ code: q.get("code") ?? "",
+ urls: (q.get("urls") ?? "").split(",").filter(Boolean),
+ cloud: q.get("cloud"),
+ };
+}
+
+/** One E2E channel: handshake, then multiplexed inner RPC and subscriptions over encrypted frames. */
+export class Channel {
+ private codec!: ref.FrameCodec;
+ private nextId = 1;
+ private readonly pending = new Map<number, { resolve: (v: Json) => void; reject: (e: Error) => void }>();
+ private readonly subs = new Map<number, (ev: Json) => void>();
+ readonly events: Json[] = [];
+ hello?: Json;
+
+ readonly wire: Wire;
+ private readonly relay: boolean;
+
+ private constructor(wire: Wire, relay: boolean) {
+ this.wire = wire;
+ this.relay = relay;
+ }
+
+ /** Opens a channel. Over the relay it waits for `presence online:true` before `hello` (§7.5). */
+ static async open(
+ wire: Wire,
+ device: ref.SignKey,
+ hostSignPub: Uint8Array,
+ o: { relay: boolean; pair?: boolean },
+ ): Promise<Channel> {
+ await wire.opened;
+ const ch = new Channel(wire, o.relay);
+ if (o.relay) await wire.next((m) => m.t === "presence" && m.online === true, "presence online");
+ const d = ref.deviceHello(device, hostSignPub, { pair: o.pair });
+ wire.send(d.hello);
+ const answer = await wire.next((m) => m.t === "welcome" || m.t === "reject", "welcome", 10_000);
+ if (answer.t === "reject") throw new Error(`rejected: ${answer.code} ${answer.message ?? ""}`);
+ const keys = d.finish(answer);
+ ch.codec = new ref.FrameCodec(keys.d2h, keys.h2d);
+ wire.onMessage = (m) => {
+ if (m.t !== "f") return false;
+ const inner = ch.codec.open(m);
+ if (inner !== undefined) ch.dispatch(inner);
+ return true;
+ };
+ return ch;
+ }
+
+ private dispatch(m: Json) {
+ const p = this.pending.get(m.id);
+ if (p && ("ok" in m || "err" in m)) {
+ this.pending.delete(m.id);
+ if ("ok" in m) p.resolve(m.ok);
+ else p.reject(Object.assign(new Error(`${m.err.status} ${m.err.message}`), { status: m.err.status }));
+ return;
+ }
+ if ("ev" in m) {
+ this.events.push(m.ev);
+ this.subs.get(m.id)?.(m.ev);
+ }
+ }
+
+ private send(inner: unknown) {
+ for (const f of this.codec.seal(inner)) this.wire.send(f);
+ }
+
+ call(method: string, body: unknown = null, ms = 15_000): Promise<Json> {
+ const id = this.nextId++;
+ const done = new Promise<Json>((resolve, reject) => {
+ this.pending.set(id, { resolve, reject });
+ setTimeout(() => {
+ if (this.pending.delete(id)) reject(new Error(`${method} timed out`));
+ }, ms);
+ });
+ this.send({ id, m: method, b: body });
+ return done;
+ }
+
+ subscribe(sub: "events" | "term", body: unknown, onEvent: (ev: Json) => void = () => {}): number {
+ const id = this.nextId++;
+ this.subs.set(id, onEvent);
+ this.send({ id, sub, b: body });
+ return id;
+ }
+
+ cancel(id: number) {
+ this.send({ id, cancel: true });
+ }
+
+ get isRelay() {
+ return this.relay;
+ }
+}
+
+export class FakePhone {
+ readonly key = ref.signKey();
+ get dk() {
+ return ref.b64url(this.key.pub);
+ }
+
+ relayUrl(cloud: string, computerId: string, pair?: string): string {
+ const base = cloud.replace(/^http/, "ws").replace(/\/$/, "");
+ return `${base}/v1/relay/device/${computerId}?v=1${pair ? `&pair=${pair}` : ""}`;
+ }
+
+ relayWire(cloud: string, computerId: string, pair?: string): Wire {
+ return Wire.connect(this.relayUrl(cloud, computerId, pair), this.key);
+ }
+
+ async relay(cloud: string, computerId: string, hostSignPub: Uint8Array): Promise<Channel> {
+ return Channel.open(this.relayWire(cloud, computerId), this.key, hostSignPub, { relay: true });
+ }
+
+ async direct(base: string, hostSignPub: Uint8Array): Promise<Channel> {
+ const url = `${base.replace(/^http/, "ws").replace(/\/$/, "")}/channel?v=1`;
+ 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> {
+ 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 code = await wire.closed();
+ if (code !== 4100) throw new Error(`pairing link closed with ${code}, expected 4100`);
+ return ok;
+ }
+
+ /** Seals and queues a `send` for an offline host (§6.4). */
+ mailboxPut(wire: Wire, p: { signKey: Uint8Array; boxKey: Uint8Array }, botId: string, text: string, clientNonce: string) {
+ const inner = JSON.stringify({ m: "send", b: { botId, text, clientNonce }, ts: Date.now() });
+ const blob = ref.sealMailbox(this.key, p.signKey, p.boxKey, clientNonce, inner);
+ wire.send({ t: "mbox.put", nonce: clientNonce, d: ref.b64url(blob) });
+ }
+}
diff --git a/cloud/test/e2e/relay.e2e.ts b/cloud/test/e2e/relay.e2e.ts
new file mode 100644
index 00000000..6d1d426d
--- /dev/null
+++ b/cloud/test/e2e/relay.e2e.ts
@@ -0,0 +1,293 @@
+// 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.
+
+import { type ChildProcess, spawn, spawnSync } from "node:child_process";
+import { generateKeyPairSync } from "node:crypto";
+import { mkdtempSync, readFileSync, rmSync } from "node:fs";
+import { createServer } from "node:net";
+import { networkInterfaces, tmpdir } from "node:os";
+import { join } from "node:path";
+import { fileURLToPath } from "node:url";
+import * as ref from "../ref.ts";
+import { Channel, FakePhone, parsePairing, waitFor, type Json, type PairingInfo, type Wire } from "./phone.ts";
+
+const CLOUD_DIR = fileURLToPath(new URL("../..", import.meta.url));
+const ROOT = join(CLOUD_DIR, "..");
+const HOST_BIN = process.env.CODYNC_HOST_BIN ?? join(ROOT, "host/target/debug/codync-host");
+const FAKE_AGENT = join(ROOT, "host/tests/fake_agent.py");
+const CLOUD_PORT = Number(process.env.CODYNC_E2E_CLOUD_PORT ?? 8787);
+const CLOUD = `http://127.0.0.1:${CLOUD_PORT}`;
+const ISSUER = "https://clerk.test.local"; // [env.dev] CLERK_ISSUER
+const WRANGLER = join(CLOUD_DIR, "node_modules/.bin/wrangler");
+
+const tmp = mkdtempSync(join(tmpdir(), "codync-e2e-"));
+const persist = join(tmp, "wrangler");
+const home = join(tmp, "home");
+const children: ChildProcess[] = [];
+
+function step(name: string) {
+ console.log(`\n▶ ${name}`);
+}
+
+function check(cond: unknown, what: string): asserts cond {
+ if (!cond) throw new Error(`check failed: ${what}`);
+ console.log(` ✓ ${what}`);
+}
+
+async function freePort(): Promise<number> {
+ return new Promise((resolve) => {
+ const s = createServer();
+ s.listen(0, "127.0.0.1", () => {
+ const port = (s.address() as { port: number }).port;
+ s.close(() => resolve(port));
+ });
+ });
+}
+
+function run(cmd: string, args: string[], env: Record<string, string> = {}): ChildProcess {
+ const child = spawn(cmd, args, { cwd: CLOUD_DIR, env: { ...process.env, ...env }, stdio: ["ignore", "pipe", "pipe"] });
+ const tag = cmd.split("/").pop();
+ child.stdout?.on("data", (d) => process.env.E2E_VERBOSE && process.stdout.write(`[${tag}] ${d}`));
+ child.stderr?.on("data", (d) => process.env.E2E_VERBOSE && process.stderr.write(`[${tag}] ${d}`));
+ children.push(child);
+ return child;
+}
+
+async function stop(child: ChildProcess) {
+ if (child.exitCode !== null || child.signalCode) return;
+ const exited = new Promise((r) => child.once("exit", r));
+ child.kill("SIGTERM");
+ await Promise.race([exited, new Promise((r) => setTimeout(r, 5000))]);
+ if (child.exitCode === null && !child.signalCode) child.kill("SIGKILL");
+}
+
+function d1(sql: string): Json[] {
+ const r = spawnSync(WRANGLER, ["d1", "execute", "codync-dev", "--local", "--env", "dev", "--persist-to", persist, "--json", "--command", sql], {
+ cwd: CLOUD_DIR,
+ encoding: "utf8",
+ });
+ if (r.status !== 0) throw new Error(`d1 failed: ${r.stderr}`);
+ return (JSON.parse(r.stdout) as { results: Json[] }[])[0]?.results ?? [];
+}
+
+// ---- Clerk test tokens ----
+
+const { publicKey, privateKey } = generateKeyPairSync("rsa", { modulusLength: 2048 });
+// @clerk/backend strips PEM armor itself; a single line survives `--var`.
+const jwtKey = publicKey
+ .export({ type: "spki", format: "pem" })
+ .toString()
+ .replace(/-----[A-Z ]+-----|\s/g, "");
+
+async function clerkToken(sub: string): Promise<string> {
+ const key = await crypto.subtle.importKey("jwk", privateKey.export({ format: "jwk" }), { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, false, [
+ "sign",
+ ]);
+ const now = Math.floor(Date.now() / 1000);
+ const part = (v: unknown) => ref.b64url(ref.enc.encode(JSON.stringify(v)));
+ const head = `${part({ alg: "RS256", typ: "JWT" })}.${part({ iss: ISSUER, sub, sid: `sess_${sub}`, iat: now - 5, nbf: now - 5, exp: now + 3600, email: `${sub}@example.com` })}`;
+ return `${head}.${ref.b64url(new Uint8Array(await crypto.subtle.sign("RSASSA-PKCS1-v1_5", key, ref.enc.encode(head))))}`;
+}
+
+async function cloud(method: string, path: string, o: { token?: string; key?: ref.SignKey; body?: unknown } = {}): Promise<{ status: number; body: Json }> {
+ const bytes = o.body === undefined ? new Uint8Array() : ref.enc.encode(JSON.stringify(o.body));
+ const headers: Record<string, string> = {};
+ if (o.token) headers.Authorization = `Bearer ${o.token}`;
+ if (o.body !== undefined) headers["Content-Type"] = "application/json";
+ if (o.key) headers["Codync-Sig"] = ref.signRequest(o.key, { method, authority: `127.0.0.1:${CLOUD_PORT}`, pathAndQuery: path, body: bytes });
+ const res = await fetch(CLOUD + path, { method, headers, body: bytes.length ? bytes : undefined });
+ return { status: res.status, body: await res.json() };
+}
+
+// ---- the host ----
+
+let hostPort = 0;
+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 });
+ await waitFor("host /health", () => fetch(`http://127.0.0.1:${hostPort}/health`).then((r) => r.ok || undefined).catch(() => undefined), 30_000);
+}
+
+async function loopback(method: string, body: unknown = {}): Promise<Json> {
+ const token = readFileSync(join(home, "token"), "utf8").trim();
+ const res = await fetch(`http://127.0.0.1:${hostPort}/api/${method}`, {
+ method: "POST",
+ headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
+ body: JSON.stringify(body),
+ });
+ const v = await res.json();
+ if (!res.ok) throw new Error(`${method} → ${res.status} ${JSON.stringify(v)}`);
+ return v;
+}
+
+/** The relay refused the upgrade (the socket never opened). */
+const refused = (wire: Wire) => wire.opened.then(
+ () => false,
+ () => true,
+);
+
+const computerOnline = (id: string) => d1(`SELECT online FROM computers WHERE id = '${id}'`)[0]?.online === 1 || undefined;
+
+// ---- scenario ----
+
+async function main() {
+ step("1. local D1 + wrangler dev");
+ const migrate = spawnSync(WRANGLER, ["d1", "migrations", "apply", "codync-dev", "--local", "--env", "dev", "--persist-to", persist], {
+ cwd: CLOUD_DIR,
+ encoding: "utf8",
+ env: { ...process.env, CI: "1" },
+ });
+ if (migrate.status !== 0) throw new Error(`migrations failed: ${migrate.stderr}`);
+ run(WRANGLER, ["dev", "--env", "dev", "--ip", "127.0.0.1", "--port", String(CLOUD_PORT), "--persist-to", persist, "--var", `CLERK_JWT_KEY:${jwtKey}`]);
+ 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");
+ await startHost();
+ const health = await (await fetch(`http://127.0.0.1:${hostPort}/health`)).json();
+ const computerId = health.computerId as string;
+ check(/^[A-Za-z0-9_-]{22}$/.test(computerId), "host reports a computerId");
+ await waitFor("computer row", () => d1(`SELECT id FROM computers WHERE id = '${computerId}'`).length > 0 || undefined);
+ 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");
+ 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");
+ // 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", {});
+ check(hello.computerId === computerId && hello.boxKey === ref.b64url(pairing.boxKey), "inner hello returns computerId and boxKey");
+ for (let i = 0; i < 20; i++) await ch.call("sync", { since: 0 });
+ check(true, "more than 16 messages on the regular link");
+
+ const bot = (await ch.call("createBot", { name: "Tester", backend: "custom", command: `python3 '${FAKE_AGENT}'`, cwd: tmp, permission: "ask" })).bot.id;
+ ch.subscribe("events", { since: 0, client: "ios" });
+ await ch.call("send", { botId: bot, text: "go", clientNonce: "e2e-1" });
+ const card = await waitFor("permission card", () =>
+ ch.events.find((e) => e.type === "entry" && e.entry.kind === "permission" && e.entry.data.status === "pending"),
+ );
+ await ch.call("respondPermission", { entryId: card.entry.id, optionId: "allow" });
+ await waitFor("final reply", () => ch.events.find((e) => e.type === "entry" && e.entry.kind === "agent" && e.entry.data.final === true), 20_000);
+ check(true, "agent reply arrived through the relay");
+
+ step("5. mailbox while the host is down");
+ await stop(host!);
+ await ch.wire.next((m) => m.t === "presence" && m.online === false, "presence offline");
+ check(true, "device saw presence online:false");
+ phone.mailboxPut(ch.wire, pairing, bot, "queued hello", "e2e-mbox-1");
+ check((await ch.wire.next((m) => m.t === "mbox.ok", "mbox.ok")).nonce === "e2e-mbox-1", "queued");
+ phone.mailboxPut(ch.wire, pairing, bot, "never mind", "e2e-mbox-2");
+ await ch.wire.next((m) => m.t === "mbox.ok", "mbox.ok 2");
+ ch.wire.send({ t: "mbox.cancel", nonce: "e2e-mbox-2" });
+ check((await ch.wire.next((m) => m.t === "mbox.cancelled", "cancelled")).nonce === "e2e-mbox-2", "second one cancelled");
+ await startHost();
+ const delivered = await ch.wire.next((m) => m.t === "mbox.delivered", "mbox.delivered", 30_000);
+ check(delivered.nonce === "e2e-mbox-1", "delivered after the host came back");
+ // Every presence online:true means a fresh handshake on the same socket (§7.2).
+ ch = await Channel.open(ch.wire, phone.key, pairing.signKey, { relay: true });
+ const history = await waitFor("mailbox entry", async () => {
+ const h = await ch.call("history", { botId: bot });
+ return h.entries.some((e: Json) => e.data?.clientNonce === "e2e-mbox-1") ? h : undefined;
+ });
+ check(!history.entries.some((e: Json) => e.data?.clientNonce === "e2e-mbox-2"), "the cancelled message never ran");
+
+ step("6. account: claim, access request with SAS, revocation");
+ const userId = "user_e2e";
+ const token = await clerkToken(userId);
+ 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);
+
+ 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");
+ const listed = (await cloud("GET", "/v1/computers", { token, key: phone2.key })).body.computers[0];
+ check(listed.access === "none", "phone 2 has no access yet");
+ const nD = ref.random(32);
+ const req = await cloud("POST", `/v1/computers/${computerId}/access-requests`, {
+ token,
+ key: phone2.key,
+ body: { commit: ref.b64url(ref.sasCommit(phone2.key.pub, nD)) },
+ });
+ const requestId = req.body.requestId as string;
+ const hostNonce = await waitFor("host nonce", async () => (await cloud("GET", `/v1/access-requests/${requestId}`, { token })).body.hostNonce);
+ check((await cloud("POST", `/v1/access-requests/${requestId}/reveal`, { token, key: phone2.key, body: { nonce: ref.b64url(nD) } })).status === 200, "revealed");
+ const sas = ref.sasCode(ref.unb64url(listed.signKey), phone2.key.pub, nD, ref.unb64url(hostNonce));
+ const shown = await waitFor("SAS on the computer", async () =>
+ (await loopback("accessRequests")).requests.find((r: Json) => r.requestId === requestId && r.code),
+ );
+ check(shown.code === sas, `the computer shows the phone's SAS (${sas})`);
+ await loopback("decideAccessRequest", { requestId, approve: true });
+ const approved = await waitFor("approved", async () => {
+ const r = (await cloud("GET", `/v1/access-requests/${requestId}`, { token })).body;
+ return r.status === "approved" ? r : undefined;
+ });
+ const ch2 = await phone2.relay(CLOUD, computerId, ref.unb64url(listed.signKey));
+ check((await ch2.call("hello", {})).computerId === computerId, "phone 2 connected through the relay");
+
+ const started = Date.now();
+ await cloud("DELETE", `/v1/computers/${computerId}/grants/${approved.grantId}`, { token });
+ const code = await ch2.wire.closed(5000);
+ check(code === 4003 && Date.now() - started < 1000, `revoked socket closed with 4003 within 1 s (${Date.now() - started} ms)`);
+ check(await refused(phone2.relayWire(CLOUD, computerId)), "phone 2 can't reconnect");
+ await stop(host!);
+ await startHost();
+ await waitFor("host back online", () => computerOnline(computerId), 20_000);
+ check(await refused(phone2.relayWire(CLOUD, computerId)), "still refused after the host reconnects");
+
+ step("6b. a grant injected into D1 is ignored by the host");
+ const phone3 = new FakePhone();
+ await cloud("POST", "/v1/devices", { token, key: phone3.key, body: { name: "Intruder", platform: "ios" } });
+ const r3 = await cloud("POST", `/v1/computers/${computerId}/access-requests`, { token, key: phone3.key, body: { commit: ref.b64url(ref.random(32)) } });
+ const dev3 = d1(`SELECT id FROM devices WHERE sign_pub = '${phone3.dk}'`)[0].id;
+ d1(`INSERT INTO grants(id, computer_id, device_id, scopes, status, created_at) VALUES ('grt_injected', '${computerId}', '${dev3}', '["control","screen"]', 'active', ${Date.now()})`);
+ await cloud("DELETE", `/v1/access-requests/${r3.body.requestId}`, { token }); // → cloud.changed → state pull
+ await new Promise((r) => setTimeout(r, 2000));
+ const devices = (await loopback("devices")).devices as Json[];
+ check(!devices.some((d) => d.key === phone3.dk), "host's device table doesn't contain the injected key");
+ check(await refused(phone3.relayWire(CLOUD, computerId)), "the injected key can't open a relay socket (not in the ACL)");
+
+ step("7. direct /channel and loopback-only bearer token");
+ const direct = await phone.direct(`http://127.0.0.1:${hostPort}`, pairing.signKey);
+ check((await direct.call("hello", {})).computerId === computerId, "direct handshake and hello");
+ const lan = Object.values(networkInterfaces())
+ .flat()
+ .find((i) => i && i.family === "IPv4" && !i.internal)?.address;
+ if (lan) {
+ const token = readFileSync(join(home, "token"), "utf8").trim();
+ const res = await fetch(`http://${lan}:${hostPort}/api/hello`, { method: "POST", headers: { Authorization: `Bearer ${token}` }, body: "{}" });
+ check(res.status === 401, `bearer token from ${lan} → 401`);
+ } else {
+ console.log(" (skipped: no non-loopback IPv4 interface)");
+ }
+
+ console.log("\nE2E passed");
+}
+
+async function cleanup() {
+ await Promise.all(children.map(stop));
+ rmSync(tmp, { recursive: true, force: true });
+}
+
+try {
+ if (spawnSync(HOST_BIN, ["--version"]).error) {
+ throw new Error(`codync-host not found at ${HOST_BIN}; run \`cargo build\` in host/ or set CODYNC_HOST_BIN`);
+ }
+ await main();
+ await cleanup();
+} catch (e) {
+ console.error(`\nE2E failed: ${e instanceof Error ? e.stack : e}`);
+ await cleanup();
+ process.exit(1);
+}
diff --git a/cloud/test/e2e/tsconfig.json b/cloud/test/e2e/tsconfig.json
new file mode 100644
index 00000000..a5ee829f
--- /dev/null
+++ b/cloud/test/e2e/tsconfig.json
@@ -0,0 +1,16 @@
+{
+ "compilerOptions": {
+ "target": "ESNext",
+ "module": "NodeNext",
+ "moduleResolution": "NodeNext",
+ "lib": ["ESNext", "DOM"],
+ "types": ["node"],
+ "strict": true,
+ "allowImportingTsExtensions": true,
+ "resolveJsonModule": true,
+ "noEmit": true,
+ "erasableSyntaxOnly": true,
+ "skipLibCheck": true
+ },
+ "include": ["*.ts", "../ref.ts", "../../vitest.config.ts"]
+}
diff --git a/cloud/test/helpers.ts b/cloud/test/helpers.ts
new file mode 100644
index 00000000..c3d64319
--- /dev/null
+++ b/cloud/test/helpers.ts
@@ -0,0 +1,216 @@
+// Shared test plumbing: Clerk tokens, signed requests, WebSocket wrappers, a registered host.
+
+import { SELF, type D1Migration } from "cloudflare:test";
+import { env as rawEnv } from "cloudflare:workers";
+import type { Env } from "../src/index";
+import { aclMessage, b64url, boxKey, computerId, enc, signKey, signRequest, type AclBody, type BoxKey, type SignKey } from "./ref";
+
+export interface TestEnv extends Env {
+ TEST_MIGRATIONS: D1Migration[];
+ TEST_CLERK_PRIVATE_JWK: string;
+}
+
+export const env = rawEnv as unknown as TestEnv;
+export const AUTHORITY = "cloud.test";
+export const ORIGIN = `https://${AUTHORITY}`;
+
+// ---- Clerk ----
+
+let clerkKey: Promise<CryptoKey> | undefined;
+
+export async function clerkToken(
+ sub: string,
+ claims: Record<string, unknown> = {},
+): Promise<string> {
+ clerkKey ??= crypto.subtle.importKey(
+ "jwk",
+ JSON.parse(env.TEST_CLERK_PRIVATE_JWK),
+ { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" },
+ false,
+ ["sign"],
+ );
+ const now = Math.floor(Date.now() / 1000);
+ const part = (v: unknown) => b64url(enc.encode(JSON.stringify(v)));
+ const head = `${part({ alg: "RS256", typ: "JWT", kid: "ins_test" })}.${part({
+ iss: env.CLERK_ISSUER,
+ sub,
+ sid: `sess_${sub}`,
+ iat: now - 5,
+ nbf: now - 5,
+ exp: now + 300,
+ email: `${sub}@example.com`,
+ ...claims,
+ })}`;
+ const sig = await crypto.subtle.sign("RSASSA-PKCS1-v1_5", await clerkKey, enc.encode(head));
+ return `${head}.${b64url(new Uint8Array(sig))}`;
+}
+
+// ---- HTTP ----
+
+export interface CallOptions {
+ token?: string;
+ key?: SignKey;
+ body?: unknown;
+ authority?: string;
+ ts?: number;
+ nonce?: string;
+ headers?: Record<string, string>;
+}
+
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+export type Json = any;
+
+export async function call(method: string, path: string, o: CallOptions = {}): Promise<{ status: number; body: Json }> {
+ const bytes = o.body === undefined ? new Uint8Array() : enc.encode(JSON.stringify(o.body));
+ // A fresh client IP per call so the per-IP registration limit only bites where a test means it to.
+ const headers: Record<string, string> = { "CF-Connecting-IP": `10.0.${Math.floor(Math.random() * 255)}.${Math.floor(Math.random() * 255)}`, ...o.headers };
+ if (o.token) headers.Authorization = `Bearer ${o.token}`;
+ if (o.body !== undefined) headers["Content-Type"] = "application/json";
+ if (o.key) {
+ headers["Codync-Sig"] = signRequest(o.key, {
+ method,
+ authority: o.authority ?? AUTHORITY,
+ pathAndQuery: path,
+ body: bytes,
+ ts: o.ts,
+ nonce: o.nonce,
+ });
+ }
+ const res = await SELF.fetch(ORIGIN + path, { method, headers, body: bytes.length ? bytes : undefined });
+ return { status: res.status, body: await res.json() };
+}
+
+// ---- WebSockets ----
+
+/** A client socket with a message queue, so tests can await specific messages. */
+export class Sock {
+ readonly msgs: Json[] = [];
+ close?: { code: number; reason: string };
+ private wake: (() => void)[] = [];
+
+ constructor(readonly ws: WebSocket) {
+ ws.accept();
+ ws.addEventListener("message", (e) => {
+ this.msgs.push(JSON.parse(e.data as string));
+ this.notify();
+ });
+ ws.addEventListener("close", (e) => {
+ this.close = { code: e.code, reason: e.reason };
+ this.notify();
+ });
+ }
+
+ private notify() {
+ for (const w of this.wake.splice(0)) w();
+ }
+
+ private async until<T>(check: () => T | undefined, ms: number, what: string): Promise<T> {
+ const deadline = Date.now() + ms;
+ for (;;) {
+ const v = check();
+ if (v !== undefined) return v;
+ const left = deadline - Date.now();
+ if (left <= 0) throw new Error(`timed out waiting for ${what}; got ${JSON.stringify(this.msgs)} close=${JSON.stringify(this.close)}`);
+ await new Promise<void>((resolve) => {
+ const t = setTimeout(resolve, left);
+ this.wake.push(() => {
+ clearTimeout(t);
+ resolve();
+ });
+ });
+ }
+ }
+
+ /** Removes and returns the first queued message matching `pred`. */
+ next(pred: (m: Json) => boolean = () => true, ms = 3000): Promise<Json> {
+ return this.until(
+ () => {
+ const i = this.msgs.findIndex(pred);
+ return i < 0 ? undefined : this.msgs.splice(i, 1)[0];
+ },
+ ms,
+ "a message",
+ );
+ }
+
+ nextT(t: string, ms = 3000): Promise<Json> {
+ return this.next((m) => m.t === t, ms);
+ }
+
+ closed(ms = 3000): Promise<number> {
+ return this.until(() => this.close?.code, ms, "close");
+ }
+
+ /** Asserts nothing matching `pred` arrives within `ms`. */
+ async none(pred: (m: Json) => boolean, ms = 200): Promise<void> {
+ await new Promise((r) => setTimeout(r, ms));
+ const hit = this.msgs.find(pred);
+ if (hit) throw new Error(`unexpected message ${JSON.stringify(hit)}`);
+ }
+
+ send(m: unknown) {
+ this.ws.send(typeof m === "string" ? m : JSON.stringify(m));
+ }
+}
+
+export async function upgrade(
+ path: string,
+ key: SignKey,
+ o: { authority?: string; nonce?: string } = {},
+): Promise<{ status: number; sock?: Sock; body?: Json }> {
+ const res = await SELF.fetch(ORIGIN + path, {
+ headers: {
+ Upgrade: "websocket",
+ "Codync-Sig": signRequest(key, { method: "GET", authority: o.authority ?? AUTHORITY, pathAndQuery: path, nonce: o.nonce }),
+ },
+ });
+ if (res.status !== 101) return { status: res.status, body: await res.json() };
+ return { status: 101, sock: new Sock(res.webSocket!) };
+}
+
+export async function socket(path: string, key: SignKey): Promise<Sock> {
+ const r = await upgrade(path, key);
+ if (!r.sock) throw new Error(`upgrade ${path} failed: ${r.status} ${JSON.stringify(r.body)}`);
+ return r.sock;
+}
+
+// ---- a host ----
+
+export interface TestHost {
+ sign: SignKey;
+ box: BoxKey;
+ cid: string;
+ ver: number;
+}
+
+export async function newHost(sign = signKey(), box = boxKey()): Promise<TestHost> {
+ const r = await call("POST", "/v1/host/register", {
+ key: sign,
+ body: { boxKey: b64url(box.pub), name: "Mac", platform: "macos", device: "laptop", version: "3.0.0" },
+ });
+ if (r.status !== 200) throw new Error(`register failed: ${JSON.stringify(r.body)}`);
+ return { sign, box, cid: computerId(sign.pub), ver: 0 };
+}
+
+export function acl(host: TestHost, devices: AclBody["devices"] = [], offers: AclBody["offers"] = []) {
+ host.ver += 1;
+ return aclMessage(host.sign, { v: 1, computerId: host.cid, ver: host.ver, devices, offers });
+}
+
+/** Connects the host, publishes an ACL and (unless `ready: false`) marks it ready. */
+export async function hostSocket(
+ host: TestHost,
+ devices: AclBody["devices"] = [],
+ o: { offers?: AclBody["offers"]; ready?: boolean } = {},
+): Promise<Sock> {
+ const sock = await socket("/v1/relay/host?v=1", host.sign);
+ sock.send(acl(host, devices, o.offers));
+ await sock.nextT("acl.ok");
+ if (o.ready !== false) sock.send({ t: "ready" });
+ return sock;
+}
+
+export const devicePath = (host: TestHost, pair?: string) =>
+ `/v1/relay/device/${host.cid}?v=1${pair ? `&pair=${pair}` : ""}`;
+
+export const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
diff --git a/cloud/test/ref.ts b/cloud/test/ref.ts
new file mode 100644
index 00000000..47ba7638
--- /dev/null
+++ b/cloud/test/ref.ts
@@ -0,0 +1,284 @@
+// Reference device/host crypto for the Codync relay protocol (spec §4–§7), built on @noble/*.
+// Test-only: checked against docs/remote-relay-vectors.json, then used by the unit tests and the e2e harness.
+// Runs in both workerd (vitest) and Node (e2e).
+
+import { chacha20poly1305 } from "@noble/ciphers/chacha.js";
+import { ed25519, x25519 } from "@noble/curves/ed25519.js";
+import { expand, extract } from "@noble/hashes/hkdf.js";
+import { sha256 } from "@noble/hashes/sha2.js";
+
+// ---- encoding ----
+
+export const enc = new TextEncoder();
+export const dec = new TextDecoder();
+
+export function b64url(bytes: Uint8Array): string {
+ let s = "";
+ for (let i = 0; i < bytes.length; i += 0x8000) s += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
+ return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
+}
+
+export function unb64url(s: string): Uint8Array {
+ return Uint8Array.from(atob(s.replace(/-/g, "+").replace(/_/g, "/")), (c) => c.charCodeAt(0));
+}
+
+export function concat(...parts: Uint8Array[]): Uint8Array {
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
+ let at = 0;
+ for (const p of parts) {
+ out.set(p, at);
+ at += p.length;
+ }
+ return out;
+}
+
+export const random = (n: number) => crypto.getRandomValues(new Uint8Array(n));
+
+const u64be = (c: number) => {
+ const out = new Uint8Array(8);
+ new DataView(out.buffer).setBigUint64(0, BigInt(c));
+ return out;
+};
+
+function dh(priv: Uint8Array, pub: Uint8Array): Uint8Array {
+ const ss = x25519.getSharedSecret(priv, pub);
+ if (ss.every((b) => b === 0)) throw new Error("all-zero shared secret");
+ return ss;
+}
+
+// ---- identity ----
+
+export const cidRaw = (hostSignPub: Uint8Array) => sha256(hostSignPub).subarray(0, 16);
+export const computerId = (hostSignPub: Uint8Array) => b64url(cidRaw(hostSignPub));
+
+export interface SignKey {
+ seed: Uint8Array;
+ pub: Uint8Array;
+}
+
+export function signKey(seed: Uint8Array = random(32)): SignKey {
+ return { seed, pub: ed25519.getPublicKey(seed) };
+}
+
+export const sign = (key: SignKey, msg: Uint8Array) => ed25519.sign(msg, key.seed);
+export const verify = (pub: Uint8Array, sig: Uint8Array, msg: Uint8Array) => ed25519.verify(sig, msg, pub);
+
+export interface BoxKey {
+ priv: Uint8Array;
+ pub: Uint8Array;
+}
+
+export function boxKey(priv: Uint8Array = random(32)): BoxKey {
+ return { priv, pub: x25519.getPublicKey(priv) };
+}
+
+// ---- Codync-Sig (§5) ----
+
+export function sigCanonical(method: string, authority: string, pathAndQuery: string, ts: number, nonce: string, body: Uint8Array) {
+ return ["codync-sig-v1", method.toUpperCase(), authority.toLowerCase(), pathAndQuery, String(ts), nonce, b64url(sha256(body))].join("\n");
+}
+
+/** The `Codync-Sig` header value. */
+export function signRequest(
+ key: SignKey,
+ req: { method: string; authority: string; pathAndQuery: string; body?: Uint8Array; ts?: number; nonce?: string },
+): string {
+ const ts = req.ts ?? Date.now();
+ const nonce = req.nonce ?? b64url(random(16));
+ const canonical = sigCanonical(req.method, req.authority, req.pathAndQuery, ts, nonce, req.body ?? new Uint8Array());
+ return `v=1,kid=${b64url(key.pub)},ts=${ts},nonce=${nonce},sig=${b64url(sign(key, enc.encode(canonical)))}`;
+}
+
+// ---- handshake (§6.2) ----
+
+export const hs1Input = (cid: Uint8Array, dk: Uint8Array, ekD: Uint8Array, n: Uint8Array) =>
+ concat(enc.encode("codync/hs1/v1"), cid, dk, ekD, n);
+
+export const transcriptHash = (cid: Uint8Array, dk: Uint8Array, ekD: Uint8Array, n: Uint8Array, ekH: Uint8Array) =>
+ sha256(concat(enc.encode("codync/hs2/v1"), cid, dk, ekD, n, ekH));
+
+export interface ChannelKeys {
+ d2h: Uint8Array;
+ h2d: Uint8Array;
+}
+
+export function channelKeys(ekPriv: Uint8Array, peerEk: Uint8Array, th: Uint8Array): ChannelKeys & { ss: Uint8Array; prk: Uint8Array } {
+ const ss = dh(ekPriv, peerEk);
+ const prk = extract(sha256, ss, th);
+ return {
+ ss,
+ prk,
+ d2h: expand(sha256, prk, enc.encode("codync/d2h/v1"), 32),
+ h2d: expand(sha256, prk, enc.encode("codync/h2d/v1"), 32),
+ };
+}
+
+/** Device side: builds `hello`, then `finish(welcome)` verifies the host and derives the keys. */
+export function deviceHello(device: SignKey, hostSignPub: Uint8Array, opts: { pair?: boolean; eph?: BoxKey; n?: Uint8Array } = {}) {
+ const eph = opts.eph ?? boxKey();
+ const n = opts.n ?? random(32);
+ const cid = cidRaw(hostSignPub);
+ const hello: Record<string, unknown> = {
+ t: "hello",
+ v: 1,
+ dk: b64url(device.pub),
+ ek: b64url(eph.pub),
+ n: b64url(n),
+ sig: b64url(sign(device, hs1Input(cid, device.pub, eph.pub, n))),
+ };
+ if (opts.pair) hello.pair = true;
+ return {
+ hello,
+ finish(welcome: { ek: string; sig: string }): ChannelKeys {
+ const ekH = unb64url(welcome.ek);
+ const th = transcriptHash(cid, device.pub, eph.pub, n, ekH);
+ if (!verify(hostSignPub, unb64url(welcome.sig), th)) throw new Error("welcome signature doesn't verify");
+ return channelKeys(eph.priv, ekH, th);
+ },
+ };
+}
+
+/** Host side (for tests that play the host): verifies `hello` and answers `welcome`. */
+export function hostWelcome(host: SignKey, hello: { dk: string; ek: string; n: string; sig: string }, eph = boxKey()) {
+ const cid = cidRaw(host.pub);
+ const dk = unb64url(hello.dk);
+ const ekD = unb64url(hello.ek);
+ const n = unb64url(hello.n);
+ if (!verify(dk, unb64url(hello.sig), hs1Input(cid, dk, ekD, n))) throw new Error("hello signature doesn't verify");
+ const th = transcriptHash(cid, dk, ekD, n, eph.pub);
+ return {
+ welcome: { t: "welcome", v: 1, ek: b64url(eph.pub), sig: b64url(sign(host, th)) },
+ keys: channelKeys(eph.priv, ekD, th),
+ };
+}
+
+// ---- frames (§6.3) ----
+
+export const CHUNK = 256 * 1024;
+
+const frameNonce = (c: number) => concat(new Uint8Array(4), u64be(c));
+const frameAad = (c: number) => concat(enc.encode("codync/frame/v1"), u64be(c));
+
+export function sealFrame(key: Uint8Array, c: number, final: boolean, chunk: Uint8Array): string {
+ const plaintext = concat(new Uint8Array([final ? 0 : 1]), chunk);
+ return b64url(chacha20poly1305(key, frameNonce(c), frameAad(c)).encrypt(plaintext));
+}
+
+export function openFrame(key: Uint8Array, c: number, d: string): { final: boolean; chunk: Uint8Array } {
+ const pt = chacha20poly1305(key, frameNonce(c), frameAad(c)).decrypt(unb64url(d));
+ if (pt[0] !== 0 && pt[0] !== 1) throw new Error("bad frame flag");
+ return { final: pt[0] === 0, chunk: pt.subarray(1) };
+}
+
+/** One direction of a channel: counters, chunking and reassembly. */
+export class FrameCodec {
+ private sendC = 0;
+ private recvC = 0;
+ private parts: Uint8Array[] = [];
+ private readonly sendKey: Uint8Array;
+ private readonly recvKey: Uint8Array;
+ private readonly maxMessage: number;
+ constructor(sendKey: Uint8Array, recvKey: Uint8Array, maxMessage = 16 * 1024 * 1024) {
+ this.sendKey = sendKey;
+ this.recvKey = recvKey;
+ this.maxMessage = maxMessage;
+ }
+
+ seal(message: unknown): { t: "f"; c: number; d: string }[] {
+ const bytes = enc.encode(JSON.stringify(message));
+ const out: { t: "f"; c: number; d: string }[] = [];
+ for (let at = 0; at === 0 || at < bytes.length; at += CHUNK) {
+ const chunk = bytes.subarray(at, at + CHUNK);
+ const final = at + CHUNK >= bytes.length;
+ out.push({ t: "f", c: this.sendC, d: sealFrame(this.sendKey, this.sendC, final, chunk) });
+ this.sendC += 1;
+ }
+ return out;
+ }
+
+ /** Returns the parsed message once its last chunk arrives; throws on a counter gap or bad tag. */
+ open(frame: { c: number; d: string }): unknown | undefined {
+ if (frame.c !== this.recvC) throw new Error(`frame counter ${frame.c}, expected ${this.recvC}`);
+ const { final, chunk } = openFrame(this.recvKey, frame.c, frame.d);
+ this.recvC += 1;
+ this.parts.push(chunk);
+ if (this.parts.reduce((n, p) => n + p.length, 0) > this.maxMessage) throw new Error("message too large");
+ if (!final) return undefined;
+ const msg = JSON.parse(dec.decode(concat(...this.parts)));
+ this.parts = [];
+ return msg;
+ }
+}
+
+// ---- mailbox (§6.4) ----
+
+export function mailboxKey(ss: Uint8Array, cid: Uint8Array, dk: Uint8Array, epk: Uint8Array) {
+ const prk = extract(sha256, ss, concat(enc.encode("codync/mbox/v1"), cid, dk, epk));
+ return expand(sha256, prk, enc.encode("codync/mbox-key/v1"), 32);
+}
+
+/** Seals one mailbox item. A fresh ephemeral key every call (MUST): the AEAD nonce is fixed. */
+export function sealMailbox(device: SignKey, hostSignPub: Uint8Array, hostBoxPub: Uint8Array, clientNonce: string, inner: string, eph = boxKey()): Uint8Array {
+ const cid = cidRaw(hostSignPub);
+ const key = mailboxKey(dh(eph.priv, hostBoxPub), cid, device.pub, eph.pub);
+ const ct = chacha20poly1305(key, new Uint8Array(12), concat(device.pub, enc.encode(clientNonce))).encrypt(enc.encode(inner));
+ const sig = sign(device, concat(enc.encode("codync/mbox/v1"), cid, eph.pub, ct));
+ return concat(eph.pub, sig, ct);
+}
+
+export function openMailbox(hostSignPub: Uint8Array, hostBox: BoxKey, dk: Uint8Array, clientNonce: string, blob: Uint8Array): string {
+ const cid = cidRaw(hostSignPub);
+ const epk = blob.subarray(0, 32);
+ const sig = blob.subarray(32, 96);
+ const ct = blob.subarray(96);
+ if (!verify(dk, sig, concat(enc.encode("codync/mbox/v1"), cid, epk, ct))) throw new Error("mailbox signature doesn't verify");
+ const key = mailboxKey(dh(hostBox.priv, epk), cid, dk, epk);
+ return dec.decode(chacha20poly1305(key, new Uint8Array(12), concat(dk, enc.encode(clientNonce))).decrypt(ct));
+}
+
+// ---- SAS, pairing offer, claim, ACL, push ----
+
+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");
+}
+
+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) =>
+ ["codync/claim/v1", claimId, nonce, userId, computerId, boxKey].join("\n");
+
+export interface AclBody {
+ v: 1;
+ computerId: string;
+ ver: number;
+ devices: { dk: string; grant: string | null }[];
+ offers: { id: string; exp: number }[];
+}
+
+/** The host's `acl` message: signs the exact JSON bytes it sends. */
+export function aclMessage(host: SignKey, acl: AclBody | string) {
+ const bytes = enc.encode(typeof acl === "string" ? acl : JSON.stringify(acl));
+ return { t: "acl", d: b64url(bytes), sig: b64url(sign(host, bytes)) };
+}
+
+export function pushKey(ss: Uint8Array, cid: Uint8Array, pushPub: Uint8Array, epk: Uint8Array) {
+ const prk = extract(sha256, ss, concat(enc.encode("codync/push/v1"), cid, pushPub, epk));
+ return expand(sha256, prk, enc.encode("codync/push-key/v1"), 32);
+}
+
+export function sealPush(hostSignPub: Uint8Array, pushPub: Uint8Array, plaintext: string, eph = boxKey()): string {
+ const cid = cidRaw(hostSignPub);
+ const key = pushKey(dh(eph.priv, pushPub), cid, pushPub, eph.pub);
+ return b64url(concat(eph.pub, chacha20poly1305(key, new Uint8Array(12), cid).encrypt(enc.encode(plaintext))));
+}
+
+export function openPush(hostSignPub: Uint8Array, push: BoxKey, sealed: string): string {
+ const bytes = unb64url(sealed);
+ const cid = cidRaw(hostSignPub);
+ const epk = bytes.subarray(0, 32);
+ const key = pushKey(dh(push.priv, epk), cid, push.pub, epk);
+ return dec.decode(chacha20poly1305(key, new Uint8Array(12), cid).decrypt(bytes.subarray(32)));
+}
diff --git a/cloud/test/relay.test.ts b/cloud/test/relay.test.ts
new file mode 100644
index 00000000..167aad9a
--- /dev/null
+++ b/cloud/test/relay.test.ts
@@ -0,0 +1,353 @@
+// ComputerRelay DO through the Worker: admission, ACL, presence, forwarding, mailbox, limits.
+
+import { runDurableObjectAlarm, runInDurableObject, SELF } from "cloudflare:test";
+import { describe, expect, it } from "vitest";
+import V from "../../docs/remote-relay-vectors.json";
+import type { ComputerRelay } from "../src/relay";
+import { acl, call, devicePath, env, hostSocket, newHost, sleep, socket, upgrade, type TestHost } from "./helpers";
+import * as ref from "./ref";
+
+const stub = (host: TestHost) => env.RELAY.get(env.RELAY.idFromName(host.cid)) as DurableObjectStub<ComputerRelay>;
+const dkOf = (k: ref.SignKey) => ref.b64url(k.pub);
+const blob = (host: TestHost, device: ref.SignKey, nonce: string) =>
+ ref.b64url(
+ ref.sealMailbox(device, host.sign.pub, host.box.pub, nonce, JSON.stringify({ m: "send", b: { botId: "b1", text: "hi", clientNonce: nonce }, ts: Date.now() })),
+ );
+
+/** A host with one authorized (local) device, both connected; the host is ready unless told otherwise. */
+async function pair(o: { ready?: boolean } = {}) {
+ const host = await newHost();
+ const device = ref.signKey();
+ const hostWs = await hostSocket(host, [{ dk: dkOf(device), grant: null }], o);
+ const dev = await socket(devicePath(host), device);
+ return { host, device, hostWs, dev };
+}
+
+describe("routing", () => {
+ it("validates version and computerId before touching a DO", async () => {
+ const key = ref.signKey();
+ const host = await newHost();
+ expect((await upgrade(`/v1/relay/device/${host.cid}?v=2`, key)).status).toBe(426);
+ expect((await upgrade(`/v1/relay/device/${host.cid}`, key)).body.error.code).toBe("upgradeRequired");
+ expect((await upgrade("/v1/relay/device/short?v=1", key)).status).toBe(400);
+ expect((await upgrade(`/v1/relay/device/${host.cid}!?v=1`, key)).status).toBe(400);
+ expect((await upgrade(`/v1/relay/device/${host.cid}?v=1&pair=nope`, key)).status).toBe(400);
+ });
+
+ it("keeps /internal/* unreachable from outside", async () => {
+ for (const path of ["/internal/block", "/v1/relay/internal/block", "/v1/relay/device/%2Finternal%2Fblock?v=1", "/relay"]) {
+ const res = await SELF.fetch(`https://cloud.test${path}`, { method: "POST", headers: { "X-Codync-Internal": "1" }, body: "{}" });
+ expect(res.status, path).not.toBe(200);
+ }
+ const host = await newHost();
+ // The DO itself refuses anything without the Worker's internal header.
+ const res = await stub(host).fetch("https://do/internal/block", { method: "POST", body: JSON.stringify({ devices: [] }) });
+ expect(res.status).toBe(404);
+ expect((await stub(host).fetch("https://do/other", { headers: { "X-Codync-Internal": "1" } })).status).toBe(404);
+ });
+
+ it("requires registration for the host and a known computer for devices", async () => {
+ const stranger = ref.signKey();
+ const r = await upgrade("/v1/relay/host?v=1", stranger);
+ expect(r.status).toBe(404);
+ expect((await upgrade(`/v1/relay/device/${ref.computerId(stranger.pub)}?v=1`, ref.signKey())).status).toBe(404);
+ // Registered but never connected: no ACL yet.
+ const host = await newHost();
+ const d = await upgrade(devicePath(host), ref.signKey());
+ expect(d.status).toBe(404);
+ expect(d.body.error.code).toBe("unknownComputer");
+ });
+
+ it("rejects a replayed upgrade signature", async () => {
+ const host = await newHost();
+ const nonce = ref.b64url(ref.random(16));
+ const first = await upgrade("/v1/relay/host?v=1", host.sign, { nonce });
+ expect(first.status).toBe(101);
+ expect((await upgrade("/v1/relay/host?v=1", host.sign, { nonce })).status).toBe(401);
+ expect((await upgrade("/v1/relay/host?v=1", host.sign, { authority: "other.example" })).status).toBe(401);
+ });
+});
+
+describe("ACL", () => {
+ it("accepts the vector ACL and enforces monotonic versions", async () => {
+ const host = await newHost(ref.signKey(ref.unb64url(V.keys.hostSignSeed)), ref.boxKey(ref.unb64url(V.keys.hostBoxPriv)));
+ expect(host.cid).toBe(V.keys.computerId);
+ const ws = await socket("/v1/relay/host?v=1", host.sign);
+ ws.send({ t: "acl", d: V.acl.d, sig: V.acl.sig });
+ expect(await ws.nextT("acl.ok")).toEqual({ t: "acl.ok", ver: 1 });
+ ws.send({ t: "acl", d: V.acl.d, sig: V.acl.sig });
+ expect(await ws.next()).toEqual({ t: "error", code: "staleVersion", ver: 1 });
+ ws.send({ t: "acl", d: V.acl.d, sig: ref.b64url(ref.random(64)) });
+ expect(await ws.next()).toEqual({ t: "error", code: "badAcl", ver: 1 });
+ // Signed by the host but for another computer.
+ ws.send(ref.aclMessage(host.sign, { v: 1, computerId: "A".repeat(22), ver: 5, devices: [], offers: [] }));
+ expect(await ws.next()).toEqual({ t: "error", code: "badAcl", ver: 1 });
+ // Signed by someone else.
+ ws.send(ref.aclMessage(ref.signKey(), { v: 1, computerId: host.cid, ver: 5, devices: [], offers: [] }));
+ expect(await ws.next()).toEqual({ t: "error", code: "badAcl", ver: 1 });
+ // The vector's device (local, grant null) is admitted; its offer is expired (exp in the past).
+ expect((await upgrade(devicePath(host), ref.signKey(ref.unb64url(V.keys.deviceSignSeed)))).status).toBe(101);
+ expect((await upgrade(devicePath(host, V.pairing.offerId), ref.signKey())).status).toBe(403);
+ });
+
+ it("closes sockets the new ACL drops", async () => {
+ const { host, device, hostWs, dev } = await pair();
+ await dev.nextT("presence");
+ hostWs.send(acl(host, []));
+ await hostWs.nextT("acl.ok");
+ expect(await dev.closed()).toBe(4003);
+ expect((await upgrade(devicePath(host), device)).status).toBe(403);
+ });
+});
+
+describe("admission", () => {
+ it("admits only devices in the ACL", async () => {
+ const { host } = await pair();
+ expect((await upgrade(devicePath(host), ref.signKey())).status).toBe(403);
+ });
+
+ it("limits pairing sockets: live offer, two at a time, 16 messages, no mailbox, closed when the offer goes", async () => {
+ const host = await newHost();
+ const offer = ref.offerId(ref.random(16));
+ const hostWs = await hostSocket(host, [], { offers: [{ id: offer, exp: Date.now() + 600_000 }] });
+ expect((await upgrade(devicePath(host, ref.offerId(ref.random(16))), ref.signKey())).status).toBe(403);
+ const a = await socket(devicePath(host, offer), ref.signKey());
+ const b = await socket(devicePath(host, offer), ref.signKey());
+ expect((await upgrade(devicePath(host, offer), ref.signKey())).status).toBe(429);
+ const open = await hostWs.nextT("open");
+ expect(open.pair).toBe(true);
+
+ a.send({ t: "mbox.put", nonce: "n", d: "AAAA" });
+ expect(await a.nextT("mbox.err")).toEqual({ t: "mbox.err", nonce: "n", code: "pairing" });
+ for (let i = 0; i < 16; i++) a.send({ t: "mbox.list" });
+ expect(await a.closed()).toBe(4008);
+
+ hostWs.send(acl(host, [], []));
+ await hostWs.nextT("acl.ok");
+ expect(await b.closed()).toBe(4410);
+ });
+
+ it("caps device sockets per computer at 16", async () => {
+ const host = await newHost();
+ const keys = Array.from({ length: 17 }, () => ref.signKey());
+ await hostSocket(host, keys.map((k) => ({ dk: dkOf(k), grant: null })));
+ for (const k of keys.slice(0, 16)) expect((await upgrade(devicePath(host), k)).status).toBe(101);
+ expect((await upgrade(devicePath(host), keys[16]!)).status).toBe(429);
+ });
+});
+
+describe("presence and forwarding", () => {
+ it("before ready: devices see offline, channel messages are dropped, mailbox is open", async () => {
+ const { host, device, hostWs, dev } = await pair({ ready: false });
+ expect(await dev.nextT("presence")).toMatchObject({ online: false });
+ dev.send({ t: "hello", v: 1 });
+ expect(await dev.nextT("presence")).toMatchObject({ online: false });
+ await hostWs.none((m) => m.t === "data" || m.t === "open");
+ dev.send({ t: "mbox.put", nonce: "n1", d: blob(host, device, "n1") });
+ expect(await dev.nextT("mbox.ok")).toEqual({ t: "mbox.ok", nonce: "n1", state: "queued" });
+
+ hostWs.send({ t: "ready" });
+ expect(await dev.nextT("presence")).toMatchObject({ online: true });
+ const open = await hostWs.nextT("open");
+ expect(open).toMatchObject({ dk: dkOf(device), pair: false });
+ expect(await hostWs.nextT("mbox.item")).toMatchObject({ from: dkOf(device), nonce: "n1" });
+ // After ready a new device socket is announced at once.
+ const late = await socket(devicePath(host), device);
+ expect(await late.nextT("presence")).toMatchObject({ online: true });
+ expect(await hostWs.nextT("open")).toMatchObject({ dk: dkOf(device) });
+ // And the mailbox is closed while the host is online.
+ late.send({ t: "mbox.put", nonce: "n2", d: blob(host, device, "n2") });
+ expect(await late.nextT("mbox.err")).toMatchObject({ code: "hostOnline" });
+ const row = await env.DB.prepare("SELECT online, last_seen_at FROM computers WHERE id = ?").bind(host.cid).first<{ online: number }>();
+ expect(row?.online).toBe(1);
+ });
+
+ it("carries a full E2E handshake and frames without reading them", async () => {
+ const { host, device, hostWs, dev } = await pair();
+ const { link } = await hostWs.nextT("open");
+ await dev.nextT("presence");
+ const d = ref.deviceHello(device, host.sign.pub);
+ dev.send(d.hello);
+ const data = await hostWs.nextT("data");
+ expect(data.link).toBe(link);
+ expect(data.m).toEqual(d.hello);
+ const h = ref.hostWelcome(host.sign, data.m);
+ hostWs.send({ t: "data", link, m: h.welcome });
+ const keys = d.finish(await dev.nextT("welcome"));
+ const phone = new ref.FrameCodec(keys.d2h, keys.h2d);
+ const computer = new ref.FrameCodec(h.keys.h2d, h.keys.d2h);
+ for (const f of phone.seal({ id: 1, m: "hello", b: {} })) dev.send(f);
+ expect(computer.open((await hostWs.nextT("data")).m)).toEqual({ id: 1, m: "hello", b: {} });
+ for (const f of computer.seal({ id: 1, ok: { name: "Mac" } })) hostWs.send({ t: "data", link, m: f });
+ expect(phone.open(await dev.nextT("f"))).toEqual({ id: 1, ok: { name: "Mac" } });
+
+ // The host closes a link with a code the device sees (4100 after pairing).
+ hostWs.send({ t: "close", link, code: 4100, reason: "paired" });
+ expect(await dev.closed()).toBe(4100);
+ expect(await hostWs.nextT("close")).toEqual({ t: "close", link });
+ });
+
+ it("answers the exact ping string by auto-response", async () => {
+ const { hostWs, dev } = await pair();
+ dev.send('{"t":"ping"}');
+ expect(await dev.nextT("pong")).toEqual({ t: "pong" });
+ hostWs.send('{"t":"ping"}');
+ expect(await hostWs.nextT("pong")).toEqual({ t: "pong" });
+ });
+
+ it("a new host socket replaces the old: 4009, then offline → online", async () => {
+ const { host, device, hostWs, dev } = await pair();
+ expect(await dev.nextT("presence")).toMatchObject({ online: true });
+ const next = await socket("/v1/relay/host?v=1", host.sign);
+ expect(await hostWs.closed()).toBe(4009);
+ expect(await dev.nextT("presence")).toMatchObject({ online: false });
+ next.send(acl(host, [{ dk: dkOf(device), grant: null }]));
+ await next.nextT("acl.ok");
+ next.send({ t: "ready" });
+ expect(await dev.nextT("presence")).toMatchObject({ online: true });
+ expect(await next.nextT("open")).toBeTruthy();
+ });
+
+ it("marks the host offline when its socket closes or goes silent", async () => {
+ const { host, hostWs, dev } = await pair();
+ await dev.nextT("presence");
+ hostWs.ws.close(1000, "bye");
+ const off = await dev.nextT("presence");
+ expect(off.online).toBe(false);
+ expect(typeof off.lastSeenAt).toBe("number");
+ const row = await env.DB.prepare("SELECT online, last_seen_at FROM computers WHERE id = ?").bind(host.cid).first<{ online: number; last_seen_at: number }>();
+ expect(row?.online).toBe(0);
+ expect(row?.last_seen_at).toBe(off.lastSeenAt);
+
+ const again = await hostSocket(host, [{ dk: dkOf(ref.signKey()), grant: null }]);
+ expect(await dev.closed()).toBe(4003); // not in the new ACL
+ // Silent for > 90 s: the alarm closes it with 1011.
+ await runInDurableObject(stub(host), (_, state) => {
+ for (const ws of state.getWebSockets("host")) ws.serializeAttachment({ ...ws.deserializeAttachment(), at: Date.now() - 91_000 });
+ });
+ await runDurableObjectAlarm(stub(host));
+ expect(await again.closed()).toBe(1011);
+ });
+});
+
+describe("mailbox", () => {
+ it("is idempotent, cancellable, listable and validated", async () => {
+ const { host, device, hostWs, dev } = await pair({ ready: false });
+ await dev.nextT("presence");
+ const put = (nonce: string, extra: object = {}) => dev.send({ t: "mbox.put", nonce, d: blob(host, device, nonce), ...extra });
+ put("a");
+ expect(await dev.nextT("mbox.ok")).toEqual({ t: "mbox.ok", nonce: "a", state: "queued" });
+ put("a");
+ expect(await dev.nextT("mbox.ok")).toEqual({ t: "mbox.ok", nonce: "a", state: "queued" });
+ put("b", { exp: Date.now() + 60_000 });
+ await dev.nextT("mbox.ok");
+ dev.send({ t: "mbox.list" });
+ const list = await dev.nextT("mbox.items");
+ expect(list.items.map((i: { nonce: string; state: string }) => [i.nonce, i.state])).toEqual([["a", "queued"], ["b", "queued"]]);
+
+ dev.send({ t: "mbox.cancel", nonce: "b" });
+ expect(await dev.nextT("mbox.cancelled")).toEqual({ t: "mbox.cancelled", nonce: "b" });
+ dev.send({ t: "mbox.cancel", nonce: "zzz" });
+ expect(await dev.nextT("mbox.gone")).toEqual({ t: "mbox.gone", nonce: "zzz", state: "unknown" });
+
+ put("late", { exp: Date.now() + 25 * 3600_000 });
+ expect(await dev.nextT("mbox.err")).toMatchObject({ nonce: "late", code: "invalid" });
+ dev.send({ t: "mbox.put", nonce: "junk", d: "AAAA" });
+ expect(await dev.nextT("mbox.err")).toMatchObject({ code: "invalid" });
+ dev.send({ t: "mbox.put", nonce: "big", d: ref.b64url(new Uint8Array(64 * 1024 + 1).fill(7)) });
+ expect(await dev.nextT("mbox.err")).toMatchObject({ nonce: "big", code: "tooLarge" });
+
+ // Delivery: one at a time in seq order; a delivering item can't be cancelled.
+ hostWs.send({ t: "ready" });
+ const item = await hostWs.nextT("mbox.item");
+ expect(item).toMatchObject({ from: dkOf(device), nonce: "a" });
+ expect(ref.openMailbox(host.sign.pub, host.box, device.pub, "a", ref.unb64url(item.d))).toContain('"clientNonce":"a"');
+ dev.send({ t: "mbox.cancel", nonce: "a" });
+ expect(await dev.nextT("mbox.gone")).toEqual({ t: "mbox.gone", nonce: "a", state: "delivering" });
+ hostWs.send({ t: "mbox.ack", seq: item.seq, ok: true });
+ expect(await dev.nextT("mbox.delivered")).toEqual({ t: "mbox.delivered", nonce: "a" });
+ });
+
+ it("delivers in order, requeues on host disconnect, and reports failures", async () => {
+ const { host, device, hostWs, dev } = await pair({ ready: false });
+ await dev.nextT("presence");
+ for (const n of ["1", "2", "3"]) {
+ dev.send({ t: "mbox.put", nonce: n, d: blob(host, device, n) });
+ await dev.nextT("mbox.ok");
+ }
+ hostWs.send({ t: "ready" });
+ const first = await hostWs.nextT("mbox.item");
+ expect(first.nonce).toBe("1");
+ await hostWs.none((m) => m.t === "mbox.item");
+ hostWs.send({ t: "mbox.ack", seq: first.seq, ok: false, code: "unknownBot" });
+ expect(await dev.nextT("mbox.failed")).toEqual({ t: "mbox.failed", nonce: "1", code: "unknownBot" });
+ const second = await hostWs.nextT("mbox.item");
+ expect(second.nonce).toBe("2");
+ // Host drops before acking: "2" goes back to the queue and comes again, same seq.
+ hostWs.ws.close(1000);
+ await dev.nextT("presence");
+ const back = await hostSocket(host, [{ dk: dkOf(device), grant: null }]);
+ const again = await back.nextT("mbox.item");
+ expect(again).toMatchObject({ seq: second.seq, nonce: "2" });
+ back.send({ t: "mbox.ack", seq: again.seq, ok: true });
+ expect((await back.nextT("mbox.item")).nonce).toBe("3");
+ });
+
+ it("enforces the per-device limit and expires items", async () => {
+ const { host, device, dev } = await pair({ ready: false });
+ await dev.nextT("presence");
+ const tiny = ref.b64url(ref.random(128));
+ for (let i = 0; i < 50; i++) dev.send({ t: "mbox.put", nonce: `n${i}`, d: tiny });
+ for (let i = 0; i < 50; i++) await dev.nextT("mbox.ok");
+ dev.send({ t: "mbox.put", nonce: "n50", d: tiny });
+ expect(await dev.nextT("mbox.err")).toEqual({ t: "mbox.err", nonce: "n50", code: "full" });
+
+ await runInDurableObject(stub(host), (_, state) => {
+ state.storage.sql.exec("UPDATE mailbox SET exp = ? WHERE nonce = 'n0'", Date.now() - 1);
+ });
+ await runDurableObjectAlarm(stub(host));
+ expect(await dev.nextT("mbox.expired")).toEqual({ t: "mbox.expired", nonce: "n0" });
+ dev.send({ t: "mbox.put", nonce: "n50", d: blob(host, device, "n50") });
+ expect(await dev.nextT("mbox.ok")).toMatchObject({ nonce: "n50" });
+ });
+
+ it("accepts mail for a host that has been offline for hours (the DO ignores leases)", async () => {
+ const host = await newHost();
+ const device = ref.signKey();
+ const hostWs = await hostSocket(host, [{ dk: dkOf(device), grant: "grt_account" }]);
+ hostWs.ws.close(1000);
+ await sleep(50);
+ await runInDurableObject(stub(host), (_, state) => {
+ state.storage.sql.exec("UPDATE meta SET v = ? WHERE k = 'lastSeenAt'", String(Date.now() - 3 * 3600_000));
+ });
+ const dev = await socket(devicePath(host), device);
+ expect(await dev.nextT("presence")).toMatchObject({ online: false });
+ dev.send({ t: "mbox.put", nonce: "later", d: blob(host, device, "later") });
+ expect(await dev.nextT("mbox.ok")).toMatchObject({ state: "queued" });
+ });
+});
+
+describe("rate limits", () => {
+ it("closes a device socket past 200 messages in 10 s", async () => {
+ const { dev } = await pair({ ready: false });
+ for (let i = 0; i < 201; i++) dev.send({ t: "mbox.list" });
+ expect(await dev.closed()).toBe(4008);
+ });
+
+ it("closes on malformed or unknown messages", async () => {
+ const { dev } = await pair();
+ dev.send("not json");
+ expect(await dev.closed()).toBe(4002);
+ });
+});
+
+describe("host health check via the API", () => {
+ it("registration reports ownership", async () => {
+ const key = ref.signKey();
+ const r = await call("POST", "/v1/host/register", {
+ key,
+ body: { boxKey: ref.b64url(ref.boxKey().pub), name: "Mac", platform: "macos", version: "3.0.0" },
+ });
+ expect(r.body).toEqual({ computerId: ref.computerId(key.pub), owned: false });
+ });
+});
diff --git a/cloud/test/setup.ts b/cloud/test/setup.ts
new file mode 100644
index 00000000..2328bb21
--- /dev/null
+++ b/cloud/test/setup.ts
@@ -0,0 +1,5 @@
+import { applyD1Migrations } from "cloudflare:test";
+import { env } from "cloudflare:workers";
+import type { TestEnv } from "./helpers";
+
+await applyD1Migrations((env as unknown as TestEnv).DB, (env as unknown as TestEnv).TEST_MIGRATIONS);
diff --git a/cloud/test/vectors.test.ts b/cloud/test/vectors.test.ts
new file mode 100644
index 00000000..8d9b7af4
--- /dev/null
+++ b/cloud/test/vectors.test.ts
@@ -0,0 +1,218 @@
+// docs/remote-relay-vectors.json, field by field: the TS reference implementation and the Worker's own code.
+
+import { describe, expect, it } from "vitest";
+import V from "../../docs/remote-relay-vectors.json";
+import { claimCanonical as workerClaimCanonical } from "../src/api";
+import { computerIdFor, fromB64url, sigCanonical, verifyEd25519, verifySig } from "../src/auth";
+import { parseAcl } from "../src/relay";
+import * as ref from "./ref";
+
+const u = ref.unb64url;
+const hostSign = ref.signKey(u(V.keys.hostSignSeed));
+const hostBox = ref.boxKey(u(V.keys.hostBoxPriv));
+const device = ref.signKey(u(V.keys.deviceSignSeed));
+const cid = ref.cidRaw(hostSign.pub);
+
+describe("keys", () => {
+ it("derives the public keys and computerId", async () => {
+ expect(ref.b64url(hostSign.pub)).toBe(V.keys.hostSignPub);
+ expect(ref.b64url(hostBox.pub)).toBe(V.keys.hostBoxPub);
+ expect(ref.b64url(device.pub)).toBe(V.keys.deviceSignPub);
+ expect(ref.computerId(hostSign.pub)).toBe(V.keys.computerId);
+ expect(await computerIdFor(hostSign.pub)).toBe(V.keys.computerId);
+ });
+});
+
+describe("handshake", () => {
+ const h = V.handshake;
+ const ekD = ref.boxKey(u(h.deviceEphPriv));
+ const ekH = ref.boxKey(u(h.hostEphPriv));
+ const n = u(h.n);
+
+ it("matches every intermediate value", () => {
+ expect(ref.b64url(ekD.pub)).toBe(h.deviceEphPub);
+ expect(ref.b64url(ekH.pub)).toBe(h.hostEphPub);
+ const hs1 = ref.hs1Input(cid, device.pub, ekD.pub, n);
+ expect(ref.b64url(hs1)).toBe(h.hs1SignInput);
+ expect(ref.b64url(ref.sign(device, hs1))).toBe(h.hs1Sig);
+ const th = ref.transcriptHash(cid, device.pub, ekD.pub, n, ekH.pub);
+ expect(ref.b64url(th)).toBe(h.transcriptHash);
+ expect(ref.b64url(ref.sign(hostSign, th))).toBe(h.hs2Sig);
+ const keys = ref.channelKeys(ekD.priv, ekH.pub, th);
+ expect(ref.b64url(keys.ss)).toBe(h.sharedSecret);
+ expect(ref.b64url(keys.prk)).toBe(h.prk);
+ expect(ref.b64url(keys.d2h)).toBe(h.kD2H);
+ expect(ref.b64url(keys.h2d)).toBe(h.kH2D);
+ });
+
+ it("runs device and host sides against each other", () => {
+ const d = ref.deviceHello(device, hostSign.pub, { eph: ekD, n });
+ expect(d.hello.sig).toBe(h.hs1Sig);
+ const hostSide = ref.hostWelcome(hostSign, d.hello as never, ekH);
+ expect(hostSide.welcome.sig).toBe(h.hs2Sig);
+ const keys = d.finish(hostSide.welcome);
+ expect(ref.b64url(keys.d2h)).toBe(h.kD2H);
+ expect(ref.b64url(hostSide.keys.h2d)).toBe(h.kH2D);
+ });
+
+ it("rejects a welcome signed by another key", () => {
+ const d = ref.deviceHello(device, hostSign.pub, { eph: ekD, n });
+ const th = ref.transcriptHash(cid, device.pub, ekD.pub, n, ekH.pub);
+ expect(() => d.finish({ ek: h.hostEphPub, sig: ref.b64url(ref.sign(ref.signKey(), th)) })).toThrow();
+ expect(() => d.finish({ ek: h.hostEphPub, sig: h.hs2Sig })).not.toThrow();
+ });
+
+ it("rejects an all-zero shared secret", () => {
+ expect(() => ref.channelKeys(ekD.priv, new Uint8Array(32), new Uint8Array(32))).toThrow();
+ });
+});
+
+describe("frames", () => {
+ const keys = { d2h: u(V.handshake.kD2H), h2d: u(V.handshake.kH2D) };
+ for (const f of V.frames) {
+ it(`${f.dir} c=${f.c}`, () => {
+ const key = f.dir === "d2h" ? keys.d2h : keys.h2d;
+ const pt = ref.concat(new Uint8Array([f.final ? 0 : 1]), ref.enc.encode(f.message));
+ expect(ref.b64url(pt)).toBe(f.plaintext);
+ expect(ref.sealFrame(key, f.c, f.final, ref.enc.encode(f.message))).toBe(f.d);
+ const opened = ref.openFrame(key, f.c, f.d);
+ expect(opened.final).toBe(f.final);
+ expect(ref.dec.decode(opened.chunk)).toBe(f.message);
+ });
+ }
+
+ it("refuses the wrong counter or direction", () => {
+ const f = V.frames[0]!;
+ expect(() => ref.openFrame(keys.d2h, 1, f.d)).toThrow();
+ expect(() => ref.openFrame(keys.h2d, 0, f.d)).toThrow();
+ });
+
+ it("chunks at 256 KiB and reassembles", () => {
+ const device = new ref.FrameCodec(keys.d2h, keys.h2d);
+ const host = new ref.FrameCodec(keys.h2d, keys.d2h);
+ const big = { id: 9, m: "send", b: { text: "x".repeat(600 * 1024) } };
+ const frames = device.seal(big);
+ expect(frames.length).toBe(3);
+ const out = frames.map((f) => host.open(f));
+ expect(out.slice(0, 2)).toEqual([undefined, undefined]);
+ expect(out[2]).toEqual(big);
+ // A skipped counter closes the channel (replay/reorder protection).
+ expect(() => host.open({ c: 5, d: device.seal({ id: 1 })[0]!.d })).toThrow();
+ });
+});
+
+describe("mailbox", () => {
+ const m = V.mailbox;
+ it("seals the vector blob", () => {
+ const eph = ref.boxKey(u(m.ephPriv));
+ expect(ref.b64url(eph.pub)).toBe(m.ephPub);
+ const blob = ref.sealMailbox(device, hostSign.pub, hostBox.pub, m.clientNonce, m.plaintext, eph);
+ expect(ref.b64url(blob)).toBe(m.blob);
+ expect(ref.b64url(blob.subarray(32, 96))).toBe(m.sig);
+ expect(ref.b64url(blob.subarray(96))).toBe(m.ciphertext);
+ const key = ref.mailboxKey(u(m.sharedSecret), cid, device.pub, eph.pub);
+ expect(ref.b64url(key)).toBe(m.key);
+ });
+
+ it("opens with the host box key and checks the clientNonce binding", () => {
+ expect(ref.openMailbox(hostSign.pub, hostBox, device.pub, m.clientNonce, u(m.blob))).toBe(m.plaintext);
+ expect(() => ref.openMailbox(hostSign.pub, hostBox, device.pub, "other", u(m.blob))).toThrow();
+ });
+
+ it("uses a fresh ephemeral key for every seal", () => {
+ const a = ref.sealMailbox(device, hostSign.pub, hostBox.pub, m.clientNonce, m.plaintext);
+ const b = ref.sealMailbox(device, hostSign.pub, hostBox.pub, m.clientNonce, m.plaintext);
+ expect(ref.b64url(a.subarray(0, 32))).not.toBe(ref.b64url(b.subarray(0, 32)));
+ });
+});
+
+describe("SAS, offer, claim, push", () => {
+ it("sas", () => {
+ const nD = u(V.sas.deviceNonce);
+ const nH = u(V.sas.hostNonce);
+ expect(ref.b64url(ref.sasCommit(device.pub, nD))).toBe(V.sas.commit);
+ expect(ref.sasCode(hostSign.pub, device.pub, nD, nH)).toBe(V.sas.code);
+ });
+
+ it("offer id", () => {
+ expect(ref.offerId(u(V.pairing.code))).toBe(V.pairing.offerId);
+ });
+
+ it("claim", async () => {
+ const c = V.claim;
+ const canonical = ref.claimCanonical(c.claimId, c.nonce, c.userId, c.computerId, c.boxKey);
+ expect(canonical).toBe(c.canonical);
+ expect(workerClaimCanonical(c.claimId, c.nonce, c.userId, c.computerId, c.boxKey)).toBe(c.canonical);
+ expect(ref.b64url(ref.sign(hostSign, ref.enc.encode(canonical)))).toBe(c.sig);
+ expect(await verifyEd25519(hostSign.pub, u(c.sig), ref.enc.encode(canonical))).toBe(true);
+ });
+
+ it("push", () => {
+ const p = V.push;
+ const push = ref.boxKey(u(p.pushPriv));
+ expect(ref.b64url(push.pub)).toBe(p.pushPub);
+ const eph = ref.boxKey(u(p.ephPriv));
+ expect(ref.b64url(eph.pub)).toBe(p.ephPub);
+ expect(ref.b64url(ref.pushKey(u(p.sharedSecret), cid, push.pub, eph.pub))).toBe(p.key);
+ expect(ref.sealPush(hostSign.pub, push.pub, p.plaintext, eph)).toBe(p.sealed);
+ expect(ref.openPush(hostSign.pub, push, p.sealed)).toBe(p.plaintext);
+ });
+});
+
+describe("Codync-Sig", () => {
+ const r = V.requestSig;
+ const req = (headers: Record<string, string>, authority = r.authority, path = r.pathAndQuery) =>
+ new Request(`https://${authority}${path}`, { method: r.method, headers });
+
+ it("builds the canonical string and header", async () => {
+ expect(ref.b64url(await import("@noble/hashes/sha2.js").then((m) => m.sha256(new Uint8Array())))).toBe(r.bodySha256);
+ expect(ref.sigCanonical(r.method, r.authority, r.pathAndQuery, r.ts, r.nonce, new Uint8Array())).toBe(r.canonical);
+ expect(await sigCanonical(r.method, r.authority, r.pathAndQuery, r.ts, r.nonce, new Uint8Array())).toBe(r.canonical);
+ const header = ref.signRequest(device, { method: r.method, authority: r.authority, pathAndQuery: r.pathAndQuery, ts: r.ts, nonce: r.nonce });
+ expect(`Codync-Sig: ${header}`).toBe(r.header);
+ });
+
+ it("verifies in the Worker within the time window only", async () => {
+ const value = r.header.slice("Codync-Sig: ".length);
+ expect(await verifySig(req({ "Codync-Sig": value }), new Uint8Array(), r.ts)).toEqual({
+ kid: V.keys.deviceSignPub,
+ ts: r.ts,
+ nonce: r.nonce,
+ });
+ expect(await verifySig(req({ "Codync-Sig": value }), new Uint8Array(), r.ts + 300_000)).not.toBeNull();
+ expect(await verifySig(req({ "Codync-Sig": value }), new Uint8Array(), r.ts + 300_001)).toBeNull();
+ expect(await verifySig(req({ "Codync-Sig": value }), new Uint8Array(), r.ts - 300_001)).toBeNull();
+ });
+
+ it("binds the authority, path and body", async () => {
+ const value = r.header.slice("Codync-Sig: ".length);
+ // Upper-case Host is the same authority; a different host is not.
+ expect(await verifySig(req({ "Codync-Sig": value }, r.authority.toUpperCase()), new Uint8Array(), r.ts)).not.toBeNull();
+ expect(await verifySig(req({ "Codync-Sig": value }, "codync-cloud.example.workers.dev"), new Uint8Array(), r.ts)).toBeNull();
+ expect(await verifySig(req({ "Codync-Sig": value }, r.authority, `${r.pathAndQuery}&pair=x`), new Uint8Array(), r.ts)).toBeNull();
+ expect(await verifySig(req({ "Codync-Sig": value }), new Uint8Array([1]), r.ts)).toBeNull();
+ expect(await verifySig(req({ "Codync-Sig": value.replace("v=1", "v=2") }), new Uint8Array(), r.ts)).toBeNull();
+ expect(await verifySig(req({}), new Uint8Array(), r.ts)).toBeNull();
+ });
+});
+
+describe("ACL", () => {
+ it("verifies the vector ACL signature and parses it", async () => {
+ const a = V.acl;
+ expect(ref.b64url(ref.enc.encode(a.json))).toBe(a.d);
+ expect(ref.aclMessage(hostSign, a.json)).toEqual({ t: "acl", d: a.d, sig: a.sig });
+ expect(await verifyEd25519(hostSign.pub, u(a.sig), u(a.d))).toBe(true);
+ expect(parseAcl(u(a.d))).toEqual(JSON.parse(a.json));
+ expect(parseAcl(ref.enc.encode('{"v":2}'))).toBeNull();
+ });
+});
+
+describe("base64url", () => {
+ it("is strict", () => {
+ expect(fromB64url("AA", 1)).toEqual(new Uint8Array([0]));
+ expect(fromB64url("AB", 1)).toBeNull(); // non-canonical trailing bits
+ expect(fromB64url("AA==")).toBeNull();
+ expect(fromB64url("A+")).toBeNull();
+ expect(fromB64url("AAA", 1)).toBeNull();
+ });
+});
diff --git a/cloud/tsconfig.json b/cloud/tsconfig.json
new file mode 100644
index 00000000..d173f4c2
--- /dev/null
+++ b/cloud/tsconfig.json
@@ -0,0 +1,16 @@
+{
+ "compilerOptions": {
+ "target": "ESNext",
+ "module": "ESNext",
+ "moduleResolution": "bundler",
+ "lib": ["ESNext"],
+ "types": ["@cloudflare/workers-types", "@cloudflare/vitest-pool-workers/types"],
+ "strict": true,
+ "allowImportingTsExtensions": true,
+ "resolveJsonModule": true,
+ "noEmit": true,
+ "skipLibCheck": true
+ },
+ "include": ["src", "test"],
+ "exclude": ["test/e2e"]
+}
diff --git a/cloud/vitest.config.ts b/cloud/vitest.config.ts
new file mode 100644
index 00000000..06ff026f
--- /dev/null
+++ b/cloud/vitest.config.ts
@@ -0,0 +1,29 @@
+import { generateKeyPairSync, randomBytes } from "node:crypto";
+import { cloudflareTest, readD1Migrations } from "@cloudflare/vitest-pool-workers";
+import { defineConfig } from "vitest/config";
+
+// A throwaway Clerk signing key: the Worker verifies networklessly with the public half (CLERK_JWT_KEY),
+// the tests mint session tokens with the private half.
+const { publicKey, privateKey } = generateKeyPairSync("rsa", { modulusLength: 2048 });
+
+export default defineConfig(async () => ({
+ plugins: [
+ cloudflareTest({
+ wrangler: { configPath: "./wrangler.toml", environment: "dev" },
+ miniflare: {
+ // The pool's bundled workerd trails wrangler's; pin to the newest date it supports.
+ compatibilityDate: "2026-08-22",
+ bindings: {
+ TEST_MIGRATIONS: await readD1Migrations("./migrations"),
+ CLERK_JWT_KEY: publicKey.export({ type: "spki", format: "pem" }).toString(),
+ TEST_CLERK_PRIVATE_JWK: JSON.stringify(privateKey.export({ format: "jwk" })),
+ CLERK_WEBHOOK_SECRET: `whsec_${randomBytes(24).toString("base64")}`,
+ },
+ },
+ }),
+ ],
+ test: {
+ setupFiles: ["./test/setup.ts"],
+ testTimeout: 20_000,
+ },
+}));
diff --git a/cloud/wrangler.toml b/cloud/wrangler.toml
new file mode 100644
index 00000000..05e9a07b
--- /dev/null
+++ b/cloud/wrangler.toml
@@ -0,0 +1,47 @@
+name = "codync-cloud"
+main = "src/index.ts"
+compatibility_date = "2026-09-01"
+compatibility_flags = ["nodejs_compat"]
+
+[[migrations]]
+tag = "v1"
+new_sqlite_classes = ["ComputerRelay"]
+
+# production (deploying needs the owner's go-ahead)
+[vars]
+CLERK_ISSUER = "<production Clerk Frontend API URL>"
+
+[[d1_databases]]
+binding = "DB"
+database_name = "codync"
+database_id = "<production id>"
+migrations_dir = "migrations"
+
+[[durable_objects.bindings]]
+name = "RELAY"
+class_name = "ComputerRelay"
+
+# New computers per IP (POST /v1/host/register).
+[[ratelimits]]
+name = "REGISTER_LIMITER"
+namespace_id = "1001"
+simple = { limit = 10, period = 60 }
+
+[triggers]
+crons = ["*/15 * * * *"]
+
+[env.staging]
+name = "codync-cloud-staging"
+vars = { CLERK_ISSUER = "https://sunny-mollusk-8651.clerk.accounts.dev" }
+d1_databases = [{ binding = "DB", database_name = "codync-staging", database_id = "8956a285-8c88-4a5b-a05c-5f79be324448", migrations_dir = "migrations" }]
+durable_objects.bindings = [{ name = "RELAY", class_name = "ComputerRelay" }]
+ratelimits = [{ name = "REGISTER_LIMITER", namespace_id = "1002", simple = { limit = 10, period = 60 } }]
+triggers = { crons = ["*/15 * * * *"] }
+
+# wrangler dev / e2e: local D1; CLERK_JWT_KEY is injected by the test (--var).
+[env.dev]
+name = "codync-cloud-dev"
+vars = { CLERK_ISSUER = "https://clerk.test.local" }
+d1_databases = [{ binding = "DB", database_name = "codync-dev", database_id = "dev", migrations_dir = "migrations" }]
+durable_objects.bindings = [{ name = "RELAY", class_name = "ComputerRelay" }]
+ratelimits = [{ name = "REGISTER_LIMITER", namespace_id = "1003", simple = { limit = 10, period = 60 } }]
diff --git a/docs/clerk-macos.md b/docs/clerk-macos.md
index db7ffe06..a4a81cd7 100644
--- a/docs/clerk-macos.md
+++ b/docs/clerk-macos.md
@@ -13,8 +13,9 @@ The footer displays **Account**, never the Mac user's local name.
4. Allow the native callback `com.pokai.Codync://callback` where Clerk's dashboard
requests allowed redirect URLs.
5. Copy only the **publishable key** into
- `apps/macos/Resources/ClerkConfig.plist` (`publishableKey`). A development
- launch can override it with `CODYNC_CLERK_PUBLISHABLE_KEY`.
+ `apps/macos/Resources/AccountConfig.plist` (`clerkPublishableKey`), next to
+ `cloudURL`, the Codync cloud the app talks to (staging for now). A development
+ launch can override them with `CODYNC_CLERK_PUBLISHABLE_KEY` and `CODYNC_CLOUD_URL`.
The checked-in public configuration uses the Codync development instance
`sunny-mollusk-8651.clerk.accounts.dev`. Native API is enabled, the Apple app
@@ -34,8 +35,10 @@ network failures leave the user in the custom account menu with a retryable
error. Log out calls Clerk's sign-out API.
The custom account menu displays the authenticated email and avatar when
-available. A Clerk session does not replace the local host pairing token,
-authorize remote host access, upload conversations, or migrate local data.
+available. `AccountSession.sessionToken()` hands the session JWT to the Codync
+cloud client. A Clerk session never authorizes a computer by itself: each
+computer approves each device after comparing a 6-digit code
+([remote-relay-spec.md](remote-relay-spec.md) §4.2). Conversations are not uploaded.
## Verification
@@ -61,7 +64,7 @@ Its top-left button opens Accounts; Computers & settings is a separate destinati
inside that sheet. The iOS native application must be registered in the same Clerk
instance with bundle ID `com.pokai.Codync.ios` and its own callback
`com.pokai.Codync.ios://callback`. The iOS public configuration is in
-`apps/ios/Resources/ClerkConfig.plist`. The repository configuration does not prove
+`apps/ios/Resources/AccountConfig.plist`. The repository configuration does not prove
that the corresponding Clerk Dashboard registration has been completed.
To retain several accounts at once, enable multi-session support in the Clerk
@@ -70,13 +73,36 @@ it lists active SDK sessions and switches with `auth.setActive(sessionId:)`; wit
single-session enabled, it asks the user to sign out before using another account.
Signing out passes the current session ID, rather than signing out all accounts.
-Pairings and caches are partitioned by the Clerk user ID on this iPhone. Local
-pairings keep their original storage namespace and are not automatically claimed
-by a newly signed-in user. Each BotStore captures a fixed storage context, and is
-retired when changing accounts. This is client-side separation, not server-side
-ownership enforcement. Cloudflare device discovery, per-device grants, account-aware
-push revocation and Keychain migration remain work in the architecture plan.
+Computers, device keys and caches are partitioned by the Clerk user ID on this
+iPhone (`SharedStore.Context`). Computers paired with a code while signed out stay
+in the local context and are not claimed by a newly signed-in user. Each account
+context gets its own `AccountStore`, retired when changing accounts; signing out
+erases that account's computers, device and push keys and caches from the iPhone.
+Signed in, the Computers screen also lists the account's computers from the cloud;
+asking one for access shows the 6-digit code to compare on the computer.
Verify with two real Google accounts: add both, switch, cancel OAuth, restart,
check each account's pairings, sign out just one, and verify the other remains.
A simulator build verifies compilation, not the Dashboard settings or OAuth flow.
+
+## Mac: computers, approvals and SSH
+
+The Mac keeps one `AccountStore` per account context too (`HostController`). This Mac's
+host and SSH computers are attached over loopback and follow into whichever account is
+active; the account's other computers are reached over the encrypted channel with the
+Mac's own device key. Log out erases the account's keys and caches, as on iPhone.
+
+**Computers & devices** (account menu) shows, for this Mac and each SSH computer:
+*Reach from anywhere* (`setCloud`, using the app's `cloudURL` when the host has none),
+*Add to account* (claim: `POST /v1/claims` → loopback `claimSign` → complete) and
+*Remove from account* (`unclaim`), a pairing QR, and the authorized devices with revoke.
+A device asking for access raises the menu bar dot and opens the approval sheet with the
+6-digit code; Approve stays disabled until the device revealed its code.
+
+SSH computers use the system OpenSSH (`apps/macos/App/SSHTunnel.swift`): `ssh -G` to
+resolve the target, `ssh-keygen -F` against `~/.ssh/known_hosts` and
+`~/.codync/ssh_known_hosts`, a fingerprint confirmation on first contact (no proxy),
+`codync-host info --json` for the identity and loopback token, then
+`ssh -N -L 127.0.0.1:<free port>:127.0.0.1:<remote port>` with keepalive and backoff.
+A changed host key or a different computer ID blocks the connection. Debug builds run
+`SSH.selfCheck()` at launch (argv, `ssh -G` parsing, validation).
diff --git a/docs/structure.md b/docs/structure.md
index 05cda0c5..829ff03d 100644
--- a/docs/structure.md
+++ b/docs/structure.md
@@ -7,6 +7,8 @@ kit/Sources/CodyncUI/ Store/ Bots/ Thread/ Marketplace/ Usage/ Resour
host/ cloud/ relay/ web/ packaging/
```
+Remote access ([spec](remote-relay-spec.md)): host `identity.rs` (keys) · `crypto.rs` (wire crypto) · `devices.rs` (authorized devices, `Caller`) · `channel.rs` (E2E channel, direct or relayed) · `relay.rs` (relay socket) · `cloud.rs` (cloud HTTP client, access requests). Kit `Client/`: `RelayCrypto`, `DeviceIdentity`, `Pairing`, `HostTransport`, `ChannelTransport`, `HostConnector`, `CloudClient`; models `Computer`, `Cloud`; `CodyncUI/Store/AccountStore`. Apps: `apps/shared/ComputerStatus.swift`, iOS `AccessRequestView`, Mac `SSHTunnel` + `ComputersView`. Cloud: `cloud/src/{index,auth,api,relay}.ts`.
+
- Directories: lowercase for repo-level roles (`apps/`, `kit/`, `host/`); PascalCase inside Swift targets (`Views/`, `Thread/`). Apple app folders are `App/` (entry point, app-wide services), `Views/`, `Resources/` (Info.plist, entitlements, xcprivacy, xcassets).
- Files follow their language: Swift `UpperCamelCase.swift` named after the file's main type; Rust/TS `snake_case.rs` / `kebab-case.ts`.
- One main type per file. Small private helpers of that type stay in it; a file of several small siblings takes the plural role (`ChatRows.swift`, `UsageViews.swift`, `Dialogs.swift`).
diff --git a/host/Cargo.lock b/host/Cargo.lock
index a35edf6f..42728fb4 100644
--- a/host/Cargo.lock
+++ b/host/Cargo.lock
@@ -2,6 +2,16 @@
# It is not intended for manual editing.
version = 4
+[[package]]
+name = "aead"
+version = "0.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1973cfbc1a2daf9cf550e74e1f088c28e7f7d8c1e1418fb6c9dc5184b7e84c99"
+dependencies = [
+ "crypto-common 0.2.2",
+ "inout",
+]
+
[[package]]
name = "aho-corasick"
version = "1.1.5"
@@ -124,6 +134,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90"
dependencies = [
"axum-core",
+ "base64 0.22.1",
"bytes",
"form_urlencoded",
"futures-util",
@@ -142,8 +153,10 @@ dependencies = [
"serde_json",
"serde_path_to_error",
"serde_urlencoded",
+ "sha1",
"sync_wrapper",
"tokio",
+ "tokio-tungstenite",
"tower",
"tower-layer",
"tower-service",
@@ -169,6 +182,12 @@ dependencies = [
"tracing",
]
+[[package]]
+name = "base64"
+version = "0.22.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
+
[[package]]
name = "base64"
version = "0.23.1"
@@ -181,6 +200,15 @@ version = "2.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
+[[package]]
+name = "block-buffer"
+version = "0.10.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
+dependencies = [
+ "generic-array",
+]
+
[[package]]
name = "block-buffer"
version = "0.12.1"
@@ -248,8 +276,32 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"
dependencies = [
"cfg-if",
- "cpufeatures",
- "rand_core",
+ "cipher",
+ "cpufeatures 0.3.1",
+ "rand_core 0.10.1",
+]
+
+[[package]]
+name = "chacha20poly1305"
+version = "0.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9b89e1c441e926b9c82a8d023f6e1b7ae0adcfaa7d621814e4d60789bac751cb"
+dependencies = [
+ "aead",
+ "chacha20",
+ "cipher",
+ "poly1305",
+]
+
+[[package]]
+name = "cipher"
+version = "0.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c"
+dependencies = [
+ "block-buffer 0.12.1",
+ "crypto-common 0.2.2",
+ "inout",
]
[[package]]
@@ -301,18 +353,28 @@ dependencies = [
"cc",
]
+[[package]]
+name = "cmov"
+version = "0.5.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a"
+
[[package]]
name = "codync-host"
-version = "2.1.0"
+version = "3.0.0"
dependencies = [
"anyhow",
"axum",
- "base64",
+ "base64 0.23.1",
+ "chacha20poly1305",
"clap",
"crossterm",
"dirs",
+ "ed25519-dalek",
"futures",
"gethostname",
+ "getrandom 0.4.3",
+ "hkdf",
"if-addrs",
"pty-process",
"qrcode",
@@ -324,10 +386,12 @@ dependencies = [
"sha2",
"tokio",
"tokio-stream",
+ "tokio-tungstenite",
"tracing",
"tracing-subscriber",
"unicode-width",
"uuid",
+ "x25519-dalek",
]
[[package]]
@@ -391,6 +455,15 @@ version = "0.8.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
+[[package]]
+name = "cpufeatures"
+version = "0.2.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
+dependencies = [
+ "libc",
+]
+
[[package]]
name = "cpufeatures"
version = "0.3.1"
@@ -428,13 +501,61 @@ dependencies = [
"winapi",
]
+[[package]]
+name = "crypto-common"
+version = "0.1.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
+dependencies = [
+ "generic-array",
+ "typenum",
+]
+
[[package]]
name = "crypto-common"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
dependencies = [
+ "getrandom 0.4.3",
"hybrid-array",
+ "rand_core 0.10.1",
+]
+
+[[package]]
+name = "ctutils"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7d5515a3834141de9eafb9717ad39eea8247b5674e6066c404e8c4b365d2a29e"
+dependencies = [
+ "cmov",
+]
+
+[[package]]
+name = "curve25519-dalek"
+version = "5.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b5eed333089e2e1c1ac8c6c0398e5e2497b4c9926ca6d0365ed1e099afa5bc23"
+dependencies = [
+ "cfg-if",
+ "cpufeatures 0.3.1",
+ "curve25519-dalek-derive",
+ "digest 0.11.3",
+ "fiat-crypto",
+ "rustc_version",
+ "subtle",
+ "zeroize",
+]
+
+[[package]]
+name = "curve25519-dalek-derive"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
]
[[package]]
@@ -471,6 +592,12 @@ dependencies = [
"syn 3.0.6",
]
+[[package]]
+name = "data-encoding"
+version = "2.11.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06"
+
[[package]]
name = "deranged"
version = "0.5.8"
@@ -499,15 +626,26 @@ dependencies = [
"syn 2.0.119",
]
+[[package]]
+name = "digest"
+version = "0.10.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
+dependencies = [
+ "block-buffer 0.10.4",
+ "crypto-common 0.1.7",
+]
+
[[package]]
name = "digest"
version = "0.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
dependencies = [
- "block-buffer",
+ "block-buffer 0.12.1",
"const-oid",
- "crypto-common",
+ "crypto-common 0.2.2",
+ "ctutils",
]
[[package]]
@@ -557,6 +695,28 @@ version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813"
+[[package]]
+name = "ed25519"
+version = "3.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "29fcf32e6c73d1079f83ab4d782de2d81620346a5f38c6237a86a22f8368980a"
+dependencies = [
+ "signature",
+]
+
+[[package]]
+name = "ed25519-dalek"
+version = "3.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6ebaa1a2bf1290ab3bfe5a7b771d050ebffab2711c19a81691c683a5144a25de"
+dependencies = [
+ "curve25519-dalek",
+ "ed25519",
+ "sha2",
+ "subtle",
+ "zeroize",
+]
+
[[package]]
name = "either"
version = "1.18.0"
@@ -591,6 +751,12 @@ version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a"
+[[package]]
+name = "fiat-crypto"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "64cd1e32ddd350061ae6edb1b082d7c54915b5c672c389143b9a63403a109f24"
+
[[package]]
name = "find-msvc-tools"
version = "0.1.13"
@@ -706,6 +872,16 @@ dependencies = [
"slab",
]
+[[package]]
+name = "generic-array"
+version = "0.14.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
+dependencies = [
+ "typenum",
+ "version_check",
+]
+
[[package]]
name = "gethostname"
version = "1.1.0"
@@ -729,6 +905,18 @@ dependencies = [
"wasm-bindgen",
]
+[[package]]
+name = "getrandom"
+version = "0.3.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "r-efi 5.3.0",
+ "wasip2",
+]
+
[[package]]
name = "getrandom"
version = "0.4.3"
@@ -738,8 +926,8 @@ dependencies = [
"cfg-if",
"js-sys",
"libc",
- "r-efi",
- "rand_core",
+ "r-efi 6.0.0",
+ "rand_core 0.10.1",
"wasm-bindgen",
]
@@ -780,6 +968,24 @@ version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
+[[package]]
+name = "hkdf"
+version = "0.13.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4aaa26c720c68b866f2c96ef5c1264b3e6f473fe5d4ce61cd44bbe913e553018"
+dependencies = [
+ "hmac",
+]
+
+[[package]]
+name = "hmac"
+version = "0.13.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f"
+dependencies = [
+ "digest 0.11.3",
+]
+
[[package]]
name = "http"
version = "1.5.0"
@@ -876,7 +1082,7 @@ version = "0.1.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff"
dependencies = [
- "base64",
+ "base64 0.23.1",
"bytes",
"futures-channel",
"futures-util",
@@ -1033,6 +1239,15 @@ dependencies = [
"rustversion",
]
+[[package]]
+name = "inout"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4250ce6452e92010fdf7268ccc5d14faa80bb12fc741938534c58f16804e03c7"
+dependencies = [
+ "hybrid-array",
+]
+
[[package]]
name = "instability"
version = "0.3.14"
@@ -1419,6 +1634,16 @@ version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
+[[package]]
+name = "poly1305"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6e2d0073b297041425c7c3df6eb4792d598a15323fe63346852b092eca02904c"
+dependencies = [
+ "cpufeatures 0.3.1",
+ "universal-hash",
+]
+
[[package]]
name = "portable-atomic"
version = "1.15.0"
@@ -1440,6 +1665,15 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391"
+[[package]]
+name = "ppv-lite86"
+version = "0.2.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
+dependencies = [
+ "zerocopy",
+]
+
[[package]]
name = "proc-macro2"
version = "1.0.107"
@@ -1495,7 +1729,7 @@ dependencies = [
"bytes",
"getrandom 0.4.3",
"lru-slab",
- "rand",
+ "rand 0.10.3",
"rand_pcg",
"ring",
"rustc-hash",
@@ -1531,12 +1765,28 @@ dependencies = [
"proc-macro2",
]
+[[package]]
+name = "r-efi"
+version = "5.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
+
[[package]]
name = "r-efi"
version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
+[[package]]
+name = "rand"
+version = "0.9.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41"
+dependencies = [
+ "rand_chacha",
+ "rand_core 0.9.5",
+]
+
[[package]]
name = "rand"
version = "0.10.3"
@@ -1545,7 +1795,26 @@ checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af"
dependencies = [
"chacha20",
"getrandom 0.4.3",
- "rand_core",
+ "rand_core 0.10.1",
+]
+
+[[package]]
+name = "rand_chacha"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
+dependencies = [
+ "ppv-lite86",
+ "rand_core 0.9.5",
+]
+
+[[package]]
+name = "rand_core"
+version = "0.9.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"
+dependencies = [
+ "getrandom 0.3.4",
]
[[package]]
@@ -1560,7 +1829,7 @@ version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a"
dependencies = [
- "rand_core",
+ "rand_core 0.10.1",
]
[[package]]
@@ -1671,7 +1940,7 @@ version = "0.13.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029"
dependencies = [
- "base64",
+ "base64 0.23.1",
"bytes",
"futures-core",
"futures-util",
@@ -1979,6 +2248,17 @@ dependencies = [
"serde",
]
+[[package]]
+name = "sha1"
+version = "0.10.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8"
+dependencies = [
+ "cfg-if",
+ "cpufeatures 0.2.17",
+ "digest 0.10.7",
+]
+
[[package]]
name = "sha2"
version = "0.11.0"
@@ -1986,8 +2266,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4"
dependencies = [
"cfg-if",
- "cpufeatures",
- "digest",
+ "cpufeatures 0.3.1",
+ "digest 0.11.3",
]
[[package]]
@@ -2036,6 +2316,12 @@ dependencies = [
"libc",
]
+[[package]]
+name = "signature"
+version = "3.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "28d567dcbaf0049cb8ac2608a76cd95ff9e4412e1899d389ee400918ca7537f5"
+
[[package]]
name = "simd_cesu8"
version = "1.2.0"
@@ -2289,6 +2575,22 @@ dependencies = [
"tokio-util",
]
+[[package]]
+name = "tokio-tungstenite"
+version = "0.29.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8f72a05e828585856dacd553fba484c242c46e391fb0e58917c942ee9202915c"
+dependencies = [
+ "futures-util",
+ "log",
+ "rustls",
+ "rustls-pki-types",
+ "tokio",
+ "tokio-rustls",
+ "tungstenite",
+ "webpki-roots 0.26.11",
+]
+
[[package]]
name = "tokio-util"
version = "0.7.19"
@@ -2416,6 +2718,24 @@ version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
+[[package]]
+name = "tungstenite"
+version = "0.29.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6c01152af293afb9c7c2a57e4b559c5620b421f6d133261c60dd2d0cdb38e6b8"
+dependencies = [
+ "bytes",
+ "data-encoding",
+ "http",
+ "httparse",
+ "log",
+ "rand 0.9.5",
+ "rustls",
+ "rustls-pki-types",
+ "sha1",
+ "thiserror",
+]
+
[[package]]
name = "typenum"
version = "1.20.1"
@@ -2451,6 +2771,16 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"
+[[package]]
+name = "universal-hash"
+version = "0.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f4987bdc12753382e0bec4a65c50738ffaabc998b9cdd1f952fb5f39b0048a96"
+dependencies = [
+ "crypto-common 0.2.2",
+ "ctutils",
+]
+
[[package]]
name = "untrusted"
version = "0.9.0"
@@ -2504,6 +2834,12 @@ version = "0.2.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
+[[package]]
+name = "version_check"
+version = "0.9.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
+
[[package]]
name = "walkdir"
version = "2.5.0"
@@ -2529,6 +2865,15 @@ version = "0.11.1+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
+[[package]]
+name = "wasip2"
+version = "1.0.4+wasi-0.2.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487"
+dependencies = [
+ "wit-bindgen",
+]
+
[[package]]
name = "wasm-bindgen"
version = "0.2.128"
@@ -2626,6 +2971,24 @@ dependencies = [
"rustls-pki-types",
]
+[[package]]
+name = "webpki-roots"
+version = "0.26.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9"
+dependencies = [
+ "webpki-roots 1.0.9",
+]
+
+[[package]]
+name = "webpki-roots"
+version = "1.0.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a"
+dependencies = [
+ "rustls-pki-types",
+]
+
[[package]]
name = "winapi"
version = "0.3.9"
@@ -2745,12 +3108,29 @@ version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
+[[package]]
+name = "wit-bindgen"
+version = "0.57.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"
+
[[package]]
name = "writeable"
version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc"
+[[package]]
+name = "x25519-dalek"
+version = "3.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e7e8131a03190127fb2263afc72b322ecadae46b6ff8c6f399ff5d02f5559af6"
+dependencies = [
+ "curve25519-dalek",
+ "rand_core 0.10.1",
+ "zeroize",
+]
+
[[package]]
name = "yoke"
version = "0.8.3"
@@ -2774,6 +3154,26 @@ dependencies = [
"synstructure",
]
+[[package]]
+name = "zerocopy"
+version = "0.8.57"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d35102a9f36d089ccae9e4c6802bc118be4487b80aaffc0ab4e0cf5ce92d2873"
+dependencies = [
+ "zerocopy-derive",
+]
+
+[[package]]
+name = "zerocopy-derive"
+version = "0.8.57"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "146c01f5ab44258da43cf276c74a2763db2ff3969c9c652c3f2de07041d0b2bc"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
[[package]]
name = "zerofrom"
version = "0.1.8"
diff --git a/host/Cargo.toml b/host/Cargo.toml
index 38e99fb4..b1608493 100644
--- a/host/Cargo.toml
+++ b/host/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "codync-host"
-version = "2.1.0"
+version = "3.0.0"
edition = "2024"
# let-chains (`if let … && let …`) need 1.88.
rust-version = "1.88"
@@ -10,13 +10,17 @@ repository = "https://github.com/leepokai/Codync"
[dependencies]
anyhow = "1.0.104"
-axum = "0.8.9"
+axum = { version = "0.8.9", features = ["ws"] }
base64 = "0.23.1"
+chacha20poly1305 = "0.11.0"
clap = { version = "4.6.7", features = ["derive", "env"] }
crossterm = { version = "0.29", features = ["event-stream"] }
dirs = "7.0.0"
+ed25519-dalek = "3.0.0"
futures = "0.3.34"
gethostname = "1.1.0"
+getrandom = "0.4"
+hkdf = "0.13.0"
if-addrs = "0.15.0"
pty-process = { version = "0.5.3", features = ["async"] }
qrcode = { version = "0.14.1", default-features = false, features = ["svg"] }
@@ -28,10 +32,12 @@ serde_json = { version = "1.0.151", features = ["preserve_order"] }
sha2 = "0.11.0"
tokio = { version = "1.53.1", features = ["full"] }
tokio-stream = { version = "0.1.19", features = ["sync"] }
+tokio-tungstenite = { version = "0.29", features = ["rustls-tls-webpki-roots"] }
tracing = "0.1.44"
tracing-subscriber = { version = "0.3.23", features = ["env-filter"] }
unicode-width = "0.2"
uuid = { version = "1.26.1", features = ["v4"] }
+x25519-dalek = { version = "3.0.0", features = ["static_secrets"] }
# rust-skills lint-* rules: all default groups plus pedantic, with the
# library-oriented pedantic lints turned off for this binary crate.
@@ -62,3 +68,4 @@ undocumented_unsafe_blocks = "warn"
lto = "thin"
codegen-units = 1
strip = true
+
diff --git a/host/src/api.rs b/host/src/api.rs
index 3a25aa4f..1cf20ad0 100644
--- a/host/src/api.rs
+++ b/host/src/api.rs
@@ -1,12 +1,16 @@
-//! HTTP API: `POST /api/<method>` commands + `GET /events` SSE.
-//! Auth: `Authorization: Bearer <token>` (or `?token=` for SSE).
+//! HTTP API: `POST /api/<method>` commands + `GET /events` SSE for this computer's own
+//! apps and helpers (loopback + `Authorization: Bearer <token>`), and `GET /channel`, the
+//! direct end-to-end encrypted channel phones use (see `channel`).
use crate::LockExt;
use crate::bot::Cmd;
+use crate::devices::{Caller, Forbidden};
use crate::hub::Hub;
-use crate::store::{BotConfig, EntryKind};
-use crate::{backends, market, usage};
+use crate::store::{BotConfig, DeviceSource, EntryKind};
+use crate::{backends, crypto, market, usage};
use anyhow::{Context, Result, anyhow, bail};
+use axum::body::Bytes;
+use axum::extract::ws::WebSocketUpgrade;
use axum::extract::{ConnectInfo, Path, Query, State};
use axum::http::{HeaderMap, StatusCode};
use axum::response::sse::{Event, KeepAlive, Sse};
@@ -17,7 +21,7 @@ use futures::{Stream, StreamExt, stream};
use serde::Deserialize;
use serde_json::{Value, json};
use std::convert::Infallible;
-use std::net::SocketAddr;
+use std::net::{IpAddr, SocketAddr};
use std::sync::Arc;
use std::sync::atomic::Ordering;
use std::time::Duration;
@@ -33,14 +37,27 @@ pub fn router(hub: Arc<Hub>) -> Router {
.route("/api/{method}", post(command))
.route("/term/{id}", get(term_stream))
.route("/ingest/statusline", post(statusline))
+ .route("/channel", get(channel))
.with_state(hub)
}
-fn authorized(hub: &Hub, headers: &HeaderMap, query_token: Option<&str>) -> bool {
- let header = headers.get("authorization").and_then(|v| v.to_str().ok()).and_then(|v| v.strip_prefix("Bearer "));
- let given = header.or(query_token).unwrap_or_default();
- // Constant-time compare.
- given.len() == hub.token.len() && given.bytes().zip(hub.token.bytes()).fold(0u8, |acc, (a, b)| acc | (a ^ b)) == 0
+/// Loopback, also as an IPv4-mapped IPv6 address (`::ffff:127.0.0.1` under `--bind ::`).
+fn is_loopback(ip: IpAddr) -> bool {
+ ip.to_canonical().is_loopback()
+}
+
+/// The bearer token only works from this computer; phones use the E2E channel.
+fn authorized(hub: &Hub, headers: &HeaderMap, peer: SocketAddr) -> bool {
+ let given = headers
+ .get("authorization")
+ .and_then(|v| v.to_str().ok())
+ .and_then(|v| v.strip_prefix("Bearer "))
+ .unwrap_or_default();
+ is_loopback(peer.ip()) && crypto::ct_eq(given.as_bytes(), hub.token.as_bytes())
+}
+
+fn unauthorized() -> ApiError {
+ ApiError(StatusCode::UNAUTHORIZED, "invalid token".into())
}
struct ApiError(StatusCode, String);
@@ -57,6 +74,20 @@ impl std::fmt::Display for UnknownMethod {
impl std::error::Error for UnknownMethod {}
+/// HTTP status and message for a failed call; channels send the same pair in `err`.
+pub fn error_status(e: &anyhow::Error) -> (StatusCode, String) {
+ if e.is::<UnknownMethod>() {
+ (StatusCode::NOT_FOUND, e.to_string())
+ } else if e.is::<Forbidden>() {
+ (StatusCode::FORBIDDEN, e.to_string())
+ } else if e.is::<crate::cloud::Conflict>() {
+ (StatusCode::CONFLICT, e.to_string())
+ } else {
+ // `{:#}` keeps the context chain ("starting `npx …`: No such file or directory").
+ (StatusCode::BAD_REQUEST, format!("{e:#}"))
+ }
+}
+
impl IntoResponse for ApiError {
fn into_response(self) -> Response {
(self.0, Json(json!({"error": self.1}))).into_response()
@@ -64,13 +95,26 @@ impl IntoResponse for ApiError {
}
async fn health(State(hub): State<Arc<Hub>>) -> Json<Value> {
- Json(json!({"ok": true, "hostId": hub.host_id, "version": env!("CARGO_PKG_VERSION")}))
+ Json(json!({
+ "ok": true,
+ "hostId": hub.host_id,
+ "computerId": hub.identity.computer_id(),
+ "version": env!("CARGO_PKG_VERSION"),
+ }))
}
-async fn statusline(State(hub): State<Arc<Hub>>, headers: HeaderMap, Json(body): Json<Value>) -> StatusCode {
- if !authorized(&hub, &headers, None) {
+async fn statusline(
+ State(hub): State<Arc<Hub>>,
+ ConnectInfo(peer): ConnectInfo<SocketAddr>,
+ headers: HeaderMap,
+ body: Bytes,
+) -> StatusCode {
+ if !authorized(&hub, &headers, peer) {
return StatusCode::UNAUTHORIZED;
}
+ let Ok(body) = serde_json::from_slice::<Value>(&body) else {
+ return StatusCode::BAD_REQUEST;
+ };
usage::ingest_statusline(&hub, &body);
StatusCode::NO_CONTENT
}
@@ -80,37 +124,59 @@ async fn command(
Path(method): Path<String>,
ConnectInfo(peer): ConnectInfo<SocketAddr>,
headers: HeaderMap,
- body: Option<Json<Value>>,
+ body: Bytes,
) -> Result<Json<Value>, ApiError> {
- if !authorized(&hub, &headers, None) {
- return Err(ApiError(StatusCode::UNAUTHORIZED, "invalid token".into()));
+ // The token is checked before the body is even looked at.
+ if !authorized(&hub, &headers, peer) {
+ return Err(unauthorized());
}
- let body = body.map_or(Value::Null, |b| b.0);
- // Letting phones see and control the screen is decided at the computer, never remotely.
- if method == "setScreenEnabled" && !peer.ip().is_loopback() {
- return Err(ApiError(
- StatusCode::FORBIDDEN,
- "Remote screen can only be turned on at the computer itself.".into(),
- ));
- }
- match dispatch(&hub, &method, body).await {
- Ok(v) => Ok(Json(v)),
- Err(e) if e.is::<UnknownMethod>() => Err(ApiError(StatusCode::NOT_FOUND, e.to_string())),
- // `{:#}` keeps the context chain ("starting `npx …`: No such file or directory").
- Err(e) => Err(ApiError(StatusCode::BAD_REQUEST, format!("{e:#}"))),
+ let body = if body.is_empty() {
+ Value::Null
+ } else {
+ serde_json::from_slice(&body).map_err(|e| ApiError(StatusCode::BAD_REQUEST, format!("invalid JSON: {e}")))?
+ };
+ dispatch(&hub, &Caller::Local, &method, body).await.map(Json).map_err(|e| {
+ let (status, message) = error_status(&e);
+ ApiError(status, message)
+ })
+}
+
+#[derive(Deserialize)]
+struct ChannelQuery {
+ v: Option<u32>,
+}
+
+/// `GET /channel?v=1`: the direct E2E channel. No bearer token: the handshake authenticates.
+async fn channel(
+ State(hub): State<Arc<Hub>>,
+ ConnectInfo(peer): ConnectInfo<SocketAddr>,
+ Query(q): Query<ChannelQuery>,
+ ws: WebSocketUpgrade,
+) -> Response {
+ if q.v != Some(1) {
+ return (StatusCode::UPGRADE_REQUIRED, Json(json!({"error": {"code": "upgradeRequired"}}))).into_response();
}
+ ws.max_message_size(crate::channel::MAX_WS_MESSAGE)
+ .on_upgrade(move |socket| crate::channel::serve_direct(hub, socket, peer.ip()))
}
fn str_arg<'a>(b: &'a Value, k: &str) -> Result<&'a str> {
b[k].as_str().ok_or_else(|| anyhow!("`{k}` is required"))
}
-pub async fn dispatch(hub: &Arc<Hub>, method: &str, b: Value) -> Result<Value> {
+/// Runs one API method for `caller` (permissions per spec §6.6).
+pub async fn dispatch(hub: &Arc<Hub>, caller: &Caller, method: &str, b: Value) -> Result<Value> {
+ crate::devices::permit(caller, method)?;
Ok(match method {
"hello" => {
let port = hub.port;
json!({
"hostId": hub.host_id,
+ "computerId": hub.identity.computer_id(),
+ "signKey": hub.identity.sign_pub_b64(),
+ "boxKey": hub.identity.box_pub_b64(),
+ "protocol": 1,
+ "cloud": crate::cloud::url(&hub.store),
"name": crate::service::host_name(),
"version": env!("CARGO_PKG_VERSION"),
"os": std::env::consts::OS,
@@ -197,17 +263,16 @@ pub async fn dispatch(hub: &Arc<Hub>, method: &str, b: Value) -> Result<Value> {
if let Some(relay) = b["relay"].as_str().filter(|r| r.starts_with("https://")) {
hub.store.kv_set("relay_url", relay.trim_end_matches('/'))?;
}
- hub.store.add_device(ticket, b["name"].as_str().unwrap_or("iPhone"))?;
+ let push_key = b["pushKey"].as_str();
+ if let Some(k) = push_key {
+ crypto::unb64_n::<32>(k).context("`pushKey` must be a 32-byte X25519 key")?;
+ }
+ let name = b["name"].as_str().unwrap_or("iPhone");
+ hub.store.add_push_ticket(ticket, caller.device_key(), push_key, b["ctx"].as_str(), name)?;
json!({})
}
"registerActivity" => {
- let bot = str_arg(&b, "botId")?.to_owned();
- let ticket = str_arg(&b, "ticket")?.to_owned();
- let mut map = hub.activities.locked();
- let list = map.entry(bot).or_default();
- if !list.contains(&ticket) {
- list.push(ticket);
- }
+ hub.store.add_activity_ticket(str_arg(&b, "ticket")?, str_arg(&b, "botId")?, caller.device_key())?;
json!({})
}
"refreshBackends" => {
@@ -225,18 +290,46 @@ pub async fn dispatch(hub: &Arc<Hub>, method: &str, b: Value) -> Result<Value> {
let path = b["path"].as_str().map(std::path::PathBuf::from);
tokio::task::spawn_blocking(move || list_dirs(path)).await??
}
- "pairing" => {
- let port = hub.port;
- // Shells out to `tailscale`: keep it off the async workers.
- let urls = tokio::task::spawn_blocking(move || crate::service::addresses(port)).await?;
- let url = crate::service::pairing_url(&crate::service::host_name(), &hub.token, &urls);
- let svg = qrcode::QrCode::new(url.as_bytes())?
- .render::<qrcode::render::svg::Color>()
- .quiet_zone(false)
- .min_dimensions(200, 200)
- .build();
- json!({"pairingUrl": url, "urls": urls, "svg": svg})
+ "pairing" => pairing(hub).await?,
+ "devices" => {
+ let connected = hub.connected.locked().clone();
+ let devices: Vec<Value> = hub
+ .store
+ .devices()?
+ .into_iter()
+ .map(|d| {
+ let mut v = serde_json::to_value(&d).expect("Device is plain data and always serializes");
+ v["connected"] = connected.contains_key(&d.key).into();
+ v
+ })
+ .collect();
+ json!({"devices": devices})
+ }
+ "revokeDevice" => {
+ let key = str_arg(&b, "key")?;
+ let device = hub.store.device(key).ok_or_else(|| anyhow!("unknown device"))?;
+ hub.revoke_device(key)?;
+ if let Some(grant) = device.grant_id.filter(|_| device.source == DeviceSource::Account) {
+ tokio::spawn(crate::cloud::revoke_grant(hub.clone(), grant));
+ }
+ json!({})
}
+ "accessRequests" => json!({"requests": hub.cloud.requests_json()}),
+ "decideAccessRequest" => {
+ let approve = b["approve"].as_bool().ok_or_else(|| anyhow!("`approve` is required"))?;
+ crate::cloud::decide(hub, str_arg(&b, "requestId")?, approve).await?;
+ json!({})
+ }
+ "unclaim" => {
+ crate::cloud::unclaim(hub).await?;
+ json!({})
+ }
+ "cloudStatus" => serde_json::to_value(hub.cloud.status())?,
+ "setCloud" => {
+ let enabled = b["enabled"].as_bool().ok_or_else(|| anyhow!("`enabled` is required"))?;
+ serde_json::to_value(crate::cloud::set_cloud(hub, enabled, b["url"].as_str())?)?
+ }
+ "claimSign" => claim_sign(hub, &b).await?,
"marketConnectors" => market::browse_connectors(&hub.store, b["search"].as_str().unwrap_or_default()).await?,
"marketSkills" => market::browse_skills(&hub.store).await?,
"connectors" => market::list_connectors(&hub.store),
@@ -357,22 +450,9 @@ fn term_size(b: &Value) -> (u16, u16) {
(dim("cols", 80), dim("rows", 24))
}
-#[derive(Deserialize)]
-struct TokenQuery {
- token: Option<String>,
-}
-
/// A setup terminal's output: everything so far, then live, ending after `exit`.
-async fn term_stream(
- State(hub): State<Arc<Hub>>,
- Path(id): Path<String>,
- headers: HeaderMap,
- Query(q): Query<TokenQuery>,
-) -> Result<Sse<impl Stream<Item = Result<Event, Infallible>>>, ApiError> {
- if !authorized(&hub, &headers, q.token.as_deref()) {
- return Err(ApiError(StatusCode::UNAUTHORIZED, "invalid token".into()));
- }
- let term = hub.terms.get(&id).ok_or_else(|| ApiError(StatusCode::NOT_FOUND, "that terminal is gone".into()))?;
+pub fn term_events(hub: &Hub, id: &str) -> Option<impl Stream<Item = Value> + Send + use<>> {
+ let term = hub.terms.get(id)?;
let (head, rx) = term.attach();
let done = head.iter().any(|v| v["type"] == "exit");
let live = BroadcastStream::new(rx).filter_map(|msg| async move { msg.ok() }).scan(done, |done, v| {
@@ -382,14 +462,27 @@ async fn term_stream(
});
async move { out }
});
- let events = stream::iter(head).chain(live).map(|v| Ok(Event::default().data(v.to_string())));
+ Some(stream::iter(head).chain(live))
+}
+
+async fn term_stream(
+ State(hub): State<Arc<Hub>>,
+ Path(id): Path<String>,
+ ConnectInfo(peer): ConnectInfo<SocketAddr>,
+ headers: HeaderMap,
+) -> Result<Sse<impl Stream<Item = Result<Event, Infallible>>>, ApiError> {
+ if !authorized(&hub, &headers, peer) {
+ return Err(unauthorized());
+ }
+ let events =
+ term_events(&hub, &id).ok_or_else(|| ApiError(StatusCode::NOT_FOUND, "that terminal is gone".into()))?;
+ let events = events.map(|v| Ok(Event::default().data(v.to_string())));
Ok(Sse::new(events).keep_alive(KeepAlive::new().interval(Duration::from_secs(15))))
}
#[derive(Deserialize)]
struct EventsQuery {
since: Option<i64>,
- token: Option<String>,
client: Option<String>,
}
@@ -409,50 +502,133 @@ impl Drop for IosClientGuard {
}
}
-/// Subscribes first, then sends a catch-up (everything after `since`, in rev
-/// order), then live events. Duplicates are fine: clients upsert by id/rev.
-async fn events(
- State(hub): State<Arc<Hub>>,
- headers: HeaderMap,
- Query(q): Query<EventsQuery>,
-) -> Result<Sse<impl Stream<Item = Result<Event, Infallible>>>, ApiError> {
- if !authorized(&hub, &headers, q.token.as_deref()) {
- return Err(ApiError(StatusCode::UNAUTHORIZED, "invalid token".into()));
- }
+/// Event types only this computer's own apps receive.
+const LOCAL_EVENTS: &[&str] = &["accessRequests", "cloud"];
+
+/// Subscribes first, then yields a catch-up (everything after `since`, in rev order),
+/// then live events. Duplicates are fine: clients upsert by id/rev. Shared by SSE and channels.
+pub fn events_stream(
+ hub: &Arc<Hub>,
+ since: i64,
+ client: Option<&str>,
+ caller: &Caller,
+) -> Result<impl Stream<Item = Value> + Send + use<>> {
let live = BroadcastStream::new(hub.events.subscribe());
- let since = q.since.unwrap_or(0);
let mut catch_up: Vec<Value> = vec![];
- for bot in hub.bots_json(since).map_err(|e| ApiError(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))? {
+ for bot in hub.bots_json(since)? {
catch_up.push(json!({"type": "bot", "rev": bot["rev"], "bot": bot}));
}
- let entries = hub
- .store
- .entries_since(since, CATCH_UP_PER_BOT)
- .map_err(|e| ApiError(StatusCode::INTERNAL_SERVER_ERROR, format!("{e:#}")))?;
- for e in entries {
+ for e in hub.store.entries_since(since, CATCH_UP_PER_BOT)? {
catch_up.push(json!({"type": "entry", "rev": e.rev, "entry": e}));
}
catch_up.sort_by_key(|v| v["rev"].as_i64().unwrap_or(0));
let hello = json!({
"type": "hello",
"hostId": hub.host_id,
+ "computerId": hub.identity.computer_id(),
"rev": hub.store.current_rev(),
"usage": hub.usage.locked().clone(),
"screen": hub.screen.state(),
});
catch_up.insert(0, hello);
- let guard = Arc::new((q.client.as_deref() == Some("ios")).then(|| IosClientGuard::new(hub.clone())));
- let head = stream::iter(catch_up.into_iter().map(|v| Ok(Event::default().data(v.to_string()))));
+ let local = matches!(caller, Caller::Local);
+ let guard = Arc::new((client == Some("ios")).then(|| IosClientGuard::new(hub.clone())));
let tail = live.filter_map(move |msg| {
let _keep = guard.clone();
async move {
match msg {
- Ok(v) => Some(Ok(Event::default().data(v.to_string()))),
+ Ok(v) if !local && v["type"].as_str().is_some_and(|t| LOCAL_EVENTS.contains(&t)) => None,
+ Ok(v) => Some(v),
// Lagged: tell the client to resync from its last rev.
- Err(_) => Some(Ok(Event::default().data(json!({"type": "resync"}).to_string()))),
+ Err(_) => Some(json!({"type": "resync"})),
}
}
});
- Ok(Sse::new(head.chain(tail)).keep_alive(KeepAlive::new().interval(Duration::from_secs(15))))
+ Ok(stream::iter(catch_up).chain(tail))
+}
+
+async fn events(
+ State(hub): State<Arc<Hub>>,
+ ConnectInfo(peer): ConnectInfo<SocketAddr>,
+ headers: HeaderMap,
+ Query(q): Query<EventsQuery>,
+) -> Result<Sse<impl Stream<Item = Result<Event, Infallible>>>, ApiError> {
+ if !authorized(&hub, &headers, peer) {
+ return Err(unauthorized());
+ }
+ let events = events_stream(&hub, q.since.unwrap_or(0), q.client.as_deref(), &Caller::Local)
+ .map_err(|e| ApiError(StatusCode::INTERNAL_SERVER_ERROR, format!("{e:#}")))?;
+ let events = events.map(|v| Ok(Event::default().data(v.to_string())));
+ Ok(Sse::new(events).keep_alive(KeepAlive::new().interval(Duration::from_secs(15))))
+}
+
+/// A new one-time pairing code and the QR that carries it (§4.1).
+async fn pairing(hub: &Arc<Hub>) -> Result<Value> {
+ let port = hub.port;
+ // Shells out to `tailscale`: keep it off the async workers.
+ let urls = tokio::task::spawn_blocking(move || crate::service::addresses(port)).await?;
+ let cloud = crate::cloud::url(&hub.store);
+ if urls.is_empty() && cloud.is_none() {
+ bail!("No network address a phone could reach, and the Codync cloud is off.");
+ }
+ let issued = hub.pairing.locked().issue();
+ hub.auth_changed();
+ let url = crate::service::pairing_url(&crate::service::PairingQr {
+ name: &crate::service::host_name(),
+ computer_id: &hub.identity.computer_id(),
+ sign_key: &hub.identity.sign_pub_b64(),
+ box_key: &hub.identity.box_pub_b64(),
+ code: &issued.code,
+ urls: &urls,
+ cloud: cloud.as_deref(),
+ });
+ let svg = qrcode::QrCode::new(url.as_bytes())?
+ .render::<qrcode::render::svg::Color>()
+ .quiet_zone(false)
+ .min_dimensions(200, 200)
+ .build();
+ Ok(json!({"pairingUrl": url, "urls": urls, "svg": svg, "expiresAt": issued.expires_at}))
+}
+
+/// Signs this computer into an account claim (§4.2 A) for the signed-in Mac app to complete.
+async fn claim_sign(hub: &Arc<Hub>, b: &Value) -> Result<Value> {
+ 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 {
+ use super::*;
+
+ #[test]
+ fn only_loopback_counts_as_this_computer() {
+ let ip = |s: &str| s.parse::<IpAddr>().expect("test addresses are valid");
+ assert!(is_loopback(ip("127.0.0.1")));
+ assert!(is_loopback(ip("::1")));
+ assert!(is_loopback(ip("::ffff:127.0.0.1")), "IPv4 loopback seen through `--bind ::`");
+ assert!(!is_loopback(ip("192.168.1.20")));
+ assert!(!is_loopback(ip("::ffff:192.168.1.20")));
+ assert!(!is_loopback(ip("100.101.102.103")));
+ }
}
diff --git a/host/src/channel.rs b/host/src/channel.rs
new file mode 100644
index 00000000..00b92536
--- /dev/null
+++ b/host/src/channel.rs
@@ -0,0 +1,915 @@
+//! The end-to-end encrypted channel between a device and this host (spec §6.1–§6.6,
+//! §9.5), independent of how it travels: a direct WebSocket (`GET /channel`, served
+//! here) or a relay link (the relay client feeds a [`Transport`] per link).
+//!
+//! Flow: `hello` → checks (cheap first) → `welcome` → encrypted frames carrying the
+//! inner RPC: requests run through [`api::dispatch`] (responses may come back out of
+//! order), `sub` streams events or a setup terminal, `cancel` ends either.
+//! The device's authorization is re-checked on every request, whenever the device
+//! table changes and when its lease runs out; a revoked device is closed at once.
+
+use crate::LockExt;
+use crate::api;
+use crate::crypto::{self, FrameError, Opener, Sealer};
+use crate::devices::{self, Caller, RejectCode};
+use crate::hub::Hub;
+use crate::store::{Device, DeviceSource, Scope, now_ms};
+use axum::extract::ws::{CloseFrame, Message, WebSocket};
+use futures::{SinkExt as _, StreamExt as _};
+use serde_json::{Value, json};
+use std::collections::HashMap;
+use std::net::IpAddr;
+use std::sync::{Arc, Mutex};
+use std::time::Duration;
+use tokio::sync::mpsc;
+use tokio::task::AbortHandle;
+use tokio::time::{Instant, sleep_until, timeout};
+use x25519_dalek::StaticSecret;
+
+/// Largest WebSocket message accepted (and the Cloudflare limit); 256 KiB chunks fit.
+pub const MAX_WS_MESSAGE: usize = 1 << 20;
+/// Largest reassembled device → host message.
+const MAX_INBOUND: usize = 1 << 20;
+const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10);
+/// Channel keys are replaced (close `4011`) after this long.
+const MAX_AGE: Duration = Duration::from_secs(24 * 60 * 60);
+/// A pairing channel only lives long enough to redeem its code.
+const PAIRING_MAX_AGE: Duration = Duration::from_secs(120);
+const DIRECT_PING: Duration = Duration::from_secs(15);
+const MAX_REQUESTS: usize = 32;
+const MAX_SUBS: usize = 4;
+
+/// WebSocket close codes (§7.6).
+mod close {
+ pub const NORMAL: u16 = 1000;
+ pub const TIMEOUT: u16 = 1011;
+ pub const UNAUTHORIZED: u16 = 4001;
+ pub const PROTOCOL: u16 = 4002;
+ pub const REKEY: u16 = 4011;
+ pub const TOO_LARGE: u16 = 4013;
+ pub const PAIRED: u16 = 4100;
+ pub const PAIRING_EXPIRED: u16 = 4410;
+}
+
+/// Something to put on the wire.
+#[derive(Debug)]
+pub enum Out {
+ /// A plaintext channel message (`welcome`, `reject`, `f`).
+ Msg(Value),
+ /// Close with this code and reason; nothing follows.
+ Close(u16, &'static str),
+}
+
+/// One channel's wire, whatever carries it. `incoming` yields the device's channel
+/// messages (`Value::Null` for anything that isn't a JSON text message) and ends when
+/// the device is gone.
+pub struct Transport {
+ pub incoming: mpsc::Receiver<Value>,
+ pub outgoing: mpsc::Sender<Out>,
+}
+
+pub enum ChannelKind {
+ Direct {
+ peer: IpAddr,
+ },
+ /// A relay link, with what the relay's `open` said about it.
+ Relay {
+ link: String,
+ dk: String,
+ pair: bool,
+ },
+}
+
+impl ChannelKind {
+ /// Where pairing attempts are counted from.
+ fn source(&self) -> String {
+ match self {
+ Self::Direct { peer } => peer.to_canonical().to_string(),
+ Self::Relay { link, .. } => format!("link:{link}"),
+ }
+ }
+}
+
+/// Serves `GET /channel` after the WebSocket upgrade.
+pub async fn serve_direct(hub: Arc<Hub>, socket: WebSocket, peer: IpAddr) {
+ let (mut sink, mut stream) = socket.split();
+ let (in_tx, incoming) = mpsc::channel(64);
+ let (outgoing, mut out_rx) = mpsc::channel::<Out>(64);
+ let reader = tokio::spawn(async move {
+ while let Some(Ok(msg)) = stream.next().await {
+ let v = match msg {
+ Message::Text(t) => serde_json::from_str(t.as_str()).unwrap_or(Value::Null),
+ Message::Binary(_) => Value::Null,
+ Message::Close(_) => break,
+ Message::Ping(_) | Message::Pong(_) => continue,
+ };
+ if in_tx.send(v).await.is_err() {
+ break;
+ }
+ }
+ });
+ let writer = tokio::spawn(async move {
+ let mut ping = tokio::time::interval(DIRECT_PING);
+ ping.tick().await;
+ loop {
+ tokio::select! {
+ out = out_rx.recv() => {
+ let msg = match out {
+ Some(Out::Msg(v)) => Message::Text(v.to_string().into()),
+ Some(Out::Close(code, reason)) => Message::Close(Some(CloseFrame { code, reason: reason.into() })),
+ None => Message::Close(None),
+ };
+ let last = matches!(msg, Message::Close(_));
+ if sink.send(msg).await.is_err() || last {
+ break;
+ }
+ }
+ _ = ping.tick() => {
+ if sink.send(Message::Ping(axum::body::Bytes::new())).await.is_err() {
+ break;
+ }
+ }
+ }
+ }
+ });
+ run(hub, Transport { incoming, outgoing }, ChannelKind::Direct { peer }).await;
+ let _ = writer.await;
+ reader.abort();
+}
+
+/// What the encrypted part of the channel sends: inner messages get sealed, the rest passes.
+enum ToDevice {
+ Inner(Value),
+ Plain(Value),
+ Close(u16, &'static str),
+}
+
+/// Owns the host → device counter: seals inner messages in order, stops at the first close.
+async fn write_frames(mut sealer: Sealer, mut rx: mpsc::Receiver<ToDevice>, out: mpsc::Sender<Out>) {
+ while let Some(msg) = rx.recv().await {
+ let sent = match msg {
+ ToDevice::Plain(v) => out.send(Out::Msg(v)).await.is_ok(),
+ ToDevice::Close(code, reason) => {
+ let _ = out.send(Out::Close(code, reason)).await;
+ return;
+ }
+ ToDevice::Inner(v) => {
+ let Some(frames) = sealer.seal(v.to_string().as_bytes()) else {
+ let _ = out.send(Out::Close(close::REKEY, "rekey")).await;
+ return;
+ };
+ let mut ok = true;
+ for f in frames {
+ ok = ok && out.send(Out::Msg(f)).await.is_ok();
+ }
+ ok
+ }
+ };
+ if !sent {
+ return;
+ }
+ }
+}
+
+/// Runs one channel to its end.
+pub async fn run(hub: Arc<Hub>, t: Transport, kind: ChannelKind) {
+ let Transport { mut incoming, outgoing } = t;
+ let Some(hs) = handshake(&hub, &mut incoming, &outgoing, &kind).await else { return };
+ let (tx, rx) = mpsc::channel(256);
+ let mut writer = tokio::spawn(write_frames(Sealer::new(hs.keys.h2d), rx, outgoing));
+ let mut ch = Channel {
+ hub,
+ tx,
+ jobs: Arc::default(),
+ key: hs.key,
+ caller: Arc::new(Caller::Local),
+ lease: None,
+ online: None,
+ };
+ let opener = Opener::new(hs.keys.d2h, MAX_INBOUND);
+ let (code, reason) = if let Some(d) = hs.device {
+ ch.set_device(&d);
+ ch.serve(&mut incoming, opener, &mut writer).await
+ } else {
+ ch.caller = Arc::new(Caller::Pairing { key: ch.key.clone() });
+ ch.pair(&mut incoming, opener, &kind.source()).await
+ };
+ for job in ch.jobs.locked().drain() {
+ if let (_, Job::Sub(h)) = job {
+ h.abort();
+ }
+ }
+ let _ = ch.tx.send(ToDevice::Close(code, reason)).await;
+ let hub = ch.hub.clone();
+ drop(ch);
+ let _ = writer.await;
+ // Only now, with the answer and the `4100` handed to the transport: a relay publishes the
+ // new ACL (offer gone) behind them on the same socket, so the pairing link isn't cut first.
+ if code == close::PAIRED {
+ hub.auth_changed();
+ }
+}
+
+struct Handshake {
+ key: String,
+ keys: crypto::Keys,
+ /// `None` for a pairing channel.
+ device: Option<Device>,
+}
+
+async fn send_reject(out: &mpsc::Sender<Out>, code: RejectCode) {
+ let _ = out.send(Out::Msg(json!({"t": "reject", "code": code, "message": code.message()}))).await;
+ let _ = out.send(Out::Close(code.close_code(), "rejected")).await;
+}
+
+async fn handshake(
+ hub: &Hub,
+ incoming: &mut mpsc::Receiver<Value>,
+ out: &mpsc::Sender<Out>,
+ kind: &ChannelKind,
+) -> Option<Handshake> {
+ let protocol_error = async || {
+ let _ = out.send(Out::Close(close::PROTOCOL, "protocolError")).await;
+ };
+ let hello = match timeout(HANDSHAKE_TIMEOUT, incoming.recv()).await {
+ Ok(Some(v)) => v,
+ Ok(None) => return None,
+ Err(_) => {
+ let _ = out.send(Out::Close(close::TIMEOUT, "no hello")).await;
+ return None;
+ }
+ };
+ let dk = hello["dk"].as_str().unwrap_or_default().to_owned();
+ let Ok(dk_raw) = crypto::unb64_n::<32>(&dk) else {
+ protocol_error().await;
+ return None;
+ };
+ if hello["t"] != "hello" {
+ protocol_error().await;
+ return None;
+ }
+ if hello["v"] != 1 {
+ send_reject(out, RejectCode::UnsupportedVersion).await;
+ return None;
+ }
+ let pair = hello["pair"].as_bool().unwrap_or(false);
+ if let ChannelKind::Relay { dk: open_dk, pair: open_pair, .. } = kind
+ && (*open_dk != dk || *open_pair != pair)
+ {
+ protocol_error().await;
+ return None;
+ }
+ // Authorization before any cryptography.
+ let device = if pair {
+ if !hub.pairing.locked().open() {
+ send_reject(out, RejectCode::PairingClosed).await;
+ return None;
+ }
+ None
+ } else {
+ match devices::authorize(hub, &dk) {
+ Ok(d) => Some(d),
+ Err(code) => {
+ send_reject(out, code).await;
+ return None;
+ }
+ }
+ };
+ let field = |k: &str| hello[k].as_str().unwrap_or_default();
+ let (Ok(ek_d), Ok(n), Ok(sig)) =
+ (crypto::unb64_n::<32>(field("ek")), crypto::unb64_n::<32>(field("n")), crypto::unb64_n::<64>(field("sig")))
+ else {
+ protocol_error().await;
+ return None;
+ };
+ let cid = hub.identity.cid_raw();
+ if crypto::verify(&dk_raw, &crypto::hs1_input(&cid, &dk_raw, &ek_d, &n), &sig).is_err() {
+ send_reject(out, RejectCode::BadSignature).await;
+ return None;
+ }
+ let ek_h = StaticSecret::from(crypto::random::<32>());
+ let ek_h_pub = crypto::x25519_pub(&ek_h);
+ let Ok(shared) = crypto::x25519(&ek_h, &ek_d) else {
+ protocol_error().await;
+ return None;
+ };
+ let th = crypto::transcript_hash(&cid, &dk_raw, &ek_d, &n, &ek_h_pub);
+ let welcome =
+ json!({"t": "welcome", "v": 1, "ek": crypto::b64(&ek_h_pub), "sig": crypto::b64(&hub.identity.sign(&th))});
+ if out.send(Out::Msg(welcome)).await.is_err() {
+ return None;
+ }
+ Some(Handshake { key: dk, keys: crypto::channel_keys(&shared, &th), device })
+}
+
+enum Job {
+ Request,
+ Sub(AbortHandle),
+}
+
+/// Marks a device connected while it has a live channel.
+struct Online(Arc<Hub>, String);
+
+impl Online {
+ fn new(hub: Arc<Hub>, key: String) -> Self {
+ *hub.connected.locked().entry(key.clone()).or_default() += 1;
+ if let Err(error) = hub.store.touch_device(&key) {
+ tracing::warn!(error = format!("{error:#}"), "couldn't record when a device was last seen");
+ }
+ Self(hub, key)
+ }
+}
+
+impl Drop for Online {
+ fn drop(&mut self) {
+ let mut map = self.0.connected.locked();
+ if let Some(n) = map.get_mut(&self.1) {
+ *n -= 1;
+ if *n == 0 {
+ map.remove(&self.1);
+ }
+ }
+ }
+}
+
+struct Channel {
+ hub: Arc<Hub>,
+ tx: mpsc::Sender<ToDevice>,
+ jobs: Arc<Mutex<HashMap<u64, Job>>>,
+ key: String,
+ caller: Arc<Caller>,
+ lease: Option<Instant>,
+ online: Option<Online>,
+}
+
+type CloseWith = (u16, &'static str);
+
+fn frame_close(e: &FrameError) -> CloseWith {
+ match e {
+ FrameError::Protocol => (close::PROTOCOL, "protocolError"),
+ FrameError::TooLarge => (close::TOO_LARGE, "tooLarge"),
+ FrameError::Rekey => (close::REKEY, "rekey"),
+ }
+}
+
+fn err(id: u64, status: u16, message: &str) -> Value {
+ json!({"id": id, "err": {"status": status, "message": message}})
+}
+
+impl Channel {
+ fn set_device(&mut self, d: &Device) {
+ self.caller = Arc::new(Caller::Device { key: d.key.clone(), scopes: d.scopes.clone() });
+ self.lease = match (d.source, d.lease_until) {
+ (DeviceSource::Account, Some(until)) => {
+ let left = u64::try_from(until - now_ms()).unwrap_or(0) + 1;
+ Some(Instant::now() + Duration::from_millis(left))
+ }
+ _ => None,
+ };
+ }
+
+ async fn send(&self, v: Value) {
+ let _ = self.tx.send(ToDevice::Inner(v)).await;
+ }
+
+ /// Re-checks the device; on failure sends `reject` and says how to close.
+ async fn recheck(&mut self) -> Result<(), CloseWith> {
+ match devices::authorize(&self.hub, &self.key) {
+ Ok(d) => {
+ self.set_device(&d);
+ Ok(())
+ }
+ Err(code) => {
+ // 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"))
+ }
+ }
+ }
+
+ async fn serve(
+ &mut self,
+ incoming: &mut mpsc::Receiver<Value>,
+ mut opener: Opener,
+ writer: &mut tokio::task::JoinHandle<()>,
+ ) -> CloseWith {
+ let mut auth = self.hub.auth.subscribe();
+ let rekey_at = Instant::now() + MAX_AGE;
+ loop {
+ let lease = self.lease;
+ tokio::select! {
+ msg = incoming.recv() => {
+ let Some(msg) = msg else { return (close::NORMAL, "") };
+ let message = match opener.open(&msg) {
+ Ok(m) => m,
+ Err(e) => return frame_close(&e),
+ };
+ if self.online.is_none() {
+ self.online = Some(Online::new(self.hub.clone(), self.key.clone()));
+ }
+ if let Some(bytes) = message
+ && let Err(close) = self.handle(&bytes).await
+ {
+ return close;
+ }
+ }
+ changed = auth.changed() => {
+ if changed.is_err() {
+ return (close::NORMAL, "");
+ }
+ if let Err(close) = self.recheck().await {
+ return close;
+ }
+ }
+ () = sleep_until(lease.unwrap_or(rekey_at)), if lease.is_some() => {
+ if let Err(close) = self.recheck().await {
+ return close;
+ }
+ }
+ () = sleep_until(rekey_at) => return (close::REKEY, "rekey"),
+ _ = &mut *writer => return (close::NORMAL, ""),
+ }
+ }
+ }
+
+ /// One inner message from an authorized device.
+ async fn handle(&mut self, bytes: &[u8]) -> Result<(), CloseWith> {
+ let protocol = (close::PROTOCOL, "protocolError");
+ let v: Value = serde_json::from_slice(bytes).map_err(|_| protocol)?;
+ let id = v["id"].as_u64().filter(|id| u32::try_from(*id).is_ok()).ok_or(protocol)?;
+ if v["cancel"] == true {
+ self.cancel(id).await;
+ return Ok(());
+ }
+ if self.jobs.locked().contains_key(&id) {
+ self.send(err(id, 400, "that id is already in use")).await;
+ return Ok(());
+ }
+ // Every request re-checks the device (revocation, lease) before it runs.
+ self.recheck().await?;
+ if let Some(kind) = v["sub"].as_str() {
+ self.subscribe(id, kind, &v["b"]).await;
+ } else if let Some(method) = v["m"].as_str() {
+ self.request(id, method.to_owned(), v["b"].clone()).await;
+ } else {
+ return Err(protocol);
+ }
+ Ok(())
+ }
+
+ fn count(&self, subs: bool) -> usize {
+ self.jobs.locked().values().filter(|j| matches!(j, Job::Sub(_)) == subs).count()
+ }
+
+ async fn request(&self, id: u64, method: String, b: Value) {
+ if self.count(false) >= MAX_REQUESTS {
+ self.send(err(id, 429, "too many requests in flight")).await;
+ return;
+ }
+ self.jobs.locked().insert(id, Job::Request);
+ let (hub, caller, jobs, tx) = (self.hub.clone(), self.caller.clone(), self.jobs.clone(), self.tx.clone());
+ tokio::spawn(async move {
+ let reply = match api::dispatch(&hub, &caller, &method, b).await {
+ Ok(ok) => json!({"id": id, "ok": ok}),
+ Err(e) => {
+ let (status, message) = api::error_status(&e);
+ err(id, status.as_u16(), &message)
+ }
+ };
+ // Cancelled: the work is done (never aborted midway), the answer is dropped.
+ if jobs.locked().remove(&id).is_some() {
+ let _ = tx.send(ToDevice::Inner(reply)).await;
+ }
+ });
+ }
+
+ async fn subscribe(&self, id: u64, kind: &str, b: &Value) {
+ if self.count(true) >= MAX_SUBS {
+ self.send(err(id, 429, "too many subscriptions")).await;
+ return;
+ }
+ let stream = match kind {
+ "events" => match api::events_stream(
+ &self.hub,
+ b["since"].as_i64().unwrap_or(0),
+ b["client"].as_str(),
+ &self.caller,
+ ) {
+ Ok(s) => s.boxed(),
+ Err(e) => {
+ self.send(err(id, 500, &format!("{e:#}"))).await;
+ return;
+ }
+ },
+ "term" => {
+ let Some(s) = api::term_events(&self.hub, b["term"].as_str().unwrap_or_default()) else {
+ self.send(err(id, 404, "that terminal is gone")).await;
+ return;
+ };
+ s.boxed()
+ }
+ _ => {
+ self.send(err(id, 400, "unknown subscription")).await;
+ return;
+ }
+ };
+ let (jobs, tx) = (self.jobs.clone(), self.tx.clone());
+ // Held while spawning so the task can't finish (and remove itself) before it's listed.
+ let mut list = self.jobs.locked();
+ let task = tokio::spawn(async move {
+ let mut stream = stream;
+ while let Some(ev) = stream.next().await {
+ if tx.send(ToDevice::Inner(json!({"id": id, "ev": ev}))).await.is_err() {
+ return;
+ }
+ }
+ if jobs.locked().remove(&id).is_some() {
+ let _ = tx.send(ToDevice::Inner(json!({"id": id, "end": true}))).await;
+ }
+ });
+ list.insert(id, Job::Sub(task.abort_handle()));
+ }
+
+ async fn cancel(&self, id: u64) {
+ let job = self.jobs.locked().remove(&id);
+ if let Some(Job::Sub(h)) = job {
+ h.abort();
+ self.send(json!({"id": id, "end": true})).await;
+ }
+ }
+
+ /// A pairing channel: exactly one `pair`, answered, then closed with `4100` (§4.1).
+ async fn pair(&mut self, incoming: &mut mpsc::Receiver<Value>, mut 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 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"));
+ let (Some(name), Some(platform)) = (name, platform) else {
+ self.send(err(id, 400, "`name` and `platform` (ios or macos) are required")).await;
+ return protocol;
+ };
+ if !self.hub.pairing.locked().attempt(source) {
+ let code = RejectCode::RateLimited;
+ let _ =
+ self.tx.send(ToDevice::Plain(json!({"t": "reject", "code": code, "message": code.message()}))).await;
+ return (code.close_code(), "rateLimited");
+ }
+ 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");
+ }
+ let device = Device {
+ key: self.key.clone(),
+ name: name.to_owned(),
+ platform: platform.to_owned(),
+ source: DeviceSource::Local,
+ grant_id: None,
+ scopes: vec![Scope::Control, Scope::Screen],
+ lease_until: None,
+ created_at: now_ms(),
+ last_seen_at: None,
+ };
+ if let Err(e) = self.hub.store.put_device(&device) {
+ tracing::error!(error = format!("{e:#}"), "couldn't save a paired device");
+ self.send(err(id, 500, "couldn't save this device")).await;
+ return (close::NORMAL, "");
+ }
+ tracing::info!(device = self.key, platform, "device paired");
+ let name = crate::service::host_name();
+ self.send(json!({"id": id, "ok": {"computerId": self.hub.identity.computer_id(), "name": name}})).await;
+ (close::PAIRED, "paired")
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ #![allow(clippy::unwrap_used, clippy::expect_used)]
+ use super::*;
+ use crate::identity::Identity;
+ use crate::store::Store;
+ use ed25519_dalek::SigningKey;
+
+ fn temp_hub() -> Arc<Hub> {
+ let dir = std::env::temp_dir().join(format!("codync-ch-{}", uuid::Uuid::new_v4()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let store = Store::open(&dir.join("t.db")).unwrap();
+ let identity = Identity::load_or_create(&dir).unwrap();
+ Hub::new(store, "host".into(), identity, "token".into(), 0)
+ }
+
+ /// The device end of a channel, over in-memory pipes.
+ struct Phone {
+ key: SigningKey,
+ tx: mpsc::Sender<Value>,
+ rx: mpsc::Receiver<Out>,
+ sealer: Option<Sealer>,
+ opener: Option<Opener>,
+ }
+
+ impl Phone {
+ fn connect(hub: &Arc<Hub>, key: SigningKey, kind: ChannelKind) -> Self {
+ let (tx, incoming) = mpsc::channel(64);
+ let (outgoing, rx) = mpsc::channel(64);
+ tokio::spawn(run(hub.clone(), Transport { incoming, outgoing }, kind));
+ Self { key, tx, rx, sealer: None, opener: None }
+ }
+
+ fn direct(hub: &Arc<Hub>, key: SigningKey) -> Self {
+ Self::connect(hub, key, ChannelKind::Direct { peer: IpAddr::from([10, 0, 0, 2]) })
+ }
+
+ fn dk(&self) -> String {
+ crypto::b64(self.key.verifying_key().as_bytes())
+ }
+
+ async fn next(&mut self) -> Out {
+ timeout(Duration::from_secs(5), self.rx.recv()).await.expect("host answers in time").expect("still open")
+ }
+
+ async fn hello(&mut self, hub: &Hub, pair: bool) -> Out {
+ let ek = StaticSecret::from(crypto::random::<32>());
+ let ek_pub = crypto::x25519_pub(&ek);
+ let n = crypto::random::<32>();
+ let dk = self.key.verifying_key().to_bytes();
+ let cid = hub.identity.cid_raw();
+ let sig = crypto::sign(&self.key, &crypto::hs1_input(&cid, &dk, &ek_pub, &n));
+ let hello = json!({"t": "hello", "v": 1, "dk": self.dk(), "ek": crypto::b64(&ek_pub),
+ "n": crypto::b64(&n), "sig": crypto::b64(&sig), "pair": pair});
+ self.tx.send(hello).await.unwrap();
+ let out = self.next().await;
+ if let Out::Msg(w) = &out
+ && w["t"] == "welcome"
+ {
+ let ek_h: [u8; 32] = crypto::unb64_n(w["ek"].as_str().unwrap()).unwrap();
+ let th = crypto::transcript_hash(&cid, &dk, &ek_pub, &n, &ek_h);
+ crypto::verify(&hub.identity.sign_pub(), &th, &crypto::unb64_n(w["sig"].as_str().unwrap()).unwrap())
+ .expect("welcome is signed by the host");
+ let keys = crypto::channel_keys(&crypto::x25519(&ek, &ek_h).unwrap(), &th);
+ self.sealer = Some(Sealer::new(keys.d2h));
+ self.opener = Some(Opener::new(keys.h2d, 16 << 20));
+ }
+ out
+ }
+
+ async fn send(&mut self, v: Value) {
+ for f in self.sealer.as_mut().unwrap().seal(v.to_string().as_bytes()).unwrap() {
+ self.tx.send(f).await.unwrap();
+ }
+ }
+
+ /// The next inner message, or the close that ended the channel.
+ async fn recv(&mut self) -> Result<Value, (u16, Value)> {
+ let mut last_plain = Value::Null;
+ loop {
+ match self.next().await {
+ Out::Msg(f) if f["t"] == "f" => {
+ if let Some(bytes) = self.opener.as_mut().unwrap().open(&f).unwrap() {
+ return Ok(serde_json::from_slice(&bytes).unwrap());
+ }
+ }
+ Out::Msg(plain) => last_plain = plain,
+ Out::Close(code, _) => return Err((code, last_plain)),
+ }
+ }
+ }
+
+ async fn call(&mut self, id: u64, m: &str, b: Value) -> Value {
+ self.send(json!({"id": id, "m": m, "b": b})).await;
+ loop {
+ let v = self.recv().await.expect("channel stays open");
+ if v["id"] == id && (v.get("ok").is_some() || v.get("err").is_some()) {
+ return v;
+ }
+ }
+ }
+ }
+
+ fn closed(out: &Out) -> u16 {
+ match out {
+ Out::Close(code, _) => *code,
+ Out::Msg(v) => panic!("expected a close, got {v}"),
+ }
+ }
+
+ async fn paired_phone(hub: &Arc<Hub>) -> SigningKey {
+ let key = SigningKey::from_bytes(&crypto::random());
+ let code = hub.pairing.locked().issue().code;
+ let mut p = Phone::direct(hub, key.clone());
+ assert!(matches!(p.hello(hub, true).await, Out::Msg(v) if v["t"] == "welcome"));
+ p.send(json!({"id": 1, "m": "pair", "b": {"code": code, "name": "Kevin's iPhone", "platform": "ios"}})).await;
+ let reply = p.recv().await.unwrap();
+ assert_eq!(reply["ok"]["computerId"], hub.identity.computer_id());
+ assert_eq!(p.recv().await.unwrap_err().0, close::PAIRED);
+ key
+ }
+
+ #[tokio::test]
+ async fn unknown_device_is_rejected() {
+ let hub = temp_hub();
+ let mut p = Phone::direct(&hub, SigningKey::from_bytes(&crypto::random()));
+ let Out::Msg(reject) = p.hello(&hub, false).await else { panic!("expected reject") };
+ assert_eq!(reject["code"], "unauthorized");
+ assert_eq!(closed(&p.next().await), 4001);
+ }
+
+ #[tokio::test]
+ async fn pairing_then_normal_connection() {
+ let hub = temp_hub();
+ let key = paired_phone(&hub).await;
+ let d = hub.store.device(&crypto::b64(key.verifying_key().as_bytes())).unwrap();
+ assert_eq!((d.source, d.name.as_str()), (DeviceSource::Local, "Kevin's iPhone"));
+ assert!(!hub.pairing.locked().open(), "the code is used up");
+
+ let mut p = Phone::direct(&hub, key);
+ assert!(matches!(p.hello(&hub, false).await, Out::Msg(v) if v["t"] == "welcome"));
+ let hello = p.call(1, "hello", json!({})).await;
+ assert_eq!(hello["ok"]["computerId"], hub.identity.computer_id());
+ assert_eq!(hello["ok"]["signKey"], hub.identity.sign_pub_b64());
+ assert_eq!(hello["ok"]["protocol"], 1);
+ assert_eq!(hub.connected.locked().get(&p.dk()), Some(&1));
+ assert!(hub.store.device(&p.dk()).unwrap().last_seen_at.is_some());
+
+ // Loopback-only methods are refused over the channel.
+ for m in ["setScreenEnabled", "pairing", "devices", "revokeDevice", "claimSign", "computerCall"] {
+ assert_eq!(p.call(2, m, json!({})).await["err"]["status"], 403, "{m}");
+ }
+ assert_eq!(p.call(3, "pair", json!({})).await["err"]["status"], 403);
+ }
+
+ #[tokio::test]
+ async fn pair_hello_without_a_code_is_refused_before_any_crypto() {
+ let hub = temp_hub();
+ let (tx, incoming) = mpsc::channel(4);
+ let (outgoing, mut rx) = mpsc::channel(4);
+ tokio::spawn(run(
+ hub.clone(),
+ Transport { incoming, outgoing },
+ ChannelKind::Direct { peer: [10, 0, 0, 2].into() },
+ ));
+ let dk = crypto::b64(SigningKey::from_bytes(&[1; 32]).verifying_key().as_bytes());
+ // A garbage key and signature: only a pre-crypto check can answer pairingClosed.
+ tx.send(json!({"t": "hello", "v": 1, "dk": dk, "ek": "x", "n": "x", "sig": "x", "pair": true})).await.unwrap();
+ let Some(Out::Msg(reject)) = rx.recv().await else { panic!("expected reject") };
+ assert_eq!(reject["code"], "pairingClosed");
+ assert_eq!(closed(&rx.recv().await.unwrap()), 4410);
+ }
+
+ #[tokio::test]
+ async fn pairing_channel_only_takes_pair_and_codes_are_single_use() {
+ let hub = temp_hub();
+ let code = hub.pairing.locked().issue().code;
+ hub.pairing.locked().issue();
+ let mut p = Phone::direct(&hub, SigningKey::from_bytes(&crypto::random()));
+ p.hello(&hub, true).await;
+ p.send(json!({"id": 1, "m": "hello", "b": {}})).await;
+ assert_eq!(p.recv().await.unwrap_err().0, close::PROTOCOL);
+
+ let mut p = Phone::direct(&hub, SigningKey::from_bytes(&crypto::random()));
+ p.hello(&hub, true).await;
+ p.send(json!({"id": 1, "m": "pair", "b": {"code": code, "name": "A", "platform": "ios"}})).await;
+ assert!(p.recv().await.unwrap()["ok"].is_object());
+
+ let mut p = Phone::direct(&hub, SigningKey::from_bytes(&crypto::random()));
+ p.hello(&hub, true).await;
+ p.send(json!({"id": 1, "m": "pair", "b": {"code": code, "name": "B", "platform": "ios"}})).await;
+ assert_eq!(p.recv().await.unwrap()["err"]["status"], 403, "a used code doesn't work twice");
+ assert_eq!(p.recv().await.unwrap_err().0, close::UNAUTHORIZED);
+ }
+
+ #[tokio::test]
+ async fn revoking_closes_the_channel_and_its_subscription() {
+ let hub = temp_hub();
+ let key = paired_phone(&hub).await;
+ let dk = crypto::b64(key.verifying_key().as_bytes());
+ let mut p = Phone::direct(&hub, key);
+ p.hello(&hub, false).await;
+ assert!(p.call(1, "registerDevice", json!({"ticket": "t1", "name": "iPhone"})).await["ok"].is_object());
+ assert!(p.call(2, "registerActivity", json!({"ticket": "a1", "botId": "b1"})).await["ok"].is_object());
+ p.send(json!({"id": 3, "sub": "events", "b": {"since": 0, "client": "ios"}})).await;
+ let hello = p.recv().await.unwrap();
+ assert_eq!((hello["id"].as_u64(), hello["ev"]["type"].as_str()), (Some(3), Some("hello")));
+ assert!(hub.ios_connected());
+
+ assert!(hub.revoke_device(&dk).unwrap());
+ let (code, reject) = p.recv().await.unwrap_err();
+ assert_eq!(code, 4003);
+ assert_eq!(reject["code"], "revoked");
+ assert!(hub.store.push_tickets().is_empty());
+ assert!(hub.store.activity_tickets("b1").is_empty());
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ assert!(!hub.ios_connected(), "the events subscription ended with the channel");
+ assert!(hub.connected.locked().is_empty());
+ }
+
+ #[tokio::test]
+ async fn account_devices_need_a_synced_live_lease() {
+ let hub = temp_hub();
+ let key = SigningKey::from_bytes(&crypto::random());
+ let dk = crypto::b64(key.verifying_key().as_bytes());
+ let device = Device {
+ key: dk.clone(),
+ name: "Phone".into(),
+ platform: "ios".into(),
+ source: DeviceSource::Account,
+ grant_id: Some("grt_x".into()),
+ scopes: vec![Scope::Control],
+ lease_until: Some(now_ms() + 300),
+ created_at: now_ms(),
+ last_seen_at: None,
+ };
+ hub.store.put_device(&device).unwrap();
+ let mut p = Phone::direct(&hub, key.clone());
+ let Out::Msg(reject) = p.hello(&hub, false).await else { panic!("expected reject") };
+ assert_eq!(reject["code"], "leaseExpired", "refused until the cloud state was applied");
+
+ hub.cloud_synced.store(true, std::sync::atomic::Ordering::Release);
+ let mut p = Phone::direct(&hub, key.clone());
+ assert!(matches!(p.hello(&hub, false).await, Out::Msg(v) if v["t"] == "welcome"));
+ assert_eq!(p.call(1, "screenOffer", json!({})).await["err"]["status"], 403, "no screen scope");
+ let (code, reject) = p.recv().await.unwrap_err();
+ assert_eq!((code, reject["code"].as_str()), (4001, Some("leaseExpired")), "closed when the lease ran out");
+ }
+
+ #[tokio::test]
+ async fn relay_link_hello_must_match_open() {
+ let hub = temp_hub();
+ let key = paired_phone(&hub).await;
+ let other = crypto::b64(SigningKey::from_bytes(&crypto::random()).verifying_key().as_bytes());
+ let kind = ChannelKind::Relay { link: "l1".into(), dk: other, pair: false };
+ let mut p = Phone::connect(&hub, key.clone(), kind);
+ assert_eq!(closed(&p.hello(&hub, false).await), close::PROTOCOL);
+
+ let dk = crypto::b64(key.verifying_key().as_bytes());
+ let mut p = Phone::connect(&hub, key, ChannelKind::Relay { link: "l2".into(), dk, pair: false });
+ assert!(matches!(p.hello(&hub, false).await, Out::Msg(v) if v["t"] == "welcome"));
+ }
+
+ #[tokio::test]
+ async fn replayed_or_bad_frames_close_the_channel() {
+ let hub = temp_hub();
+ let key = paired_phone(&hub).await;
+ let mut p = Phone::direct(&hub, key);
+ p.hello(&hub, false).await;
+ let frames = p.sealer.as_mut().unwrap().seal(br#"{"id":1,"m":"hello","b":{}}"#).unwrap();
+ p.tx.send(frames[0].clone()).await.unwrap();
+ assert!(p.recv().await.unwrap()["ok"].is_object());
+ p.tx.send(frames[0].clone()).await.unwrap();
+ assert_eq!(p.recv().await.unwrap_err().0, close::PROTOCOL, "replay");
+ }
+
+ #[tokio::test]
+ async fn cancelled_subscription_ends() {
+ let hub = temp_hub();
+ let key = paired_phone(&hub).await;
+ let mut p = Phone::direct(&hub, key);
+ p.hello(&hub, false).await;
+ p.send(json!({"id": 7, "sub": "events", "b": {"since": 0}})).await;
+ assert_eq!(p.recv().await.unwrap()["ev"]["type"], "hello");
+ p.send(json!({"id": 7, "cancel": true})).await;
+ assert_eq!(p.recv().await.unwrap(), json!({"id": 7, "end": true}));
+ assert_eq!(p.call(8, "hello", json!({})).await["id"], 8, "the channel goes on");
+ p.send(json!({"id": 9, "sub": "term", "b": {"term": "nope"}})).await;
+ assert_eq!(p.recv().await.unwrap()["err"]["status"], 404);
+ }
+
+ #[tokio::test]
+ async fn device_table_changes_only_after_the_pairing_close_is_queued() {
+ let hub = temp_hub();
+ let code = hub.pairing.locked().issue().code;
+ let key = SigningKey::from_bytes(&crypto::random());
+ let dk = crypto::b64(key.verifying_key().as_bytes());
+ let mut auth = hub.auth.subscribe();
+ auth.mark_unchanged();
+ let mut p = Phone::connect(&hub, key, ChannelKind::Relay { link: "p".into(), dk, pair: true });
+ p.hello(&hub, true).await;
+ p.send(json!({"id": 1, "m": "pair", "b": {"code": code, "name": "A", "platform": "ios"}})).await;
+ auth.changed().await.unwrap();
+ // The relay republishes the ACL on this change: the answer and 4100 must already be queued.
+ let mut last = None;
+ while let Ok(out) = p.rx.try_recv() {
+ last = Some(out);
+ }
+ assert!(matches!(last, Some(Out::Close(close::PAIRED, _))), "got {last:?}");
+ }
+}
diff --git a/host/src/cloud.rs b/host/src/cloud.rs
new file mode 100644
index 00000000..b29556de
--- /dev/null
+++ b/host/src/cloud.rs
@@ -0,0 +1,736 @@
+//! The Codync cloud (Cloudflare relay + accounts, spec §4.2, §4.3, §8.4, §9.6): which one
+//! this host uses, its `/v1/host/*` API (signed with `Codync-Sig`), the state pull that may
+//! only renew or remove account devices, never add one, and account access requests with
+//! the commit-then-reveal SAS. The relay socket itself lives in `relay`.
+
+use crate::LockExt;
+use crate::crypto::{self, b64};
+use crate::hub::Hub;
+use crate::store::{Device, DeviceSource, Scope, Store, now_ms};
+use anyhow::{Context, Result, anyhow, bail};
+use reqwest::Method;
+use serde::{Deserialize, Serialize};
+use serde_json::{Value, json};
+use std::sync::Arc;
+use std::sync::Mutex;
+use std::time::Duration;
+use tokio::sync::watch;
+
+/// The production cloud, once it is deployed. `None`: without `CODYNC_CLOUD_URL` or a
+/// URL set with `codync-host cloud --url`, the cloud is off (QR + direct connections only).
+pub const DEFAULT_CLOUD_URL: Option<&str> = None;
+
+/// How long one successful state pull keeps an account device allowed.
+pub const LEASE_MS: i64 = 15 * 60 * 1000;
+const TIMEOUT: Duration = Duration::from_secs(15);
+/// Grant revocations the cloud hasn't confirmed yet (kv, JSON array of grant ids).
+const PENDING_REVOKES: &str = "grant_revokes";
+/// When this host sent its recent SAS nonces (kv, JSON array of ms).
+const SAS_NONCES: &str = "sas_nonces";
+/// Every host nonce is one guess at the phone's code for whoever controls the cloud, revealed
+/// or not: at most this many per hour keeps a 6-digit SAS out of reach of a search.
+const SAS_NONCES_PER_HOUR: usize = 5;
+const HOUR_MS: i64 = 60 * 60 * 1000;
+
+/// The cloud base URL in use, or `None` when the cloud is off.
+/// `CODYNC_CLOUD=off` > turned off here > `CODYNC_CLOUD_URL` > kv `cloud_url` > the default.
+pub fn url(store: &Store) -> Option<String> {
+ if std::env::var("CODYNC_CLOUD").is_ok_and(|v| v == "off")
+ || store.kv_get("cloud_enabled").as_deref() == Some("false")
+ {
+ return None;
+ }
+ std::env::var("CODYNC_CLOUD_URL")
+ .ok()
+ .or_else(|| store.kv_get("cloud_url"))
+ .or_else(|| DEFAULT_CLOUD_URL.map(str::to_owned))
+ .map(|u| u.trim_end_matches('/').to_owned())
+ .filter(|u| !u.is_empty())
+}
+
+/// A cloud URL this host may be pointed at: https, or plain http to this computer (local dev).
+fn valid_url(u: &str) -> bool {
+ let Ok(parsed) = reqwest::Url::parse(u) else { return false };
+ let local = matches!(parsed.host_str(), Some("127.0.0.1" | "localhost" | "[::1]"));
+ parsed.path() == "/"
+ && parsed.query().is_none()
+ && (parsed.scheme() == "https" || (parsed.scheme() == "http" && local))
+}
+
+#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct Owner {
+ pub user_id: String,
+ #[serde(default)]
+ pub email: Option<String>,
+}
+
+/// `cloudStatus` and the `cloud` event.
+#[derive(Serialize, Clone, Debug, Default, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct CloudStatus {
+ pub enabled: bool,
+ pub url: Option<String>,
+ pub registered: bool,
+ pub connected: bool,
+ pub owner: Option<Owner>,
+ pub last_error: Option<String>,
+}
+
+/// A pending account access request, with this host's own nonce (memory only).
+#[derive(Clone)]
+struct Request {
+ id: String,
+ device_key: [u8; 32],
+ device_name: String,
+ platform: String,
+ email: Option<String>,
+ commit: [u8; 32],
+ host_nonce: [u8; 32],
+ /// The SAS, once the device revealed a nonce that matches its commit.
+ code: Option<String>,
+ created_at: i64,
+ expires_at: i64,
+}
+
+impl Request {
+ fn json(&self) -> Value {
+ json!({
+ "requestId": self.id,
+ "deviceKey": b64(&self.device_key),
+ "deviceName": self.device_name,
+ "platform": self.platform,
+ "email": self.email,
+ "code": self.code,
+ "createdAt": self.created_at,
+ "expiresAt": self.expires_at,
+ })
+ }
+}
+
+pub struct Cloud {
+ status: Mutex<CloudStatus>,
+ requests: Mutex<Vec<Request>>,
+ /// One state pull at a time.
+ pulling: tokio::sync::Mutex<()>,
+ /// Bumped when the cloud is turned on or off or pointed elsewhere: the relay restarts.
+ pub config: watch::Sender<u64>,
+}
+
+impl Default for Cloud {
+ fn default() -> Self {
+ Self {
+ status: Mutex::default(),
+ requests: Mutex::default(),
+ pulling: tokio::sync::Mutex::new(()),
+ config: watch::Sender::new(0),
+ }
+ }
+}
+
+impl Cloud {
+ pub fn status(&self) -> CloudStatus {
+ self.status.locked().clone()
+ }
+
+ pub fn requests_json(&self) -> Vec<Value> {
+ self.requests.locked().iter().map(Request::json).collect()
+ }
+}
+
+/// Changes the status and tells this computer's apps when it actually changed.
+pub fn update_status(hub: &Hub, f: impl FnOnce(&mut CloudStatus)) {
+ let changed = {
+ let mut s = hub.cloud.status.locked();
+ let before = s.clone();
+ f(&mut s);
+ (*s != before).then(|| s.clone())
+ };
+ if let Some(s) = changed {
+ let _ = hub.events.send(json!({"type": "cloud", "cloud": s}));
+ }
+}
+
+fn emit_requests(hub: &Hub) {
+ let _ = hub.events.send(json!({"type": "accessRequests", "requests": hub.cloud.requests_json()}));
+}
+
+/// An error answer from the cloud (`{"error":{"code","message"}}`).
+#[derive(Debug)]
+pub struct CloudError {
+ pub status: u16,
+ pub code: String,
+ pub message: String,
+}
+
+impl std::fmt::Display for CloudError {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "the Codync cloud refused ({} {}): {}", self.status, self.code, self.message)
+ }
+}
+
+impl std::error::Error for CloudError {}
+
+fn cloud_status_of(e: &anyhow::Error) -> Option<u16> {
+ e.downcast_ref::<CloudError>().map(|c| c.status)
+}
+
+/// Something that has to wait for the other side first (409).
+#[derive(Debug)]
+pub struct Conflict(pub &'static str);
+
+impl std::fmt::Display for Conflict {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str(self.0)
+ }
+}
+
+impl std::error::Error for Conflict {}
+
+/// The lowercase `Host` header value for `base` (with a non-default port), as `Codync-Sig` signs it.
+pub fn authority(base: &str) -> Result<String> {
+ let u = reqwest::Url::parse(base).context("invalid cloud URL")?;
+ let host = u.host_str().ok_or_else(|| anyhow!("cloud URL has no host"))?;
+ Ok(match u.port() {
+ Some(p) => format!("{host}:{p}"),
+ None => host.to_owned(),
+ }
+ .to_ascii_lowercase())
+}
+
+fn base(hub: &Hub) -> Result<String> {
+ url(&hub.store).ok_or_else(|| anyhow!("The Codync cloud is off on this computer."))
+}
+
+/// One signed `/v1/host/*` call.
+async fn call(hub: &Hub, base: &str, method: Method, path: &str, body: Option<&Value>) -> Result<Value> {
+ let bytes = body.map(serde_json::to_vec).transpose()?.unwrap_or_default();
+ let sig = hub.identity.sign_request(method.as_str(), &authority(base)?, path, &bytes);
+ let mut req = crate::http().request(method, format!("{base}{path}")).header("Codync-Sig", sig).timeout(TIMEOUT);
+ if body.is_some() {
+ req = req.header("content-type", "application/json").body(bytes);
+ }
+ let res = req.send().await.context("the Codync cloud is unreachable")?;
+ let status = res.status();
+ let v: Value = res.json().await.unwrap_or(Value::Null);
+ if !status.is_success() {
+ let e = &v["error"];
+ return Err(CloudError {
+ status: status.as_u16(),
+ code: e["code"].as_str().unwrap_or("internal").to_owned(),
+ message: e["message"].as_str().unwrap_or_default().to_owned(),
+ }
+ .into());
+ }
+ Ok(v)
+}
+
+/// `POST /v1/host/register`: makes this computer known to the cloud (no account needed).
+pub async fn register(hub: &Hub, base: &str) -> Result<()> {
+ let body = json!({
+ "boxKey": hub.identity.box_pub_b64(),
+ "name": crate::service::host_name(),
+ "platform": std::env::consts::OS,
+ "device": tokio::task::spawn_blocking(crate::service::device).await?,
+ "version": env!("CARGO_PKG_VERSION"),
+ });
+ let v = call(hub, base, Method::POST, "/v1/host/register", Some(&body)).await?;
+ if v["computerId"].as_str() != Some(hub.identity.computer_id().as_str()) {
+ bail!("the cloud registered a different computer id");
+ }
+ tracing::info!(computer_id = hub.identity.computer_id(), "registered with the Codync cloud");
+ update_status(hub, |s| s.registered = true);
+ Ok(())
+}
+
+// MARK: state (§4.3)
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct State {
+ owner: Option<Owner>,
+ #[serde(default)]
+ grants: Vec<Grant>,
+ #[serde(default)]
+ requests: Vec<StateRequest>,
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct Grant {
+ pub grant_id: String,
+ pub device_key: String,
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct StateRequest {
+ request_id: String,
+ device_key: String,
+ #[serde(default)]
+ device_name: String,
+ #[serde(default)]
+ platform: String,
+ #[serde(default)]
+ email: Option<String>,
+ commit: String,
+ #[serde(default)]
+ host_nonce: Option<String>,
+ #[serde(default)]
+ device_nonce: Option<String>,
+ #[serde(default)]
+ created_at: i64,
+ #[serde(default)]
+ expires_at: i64,
+}
+
+/// `GET /v1/host/state` and apply it: renew or remove account devices, answer access requests.
+pub async fn pull(hub: &Hub, base: &str) -> Result<()> {
+ let _one = hub.cloud.pulling.lock().await;
+ let state: State = serde_json::from_value(call(hub, base, Method::GET, "/v1/host/state", None).await?)
+ .context("reading the cloud state")?;
+ apply_grants(hub, &state.grants)?;
+ update_status(hub, |s| s.owner = state.owner);
+ sync_requests(hub, base, state.requests).await;
+ retry_revokes(hub, base).await;
+ Ok(())
+}
+
+/// The cloud can only shorten access: a local account device listed with the same grant and
+/// key is renewed, one missing is removed; grants this host never approved are ignored.
+pub fn apply_grants(hub: &Hub, grants: &[Grant]) -> Result<()> {
+ let until = now_ms() + LEASE_MS;
+ let mut known = vec![false; grants.len()];
+ for d in hub.store.devices()? {
+ if d.source != DeviceSource::Account {
+ continue;
+ }
+ let listed = grants.iter().position(|g| Some(&g.grant_id) == d.grant_id.as_ref() && g.device_key == d.key);
+ if let Some(i) = listed {
+ known[i] = true;
+ hub.store.set_lease(&d.key, until)?;
+ } else {
+ tracing::info!(device = d.key, "account device's grant is gone from the cloud");
+ hub.revoke_device(&d.key)?;
+ }
+ }
+ for (g, _) in grants.iter().zip(known).filter(|(_, k)| !k) {
+ tracing::warn!(grant_id = g.grant_id, "unknown grant from cloud ignored");
+ }
+ Ok(())
+}
+
+enum Next {
+ /// Seen for the first time without a host nonce: send ours.
+ Offer(Box<Request>),
+ /// Refuse (lost our nonce in a restart, tampered with, or the commit didn't match).
+ Deny(String),
+}
+
+/// Keeps the pending access requests in step with the cloud (§4.2 B steps 4 and 6).
+async fn sync_requests(hub: &Hub, base: &str, list: Vec<StateRequest>) {
+ let mut next = vec![];
+ let mut changed = false;
+ let mut throttled = false;
+ {
+ let mut mine = hub.cloud.requests.locked();
+ let before = mine.len();
+ mine.retain(|r| {
+ let kept = list.iter().any(|s| s.request_id == r.id);
+ if !kept && r.code.is_none() {
+ // Still counted against the hourly nonce budget.
+ tracing::warn!(request_id = r.id, "access request vanished without revealing its nonce");
+ }
+ kept
+ });
+ changed |= mine.len() != before;
+ let mut budget = nonce_budget(&hub.store);
+ for s in &list {
+ let (Ok(dk), Ok(commit)) = (crypto::unb64_n::<32>(&s.device_key), crypto::unb64_n::<32>(&s.commit)) else {
+ next.push(Next::Deny(s.request_id.clone()));
+ continue;
+ };
+ let Some(i) = mine.iter().position(|r| r.id == s.request_id) else {
+ // Our nonce is only in memory: after a restart this request can't be finished.
+ if s.host_nonce.is_some() {
+ next.push(Next::Deny(s.request_id.clone()));
+ } else if mine.iter().any(|r| r.device_key == dk && r.code.is_none())
+ || next.iter().any(|n| matches!(n, Next::Offer(r) if r.device_key == dk))
+ {
+ // One unrevealed request per device at a time; this one waits its turn.
+ } else if budget.len() >= SAS_NONCES_PER_HOUR {
+ throttled = true;
+ } else {
+ budget.push(now_ms());
+ next.push(Next::Offer(Box::new(Request {
+ id: s.request_id.clone(),
+ device_key: dk,
+ device_name: s.device_name.clone(),
+ platform: s.platform.clone(),
+ email: s.email.clone(),
+ commit,
+ host_nonce: crypto::random(),
+ code: None,
+ created_at: s.created_at,
+ expires_at: s.expires_at,
+ })));
+ }
+ continue;
+ };
+ let r = &mut mine[i];
+ let ours = b64(&r.host_nonce);
+ if r.device_key != dk || r.commit != commit || s.host_nonce.as_deref() != Some(ours.as_str()) {
+ tracing::warn!(request_id = r.id, "access request changed in the cloud; denying it");
+ next.push(Next::Deny(r.id.clone()));
+ mine.remove(i);
+ changed = true;
+ continue;
+ }
+ if r.code.is_some() {
+ continue;
+ }
+ let Some(nd) = s.device_nonce.as_deref() else { continue };
+ match crypto::unb64_n::<32>(nd) {
+ Ok(nd) if crypto::sas_commit(&dk, &nd) == r.commit => {
+ r.code = Some(crypto::sas_code(&hub.identity.sign_pub(), &dk, &nd, &r.host_nonce));
+ changed = true;
+ }
+ _ => {
+ tracing::warn!(request_id = r.id, "device nonce doesn't match its commit; denying the request");
+ next.push(Next::Deny(r.id.clone()));
+ mine.remove(i);
+ changed = true;
+ }
+ }
+ }
+ // Saved before any nonce leaves, so a restart can't reset the budget.
+ set_nonce_budget(&hub.store, &budget);
+ }
+ if throttled {
+ tracing::warn!("accessRequests throttled: too many account access requests this hour");
+ update_status(hub, |s| {
+ s.last_error = Some("Too many requests to use this computer. New ones wait up to an hour.".into());
+ });
+ }
+ for n in next {
+ match n {
+ Next::Offer(r) => {
+ let path = format!("/v1/host/access-requests/{}/nonce", r.id);
+ match call(hub, base, Method::POST, &path, Some(&json!({"nonce": b64(&r.host_nonce)}))).await {
+ Ok(_) => {
+ hub.cloud.requests.locked().push(*r);
+ changed = true;
+ }
+ // Someone else set a nonce: not one we can stand behind.
+ Err(e) if cloud_status_of(&e) == Some(409) => deny(hub, base, &r.id).await,
+ Err(e) => {
+ tracing::warn!(
+ error = format!("{e:#}"),
+ request_id = r.id,
+ "couldn't answer an access request"
+ );
+ }
+ }
+ }
+ Next::Deny(id) => deny(hub, base, &id).await,
+ }
+ }
+ if changed {
+ emit_requests(hub);
+ }
+}
+
+/// The host nonces sent in the last hour.
+fn nonce_budget(store: &Store) -> Vec<i64> {
+ let since = now_ms() - HOUR_MS;
+ let sent: Vec<i64> = store.kv_get(SAS_NONCES).and_then(|v| serde_json::from_str(&v).ok()).unwrap_or_default();
+ sent.into_iter().filter(|t| *t > since).collect()
+}
+
+fn set_nonce_budget(store: &Store, sent: &[i64]) {
+ let saved = serde_json::to_string(sent).map_err(anyhow::Error::from).and_then(|v| store.kv_set(SAS_NONCES, &v));
+ if let Err(e) = saved {
+ tracing::warn!(error = format!("{e:#}"), "couldn't save the access request budget");
+ }
+}
+
+async fn decision(hub: &Hub, base: &str, id: &str, approve: bool) -> Result<Value> {
+ let path = format!("/v1/host/access-requests/{id}/decision");
+ let decision = if approve { "approve" } else { "deny" };
+ call(hub, base, Method::POST, &path, Some(&json!({"decision": decision}))).await
+}
+
+async fn deny(hub: &Hub, base: &str, id: &str) {
+ if let Err(e) = decision(hub, base, id, false).await {
+ tracing::warn!(error = format!("{e:#}"), request_id = id, "couldn't deny an access request");
+ }
+}
+
+/// `decideAccessRequest`: approving adds the device the user saw (its key, the SAS they
+/// compared) with the grant the cloud returns; nothing else can add an account device.
+pub async fn decide(hub: &Hub, id: &str, approve: bool) -> Result<()> {
+ let base = base(hub)?;
+ let r =
+ hub.cloud.requests.locked().iter().find(|r| r.id == id).cloned().ok_or_else(|| anyhow!("unknown request"))?;
+ if approve && r.code.is_none() {
+ return Err(Conflict("The device hasn't shown its code yet.").into());
+ }
+ let answer = decision(hub, &base, id, approve).await;
+ hub.cloud.requests.locked().retain(|x| x.id != id);
+ emit_requests(hub);
+ let answer = answer?;
+ if !approve {
+ return Ok(());
+ }
+ let grant = answer["grantId"]
+ .as_str()
+ .filter(|g| g.starts_with("grt_"))
+ .ok_or_else(|| anyhow!("the cloud gave no grant"))?;
+ hub.store.put_device(&Device {
+ key: b64(&r.device_key),
+ name: r.device_name.chars().take(100).collect(),
+ platform: r.platform,
+ source: DeviceSource::Account,
+ grant_id: Some(grant.to_owned()),
+ scopes: vec![Scope::Control, Scope::Screen],
+ lease_until: Some(now_ms() + LEASE_MS),
+ created_at: now_ms(),
+ last_seen_at: None,
+ })?;
+ tracing::info!(grant_id = grant, "account device approved");
+ hub.auth_changed();
+ Ok(())
+}
+
+// MARK: grants removed here
+
+fn pending_revokes(store: &Store) -> Vec<String> {
+ store.kv_get(PENDING_REVOKES).and_then(|v| serde_json::from_str(&v).ok()).unwrap_or_default()
+}
+
+fn set_pending_revokes(store: &Store, ids: &[String]) {
+ let saved = serde_json::to_string(ids).map_err(anyhow::Error::from).and_then(|v| store.kv_set(PENDING_REVOKES, &v));
+ if let Err(e) = saved {
+ tracing::warn!(error = format!("{e:#}"), "couldn't remember a grant to revoke");
+ }
+}
+
+/// Tells the cloud an account device was removed here. Local removal already took effect;
+/// a failure is retried on later state pulls.
+pub async fn revoke_grant(hub: Arc<Hub>, grant_id: String) {
+ let mut pending = pending_revokes(&hub.store);
+ if !pending.contains(&grant_id) {
+ pending.push(grant_id);
+ set_pending_revokes(&hub.store, &pending);
+ }
+ if let Ok(base) = base(&hub) {
+ retry_revokes(&hub, &base).await;
+ }
+}
+
+async fn retry_revokes(hub: &Hub, base: &str) {
+ let pending = pending_revokes(&hub.store);
+ if pending.is_empty() {
+ return;
+ }
+ let mut left = vec![];
+ for id in pending {
+ match call(hub, base, Method::POST, &format!("/v1/host/grants/{id}/revoke"), Some(&json!({}))).await {
+ Ok(_) => {}
+ Err(e) if cloud_status_of(&e) == Some(404) => {}
+ Err(e) => {
+ tracing::warn!(error = format!("{e:#}"), grant_id = id, "couldn't revoke a grant in the cloud");
+ left.push(id);
+ }
+ }
+ }
+ set_pending_revokes(&hub.store, &left);
+}
+
+// MARK: loopback methods
+
+/// `unclaim`: takes this computer out of its account.
+pub async fn unclaim(hub: &Hub) -> Result<()> {
+ let base = base(hub)?;
+ call(hub, &base, Method::POST, "/v1/host/unclaim", Some(&json!({}))).await?;
+ tracing::info!("left the account");
+ pull(hub, &base).await
+}
+
+/// `setCloud`: turns the cloud on or off (optionally pointing it elsewhere); the relay restarts.
+pub fn set_cloud(hub: &Hub, enabled: bool, new_url: Option<&str>) -> Result<CloudStatus> {
+ if let Some(u) = new_url {
+ let u = u.trim().trim_end_matches('/');
+ if !valid_url(&format!("{u}/")) {
+ bail!("The cloud URL must be https://… (or http:// to this computer).");
+ }
+ hub.store.kv_set("cloud_url", u)?;
+ }
+ hub.store.kv_set("cloud_enabled", if enabled { "true" } else { "false" })?;
+ let now = url(&hub.store);
+ update_status(hub, |s| {
+ s.enabled = now.is_some();
+ s.url.clone_from(&now);
+ });
+ hub.cloud.config.send_modify(|g| *g += 1);
+ Ok(hub.cloud.status())
+}
+
+#[cfg(test)]
+mod tests {
+ #![allow(clippy::unwrap_used, clippy::expect_used)]
+ use super::*;
+ use crate::identity::Identity;
+
+ fn temp_hub() -> Arc<Hub> {
+ let dir = std::env::temp_dir().join(format!("codync-cloud-{}", uuid::Uuid::new_v4()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let store = Store::open(&dir.join("t.db")).unwrap();
+ Hub::new(store, "host".into(), Identity::load_or_create(&dir).unwrap(), "token".into(), 0)
+ }
+
+ fn account_device(key: &str, grant: &str) -> Device {
+ Device {
+ key: key.into(),
+ name: "Phone".into(),
+ platform: "ios".into(),
+ source: DeviceSource::Account,
+ grant_id: Some(grant.into()),
+ scopes: vec![Scope::Control, Scope::Screen],
+ lease_until: Some(now_ms() + 1000),
+ created_at: now_ms(),
+ last_seen_at: None,
+ }
+ }
+
+ #[test]
+ fn state_only_renews_or_removes() {
+ let hub = temp_hub();
+ hub.store.put_device(&account_device("kept", "grt_a")).unwrap();
+ hub.store.put_device(&account_device("gone", "grt_b")).unwrap();
+ hub.store.put_device(&account_device("swapped", "grt_c")).unwrap();
+ let mut local = account_device("qr", "x");
+ (local.source, local.grant_id, local.lease_until) = (DeviceSource::Local, None, None);
+ hub.store.put_device(&local).unwrap();
+ let grant = |g: &str, k: &str| Grant { grant_id: g.into(), device_key: k.into() };
+ apply_grants(&hub, &[grant("grt_a", "kept"), grant("grt_c", "another key"), grant("grt_injected", "attacker")])
+ .unwrap();
+ let keys: Vec<String> = hub.store.devices().unwrap().into_iter().map(|d| d.key).collect();
+ assert_eq!(keys, ["kept", "qr"], "unknown grants add nothing; a grant naming another key doesn't count");
+ assert!(hub.store.device("kept").unwrap().lease_until.unwrap() > now_ms() + LEASE_MS - 5000, "renewed");
+ assert_eq!(hub.store.device("qr").unwrap().lease_until, None, "QR devices aren't touched");
+ }
+
+ #[test]
+ fn only_safe_cloud_urls() {
+ assert!(valid_url("https://codync-cloud.example.workers.dev/"));
+ assert!(valid_url("http://127.0.0.1:8787/"));
+ assert!(!valid_url("http://example.com/"));
+ assert!(!valid_url("https://example.com/path/"));
+ assert!(!valid_url("ftp://example.com/"));
+ assert_eq!(authority("https://Codync.Example.dev").unwrap(), "codync.example.dev");
+ assert_eq!(authority("http://127.0.0.1:8787").unwrap(), "127.0.0.1:8787");
+ assert_eq!(authority("https://x.dev:443").unwrap(), "x.dev", "default port is left out");
+ }
+
+ #[derive(Default)]
+ struct FakeCloud {
+ state: Mutex<Value>,
+ posts: Mutex<Vec<(String, Value)>>,
+ }
+
+ async fn fake_cloud(fake: Arc<FakeCloud>) -> String {
+ use axum::extract::{OriginalUri, State as Ax};
+ use axum::routing::{get, post};
+ let app = axum::Router::new()
+ .route("/v1/host/state", get(|Ax(f): Ax<Arc<FakeCloud>>| async move { axum::Json(f.state.lock().unwrap().clone()) }))
+ .route(
+ "/v1/host/access-requests/{id}/{action}",
+ post(|Ax(f): Ax<Arc<FakeCloud>>, OriginalUri(uri): OriginalUri, axum::Json(b): axum::Json<Value>| async move {
+ let path = uri.path().to_owned();
+ f.posts.lock().unwrap().push((path.clone(), b.clone()));
+ axum::Json(if path.ends_with("/decision") && b["decision"] == "approve" {
+ json!({"status": "approved", "grantId": "grt_new"})
+ } else {
+ json!({})
+ })
+ }),
+ )
+ .with_state(fake);
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let base = format!("http://{}", listener.local_addr().unwrap());
+ tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
+ base
+ }
+
+ #[tokio::test]
+ async fn access_request_needs_a_matching_reveal_before_approval() {
+ let hub = temp_hub();
+ let fake = Arc::new(FakeCloud::default());
+ let base = fake_cloud(fake.clone()).await;
+ hub.store.kv_set("cloud_url", &base).unwrap();
+ let (dk, other_dk): ([u8; 32], [u8; 32]) = (crypto::random(), crypto::random());
+ let (nd, wrong): ([u8; 32], [u8; 32]) = (crypto::random(), crypto::random());
+ let request = |id: &str, host_nonce: Option<String>, device_nonce: Option<[u8; 32]>| {
+ let dk = if id == "req_bad" { other_dk } else { dk };
+ json!({"requestId": id, "deviceKey": b64(&dk), "deviceName": "Kevin's iPhone", "platform": "ios",
+ "email": "[email protected]", "commit": b64(&crypto::sas_commit(&dk, &nd)),
+ "hostNonce": host_nonce, "deviceNonce": device_nonce.map(|n| b64(&n)),
+ "createdAt": 1, "expiresAt": 2})
+ };
+ *fake.state.lock().unwrap() = json!({"owner": {"userId": "user_1", "email": "[email protected]"}, "grants": [],
+ "requests": [request("req_ok", None, None), request("req_bad", None, None)]});
+ pull(&hub, &base).await.unwrap();
+ let nonces: Vec<(String, Value)> = fake.posts.lock().unwrap().clone();
+ assert_eq!(nonces.len(), 2, "the host sends one nonce per request");
+ let nh =
+ |id: &str| nonces.iter().find(|(p, _)| p.contains(id)).unwrap().1["nonce"].as_str().unwrap().to_owned();
+ assert_eq!(hub.cloud.requests_json()[0]["code"], Value::Null, "no code before the reveal");
+ let early = decide(&hub, "req_ok", true).await.unwrap_err();
+ assert!(early.is::<Conflict>(), "approve before the reveal is refused");
+ assert_eq!(hub.cloud.status().owner.unwrap().user_id, "user_1");
+
+ *fake.state.lock().unwrap() = json!({"owner": null, "grants": [], "requests": [
+ request("req_ok", Some(nh("req_ok")), Some(nd)),
+ request("req_bad", Some(nh("req_bad")), Some(wrong)),
+ ]});
+ pull(&hub, &base).await.unwrap();
+ let denied =
+ fake.posts.lock().unwrap().iter().any(|(p, b)| p.ends_with("req_bad/decision") && b["decision"] == "deny");
+ assert!(denied, "a reveal that doesn't match its commit is denied");
+ let list = hub.cloud.requests_json();
+ assert_eq!(list.len(), 1);
+ let nh_ok: [u8; 32] = crypto::unb64_n(&nh("req_ok")).unwrap();
+ assert_eq!(list[0]["code"], crypto::sas_code(&hub.identity.sign_pub(), &dk, &nd, &nh_ok));
+
+ decide(&hub, "req_ok", true).await.unwrap();
+ let d = hub.store.device(&b64(&dk)).unwrap();
+ assert_eq!((d.source, d.grant_id.as_deref()), (DeviceSource::Account, Some("grt_new")));
+ assert!(hub.cloud.requests_json().is_empty());
+ }
+
+ #[tokio::test]
+ async fn host_nonces_are_rationed() {
+ let hub = temp_hub();
+ let fake = Arc::new(FakeCloud::default());
+ let base = fake_cloud(fake.clone()).await;
+ let request =
+ |id: String, dk: [u8; 32]| json!({"requestId": id, "deviceKey": b64(&dk), "commit": b64(&[0u8; 32])});
+ let one_key: [u8; 32] = crypto::random();
+ let mut requests: Vec<Value> = (0..2).map(|i| request(format!("same_{i}"), one_key)).collect();
+ requests.extend((0..8).map(|i| request(format!("req_{i}"), crypto::random())));
+ *fake.state.lock().unwrap() = json!({"owner": null, "grants": [], "requests": requests});
+ pull(&hub, &base).await.unwrap();
+ let sent = fake.posts.lock().unwrap().len();
+ assert_eq!(sent, SAS_NONCES_PER_HOUR, "a compromised cloud gets a few guesses an hour, not a million");
+ assert!(!fake.posts.lock().unwrap().iter().any(|(p, _)| p.contains("same_1")), "one open request per key");
+
+ // Requests that never reveal still used up the budget, across a restart too.
+ *fake.state.lock().unwrap() =
+ json!({"owner": null, "grants": [], "requests": [request("late".into(), crypto::random())]});
+ hub.cloud.requests.locked().clear();
+ pull(&hub, &base).await.unwrap();
+ assert_eq!(fake.posts.lock().unwrap().len(), SAS_NONCES_PER_HOUR);
+ assert!(hub.cloud.status().last_error.is_some(), "the Mac hears about it");
+ }
+}
diff --git a/host/src/crypto.rs b/host/src/crypto.rs
new file mode 100644
index 00000000..d6910f6b
--- /dev/null
+++ b/host/src/crypto.rs
@@ -0,0 +1,533 @@
+//! Wire cryptography of the phone ↔ host protocol (docs/remote-relay-spec.md §5, §6):
+//! the signed-ephemeral handshake, frame sealing and chunking, mailbox opening,
+//! push sealing, SAS, pairing offer ids and the canonical strings that get signed.
+//!
+//! Pure functions over bytes, no host state: `tests/e2e.rs` includes this file
+//! as its device-side implementation, so it must only use external crates.
+//! Every construction is checked against `docs/remote-relay-vectors.json`.
+
+use anyhow::{Result, anyhow, bail, ensure};
+use base64::Engine as _;
+use base64::engine::general_purpose::URL_SAFE_NO_PAD;
+use chacha20poly1305::aead::{Aead, KeyInit, Payload};
+use chacha20poly1305::{ChaCha20Poly1305, Nonce};
+use ed25519_dalek::{Signature, SigningKey, VerifyingKey};
+use hkdf::Hkdf;
+use sha2::{Digest, Sha256};
+use x25519_dalek::{PublicKey, StaticSecret};
+
+/// Largest plaintext chunk in one frame (§6.3).
+pub const CHUNK: usize = 256 * 1024;
+/// A channel is rekeyed (closed with `4011`) before either counter reaches this (§3.5).
+pub const REKEY_AT: u64 = 1 << 32;
+
+const FLAG_FINAL: u8 = 0x00;
+const FLAG_MORE: u8 = 0x01;
+
+pub fn b64(bytes: &[u8]) -> String {
+ URL_SAFE_NO_PAD.encode(bytes)
+}
+
+pub fn unb64(s: &str) -> Result<Vec<u8>> {
+ URL_SAFE_NO_PAD.decode(s).map_err(|_| anyhow!("not base64url"))
+}
+
+/// Decodes base64url of exactly `N` bytes.
+pub fn unb64_n<const N: usize>(s: &str) -> Result<[u8; N]> {
+ unb64(s)?.try_into().map_err(|_| anyhow!("expected {N} bytes"))
+}
+
+pub fn random<const N: usize>() -> [u8; N] {
+ let mut out = [0u8; N];
+ getrandom::fill(&mut out).expect("the OS random source is always available on macOS and Linux");
+ out
+}
+
+pub fn sha256(parts: &[&[u8]]) -> [u8; 32] {
+ let mut h = Sha256::new();
+ for p in parts {
+ h.update(p);
+ }
+ h.finalize().into()
+}
+
+/// Constant-time equality for secrets (pairing codes, tokens).
+pub fn ct_eq(a: &[u8], b: &[u8]) -> bool {
+ a.len() == b.len() && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
+}
+
+/// `SHA-256(hostSignPub)[0..16]`: the raw computer id.
+pub fn computer_id_raw(sign_pub: &[u8; 32]) -> [u8; 16] {
+ let mut out = [0u8; 16];
+ out.copy_from_slice(&sha256(&[sign_pub])[..16]);
+ out
+}
+
+pub fn computer_id(sign_pub: &[u8; 32]) -> String {
+ b64(&computer_id_raw(sign_pub))
+}
+
+pub fn verify(key: &[u8; 32], msg: &[u8], sig: &[u8; 64]) -> Result<()> {
+ let key = VerifyingKey::from_bytes(key).map_err(|_| anyhow!("bad public key"))?;
+ key.verify_strict(msg, &Signature::from_bytes(sig)).map_err(|_| anyhow!("bad signature"))
+}
+
+pub fn sign(key: &SigningKey, msg: &[u8]) -> [u8; 64] {
+ use ed25519_dalek::Signer as _;
+ key.sign(msg).to_bytes()
+}
+
+/// X25519 that refuses the all-zero result (a low-order peer key).
+pub fn x25519(secret: &StaticSecret, public: &[u8; 32]) -> Result<[u8; 32]> {
+ let ss = secret.diffie_hellman(&PublicKey::from(*public));
+ ensure!(ss.was_contributory(), "low-order public key");
+ Ok(ss.to_bytes())
+}
+
+pub fn x25519_pub(secret: &StaticSecret) -> [u8; 32] {
+ PublicKey::from(secret).to_bytes()
+}
+
+fn hkdf_key(salt: &[u8], ikm: &[u8], info: &[u8]) -> [u8; 32] {
+ let hk = Hkdf::<Sha256>::new(Some(salt), ikm);
+ let mut out = [0u8; 32];
+ hk.expand(info, &mut out).expect("32 bytes is a valid HKDF-SHA256 output length");
+ out
+}
+
+fn aead(key: &[u8; 32]) -> ChaCha20Poly1305 {
+ ChaCha20Poly1305::new(key.into())
+}
+
+// MARK: handshake (§6.2)
+
+/// What the device signs in `hello`.
+pub fn hs1_input(cid_raw: &[u8; 16], dk: &[u8; 32], ek_d: &[u8; 32], n: &[u8; 32]) -> Vec<u8> {
+ [b"codync/hs1/v1".as_slice(), cid_raw, dk, ek_d, n].concat()
+}
+
+/// `TH`: what the host signs in `welcome`, and the HKDF salt.
+pub fn transcript_hash(cid_raw: &[u8; 16], dk: &[u8; 32], ek_d: &[u8; 32], n: &[u8; 32], ek_h: &[u8; 32]) -> [u8; 32] {
+ sha256(&[b"codync/hs2/v1", cid_raw, dk, ek_d, n, ek_h])
+}
+
+/// Per-direction channel keys.
+pub struct Keys {
+ pub d2h: [u8; 32],
+ pub h2d: [u8; 32],
+}
+
+pub fn channel_keys(shared: &[u8; 32], th: &[u8; 32]) -> Keys {
+ let hk = Hkdf::<Sha256>::new(Some(th), shared);
+ let mut keys = Keys { d2h: [0; 32], h2d: [0; 32] };
+ hk.expand(b"codync/d2h/v1", &mut keys.d2h).expect("32 bytes is a valid HKDF-SHA256 output length");
+ hk.expand(b"codync/h2d/v1", &mut keys.h2d).expect("32 bytes is a valid HKDF-SHA256 output length");
+ keys
+}
+
+// MARK: frames (§6.3)
+
+fn frame_nonce(c: u64) -> Nonce {
+ let mut n = [0u8; 12];
+ n[4..].copy_from_slice(&c.to_be_bytes());
+ n.into()
+}
+
+fn frame_aad(c: u64) -> Vec<u8> {
+ [b"codync/frame/v1".as_slice(), &c.to_be_bytes()].concat()
+}
+
+pub fn seal_frame(key: &[u8; 32], c: u64, last: bool, chunk: &[u8]) -> Vec<u8> {
+ let plaintext = [&[if last { FLAG_FINAL } else { FLAG_MORE }], chunk].concat();
+ aead(key)
+ .encrypt(&frame_nonce(c), Payload { msg: &plaintext, aad: &frame_aad(c) })
+ .expect("ChaCha20-Poly1305 accepts any chunk up to 256 KiB")
+}
+
+/// Returns `(last, chunk)`.
+pub fn open_frame(key: &[u8; 32], c: u64, d: &[u8]) -> Result<(bool, Vec<u8>)> {
+ let mut plain = aead(key)
+ .decrypt(&frame_nonce(c), Payload { msg: d, aad: &frame_aad(c) })
+ .map_err(|_| anyhow!("frame doesn't decrypt"))?;
+ ensure!(!plain.is_empty(), "empty frame");
+ let flag = plain.remove(0);
+ match flag {
+ FLAG_FINAL => Ok((true, plain)),
+ FLAG_MORE => Ok((false, plain)),
+ _ => bail!("bad frame flag"),
+ }
+}
+
+/// The sending half of a channel direction: counts frames from 0.
+pub struct Sealer {
+ key: [u8; 32],
+ next: u64,
+}
+
+impl Sealer {
+ pub fn new(key: [u8; 32]) -> Self {
+ Self { key, next: 0 }
+ }
+
+ /// One inner message as `f` frames (`{"t":"f","c","d"}`), or `None` once the counter must rekey.
+ pub fn seal(&mut self, message: &[u8]) -> Option<Vec<serde_json::Value>> {
+ let chunks: Vec<&[u8]> = if message.is_empty() { vec![&[]] } else { message.chunks(CHUNK).collect() };
+ if self.next + chunks.len() as u64 > REKEY_AT {
+ return None;
+ }
+ let total = chunks.len();
+ Some(
+ chunks
+ .into_iter()
+ .enumerate()
+ .map(|(i, chunk)| {
+ let c = self.next;
+ self.next += 1;
+ serde_json::json!({"t": "f", "c": c, "d": b64(&seal_frame(&self.key, c, i + 1 == total, chunk))})
+ })
+ .collect(),
+ )
+ }
+}
+
+/// Why a received frame ends the channel.
+#[derive(Debug, PartialEq, Eq)]
+pub enum FrameError {
+ /// Wrong counter, bad tag, malformed frame: close `4002`.
+ Protocol,
+ /// The reassembled message is over the limit: close `4013`.
+ TooLarge,
+ /// The counter reached 2^32: close `4011`.
+ Rekey,
+}
+
+/// The receiving half: requires consecutive counters and reassembles chunks.
+pub struct Opener {
+ key: [u8; 32],
+ next: u64,
+ buf: Vec<u8>,
+ limit: usize,
+}
+
+impl Opener {
+ pub fn new(key: [u8; 32], limit: usize) -> Self {
+ Self { key, next: 0, buf: vec![], limit }
+ }
+
+ /// Feeds one `f` frame; returns a whole inner message once its last chunk arrived.
+ pub fn open(&mut self, frame: &serde_json::Value) -> Result<Option<Vec<u8>>, FrameError> {
+ if self.next >= REKEY_AT {
+ return Err(FrameError::Rekey);
+ }
+ let c = frame["c"].as_u64().ok_or(FrameError::Protocol)?;
+ if frame["t"] != "f" || c != self.next {
+ return Err(FrameError::Protocol);
+ }
+ let d = frame["d"].as_str().and_then(|d| unb64(d).ok()).ok_or(FrameError::Protocol)?;
+ let (last, chunk) = open_frame(&self.key, c, &d).map_err(|_| FrameError::Protocol)?;
+ self.next += 1;
+ if self.buf.len() + chunk.len() > self.limit {
+ return Err(FrameError::TooLarge);
+ }
+ self.buf.extend_from_slice(&chunk);
+ Ok(last.then(|| std::mem::take(&mut self.buf)))
+ }
+}
+
+// MARK: mailbox (§6.4)
+
+/// Verifies and decrypts a mailbox blob sent by `dk`; returns the inner JSON bytes.
+pub fn open_mailbox(
+ box_secret: &StaticSecret,
+ cid_raw: &[u8; 16],
+ dk: &[u8; 32],
+ client_nonce: &str,
+ blob: &[u8],
+) -> Result<Vec<u8>> {
+ ensure!(blob.len() > 32 + 64 + 16, "mailbox blob too short");
+ let (epk, rest) = blob.split_at(32);
+ let (sig, ct) = rest.split_at(64);
+ let epk: [u8; 32] = epk.try_into()?;
+ let sig: [u8; 64] = sig.try_into()?;
+ verify(dk, &[b"codync/mbox/v1".as_slice(), cid_raw, &epk, ct].concat(), &sig)?;
+ let key = mailbox_key(&x25519(box_secret, &epk)?, cid_raw, dk, &epk);
+ aead(&key)
+ .decrypt(&[0u8; 12].into(), Payload { msg: ct, aad: &[dk.as_slice(), client_nonce.as_bytes()].concat() })
+ .map_err(|_| anyhow!("mailbox blob doesn't decrypt"))
+}
+
+fn mailbox_key(shared: &[u8; 32], cid_raw: &[u8; 16], dk: &[u8; 32], epk: &[u8; 32]) -> [u8; 32] {
+ hkdf_key(&[b"codync/mbox/v1".as_slice(), cid_raw, dk, epk].concat(), shared, b"codync/mbox-key/v1")
+}
+
+// MARK: push (§6.7)
+
+/// Seals a notification's `{"title","body"}` JSON to a device's push key with a fresh
+/// ephemeral key (`eph`; tests pass a fixed one). Returns `sealed`.
+pub fn seal_push(cid_raw: &[u8; 16], push_key: &[u8; 32], plaintext: &[u8], eph: &StaticSecret) -> Result<String> {
+ let epk = x25519_pub(eph);
+ let shared = x25519(eph, push_key)?;
+ let key =
+ hkdf_key(&[b"codync/push/v1".as_slice(), cid_raw, push_key, &epk].concat(), &shared, b"codync/push-key/v1");
+ let ct = aead(&key)
+ .encrypt(&[0u8; 12].into(), Payload { msg: plaintext, aad: cid_raw })
+ .map_err(|_| anyhow!("push payload too large"))?;
+ Ok(b64(&[epk.as_slice(), &ct].concat()))
+}
+
+// MARK: SAS, offers, canonical strings (§4, §5)
+
+pub fn sas_commit(dk: &[u8; 32], device_nonce: &[u8; 32]) -> [u8; 32] {
+ sha256(&[b"codync/sascommit/v1", dk, device_nonce])
+}
+
+/// 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}")
+}
+
+/// The ACL `offers[].id` (and relay `pair=`) for a pairing code.
+pub fn offer_id(code: &[u8; 16]) -> String {
+ b64(&sha256(&[b"codync/offer/v1", code])[..16])
+}
+
+/// What the host signs to join an account (`claimSign`).
+pub fn claim_input(claim_id: &str, nonce: &str, user_id: &str, computer_id: &str, box_key: &str) -> String {
+ format!("codync/claim/v1\n{claim_id}\n{nonce}\n{user_id}\n{computer_id}\n{box_key}")
+}
+
+/// The `Codync-Sig` signing input.
+pub fn request_sig_input(method: &str, authority: &str, path_query: &str, ts: i64, nonce: &str, body: &[u8]) -> String {
+ format!(
+ "codync-sig-v1\n{}\n{}\n{path_query}\n{ts}\n{nonce}\n{}",
+ method.to_ascii_uppercase(),
+ authority.to_ascii_lowercase(),
+ b64(&sha256(&[body]))
+ )
+}
+
+/// The `Codync-Sig` header value.
+pub fn request_sig_header(key: &SigningKey, ts: i64, nonce: &str, input: &str) -> String {
+ let kid = b64(key.verifying_key().as_bytes());
+ let sig = b64(&sign(key, input.as_bytes()));
+ format!("v=1,kid={kid},ts={ts},nonce={nonce},sig={sig}")
+}
+
+#[cfg(test)]
+mod tests {
+ #![allow(clippy::unwrap_used)]
+ use super::*;
+ use serde_json::Value;
+
+ fn vectors() -> Value {
+ serde_json::from_str(include_str!("../../docs/remote-relay-vectors.json")).unwrap()
+ }
+
+ fn b(v: &Value) -> Vec<u8> {
+ unb64(v.as_str().unwrap()).unwrap()
+ }
+
+ fn b32(v: &Value) -> [u8; 32] {
+ unb64_n(v.as_str().unwrap()).unwrap()
+ }
+
+ struct Keys {
+ host: SigningKey,
+ host_box: StaticSecret,
+ device: SigningKey,
+ }
+
+ fn keys(v: &Value) -> Keys {
+ let k = &v["keys"];
+ let host = SigningKey::from_bytes(&b32(&k["hostSignSeed"]));
+ let host_box = StaticSecret::from(b32(&k["hostBoxPriv"]));
+ let device = SigningKey::from_bytes(&b32(&k["deviceSignSeed"]));
+ assert_eq!(b64(host.verifying_key().as_bytes()), k["hostSignPub"]);
+ assert_eq!(b64(&x25519_pub(&host_box)), k["hostBoxPub"]);
+ assert_eq!(b64(device.verifying_key().as_bytes()), k["deviceSignPub"]);
+ assert_eq!(computer_id(host.verifying_key().as_bytes()), k["computerId"]);
+ Keys { host, host_box, device }
+ }
+
+ #[test]
+ fn handshake_vectors() {
+ let v = vectors();
+ let k = keys(&v);
+ let h = &v["handshake"];
+ let cid = computer_id_raw(k.host.verifying_key().as_bytes());
+ let dk = k.device.verifying_key().to_bytes();
+ let dev_eph = StaticSecret::from(b32(&h["deviceEphPriv"]));
+ let host_eph = StaticSecret::from(b32(&h["hostEphPriv"]));
+ let (ek_d, ek_h) = (x25519_pub(&dev_eph), x25519_pub(&host_eph));
+ assert_eq!(b64(&ek_d), h["deviceEphPub"]);
+ assert_eq!(b64(&ek_h), h["hostEphPub"]);
+ let n = b32(&h["n"]);
+
+ let hs1 = hs1_input(&cid, &dk, &ek_d, &n);
+ assert_eq!(b64(&hs1), h["hs1SignInput"]);
+ let sig = sign(&k.device, &hs1);
+ assert_eq!(b64(&sig), h["hs1Sig"]);
+ verify(&dk, &hs1, &sig).unwrap();
+
+ let th = transcript_hash(&cid, &dk, &ek_d, &n, &ek_h);
+ assert_eq!(b64(&th), h["transcriptHash"]);
+ assert_eq!(b64(&sign(&k.host, &th)), h["hs2Sig"]);
+
+ let ss = x25519(&dev_eph, &ek_h).unwrap();
+ assert_eq!(ss, x25519(&host_eph, &ek_d).unwrap());
+ assert_eq!(b64(&ss), h["sharedSecret"]);
+ let (prk, _) = Hkdf::<Sha256>::extract(Some(&th), &ss);
+ assert_eq!(b64(&prk), h["prk"]);
+ let keys = channel_keys(&ss, &th);
+ assert_eq!(b64(&keys.d2h), h["kD2H"]);
+ assert_eq!(b64(&keys.h2d), h["kH2D"]);
+
+ assert!(x25519(&host_eph, &[0u8; 32]).is_err(), "all-zero shared secret is refused");
+ let mut tampered = hs1.clone();
+ tampered[20] ^= 1;
+ assert!(verify(&dk, &tampered, &sig).is_err());
+ }
+
+ #[test]
+ fn frame_vectors() {
+ let v = vectors();
+ let h = &v["handshake"];
+ let (d2h, h2d) = (b32(&h["kD2H"]), b32(&h["kH2D"]));
+ for f in v["frames"].as_array().unwrap() {
+ let key = if f["dir"] == "d2h" { &d2h } else { &h2d };
+ let c = f["c"].as_u64().unwrap();
+ let last = f["final"].as_bool().unwrap();
+ let msg = f["message"].as_str().unwrap().as_bytes();
+ let plaintext = b(&f["plaintext"]);
+ assert_eq!(plaintext[0], u8::from(!last));
+ assert_eq!(&plaintext[1..], msg);
+ let d = seal_frame(key, c, last, msg);
+ assert_eq!(b64(&d), f["d"]);
+ assert_eq!(open_frame(key, c, &d).unwrap(), (last, msg.to_vec()));
+ assert!(open_frame(key, c + 1, &d).is_err(), "the counter is bound to the frame");
+ }
+ }
+
+ #[test]
+ fn sealer_and_opener_chunk_count_and_limit() {
+ let key = [7u8; 32];
+ let mut sealer = Sealer::new(key);
+ let mut opener = Opener::new(key, 1024 * 1024);
+ let big = vec![b'x'; CHUNK * 2 + 5];
+ let frames = sealer.seal(&big).unwrap();
+ assert_eq!(frames.len(), 3);
+ assert_eq!(opener.open(&frames[0]), Ok(None));
+ assert_eq!(opener.open(&frames[1]), Ok(None));
+ assert_eq!(opener.open(&frames[2]), Ok(Some(big)));
+
+ let empty = sealer.seal(b"").unwrap();
+ assert_eq!(opener.open(&empty[0]), Ok(Some(vec![])));
+
+ // Replay and reordering are both a counter mismatch.
+ let a = sealer.seal(b"a").unwrap();
+ let b = sealer.seal(b"b").unwrap();
+ assert_eq!(opener.open(&b[0]), Err(FrameError::Protocol));
+ let mut small = Opener::new(key, 4);
+ let mut s2 = Sealer::new(key);
+ assert_eq!(small.open(&s2.seal(b"12345").unwrap()[0]), Err(FrameError::TooLarge));
+ drop(a);
+
+ let mut near_end = Sealer { key, next: REKEY_AT - 1 };
+ assert!(near_end.seal(b"x").is_some());
+ assert!(near_end.seal(b"x").is_none(), "no frame may use counter 2^32");
+ }
+
+ #[test]
+ fn mailbox_vector_opens() {
+ let v = vectors();
+ let k = keys(&v);
+ let m = &v["mailbox"];
+ let cid = computer_id_raw(k.host.verifying_key().as_bytes());
+ let dk = k.device.verifying_key().to_bytes();
+ let eph = StaticSecret::from(b32(&m["ephPriv"]));
+ let epk = x25519_pub(&eph);
+ assert_eq!(b64(&epk), m["ephPub"]);
+ let ss = x25519(&k.host_box, &epk).unwrap();
+ assert_eq!(b64(&ss), m["sharedSecret"]);
+ assert_eq!(b64(&mailbox_key(&ss, &cid, &dk, &epk)), m["key"]);
+ let blob = b(&m["blob"]);
+ assert_eq!(blob, [epk.as_slice(), &b(&m["sig"]), &b(&m["ciphertext"])].concat());
+
+ let nonce = m["clientNonce"].as_str().unwrap();
+ let plain = open_mailbox(&k.host_box, &cid, &dk, nonce, &blob).unwrap();
+ assert_eq!(plain, m["plaintext"].as_str().unwrap().as_bytes());
+
+ assert!(open_mailbox(&k.host_box, &cid, &dk, "other-nonce", &blob).is_err(), "nonce is authenticated");
+ let mut tampered = blob.clone();
+ *tampered.last_mut().unwrap() ^= 1;
+ assert!(open_mailbox(&k.host_box, &cid, &dk, nonce, &tampered).is_err(), "signature covers ct");
+ let other = SigningKey::from_bytes(&[9u8; 32]).verifying_key().to_bytes();
+ assert!(open_mailbox(&k.host_box, &cid, &other, nonce, &blob).is_err(), "sender is authenticated");
+ }
+
+ #[test]
+ fn push_vector_seals() {
+ let v = vectors();
+ let k = keys(&v);
+ let p = &v["push"];
+ let cid = computer_id_raw(k.host.verifying_key().as_bytes());
+ let push_priv = StaticSecret::from(b32(&p["pushPriv"]));
+ let push_key = x25519_pub(&push_priv);
+ assert_eq!(b64(&push_key), p["pushPub"]);
+ let eph = StaticSecret::from(b32(&p["ephPriv"]));
+ assert_eq!(b64(&x25519_pub(&eph)), p["ephPub"]);
+ let ss = x25519(&eph, &push_key).unwrap();
+ assert_eq!(b64(&ss), p["sharedSecret"]);
+ let sealed = seal_push(&cid, &push_key, p["plaintext"].as_str().unwrap().as_bytes(), &eph).unwrap();
+ assert_eq!(sealed, p["sealed"]);
+ }
+
+ #[test]
+ #[allow(clippy::many_single_char_names)] // vector sections, named as in the JSON
+ fn sas_offer_claim_and_request_sig_vectors() {
+ let v = vectors();
+ let k = keys(&v);
+ let dk = k.device.verifying_key().to_bytes();
+ let s = &v["sas"];
+ 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"]);
+
+ let p = &v["pairing"];
+ assert_eq!(offer_id(&unb64_n(p["code"].as_str().unwrap()).unwrap()), p["offerId"]);
+
+ let c = &v["claim"];
+ let input = claim_input(
+ c["claimId"].as_str().unwrap(),
+ c["nonce"].as_str().unwrap(),
+ c["userId"].as_str().unwrap(),
+ c["computerId"].as_str().unwrap(),
+ c["boxKey"].as_str().unwrap(),
+ );
+ assert_eq!(input, c["canonical"]);
+ assert_eq!(b64(&sign(&k.host, input.as_bytes())), c["sig"]);
+
+ let r = &v["requestSig"];
+ assert_eq!(b64(&sha256(&[b""])), r["bodySha256"]);
+ let ts = r["ts"].as_i64().unwrap();
+ let nonce = r["nonce"].as_str().unwrap();
+ let input = request_sig_input(
+ r["method"].as_str().unwrap(),
+ r["authority"].as_str().unwrap(),
+ r["pathAndQuery"].as_str().unwrap(),
+ ts,
+ nonce,
+ b"",
+ );
+ assert_eq!(input, r["canonical"]);
+ let header = request_sig_header(&k.device, ts, nonce, &input);
+ assert_eq!(format!("Codync-Sig: {header}"), r["header"]);
+
+ let a = &v["acl"];
+ let json = a["json"].as_str().unwrap();
+ assert_eq!(b64(json.as_bytes()), a["d"]);
+ assert_eq!(b64(&sign(&k.host, json.as_bytes())), a["sig"]);
+ }
+}
diff --git a/host/src/devices.rs b/host/src/devices.rs
new file mode 100644
index 00000000..07cab5ae
--- /dev/null
+++ b/host/src/devices.rs
@@ -0,0 +1,255 @@
+//! Who is calling and what they may do (spec §4.1, §4.3, §6.6): the caller kinds,
+//! per-method permissions, the device authorization check and QR pairing codes.
+//! The authorized-device table itself lives in `store`.
+
+use crate::crypto;
+use crate::hub::Hub;
+use crate::store::{Device, DeviceSource, Scope, now_ms};
+use serde::Serialize;
+use std::sync::atomic::Ordering;
+use std::time::{Duration, Instant};
+
+pub enum Caller {
+ /// This computer's own apps and helpers: loopback + the bearer token.
+ Local,
+ /// An authorized device over an E2E channel.
+ Device { key: String, scopes: Vec<Scope> },
+ /// A channel opened to redeem a pairing code; may only call `pair`.
+ Pairing { key: String },
+}
+
+impl Caller {
+ /// The key push and Live Activity tickets are bound to.
+ pub fn device_key(&self) -> &str {
+ match self {
+ Self::Local => "local",
+ Self::Device { key, .. } | Self::Pairing { key } => key,
+ }
+ }
+}
+
+/// Methods only this computer may call.
+const LOCAL_ONLY: &[&str] = &[
+ "setScreenEnabled",
+ "pairing",
+ "computerCall",
+ "claimSign",
+ "unclaim",
+ "devices",
+ "revokeDevice",
+ "accessRequests",
+ "decideAccessRequest",
+ "cloudStatus",
+ "setCloud",
+];
+const SCREEN: &[&str] = &["screenOffer", "screenClose", "screenTakeover"];
+
+/// A method the caller isn't allowed to call (403).
+#[derive(Debug)]
+pub struct Forbidden;
+
+impl std::fmt::Display for Forbidden {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str("This can only be done at the computer itself.")
+ }
+}
+
+impl std::error::Error for Forbidden {}
+
+pub fn permit(caller: &Caller, method: &str) -> Result<(), Forbidden> {
+ let ok = match caller {
+ Caller::Local => method != "pair",
+ Caller::Pairing { .. } => false,
+ Caller::Device { scopes, .. } => {
+ let needs = if SCREEN.contains(&method) { Scope::Screen } else { Scope::Control };
+ !LOCAL_ONLY.contains(&method) && method != "pair" && scopes.contains(&needs)
+ }
+ };
+ if ok { Ok(()) } else { Err(Forbidden) }
+}
+
+/// Why a channel refuses a device (`reject.code`).
+#[derive(Serialize, Clone, Copy, Debug, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub enum RejectCode {
+ Unauthorized,
+ Revoked,
+ LeaseExpired,
+ BadSignature,
+ UnsupportedVersion,
+ PairingClosed,
+ RateLimited,
+}
+
+impl RejectCode {
+ /// The WebSocket close code sent after the `reject`.
+ pub fn close_code(self) -> u16 {
+ match self {
+ Self::Revoked => 4003,
+ Self::RateLimited => 4008,
+ Self::UnsupportedVersion => 4400,
+ Self::PairingClosed => 4410,
+ Self::Unauthorized | Self::LeaseExpired | Self::BadSignature => 4001,
+ }
+ }
+
+ pub fn message(self) -> &'static str {
+ match self {
+ Self::Unauthorized => "This device isn't allowed on this computer. Pair it again.",
+ Self::Revoked => "This device's access was removed on the computer.",
+ Self::LeaseExpired => "The computer can't confirm this device's access right now. Try again shortly.",
+ Self::BadSignature => "The device's signature didn't check out.",
+ Self::UnsupportedVersion => "Update Codync to connect to this computer.",
+ Self::PairingClosed => "Pairing isn't open. Show a new code on the computer.",
+ Self::RateLimited => "Too many pairing attempts. Wait a minute and try again.",
+ }
+ }
+}
+
+/// Whether `key` may use a channel right now (§4.3): a local device always, an account
+/// device only while its lease runs and the cloud state was applied on this connection.
+pub fn authorize(hub: &Hub, key: &str) -> Result<Device, RejectCode> {
+ let d = hub.store.device(key).ok_or(RejectCode::Unauthorized)?;
+ if d.source == DeviceSource::Account
+ && (!hub.cloud_synced.load(Ordering::Acquire) || d.lease_until.is_none_or(|t| t <= now_ms()))
+ {
+ return Err(RejectCode::LeaseExpired);
+ }
+ Ok(d)
+}
+
+// MARK: pairing codes
+
+const CODE_TTL_MS: i64 = 10 * 60 * 1000;
+const MAX_CODES: usize = 5;
+const PER_SOURCE_PER_MINUTE: usize = 3;
+const TOTAL_PER_MINUTE: usize = 10;
+
+struct PairingCode {
+ code: [u8; 16],
+ expires_at: i64,
+}
+
+/// One-time QR codes (memory only) and the attempt limits that guard them.
+#[derive(Default)]
+pub struct Pairing {
+ codes: Vec<PairingCode>,
+ attempts: Vec<(String, Instant)>,
+}
+
+/// A code just issued, for the QR.
+pub struct Issued {
+ pub code: String,
+ pub expires_at: i64,
+}
+
+impl Pairing {
+ fn prune(&mut self, now: i64) {
+ self.codes.retain(|c| c.expires_at > now);
+ }
+
+ /// A new code; the oldest is dropped beyond five.
+ pub fn issue(&mut self) -> Issued {
+ let now = now_ms();
+ self.prune(now);
+ if self.codes.len() >= MAX_CODES {
+ self.codes.remove(0);
+ }
+ let code = crypto::random::<16>();
+ let expires_at = now + CODE_TTL_MS;
+ self.codes.push(PairingCode { code, expires_at });
+ Issued { code: crypto::b64(&code), expires_at }
+ }
+
+ /// The live codes as ACL offers: `(offerId, expiresAt)`.
+ pub fn offers(&mut self) -> Vec<(String, i64)> {
+ self.prune(now_ms());
+ self.codes.iter().map(|c| (crypto::offer_id(&c.code), c.expires_at)).collect()
+ }
+
+ /// Whether any code is still unused and unexpired.
+ pub fn open(&mut self) -> bool {
+ self.prune(now_ms());
+ !self.codes.is_empty()
+ }
+
+ /// Counts a `pair` attempt from `source` (peer IP or relay link); false when over the limit.
+ pub fn attempt(&mut self, source: &str) -> bool {
+ let now = Instant::now();
+ self.attempts.retain(|(_, t)| now.duration_since(*t) < Duration::from_secs(60));
+ let from_source = self.attempts.iter().filter(|(s, _)| s == source).count();
+ if from_source >= PER_SOURCE_PER_MINUTE || self.attempts.len() >= TOTAL_PER_MINUTE {
+ return false;
+ }
+ self.attempts.push((source.to_owned(), now));
+ true
+ }
+
+ /// Uses up `code` if it is valid (constant-time over every live code).
+ pub fn redeem(&mut self, code: &str) -> bool {
+ self.prune(now_ms());
+ let Ok(given) = crypto::unb64_n::<16>(code) else { return false };
+ 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()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ #![allow(clippy::unwrap_used)]
+ use super::*;
+
+ #[test]
+ fn method_permissions_follow_the_caller() {
+ let both = Caller::Device { key: "k".into(), scopes: vec![Scope::Control, Scope::Screen] };
+ let control = Caller::Device { key: "k".into(), scopes: vec![Scope::Control] };
+ for m in LOCAL_ONLY {
+ assert!(permit(&Caller::Local, m).is_ok());
+ assert!(permit(&both, m).is_err(), "{m} is loopback only");
+ }
+ assert!(permit(&both, "send").is_ok());
+ assert!(permit(&both, "screenOffer").is_ok());
+ assert!(permit(&control, "screenOffer").is_err(), "screen needs the screen scope");
+ assert!(permit(&control, "screenStatus").is_ok(), "status is control");
+ assert!(permit(&Caller::Device { key: "k".into(), scopes: vec![] }, "hello").is_err());
+ assert!(permit(&both, "pair").is_err(), "pair only on a pairing channel");
+ assert!(permit(&Caller::Pairing { key: "k".into() }, "hello").is_err());
+ assert_eq!(both.device_key(), "k");
+ assert_eq!(Caller::Local.device_key(), "local");
+ }
+
+ #[test]
+ fn codes_are_single_use_and_capped() {
+ let mut p = Pairing::default();
+ assert!(!p.open());
+ let first = p.issue();
+ assert!(p.open());
+ 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.redeem(&first.code));
+ assert!(!p.redeem(&first.code), "single use");
+ assert!(!p.open());
+
+ let codes: Vec<Issued> = (0..6).map(|_| p.issue()).collect();
+ assert!(!p.redeem(&codes[0].code), "the oldest of six is dropped");
+ assert!(p.redeem(&codes[5].code));
+
+ p.codes[0].expires_at = now_ms() - 1;
+ assert!(!p.redeem(&codes[1].code), "expired");
+ }
+
+ #[test]
+ fn attempts_are_limited_per_source_and_in_total() {
+ let mut p = Pairing::default();
+ assert!((0..3).all(|_| p.attempt("1.2.3.4")));
+ assert!(!p.attempt("1.2.3.4"));
+ assert!((0..7).all(|i| p.attempt(&format!("link{i}"))));
+ assert!(!p.attempt("fresh"), "ten per minute across the host");
+ }
+}
diff --git a/host/src/hub.rs b/host/src/hub.rs
index 2db002db..04fc9a5e 100644
--- a/host/src/hub.rs
+++ b/host/src/hub.rs
@@ -2,6 +2,8 @@
use crate::LockExt;
use crate::bot::{self, BotHandle, Cmd};
+use crate::devices::Pairing;
+use crate::identity::Identity;
use crate::screen::Screen;
use crate::store::{BotConfig, BotRow, Entry, EntryKind, Store};
use crate::usage::Usage;
@@ -10,10 +12,10 @@ use anyhow::{Result, anyhow, bail};
use serde::Serialize;
use serde_json::{Value, json};
use std::collections::HashMap;
-use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;
-use tokio::sync::broadcast;
+use tokio::sync::{broadcast, watch};
/// What a bot is doing right now (wire values: `idle` / `working` / `needsInput` / `error`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
@@ -36,6 +38,8 @@ pub struct Runtime {
pub struct Hub {
pub store: Store,
pub host_id: String,
+ pub identity: Identity,
+ /// Loopback-only bearer token for this computer's own apps and helpers.
pub token: String,
pub port: u16,
pub events: broadcast::Sender<Value>,
@@ -46,20 +50,29 @@ pub struct Hub {
pub ios_clients: AtomicUsize,
pub usage: Mutex<Usage>,
keep_awake: Mutex<service::KeepAwake>,
- /// botId -> Live Activity push tickets.
- pub activities: Mutex<HashMap<String, Vec<String>>>,
+ /// Generation of the authorized-device table and pairing offers: bumped on every
+ /// change so open channels re-check their device (and the ACL is republished).
+ pub auth: watch::Sender<u64>,
+ pub pairing: Mutex<Pairing>,
+ /// Device key -> open channels that have exchanged at least one frame.
+ pub connected: Mutex<HashMap<String, usize>>,
+ /// The cloud's `/v1/host/state` was applied on the current relay connection;
+ /// account devices are refused until then (§4.3).
+ pub cloud_synced: AtomicBool,
+ pub cloud: crate::cloud::Cloud,
pub screen: Arc<Screen>,
/// Setup terminals (installs, sign-ins).
pub terms: Arc<crate::term::Terms>,
}
impl Hub {
- pub fn new(store: Store, host_id: String, token: String, port: u16) -> Arc<Self> {
+ pub fn new(store: Store, host_id: String, identity: Identity, token: String, port: u16) -> Arc<Self> {
let (events, _) = broadcast::channel(1024);
let screen = Arc::new(Screen::new(Screen::load_enabled(&store), events.clone()));
Arc::new(Self {
store,
host_id,
+ identity,
token,
port,
events,
@@ -69,7 +82,11 @@ impl Hub {
ios_clients: AtomicUsize::new(0),
usage: Mutex::default(),
keep_awake: Mutex::default(),
- activities: Mutex::default(),
+ auth: watch::Sender::new(0),
+ pairing: Mutex::default(),
+ connected: Mutex::default(),
+ cloud_synced: AtomicBool::new(false),
+ cloud: crate::cloud::Cloud::default(),
screen,
terms: Arc::default(),
})
@@ -226,6 +243,8 @@ impl Hub {
if before.status != after.status || before.activity != after.activity {
self.emit_bot(id);
self.update_keep_awake();
+ }
+ if before.status != after.status {
push::live_activity_update(self, id, &after);
}
}
@@ -284,6 +303,23 @@ impl Hub {
*self.usage.locked() = usage;
}
+ // MARK: devices
+
+ /// Tells open channels (and the ACL publisher) that devices or pairing offers changed.
+ pub fn auth_changed(&self) {
+ self.auth.send_modify(|g| *g += 1);
+ }
+
+ /// Removes an authorized device: its tickets go with it and its open channels close.
+ pub fn revoke_device(&self, key: &str) -> Result<bool> {
+ let removed = self.store.remove_device(key)?;
+ if removed {
+ tracing::info!(device = key, "device revoked");
+ self.auth_changed();
+ }
+ Ok(removed)
+ }
+
pub fn ios_connected(&self) -> bool {
self.ios_clients.load(Ordering::Relaxed) > 0
}
diff --git a/host/src/identity.rs b/host/src/identity.rs
new file mode 100644
index 00000000..91779e7d
--- /dev/null
+++ b/host/src/identity.rs
@@ -0,0 +1,192 @@
+//! This computer's long-term keys (spec §3.1): an Ed25519 signing key (its
+//! identity; the computer id is derived from it) and an X25519 box key (mailbox).
+//!
+//! Kept in `identity.json` (0600) next to, never inside, the database: copying
+//! the database must not copy the identity. Blocking `std::fs`: load once at start.
+
+use crate::crypto::{self, b64};
+use anyhow::{Context, Result, bail};
+use ed25519_dalek::SigningKey;
+use serde::{Deserialize, Serialize};
+use std::path::{Path, PathBuf};
+use x25519_dalek::StaticSecret;
+
+const FILE: &str = "identity.json";
+
+pub struct Identity {
+ pub sign: SigningKey,
+ pub box_secret: StaticSecret,
+}
+
+#[derive(Serialize, Deserialize)]
+struct File {
+ v: u32,
+ sign: String,
+ #[serde(rename = "box")]
+ box_key: String,
+}
+
+fn path(dir: &Path) -> PathBuf {
+ dir.join(FILE)
+}
+
+impl Identity {
+ /// Reads `identity.json`; `None` when this computer has none yet. A malformed file is an
+ /// error, never silently replaced (that would make this a different computer).
+ pub fn load(dir: &Path) -> Result<Option<Self>> {
+ let p = path(dir);
+ let text = match std::fs::read_to_string(&p) {
+ Ok(t) => t,
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
+ Err(e) => return Err(e).with_context(|| format!("reading {}", p.display())),
+ };
+ let parse = || -> Result<Self> {
+ let f: File = serde_json::from_str(&text)?;
+ if f.v != 1 {
+ bail!("unsupported version {}", f.v);
+ }
+ Ok(Self {
+ sign: SigningKey::from_bytes(&crypto::unb64_n(&f.sign)?),
+ box_secret: StaticSecret::from(crypto::unb64_n::<32>(&f.box_key)?),
+ })
+ };
+ parse().map(Some).with_context(|| {
+ format!(
+ "{} is damaged; restore it, or delete it to become a new computer (every phone pairs again)",
+ p.display()
+ )
+ })
+ }
+
+ pub fn load_or_create(dir: &Path) -> Result<Self> {
+ if let Some(id) = Self::load(dir)? {
+ return Ok(id);
+ }
+ let id = Self {
+ sign: SigningKey::from_bytes(&crypto::random()),
+ box_secret: StaticSecret::from(crypto::random::<32>()),
+ };
+ let file = File { v: 1, sign: b64(id.sign.as_bytes()), box_key: b64(id.box_secret.as_bytes()) };
+ let p = path(dir);
+ let tmp = dir.join(format!("{FILE}.tmp"));
+ write_private(&tmp, serde_json::to_string(&file)?.as_bytes())?;
+ std::fs::rename(&tmp, &p).with_context(|| format!("writing {}", p.display()))?;
+ tracing::info!(computer_id = id.computer_id(), "created this computer's identity");
+ Ok(id)
+ }
+
+ pub fn sign_pub(&self) -> [u8; 32] {
+ self.sign.verifying_key().to_bytes()
+ }
+
+ pub fn box_pub(&self) -> [u8; 32] {
+ crypto::x25519_pub(&self.box_secret)
+ }
+
+ pub fn sign_pub_b64(&self) -> String {
+ b64(&self.sign_pub())
+ }
+
+ pub fn box_pub_b64(&self) -> String {
+ b64(&self.box_pub())
+ }
+
+ pub fn cid_raw(&self) -> [u8; 16] {
+ crypto::computer_id_raw(&self.sign_pub())
+ }
+
+ pub fn computer_id(&self) -> String {
+ crypto::computer_id(&self.sign_pub())
+ }
+
+ pub fn sign(&self, msg: &[u8]) -> [u8; 64] {
+ crypto::sign(&self.sign, msg)
+ }
+
+ /// `Codync-Sig` header value for a request to `authority` (the lowercase Host header,
+ /// with a non-default port). The spec's `sign_request(method, path_query, body)`
+ /// plus the authority, which the signature covers.
+ pub fn sign_request(&self, method: &str, authority: &str, path_query: &str, body: &[u8]) -> String {
+ let ts = crate::store::now_ms();
+ let nonce = b64(&crypto::random::<16>());
+ let input = crypto::request_sig_input(method, authority, path_query, ts, &nonce, body);
+ crypto::request_sig_header(&self.sign, ts, &nonce, &input)
+ }
+}
+
+/// Creates `path` readable by this user only, before any secret is written to it.
+fn write_private(path: &Path, bytes: &[u8]) -> Result<()> {
+ use std::io::Write as _;
+ let mut opts = std::fs::OpenOptions::new();
+ opts.write(true).create(true).truncate(true);
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::OpenOptionsExt as _;
+ opts.mode(0o600);
+ }
+ let mut f = opts.open(path).with_context(|| format!("creating {}", path.display()))?;
+ #[cfg(unix)]
+ {
+ // `mode` only applies to new files: a leftover tmp keeps its old permissions.
+ use std::os::unix::fs::PermissionsExt as _;
+ f.set_permissions(std::fs::Permissions::from_mode(0o600))?;
+ }
+ f.write_all(bytes)?;
+ f.sync_all()?;
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ #![allow(clippy::unwrap_used)]
+ use super::*;
+
+ fn temp_dir() -> PathBuf {
+ let dir = std::env::temp_dir().join(format!("codync-id-{}", uuid::Uuid::new_v4()));
+ std::fs::create_dir_all(&dir).unwrap();
+ dir
+ }
+
+ #[test]
+ fn created_once_private_and_stable() {
+ let dir = temp_dir();
+ assert!(Identity::load(&dir).unwrap().is_none());
+ let a = Identity::load_or_create(&dir).unwrap();
+ let b = Identity::load_or_create(&dir).unwrap();
+ assert_eq!(a.computer_id(), b.computer_id());
+ assert_eq!(a.box_pub(), b.box_pub());
+ assert_eq!(a.computer_id().len(), 22);
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt as _;
+ let mode = std::fs::metadata(dir.join(FILE)).unwrap().permissions().mode();
+ assert_eq!(mode & 0o777, 0o600);
+ }
+ assert!(!dir.join(format!("{FILE}.tmp")).exists());
+ }
+
+ #[test]
+ fn damaged_file_is_an_error_not_a_new_identity() {
+ let dir = temp_dir();
+ std::fs::write(dir.join(FILE), "{\"v\":1,\"sign\":\"nope\"}").unwrap();
+ assert!(Identity::load_or_create(&dir).is_err());
+ assert_eq!(std::fs::read_to_string(dir.join(FILE)).unwrap(), "{\"v\":1,\"sign\":\"nope\"}");
+ }
+
+ #[test]
+ fn signed_requests_verify() {
+ let id = Identity::load_or_create(&temp_dir()).unwrap();
+ let header = id.sign_request("post", "Cloud.Example:8787", "/v1/host/register", b"{}");
+ let field = |k: &str| header.split(',').find_map(|p| p.strip_prefix(&format!("{k}="))).unwrap().to_owned();
+ assert_eq!(field("kid"), id.sign_pub_b64());
+ let input = crypto::request_sig_input(
+ "POST",
+ "cloud.example:8787",
+ "/v1/host/register",
+ field("ts").parse().unwrap(),
+ &field("nonce"),
+ b"{}",
+ );
+ crypto::verify(&id.sign_pub(), input.as_bytes(), &crypto::unb64_n(&field("sig")).unwrap()).unwrap();
+ }
+}
diff --git a/host/src/main.rs b/host/src/main.rs
index a87ef63c..f98188e8 100644
--- a/host/src/main.rs
+++ b/host/src/main.rs
@@ -5,11 +5,17 @@ mod api;
mod auth;
mod backends;
mod bot;
+mod channel;
+mod cloud;
+mod crypto;
+mod devices;
mod hub;
+mod identity;
mod market;
mod mcp;
mod push;
mod registry;
+mod relay;
mod screen;
mod service;
mod store;
@@ -65,7 +71,7 @@ enum Sub {
#[arg(long, default_value = "0.0.0.0")]
bind: String,
},
- /// Show the pairing QR code for the Codync iOS app.
+ /// Show a one-time pairing QR code for the Codync iOS app (the host must be running).
Pair {
#[arg(long, default_value_t = service::DEFAULT_PORT)]
port: u16,
@@ -73,6 +79,39 @@ enum Sub {
#[arg(long)]
json: bool,
},
+ /// This computer's identity and local API details (for SSH setups).
+ Info {
+ #[arg(long, default_value_t = service::DEFAULT_PORT)]
+ port: u16,
+ #[arg(long)]
+ json: bool,
+ },
+ /// List or revoke the devices allowed to use this computer.
+ Devices {
+ #[arg(long, default_value_t = service::DEFAULT_PORT)]
+ port: u16,
+ #[command(subcommand)]
+ action: Option<DevicesAction>,
+ },
+ /// List, approve or deny account devices asking to use this computer.
+ Access {
+ #[arg(long, default_value_t = service::DEFAULT_PORT)]
+ port: u16,
+ #[command(subcommand)]
+ action: Option<AccessAction>,
+ },
+ /// Show or change the Codync cloud (reach this computer from anywhere).
+ Cloud {
+ #[arg(long, default_value_t = service::DEFAULT_PORT)]
+ port: u16,
+ #[arg(long, conflicts_with = "disable")]
+ enable: bool,
+ #[arg(long)]
+ disable: bool,
+ /// Cloud base URL (https://…); turns the cloud on unless --disable.
+ #[arg(long)]
+ url: Option<String>,
+ },
/// Install and start the host as a background service (launchd / systemd --user).
Install {
#[arg(long, default_value_t = service::DEFAULT_PORT)]
@@ -93,11 +132,12 @@ enum Sub {
#[arg(last = true)]
wrapped: Vec<String>,
},
- /// Rotate the pairing token (unpairs every phone).
+ /// Rotate the local API token used by this computer's own apps and helpers.
ResetToken,
/// Message your bots from this terminal.
Tui {
- /// Host to connect to (default: this computer).
+ /// Host to connect to (default: this computer). The API only answers local
+ /// callers: for another computer, forward its port with `ssh -L` and use the tunnel.
#[arg(long)]
url: Option<String>,
/// Token for `--url` (default: this computer's `~/.codync/token`).
@@ -114,6 +154,24 @@ enum Sub {
},
}
+#[derive(Subcommand)]
+enum DevicesAction {
+ /// Show every allowed device (the default).
+ List,
+ /// Remove a device's access; it disconnects at once.
+ 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 {
/// See and operate this computer's desktop.
@@ -125,7 +183,7 @@ enum McpServer {
},
}
-/// Host identity + auth token live in the database; the token is mirrored to
+/// The database id + local API token live in the database; the token is mirrored to
/// `~/.codync/token` (0600) for local helpers like the statusline command.
fn open_store() -> Result<(store::Store, String, String)> {
let dir = service::data_dir();
@@ -170,26 +228,46 @@ 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 } => {
- let (_, host_id, token) = open_store()?;
- let urls = service::addresses(port);
- let name = service::host_name();
- let url = service::pairing_url(&name, &token, &urls);
- if json {
- println!(
- "{}",
- json!({"name": name, "hostId": host_id, "token": token, "urls": urls, "pairingUrl": url})
- );
- } else {
- 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, or open this link on the phone:\n{url}\n");
- if urls.is_empty() {
- println!("⚠︎ No Tailscale or LAN address found — the phone won't be able to reach this machine.");
- } else if !urls.iter().any(|u| u.contains("://100.") || u.contains(".ts.net")) {
- println!("Tip: install Tailscale on this machine and your phone to reach it from anywhere.");
+ Sub::Pair { port, json } => pair(port, json).await,
+ Sub::Info { port, json } => info(port, json).await,
+ Sub::Devices { port, action } => match action.unwrap_or(DevicesAction::List) {
+ DevicesAction::List => {
+ let v = local_call(port, "devices", json!({})).await?;
+ for d in v["devices"].as_array().into_iter().flatten() {
+ println!(
+ "{} {} ({}, {}){}",
+ d["key"].as_str().unwrap_or_default(),
+ d["name"].as_str().unwrap_or_default(),
+ d["platform"].as_str().unwrap_or_default(),
+ d["source"].as_str().unwrap_or_default(),
+ if d["connected"] == true { " connected" } else { "" }
+ );
}
+ Ok(())
+ }
+ DevicesAction::Revoke { key } => {
+ local_call(port, "revokeDevice", json!({"key": key})).await?;
+ println!("Revoked.");
+ Ok(())
}
+ },
+ Sub::Access { port, action } => access(port, action.unwrap_or(AccessAction::List)).await,
+ Sub::Cloud { port, enable, disable, url } => {
+ let status = if enable || disable || url.is_some() {
+ local_call(port, "setCloud", json!({"enabled": !disable, "url": url})).await?
+ } else {
+ local_call(port, "cloudStatus", json!({})).await?
+ };
+ let text = |k: &str| status[k].as_str().unwrap_or("-").to_owned();
+ let owner = status["owner"]["email"].as_str().or(status["owner"]["userId"].as_str()).unwrap_or("none");
+ println!(
+ "enabled: {}\nurl: {}\nregistered: {}\nconnected: {}\naccount: {owner}\nlast error: {}",
+ status["enabled"],
+ text("url"),
+ status["registered"],
+ status["connected"],
+ text("lastError"),
+ );
Ok(())
}
Sub::Install { port } => {
@@ -238,7 +316,7 @@ async fn main() -> Result<()> {
Sub::ResetToken => {
let (store, _, _) = open_store()?;
rotate_token(&store)?;
- println!("Token rotated. Restart the host and pair your phone again.");
+ println!("Token rotated. Restart the host so local helpers pick it up.");
Ok(())
}
Sub::Mcp { server: McpServer::Computer { bot, port } } => mcp::serve(bot, port).await,
@@ -268,13 +346,15 @@ async fn serve(bind: &str, port: u16) -> Result<()> {
.init();
let (store, host_id, token) = open_store()?;
write_token_file(&token)?;
+ let identity = identity::Identity::load_or_create(&service::data_dir())?;
tokio::task::spawn_blocking(backends::hydrate_path).await?;
- let hub = hub::Hub::new(store, host_id, token, port);
+ let hub = hub::Hub::new(store, host_id, identity, token, port);
hub.start()?;
tokio::spawn(registry::refresh_loop());
tokio::spawn(backends::refresh_sign_in());
tokio::spawn(usage::poll(hub.clone()));
tokio::spawn(screen::serve_helpers(hub.screen.clone()));
+ tokio::spawn(relay::run(hub.clone()));
#[cfg(target_os = "linux")]
tokio::spawn(screen::supervise_linux_helper(hub.screen.clone()));
let listener =
@@ -317,6 +397,128 @@ async fn shutdown_signal() {
}
}
+/// Calls the running host's local API (`~/.codync/token` over loopback).
+async fn local_call(port: u16, method: &str, body: serde_json::Value) -> Result<serde_json::Value> {
+ let not_running =
+ || anyhow::anyhow!("codync-host isn't running here. Start it with `codync-host install` (or `serve`).");
+ let token = std::fs::read_to_string(service::data_dir().join("token")).map_err(|_| not_running())?;
+ let res = http()
+ .post(format!("http://127.0.0.1:{port}/api/{method}"))
+ .bearer_auth(token.trim())
+ .json(&body)
+ .timeout(Duration::from_secs(20))
+ .send()
+ .await
+ .map_err(|_| not_running())?;
+ let status = res.status();
+ let v: serde_json::Value = res.json().await.context("reading the host's answer")?;
+ if !status.is_success() {
+ anyhow::bail!("{}", v["error"].as_str().unwrap_or("the host refused"));
+ }
+ Ok(v)
+}
+
+async fn pair(port: u16, as_json: bool) -> Result<()> {
+ let hello = local_call(port, "hello", json!({})).await?;
+ let p = local_call(port, "pairing", json!({})).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"],
+ })
+ );
+ 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 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")))
+ })
+ {
+ println!(
+ "Tip: the phone reaches this computer on the same network only. Turn on the Codync cloud or Tailscale to reach it from anywhere."
+ );
+ }
+ Ok(())
+}
+
+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<&serde_json::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();
+ let (Some(id), Ok(token)) = (identity::Identity::load(&dir)?, std::fs::read_to_string(dir.join("token"))) else {
+ eprintln!("start codync-host once first");
+ std::process::exit(1);
+ };
+ let running = http()
+ .get(format!("http://127.0.0.1:{port}/health"))
+ .timeout(Duration::from_secs(2))
+ .send()
+ .await
+ .is_ok_and(|r| r.status().is_success());
+ let v = json!({
+ "name": service::host_name(),
+ "computerId": id.computer_id(),
+ "signKey": id.sign_pub_b64(),
+ "boxKey": id.box_pub_b64(),
+ "version": env!("CARGO_PKG_VERSION"),
+ "port": port,
+ "token": token.trim(),
+ "running": running,
+ });
+ if as_json {
+ println!("{v}");
+ } else {
+ println!(
+ "name: {}\ncomputer: {}\nversion: {}\nport: {port}\nrunning: {running}",
+ v["name"].as_str().unwrap_or_default(),
+ v["computerId"].as_str().unwrap_or_default(),
+ env!("CARGO_PKG_VERSION"),
+ );
+ }
+ Ok(())
+}
+
/// Never blocks Claude Code: 1 s budget, all errors ignored.
async fn statusline(port: u16, wrapped: String) {
let mut input = String::new();
diff --git a/host/src/push.rs b/host/src/push.rs
index 201dcef3..11f92157 100644
--- a/host/src/push.rs
+++ b/host/src/push.rs
@@ -5,6 +5,7 @@
//! none are sent while the phone app is connected (it's in the foreground).
use crate::LockExt;
+use crate::crypto;
use crate::hub::{BotStatus, Hub, Runtime};
use crate::store::BotConfig;
use serde::Serialize;
@@ -12,6 +13,7 @@ use serde_json::{Value, json};
use std::collections::HashMap;
use std::sync::{LazyLock, Mutex};
use std::time::{Duration, Instant};
+use x25519_dalek::StaticSecret;
/// The two alert kinds (wire values double as the APNs category).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize)]
@@ -21,11 +23,8 @@ pub enum AlertKind {
NeedsInput,
}
-/// `(bot id, Some(kind))` for alerts, `(bot id, None)` for Live Activity updates.
-type ThrottleKey = (String, Option<AlertKind>);
-
-/// Throttle key → last send.
-static LAST_SENT: LazyLock<Mutex<HashMap<ThrottleKey, Instant>>> = LazyLock::new(Mutex::default);
+/// (bot id, kind) → last alert.
+static LAST_SENT: LazyLock<Mutex<HashMap<(String, AlertKind), Instant>>> = LazyLock::new(Mutex::default);
/// Tickets the relay reported as dead (app uninstalled / token rotated); purged on the next push.
static GONE: Mutex<Vec<String>> = Mutex::new(Vec::new());
@@ -37,7 +36,7 @@ fn relay_url(hub: &Hub) -> Option<String> {
}
/// True when `key` was sent less than `min_gap` ago; otherwise records now.
-fn throttled(key: ThrottleKey, min_gap: Duration) -> bool {
+fn throttled(key: (String, AlertKind), min_gap: Duration) -> bool {
let mut last = LAST_SENT.locked();
if last.get(&key).is_some_and(|t| t.elapsed() < min_gap) {
return true;
@@ -65,44 +64,56 @@ pub fn notify(hub: &Hub, bot: &BotConfig, title: &str, body: &str, kind: AlertKi
if bot.notify == Some(false) || bot.hidden || hub.ios_connected() {
return;
}
- if throttled((bot.id.clone(), Some(kind)), Duration::from_secs(5)) {
+ if throttled((bot.id.clone(), kind), Duration::from_secs(5)) {
return;
}
let Some(relay) = relay_url(hub) else { return };
for t in std::mem::take(&mut *GONE.locked()) {
- if let Err(error) = hub.store.remove_device(&t) {
+ if let Err(error) = hub.store.remove_push_ticket(&t) {
tracing::warn!(%error, "couldn't forget a dead push ticket");
}
}
- for ticket in hub.store.devices() {
+ // The relay and APNs only see a generic line; the real one is sealed to each device (§6.7).
+ let generic = match kind {
+ AlertKind::NeedsInput => "Needs you",
+ AlertKind::Done => "Done",
+ };
+ let secret = json!({"title": title, "body": crate::acp::truncate(body, 140)}).to_string();
+ let computer_id = hub.identity.computer_id();
+ for t in hub.store.push_tickets() {
+ let mut data = json!({"botId": bot.id, "computerId": computer_id, "ctx": t.ctx});
+ if let Some(key) = t.push_key.as_deref().and_then(|k| crypto::unb64_n::<32>(k).ok()) {
+ let eph = StaticSecret::from(crypto::random::<32>());
+ match crypto::seal_push(&hub.identity.cid_raw(), &key, secret.as_bytes(), &eph) {
+ Ok(sealed) => data["sealed"] = sealed.into(),
+ Err(error) => tracing::warn!(error = format!("{error:#}"), "couldn't seal a notification"),
+ }
+ }
post(
format!("{relay}/push"),
json!({
- "ticket": ticket,
- "alert": {"title": title, "body": crate::acp::truncate(body, 140)},
+ "ticket": t.ticket,
+ "alert": {"title": "Codync", "body": generic},
+ "mutableContent": true,
"threadId": bot.id,
"category": kind,
- "data": {"botId": bot.id},
+ "data": data,
}),
);
}
}
-/// Throttled Live Activity content updates for bots the phone is watching.
+/// Live Activity status updates for bots a phone is watching. Only the status enum and
+/// start time travel: no free text leaves the computer this way.
pub fn live_activity_update(hub: &Hub, bot_id: &str, rt: &Runtime) {
- let tickets = hub.activities.locked().get(bot_id).cloned().unwrap_or_default();
+ let tickets = hub.store.activity_tickets(bot_id);
if tickets.is_empty() {
return;
}
- // Status changes always go out; activity-line churn at most every 8 s.
- let urgent = rt.status != BotStatus::Working;
- if !urgent && throttled((bot_id.to_owned(), None), Duration::from_secs(8)) {
- return;
- }
let Some(relay) = relay_url(hub) else { return };
#[allow(clippy::cast_precision_loss)] // epoch milliseconds fit an f64 mantissa until year 287,396
let started_at = rt.started_at.map(|ms| ms as f64 / 1000.0 - SWIFT_REFERENCE_EPOCH);
- let state = json!({"status": rt.status, "activity": rt.activity, "startedAt": started_at});
+ let state = json!({"status": rt.status, "activity": "", "startedAt": started_at});
for ticket in tickets {
post(
format!("{relay}/push"),
@@ -112,7 +123,7 @@ pub fn live_activity_update(hub: &Hub, bot_id: &str, rt: &Runtime) {
}
pub fn live_activity_end(hub: &Hub, bot_id: &str) {
- let tickets = hub.activities.locked().remove(bot_id).unwrap_or_default();
+ let tickets = hub.store.take_activity_tickets(bot_id);
let Some(relay) = relay_url(hub) else { return };
let state = json!({"status": BotStatus::Idle, "activity": "", "startedAt": null});
for ticket in tickets {
diff --git a/host/src/relay.rs b/host/src/relay.rs
new file mode 100644
index 00000000..793e44bf
--- /dev/null
+++ b/host/src/relay.rs
@@ -0,0 +1,738 @@
+//! The outbound WebSocket to this computer's relay in the Codync cloud (spec §7, §9.6).
+//!
+//! Every connection runs the same order: register (once per URL) → connect with
+//! `Codync-Sig` → pull the cloud state (≤ 10 s; account devices wait for it) → publish the
+//! signed ACL → `acl.ok` → `ready`. Then device links are multiplexed onto `channel::run`
+//! (the relay only ever sees ciphertext), queued mailbox sends are delivered in order and
+//! acknowledged, and every change to the device table republishes the ACL. A reconnect
+//! drops all link state.
+
+use crate::LockExt;
+use crate::channel::{self, ChannelKind, Out, Transport};
+use crate::crypto::{self, b64};
+use crate::devices::{self, Caller};
+use crate::hub::Hub;
+use crate::store::DeviceSource;
+use crate::{api, cloud};
+use anyhow::{Context, Result, anyhow, bail};
+use futures::{SinkExt as _, StreamExt as _};
+use serde::Serialize;
+use serde_json::{Value, json};
+use std::collections::HashMap;
+use std::sync::Arc;
+use std::sync::atomic::Ordering;
+use std::time::Duration;
+use tokio::sync::mpsc;
+use tokio::task::JoinSet;
+use tokio::time::{Instant, sleep, timeout};
+use tokio_stream::StreamMap;
+use tokio_stream::wrappers::ReceiverStream;
+use tokio_tungstenite::tungstenite::{self, Message, client::IntoClientRequest as _};
+
+const PATH: &str = "/v1/relay/host?v=1";
+/// Must be exactly this string: the relay answers it without waking up.
+const PING: &str = r#"{"t":"ping"}"#;
+const PING_EVERY: Duration = Duration::from_secs(30);
+/// Nothing heard for this long (not even a pong): the socket is dead.
+const SILENT: Duration = Duration::from_secs(90);
+const STATE_WAIT: Duration = Duration::from_secs(10);
+const STATE_EVERY: Duration = Duration::from_secs(5 * 60);
+const CONNECT_TIMEOUT: Duration = Duration::from_secs(20);
+const STABLE: Duration = Duration::from_secs(60);
+const REPLACED_WAIT: Duration = Duration::from_secs(5 * 60);
+/// A device's messages waiting for its channel; the relay already rate-limits devices.
+const LINK_BUFFER: usize = 256;
+/// A mailbox send older than this is refused (TTL 24 h + clock slack).
+const MAILBOX_MAX_AGE_MS: i64 = 25 * 60 * 60 * 1000;
+const REPLACED: u16 = 4009;
+const RATE_LIMITED: u16 = 4008;
+
+/// Keeps this computer on the relay while the cloud is on; restarts when it's reconfigured.
+pub async fn run(hub: Arc<Hub>) {
+ let mut config = hub.cloud.config.subscribe();
+ loop {
+ config.mark_unchanged();
+ let url = cloud::url(&hub.store);
+ cloud::update_status(&hub, |s| {
+ s.enabled = url.is_some();
+ s.url.clone_from(&url);
+ s.registered = false;
+ s.connected = false;
+ if url.is_none() {
+ s.owner = None;
+ s.last_error = None;
+ }
+ });
+ let restart = if let Some(url) = url {
+ tokio::select! {
+ () = supervise(&hub, &url) => Ok(()),
+ r = config.changed() => r,
+ }
+ } else {
+ // No cloud: account devices can't be renewed, so they aren't honored either.
+ hub.cloud_synced.store(false, Ordering::Release);
+ config.changed().await
+ };
+ hub.cloud_synced.store(false, Ordering::Release);
+ if restart.is_err() {
+ return;
+ }
+ }
+}
+
+/// Exponential backoff with full jitter.
+struct Backoff {
+ next: Duration,
+ max: Duration,
+}
+
+impl Backoff {
+ fn new(max: Duration) -> Self {
+ Self { next: Duration::from_secs(1), max }
+ }
+
+ fn wait(&mut self) -> Duration {
+ let cap = self.next;
+ self.next = (self.next * 2).min(self.max);
+ let r = u64::from_le_bytes(crypto::random());
+ let cap_ms = u64::try_from(cap.as_millis()).unwrap_or(u64::MAX);
+ Duration::from_millis(r % (cap_ms + 1)).max(Duration::from_millis(250))
+ }
+
+ fn reset(&mut self) {
+ self.next = Duration::from_secs(1);
+ }
+}
+
+async fn supervise(hub: &Arc<Hub>, url: &str) {
+ let mut register_wait = Backoff::new(Duration::from_secs(30 * 60));
+ let mut wait = Backoff::new(Duration::from_secs(60));
+ let mut registered = false;
+ loop {
+ if !registered {
+ if let Err(e) = cloud::register(hub, url).await {
+ tracing::warn!(error = format!("{e:#}"), "couldn't register with the Codync cloud");
+ cloud::update_status(hub, |s| s.last_error = Some(format!("{e:#}")));
+ sleep(register_wait.wait()).await;
+ continue;
+ }
+ registered = true;
+ register_wait.reset();
+ }
+ let started = Instant::now();
+ let outcome = session(hub, url).await;
+ cloud::update_status(hub, |s| s.connected = false);
+ match outcome {
+ Ok(Some(REPLACED)) => {
+ tracing::error!(
+ computer_id = hub.identity.computer_id(),
+ "another host took over this computer's relay; was identity.json copied to another machine?"
+ );
+ cloud::update_status(hub, |s| s.last_error = Some("Another computer is using this identity.".into()));
+ sleep(REPLACED_WAIT).await;
+ continue;
+ }
+ Ok(code) => tracing::info!(code, "relay connection closed"),
+ Err(e) => {
+ // The relay refused the upgrade: maybe the cloud forgot us; register again.
+ if let Some(tungstenite::Error::Http(res)) = e.downcast_ref::<tungstenite::Error>() {
+ registered = !res.status().is_client_error();
+ }
+ tracing::warn!(error = format!("{e:#}"), "relay connection failed");
+ cloud::update_status(hub, |s| s.last_error = Some(format!("{e:#}")));
+ }
+ }
+ if started.elapsed() >= STABLE {
+ wait.reset();
+ }
+ sleep(wait.wait()).await;
+ }
+}
+
+/// `https://x` → `wss://x/v1/relay/host?v=1`.
+fn relay_url(base: &str) -> Result<String> {
+ let rest = base
+ .strip_prefix("https://")
+ .map(|r| format!("wss://{r}"))
+ .or_else(|| base.strip_prefix("http://").map(|r| format!("ws://{r}")))
+ .ok_or_else(|| anyhow!("unsupported cloud URL"))?;
+ Ok(format!("{rest}{PATH}"))
+}
+
+type Sink = futures::stream::SplitSink<
+ tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>,
+ Message,
+>;
+
+/// One relay connection; returns the close code the relay sent, if any.
+async fn session(hub: &Arc<Hub>, base: &str) -> Result<Option<u16>> {
+ let mut req = relay_url(base)?.into_client_request()?;
+ let sig = hub.identity.sign_request("GET", &cloud::authority(base)?, PATH, b"");
+ req.headers_mut().insert("Codync-Sig", sig.parse()?);
+ let (ws, _) = timeout(CONNECT_TIMEOUT, tokio_tungstenite::connect_async(req))
+ .await
+ .map_err(|_| anyhow!("timed out connecting to the relay"))??;
+ // Account devices wait for this connection's state pull (§4.3).
+ hub.cloud_synced.store(false, Ordering::Release);
+ cloud::update_status(hub, |s| {
+ s.connected = true;
+ s.last_error = None;
+ });
+ tracing::info!(computer_id = hub.identity.computer_id(), "connected to the relay");
+ let (sink, mut stream) = ws.split();
+ let mut s = Session {
+ hub: hub.clone(),
+ base: base.to_owned(),
+ sink,
+ links: HashMap::new(),
+ outs: StreamMap::new(),
+ pulls: JoinSet::new(),
+ held: None,
+ ready: false,
+ retried: false,
+ };
+ if timeout(STATE_WAIT, pull_state(hub.clone(), base.to_owned())).await.is_err() {
+ tracing::warn!("the cloud state didn't arrive in time; account devices wait for it");
+ }
+ let mut auth = hub.auth.subscribe();
+ auth.mark_unchanged();
+ s.publish_acl().await?;
+ let mut ping = tokio::time::interval(PING_EVERY);
+ ping.reset();
+ let mut poll = tokio::time::interval(STATE_EVERY);
+ poll.reset();
+ let mut heard = Instant::now();
+ loop {
+ tokio::select! {
+ // Links first: a pairing answer and its `4100` go out before the ACL that ends the offer.
+ biased;
+ Some((link, out)) = s.outs.next() => s.link_out(link, out).await?,
+ msg = stream.next() => {
+ heard = Instant::now();
+ match msg {
+ None => return Ok(None),
+ Some(Err(e)) => return Err(e).context("relay socket"),
+ Some(Ok(Message::Text(t))) => s.on_message(t.as_str()).await?,
+ Some(Ok(Message::Close(frame))) => return Ok(frame.map(|f| u16::from(f.code))),
+ Some(Ok(_)) => {}
+ }
+ }
+ changed = auth.changed() => {
+ if changed.is_err() {
+ return Ok(None);
+ }
+ s.publish_acl().await?;
+ }
+ _ = ping.tick() => {
+ if heard.elapsed() > SILENT {
+ bail!("the relay stopped answering");
+ }
+ s.sink.send(Message::Text(PING.into())).await?;
+ // The state pull failed on this connection: account devices stay out until one works.
+ if !hub.cloud_synced.load(Ordering::Acquire) && s.pulls.is_empty() {
+ s.pull();
+ }
+ }
+ _ = poll.tick() => {
+ if hub.cloud.status().owner.is_some() {
+ s.pull();
+ }
+ }
+ Some(_) = s.pulls.join_next() => s.deliver_held().await?,
+ }
+ }
+}
+
+/// A state pull on the current connection; success lets account devices in.
+async fn pull_state(hub: Arc<Hub>, base: String) {
+ match cloud::pull(&hub, &base).await {
+ Ok(()) => hub.cloud_synced.store(true, Ordering::Release),
+ Err(e) => {
+ tracing::warn!(error = format!("{e:#}"), "couldn't get the cloud state");
+ cloud::update_status(&hub, |s| s.last_error = Some(format!("{e:#}")));
+ }
+ }
+}
+
+struct Session {
+ hub: Arc<Hub>,
+ base: String,
+ sink: Sink,
+ /// Device messages into each link's channel.
+ links: HashMap<String, mpsc::Sender<Value>>,
+ /// What each link's channel sends back.
+ outs: StreamMap<String, ReceiverStream<Out>>,
+ /// State pulls in flight; dropped (aborted) with the connection.
+ pulls: JoinSet<()>,
+ /// An account device's queued send that arrived before this connection's state pull
+ /// succeeded. The relay sends the next item only after an ack, so there is at most one.
+ held: Option<Value>,
+ ready: bool,
+ /// The last ACL was refused once already.
+ retried: bool,
+}
+
+impl Session {
+ async fn send(&mut self, v: &Value) -> Result<()> {
+ self.sink.send(Message::Text(v.to_string().into())).await.context("relay socket")
+ }
+
+ fn pull(&mut self) {
+ self.pulls.spawn(pull_state(self.hub.clone(), self.base.clone()));
+ }
+
+ /// Delivers the held mailbox item once a state pull has succeeded.
+ async fn deliver_held(&mut self) -> Result<()> {
+ if !self.hub.cloud_synced.load(Ordering::Acquire) {
+ return Ok(());
+ }
+ let Some(item) = self.held.take() else { return Ok(()) };
+ let ack = mailbox_item(&self.hub, &item).await;
+ self.send(&ack).await
+ }
+
+ async fn publish_acl(&mut self) -> Result<()> {
+ let msg = signed_acl(&self.hub)?;
+ self.send(&msg).await
+ }
+
+ async fn link_out(&mut self, link: String, out: Out) -> Result<()> {
+ let msg = match out {
+ Out::Msg(m) => json!({"t": "data", "link": link, "m": m}),
+ Out::Close(code, reason) => {
+ self.links.remove(&link);
+ self.outs.remove(&link);
+ json!({"t": "close", "link": link, "code": code, "reason": reason})
+ }
+ };
+ self.send(&msg).await
+ }
+
+ async fn close_link(&mut self, link: &str, code: u16, reason: &str) -> Result<()> {
+ self.links.remove(link);
+ self.outs.remove(link);
+ self.send(&json!({"t": "close", "link": link, "code": code, "reason": reason})).await
+ }
+
+ async fn on_message(&mut self, text: &str) -> Result<()> {
+ let v: Value = serde_json::from_str(text).unwrap_or_default();
+ match v["t"].as_str().unwrap_or_default() {
+ "open" => {
+ let (Some(link), Some(dk)) = (v["link"].as_str(), v["dk"].as_str()) else { return Ok(()) };
+ let (in_tx, incoming) = mpsc::channel(LINK_BUFFER);
+ let (outgoing, out_rx) = mpsc::channel(64);
+ self.links.insert(link.to_owned(), in_tx);
+ self.outs.insert(link.to_owned(), ReceiverStream::new(out_rx));
+ let kind = ChannelKind::Relay {
+ link: link.to_owned(),
+ dk: dk.to_owned(),
+ pair: v["pair"].as_bool().unwrap_or(false),
+ };
+ tokio::spawn(channel::run(self.hub.clone(), Transport { incoming, outgoing }, kind));
+ }
+ "data" => {
+ let link = v["link"].as_str().unwrap_or_default();
+ let Some(tx) = self.links.get(link) else { return Ok(()) };
+ let m = if v["m"].is_object() { v["m"].clone() } else { Value::Null };
+ match tx.try_send(m) {
+ Ok(()) => {}
+ Err(mpsc::error::TrySendError::Full(_)) => {
+ tracing::warn!(link, "device link overflowed; closing it");
+ self.close_link(link, RATE_LIMITED, "rateLimited").await?;
+ }
+ Err(mpsc::error::TrySendError::Closed(_)) => {
+ self.links.remove(link);
+ }
+ }
+ }
+ // The device is gone: its channel ends when its input does.
+ "close" => {
+ if let Some(link) = v["link"].as_str() {
+ self.links.remove(link);
+ self.outs.remove(link);
+ }
+ }
+ "mbox.item" => {
+ let from = v["from"].as_str().unwrap_or_default();
+ let account = self.hub.store.device(from).is_some_and(|d| d.source == DeviceSource::Account);
+ if account && !self.hub.cloud_synced.load(Ordering::Acquire) {
+ // Refusing it would drop it for good; unacknowledged, it waits for the pull
+ // (or goes back to the queue if this connection ends).
+ self.held = Some(v);
+ if self.pulls.is_empty() {
+ self.pull();
+ }
+ return Ok(());
+ }
+ let ack = mailbox_item(&self.hub, &v).await;
+ self.send(&ack).await?;
+ }
+ "cloud.changed" => self.pull(),
+ "acl.ok" => {
+ self.retried = false;
+ if !self.ready {
+ self.ready = true;
+ self.send(&json!({"t": "ready"})).await?;
+ tracing::info!(computer_id = self.hub.identity.computer_id(), "relay ready");
+ }
+ }
+ "error" => {
+ let code = v["code"].as_str().unwrap_or_default();
+ if !matches!(code, "staleVersion" | "badAcl") {
+ return Ok(());
+ }
+ if self.retried {
+ bail!("the relay refused this computer's ACL ({code})");
+ }
+ // The relay has a newer version than this database (deleted or restored): jump past it.
+ self.retried = true;
+ bump_acl_ver(&self.hub, v["ver"].as_i64().unwrap_or(0))?;
+ self.publish_acl().await?;
+ }
+ _ => {}
+ }
+ Ok(())
+ }
+}
+
+// MARK: ACL (§4.3)
+
+fn bump_acl_ver(hub: &Hub, at_least: i64) -> Result<()> {
+ let ver = hub.store.kv_get("acl_ver").and_then(|v| v.parse().ok()).unwrap_or(0_i64).max(at_least);
+ hub.store.kv_set("acl_ver", &ver.to_string())
+}
+
+/// The next ACL (version bumped), signed: `{"t":"acl","d","sig"}`.
+fn signed_acl(hub: &Hub) -> Result<Value> {
+ let ver = hub.store.kv_get("acl_ver").and_then(|v| v.parse().ok()).unwrap_or(0_i64) + 1;
+ hub.store.kv_set("acl_ver", &ver.to_string())?;
+ let devices: Vec<Value> =
+ hub.store.devices()?.into_iter().map(|d| json!({"dk": d.key, "grant": d.grant_id})).collect();
+ let offers: Vec<Value> =
+ hub.pairing.locked().offers().into_iter().map(|(id, exp)| json!({"id": id, "exp": exp})).collect();
+ let acl = json!({
+ "v": 1,
+ "computerId": hub.identity.computer_id(),
+ "ver": ver,
+ "devices": devices,
+ "offers": offers,
+ })
+ .to_string();
+ Ok(json!({"t": "acl", "d": b64(acl.as_bytes()), "sig": b64(&hub.identity.sign(acl.as_bytes()))}))
+}
+
+// MARK: mailbox (§6.4, §7.7)
+
+/// Why a queued send was refused (`mbox.ack.code`).
+#[derive(Serialize, Clone, Copy, Debug, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+enum MailboxFailure {
+ Unauthorized,
+ UnknownBot,
+ Invalid,
+}
+
+/// Delivers one queued send and says how it went: `{"t":"mbox.ack","seq","ok","code"?}`.
+async fn mailbox_item(hub: &Arc<Hub>, item: &Value) -> Value {
+ let seq = item["seq"].clone();
+ match deliver(hub, item).await {
+ Ok(()) => json!({"t": "mbox.ack", "seq": seq, "ok": true}),
+ Err(code) => {
+ tracing::info!(?code, "refused a queued message");
+ json!({"t": "mbox.ack", "seq": seq, "ok": false, "code": code})
+ }
+ }
+}
+
+async fn deliver(hub: &Arc<Hub>, item: &Value) -> Result<(), MailboxFailure> {
+ use MailboxFailure::{Invalid, Unauthorized, UnknownBot};
+ let from = item["from"].as_str().unwrap_or_default();
+ let device = devices::authorize(hub, from).map_err(|_| Unauthorized)?;
+ let dk = crypto::unb64_n::<32>(from).map_err(|_| Invalid)?;
+ let nonce = item["nonce"].as_str().filter(|n| !n.is_empty()).ok_or(Invalid)?;
+ let blob = item["d"].as_str().and_then(|d| crypto::unb64(d).ok()).ok_or(Invalid)?;
+ let plain = crypto::open_mailbox(&hub.identity.box_secret, &hub.identity.cid_raw(), &dk, nonce, &blob)
+ .map_err(|_| Invalid)?;
+ let inner: Value = serde_json::from_slice(&plain).map_err(|_| Invalid)?;
+ let b = &inner["b"];
+ let fresh = inner["ts"].as_i64().is_some_and(|ts| crate::store::now_ms() - ts <= MAILBOX_MAX_AGE_MS);
+ if inner["m"] != "send" || b["clientNonce"].as_str() != Some(nonce) || !fresh {
+ return Err(Invalid);
+ }
+ let bot = b["botId"].as_str().ok_or(Invalid)?;
+ if hub.store.bot(bot).ok().flatten().is_none_or(|r| r.deleted) {
+ return Err(UnknownBot);
+ }
+ let caller = Caller::Device { key: device.key, scopes: device.scopes };
+ // `send` skips a clientNonce it already has: a redelivery never runs twice.
+ api::dispatch(hub, &caller, "send", b.clone())
+ .await
+ .map(drop)
+ .map_err(|e| if e.is::<devices::Forbidden>() { Unauthorized } else { Invalid })
+}
+
+#[cfg(test)]
+mod tests {
+ #![allow(clippy::unwrap_used, clippy::expect_used)]
+ use super::*;
+ use crate::identity::Identity;
+ use crate::store::{BotConfig, Device, DeviceSource, Scope, Store, now_ms};
+ use axum::extract::ws::{Message as AxMessage, WebSocket, WebSocketUpgrade};
+ use axum::extract::{Request, State};
+ use axum::routing::{any, get, post};
+ use chacha20poly1305::aead::{Aead, KeyInit, Payload};
+ use ed25519_dalek::SigningKey;
+ use hkdf::Hkdf;
+ use sha2::Sha256;
+ use x25519_dalek::StaticSecret;
+
+ fn temp_hub() -> Arc<Hub> {
+ let dir = std::env::temp_dir().join(format!("codync-relay-{}", uuid::Uuid::new_v4()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let store = Store::open(&dir.join("t.db")).unwrap();
+ Hub::new(store, "host".into(), Identity::load_or_create(&dir).unwrap(), "token".into(), 0)
+ }
+
+ /// What the fake cloud saw and does.
+ #[derive(Default)]
+ struct Fake {
+ /// ACL version the "DO" already stored (a previous database).
+ stored_ver: std::sync::Mutex<i64>,
+ /// Messages from the host, in order.
+ from_host: std::sync::Mutex<Vec<Value>>,
+ /// Messages to push to the host after `ready`.
+ script: std::sync::Mutex<Vec<Value>>,
+ state: std::sync::Mutex<Value>,
+ /// State pulls to fail (500) before answering.
+ state_failures: std::sync::Mutex<u32>,
+ signatures_ok: std::sync::Mutex<Vec<bool>>,
+ }
+
+ fn check_sig(req: &Request, sign_pub: &[u8; 32], authority: &str) -> bool {
+ let h = req.headers().get("codync-sig").and_then(|v| v.to_str().ok()).unwrap_or_default();
+ let field = |k: &str| h.split(',').find_map(|p| p.strip_prefix(&format!("{k}="))).unwrap_or_default();
+ let ts: i64 = field("ts").parse().unwrap_or(0);
+ let path = req.uri().path_and_query().unwrap().as_str();
+ let input = crypto::request_sig_input(req.method().as_str(), authority, path, ts, field("nonce"), b"");
+ field("kid") == b64(sign_pub)
+ && crypto::verify(sign_pub, input.as_bytes(), &crypto::unb64_n(field("sig")).unwrap()).is_ok()
+ }
+
+ async fn fake_cloud(fake: Arc<Fake>, hub: Arc<Hub>) -> String {
+ use axum::response::IntoResponse as _;
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let authority = listener.local_addr().unwrap().to_string();
+ let sign_pub = hub.identity.sign_pub();
+ let cid = hub.identity.computer_id();
+ let a1 = authority.clone();
+ let app = axum::Router::new()
+ .route(
+ "/v1/host/register",
+ post(move |State(f): State<Arc<Fake>>, req: Request| async move {
+ let ok = req.headers().contains_key("codync-sig");
+ f.signatures_ok.lock().unwrap().push(ok);
+ axum::Json(json!({"computerId": cid, "owned": false}))
+ }),
+ )
+ .route(
+ "/v1/host/state",
+ get(move |State(f): State<Arc<Fake>>, req: Request| async move {
+ f.signatures_ok.lock().unwrap().push(check_sig(&req, &sign_pub, &a1));
+ let mut failures = f.state_failures.lock().unwrap();
+ if *failures > 0 {
+ *failures -= 1;
+ return (axum::http::StatusCode::INTERNAL_SERVER_ERROR, axum::Json(json!({}))).into_response();
+ }
+ axum::Json(f.state.lock().unwrap().clone()).into_response()
+ }),
+ )
+ .route(
+ "/v1/relay/host",
+ any(move |State(f): State<Arc<Fake>>, ws: WebSocketUpgrade, req: Request| async move {
+ let _ = req;
+ ws.on_upgrade(move |socket| fake_do(f, socket))
+ }),
+ )
+ .with_state(fake);
+ tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
+ format!("http://{authority}")
+ }
+
+ async fn fake_do(f: Arc<Fake>, mut ws: WebSocket) {
+ while let Some(Ok(AxMessage::Text(t))) = ws.recv().await {
+ let v: Value = serde_json::from_str(t.as_str()).unwrap();
+ f.from_host.lock().unwrap().push(v.clone());
+ let reply = match v["t"].as_str().unwrap() {
+ "acl" => {
+ let d = crypto::unb64(v["d"].as_str().unwrap()).unwrap();
+ let acl: Value = serde_json::from_slice(&d).unwrap();
+ let ver = acl["ver"].as_i64().unwrap();
+ let mut stored = f.stored_ver.lock().unwrap();
+ if ver <= *stored {
+ json!({"t": "error", "code": "staleVersion", "ver": *stored})
+ } else {
+ *stored = ver;
+ json!({"t": "acl.ok", "ver": ver})
+ }
+ }
+ "ready" => {
+ let script: Vec<Value> = f.script.lock().unwrap().drain(..).collect();
+ for m in script {
+ ws.send(AxMessage::Text(m.to_string().into())).await.unwrap();
+ }
+ continue;
+ }
+ _ => continue,
+ };
+ ws.send(AxMessage::Text(reply.to_string().into())).await.unwrap();
+ }
+ }
+
+ /// Device side of §6.4, for the test.
+ fn seal_mailbox(hub: &Hub, device: &SigningKey, nonce: &str, plain: &[u8]) -> String {
+ let cid = hub.identity.cid_raw();
+ let dk = device.verifying_key().to_bytes();
+ let eph = StaticSecret::from(crypto::random::<32>());
+ let epk = crypto::x25519_pub(&eph);
+ let ss = crypto::x25519(&eph, &hub.identity.box_pub()).unwrap();
+ let salt = [b"codync/mbox/v1".as_slice(), &cid, &dk, &epk].concat();
+ let mut key = [0u8; 32];
+ Hkdf::<Sha256>::new(Some(&salt), &ss).expand(b"codync/mbox-key/v1", &mut key).unwrap();
+ let aad = [dk.as_slice(), nonce.as_bytes()].concat();
+ let ct = chacha20poly1305::ChaCha20Poly1305::new(&key.into())
+ .encrypt(&[0u8; 12].into(), Payload { msg: plain, aad: &aad })
+ .unwrap();
+ let sig = crypto::sign(device, &[b"codync/mbox/v1".as_slice(), &cid, &epk, &ct].concat());
+ b64(&[epk.as_slice(), &sig, &ct].concat())
+ }
+
+ async fn wait_for(f: &Fake, pred: impl Fn(&[Value]) -> bool) {
+ let deadline = Instant::now() + Duration::from_secs(10);
+ while !pred(&f.from_host.lock().unwrap()) {
+ assert!(Instant::now() < deadline, "timed out; host sent {:?}", f.from_host.lock().unwrap());
+ sleep(Duration::from_millis(20)).await;
+ }
+ }
+
+ #[tokio::test]
+ async fn connects_publishes_acl_past_a_stale_version_and_delivers_mail() {
+ let hub = temp_hub();
+ let fake = Arc::new(Fake::default());
+ // The relay remembers version 7 from before this database was deleted.
+ *fake.stored_ver.lock().unwrap() = 7;
+ let grant_key = SigningKey::from_bytes(&crypto::random());
+ let phone = SigningKey::from_bytes(&crypto::random());
+ let dk = b64(phone.verifying_key().as_bytes());
+ hub.store
+ .put_device(&Device {
+ key: dk.clone(),
+ name: "Phone".into(),
+ platform: "ios".into(),
+ source: DeviceSource::Local,
+ grant_id: None,
+ scopes: vec![Scope::Control, Scope::Screen],
+ lease_until: None,
+ created_at: now_ms(),
+ last_seen_at: None,
+ })
+ .unwrap();
+ let injected = b64(grant_key.verifying_key().as_bytes());
+ *fake.state.lock().unwrap() = json!({"owner": null, "requests": [],
+ "grants": [{"grantId": "grt_x", "deviceKey": injected, "deviceName": "x", "platform": "ios", "scopes": ["control"]}]});
+
+ let cwd = std::env::temp_dir().to_string_lossy().into_owned();
+ let cfg: BotConfig =
+ serde_json::from_value(json!({"id": "", "name": "B", "cwd": cwd, "backend": "custom", "command": "true"}))
+ .unwrap();
+ let bot = hub.create_bot(cfg).unwrap();
+ let bot_id = bot["id"].as_str().unwrap().to_owned();
+ let nonce = "3F2504E0-4F89-11D3-9A0C-0305E82C3301";
+ let inner = json!({"m": "send", "b": {"botId": bot_id, "text": "hi", "clientNonce": nonce}, "ts": now_ms()});
+ let blob = seal_mailbox(&hub, &phone, nonce, inner.to_string().as_bytes());
+ let stranger = SigningKey::from_bytes(&crypto::random());
+ *fake.script.lock().unwrap() = vec![
+ json!({"t": "mbox.item", "seq": 1, "from": dk, "nonce": nonce, "d": blob, "exp": now_ms() + 1000}),
+ json!({"t": "mbox.item", "seq": 2, "from": dk, "nonce": nonce, "d": blob, "exp": now_ms() + 1000}),
+ json!({"t": "mbox.item", "seq": 3, "from": b64(stranger.verifying_key().as_bytes()), "nonce": nonce, "d": blob, "exp": 0}),
+ json!({"t": "open", "link": "L1", "dk": b64(stranger.verifying_key().as_bytes()), "pair": false}),
+ json!({"t": "data", "link": "L1", "m": {"t": "hello", "v": 1, "dk": dk}}),
+ ];
+
+ let base = fake_cloud(fake.clone(), hub.clone()).await;
+ hub.store.kv_set("cloud_url", &base).unwrap();
+ tokio::spawn(run(hub.clone()));
+
+ wait_for(&fake, |m| m.iter().filter(|v| v["t"] == "mbox.ack").count() == 3).await;
+ wait_for(&fake, |m| m.iter().any(|v| v["t"] == "close" && v["link"] == "L1")).await;
+ let sent = fake.from_host.lock().unwrap().clone();
+ let kinds: Vec<&str> = sent.iter().map(|v| v["t"].as_str().unwrap()).collect();
+ assert_eq!(&kinds[..3], ["acl", "acl", "ready"], "stale ACL is re-signed once, then ready");
+ let acl: Value = serde_json::from_slice(&crypto::unb64(sent[1]["d"].as_str().unwrap()).unwrap()).unwrap();
+ assert_eq!(acl["ver"], 8, "max(local, relay) + 1");
+ assert_eq!(acl["devices"], json!([{"dk": dk, "grant": null}]), "a grant injected by the cloud isn't listed");
+ crypto::verify(
+ &hub.identity.sign_pub(),
+ &crypto::unb64(sent[1]["d"].as_str().unwrap()).unwrap(),
+ &crypto::unb64_n(sent[1]["sig"].as_str().unwrap()).unwrap(),
+ )
+ .unwrap();
+ assert!(fake.signatures_ok.lock().unwrap().iter().all(|ok| *ok));
+ assert!(hub.cloud_synced.load(Ordering::Acquire), "the state was applied on this connection");
+
+ let acks: Vec<&Value> = sent.iter().filter(|v| v["t"] == "mbox.ack").collect();
+ assert_eq!(acks[0]["ok"], true);
+ assert_eq!(acks[1]["ok"], true, "a redelivery is acknowledged");
+ assert_eq!((acks[2]["ok"].as_bool(), acks[2]["code"].as_str()), (Some(false), Some("unauthorized")));
+ let history = hub.store.history(&bot_id, i64::MAX, 50).unwrap();
+ assert_eq!(history.iter().filter(|e| e.data["clientNonce"] == nonce).count(), 1, "delivered exactly once");
+
+ let close = sent.iter().find(|v| v["t"] == "close").unwrap();
+ assert_eq!(close["code"], 4002, "hello.dk must match the link's open.dk");
+ assert!(hub.cloud.status().connected);
+ }
+
+ #[tokio::test]
+ async fn account_mail_waits_for_a_state_pull_instead_of_failing() {
+ let hub = temp_hub();
+ let fake = Arc::new(Fake::default());
+ let phone = SigningKey::from_bytes(&crypto::random());
+ let dk = b64(phone.verifying_key().as_bytes());
+ hub.store
+ .put_device(&Device {
+ key: dk.clone(),
+ name: "Phone".into(),
+ platform: "ios".into(),
+ source: DeviceSource::Account,
+ grant_id: Some("grt_a".into()),
+ scopes: vec![Scope::Control, Scope::Screen],
+ lease_until: Some(now_ms() + 60_000),
+ created_at: now_ms(),
+ last_seen_at: None,
+ })
+ .unwrap();
+ *fake.state.lock().unwrap() =
+ json!({"owner": null, "requests": [], "grants": [{"grantId": "grt_a", "deviceKey": dk}]});
+ // The pull on connect fails: without the fix the item below would be refused for good.
+ *fake.state_failures.lock().unwrap() = 1;
+ let cwd = std::env::temp_dir().to_string_lossy().into_owned();
+ let cfg: BotConfig =
+ serde_json::from_value(json!({"id": "", "name": "B", "cwd": cwd, "backend": "custom", "command": "true"}))
+ .unwrap();
+ let bot_id = hub.create_bot(cfg).unwrap()["id"].as_str().unwrap().to_owned();
+ let nonce = "9A1B2C3D-4F89-11D3-9A0C-0305E82C3301";
+ let inner = json!({"m": "send", "b": {"botId": bot_id, "text": "hi", "clientNonce": nonce}, "ts": now_ms()});
+ let blob = seal_mailbox(&hub, &phone, nonce, inner.to_string().as_bytes());
+ *fake.script.lock().unwrap() =
+ vec![json!({"t": "mbox.item", "seq": 1, "from": dk, "nonce": nonce, "d": blob, "exp": now_ms() + 1000})];
+
+ let base = fake_cloud(fake.clone(), hub.clone()).await;
+ hub.store.kv_set("cloud_url", &base).unwrap();
+ tokio::spawn(run(hub.clone()));
+
+ wait_for(&fake, |m| m.iter().any(|v| v["t"] == "mbox.ack")).await;
+ let sent = fake.from_host.lock().unwrap().clone();
+ let ack = sent.iter().find(|v| v["t"] == "mbox.ack").unwrap();
+ assert_eq!(ack["ok"], true, "delivered once the retried pull confirmed the grant: {ack}");
+ assert!(hub.cloud_synced.load(Ordering::Acquire));
+ }
+}
diff --git a/host/src/service.rs b/host/src/service.rs
index 7361d761..f439eedd 100644
--- a/host/src/service.rs
+++ b/host/src/service.rs
@@ -254,8 +254,33 @@ fn pct(s: &str) -> String {
out
}
-pub fn pairing_url(name: &str, token: &str, urls: &[String]) -> String {
- format!("codync://pair?name={}&token={}&urls={}", pct(name), pct(token), pct(&urls.join(",")))
+/// What the pairing QR carries (spec §4.1): public keys and a one-time code, no secrets
+/// that outlive the code.
+pub struct PairingQr<'a> {
+ pub name: &'a str,
+ pub computer_id: &'a str,
+ pub sign_key: &'a str,
+ pub box_key: &'a str,
+ pub code: &'a str,
+ pub urls: &'a [String],
+ pub cloud: Option<&'a str>,
+}
+
+pub fn pairing_url(q: &PairingQr) -> String {
+ let mut url = format!(
+ "codync://pair?v=3&name={}&id={}&sk={}&bk={}&code={}&urls={}",
+ pct(q.name),
+ q.computer_id,
+ q.sign_key,
+ q.box_key,
+ q.code,
+ pct(&q.urls.join(","))
+ );
+ if let Some(cloud) = q.cloud {
+ url.push_str("&cloud=");
+ url.push_str(&pct(cloud));
+ }
+ url
}
fn read_settings(settings: &Path) -> Result<Option<Value>> {
@@ -343,11 +368,22 @@ mod tests {
#[test]
fn pairing_url_is_escaped() {
- let u = pairing_url("Kevin's Mac", "t0k", &["http://100.1.2.3:19222".into(), "http://a:1".into()]);
+ let urls = ["http://100.1.2.3:19222".to_owned(), "http://a:1".to_owned()];
+ let mut q = PairingQr {
+ name: "Kevin's Mac",
+ computer_id: "cid",
+ sign_key: "sk",
+ box_key: "bk",
+ code: "c0de",
+ urls: &urls,
+ cloud: None,
+ };
assert_eq!(
- u,
- "codync://pair?name=Kevin%27s%20Mac&token=t0k&urls=http%3A%2F%2F100.1.2.3%3A19222%2Chttp%3A%2F%2Fa%3A1"
+ pairing_url(&q),
+ "codync://pair?v=3&name=Kevin%27s%20Mac&id=cid&sk=sk&bk=bk&code=c0de&urls=http%3A%2F%2F100.1.2.3%3A19222%2Chttp%3A%2F%2Fa%3A1"
);
+ q.cloud = Some("https://cloud.example");
+ assert!(pairing_url(&q).ends_with("&cloud=https%3A%2F%2Fcloud.example"));
}
#[test]
diff --git a/host/src/store.rs b/host/src/store.rs
index 080d9cc5..4a8c84f9 100644
--- a/host/src/store.rs
+++ b/host/src/store.rs
@@ -175,6 +175,96 @@ fn parse_bot((id, cfg, rev, deleted, session_id, read_rev): RawBot) -> Option<Bo
}
}
+/// Current schema version (kv `schema`).
+const SCHEMA: i64 = 3;
+
+/// 3: authorized devices (keys, not push tickets) with their push and Live Activity
+/// tickets. The old ticket-only `devices` table is dropped; phones re-register on connect.
+fn migrate(c: &Connection) -> Result<()> {
+ let version: i64 =
+ c.query_row("SELECT CAST(v AS INTEGER) FROM kv WHERE k = 'schema'", [], |r| r.get(0)).optional()?.unwrap_or(0);
+ if version >= SCHEMA {
+ return Ok(());
+ }
+ c.execute_batch(
+ "BEGIN;
+ DROP TABLE IF EXISTS devices;
+ CREATE TABLE devices(
+ key TEXT PRIMARY KEY, name TEXT NOT NULL, platform TEXT NOT NULL,
+ source TEXT NOT NULL, grant_id TEXT, scopes TEXT NOT NULL,
+ lease_until INTEGER, created_at INTEGER NOT NULL, last_seen_at INTEGER);
+ CREATE TABLE IF NOT EXISTS push_tickets(
+ ticket TEXT PRIMARY KEY, device_key TEXT NOT NULL, push_key TEXT, ctx TEXT, name TEXT,
+ created_at INTEGER NOT NULL);
+ CREATE TABLE IF NOT EXISTS activity_tickets(
+ ticket TEXT PRIMARY KEY, bot_id TEXT NOT NULL, device_key TEXT NOT NULL, created_at INTEGER NOT NULL);
+ INSERT INTO kv(k, v) VALUES('schema', '3') ON CONFLICT(k) DO UPDATE SET v = '3';
+ COMMIT;",
+ )?;
+ Ok(())
+}
+
+/// Where an authorized device came from (wire values `local` / `account`).
+#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub enum DeviceSource {
+ /// Paired with the QR code shown on this computer.
+ Local,
+ /// Approved here for a signed-in account; kept alive by a lease the cloud renews.
+ Account,
+}
+
+/// What a device may do (wire values `control` / `screen`).
+#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub enum Scope {
+ Control,
+ Screen,
+}
+
+/// One row of the authorized-device table (spec §4.3).
+#[derive(Serialize, Clone, Debug)]
+#[serde(rename_all = "camelCase")]
+pub struct Device {
+ pub key: String,
+ pub name: String,
+ pub platform: String,
+ pub source: DeviceSource,
+ #[serde(skip)]
+ pub grant_id: Option<String>,
+ pub scopes: Vec<Scope>,
+ pub lease_until: Option<i64>,
+ pub created_at: i64,
+ pub last_seen_at: Option<i64>,
+}
+
+/// A push ticket with the device's push key (§6.7) and account context.
+pub struct PushTicket {
+ pub ticket: String,
+ pub push_key: Option<String>,
+ pub ctx: Option<String>,
+}
+
+const DEVICE_COLS: &str = "key, name, platform, source, grant_id, scopes, lease_until, created_at, last_seen_at";
+
+fn row_device(r: &rusqlite::Row) -> rusqlite::Result<Device> {
+ let source: String = r.get(3)?;
+ let scopes: String = r.get(5)?;
+ Ok(Device {
+ key: r.get(0)?,
+ name: r.get(1)?,
+ platform: r.get(2)?,
+ // Unknown values grant nothing: an unreadable source is an account device (leased),
+ // unreadable scopes are none.
+ source: serde_json::from_value(Value::String(source)).unwrap_or(DeviceSource::Account),
+ grant_id: r.get(4)?,
+ scopes: serde_json::from_str(&scopes).unwrap_or_default(),
+ lease_until: r.get(6)?,
+ created_at: r.get(7)?,
+ last_seen_at: r.get(8)?,
+ })
+}
+
const ENTRY_COLS: &str = "seq, id, bot_id, rev, kind, turn, data, created_at, updated_at";
const BOT_COLS: &str = "id, config, rev, deleted, session_id, read_rev";
@@ -193,9 +283,9 @@ impl Store {
rev INTEGER NOT NULL, kind TEXT NOT NULL, turn INTEGER NOT NULL, data TEXT NOT NULL,
created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL);
CREATE INDEX IF NOT EXISTS entries_rev ON entries(rev);
- CREATE INDEX IF NOT EXISTS entries_bot ON entries(bot_id, seq);
- CREATE TABLE IF NOT EXISTS devices(ticket TEXT PRIMARY KEY, name TEXT, created_at INTEGER NOT NULL);",
+ CREATE INDEX IF NOT EXISTS entries_bot ON entries(bot_id, seq);",
)?;
+ migrate(&c)?;
Ok(Self { db: Mutex::new(c) })
}
@@ -413,27 +503,120 @@ impl Store {
// MARK: devices
- pub fn add_device(&self, ticket: &str, name: &str) -> Result<()> {
+ pub fn device(&self, key: &str) -> Option<Device> {
+ let c = self.db.locked();
+ let row = c.query_row(&format!("SELECT {DEVICE_COLS} FROM devices WHERE key = ?1"), [key], row_device);
+ logged("device", row.optional()).flatten()
+ }
+
+ pub fn devices(&self) -> Result<Vec<Device>> {
+ let c = self.db.locked();
+ let mut st = c.prepare(&format!("SELECT {DEVICE_COLS} FROM devices ORDER BY created_at"))?;
+ Ok(st.query_map([], row_device)?.collect::<rusqlite::Result<_>>()?)
+ }
+
+ /// Adds (or, for a key paired again, refreshes) an authorized device.
+ pub fn put_device(&self, d: &Device) -> Result<()> {
let c = self.db.locked();
c.execute(
- "INSERT INTO devices(ticket, name, created_at) VALUES(?1, ?2, ?3)
- ON CONFLICT(ticket) DO UPDATE SET name = ?2",
- params![ticket, name, now_ms()],
+ "INSERT INTO devices(key, name, platform, source, grant_id, scopes, lease_until, created_at)
+ VALUES(?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)
+ ON CONFLICT(key) DO UPDATE SET name = ?2, platform = ?3, source = ?4, grant_id = ?5,
+ scopes = ?6, lease_until = ?7",
+ params![
+ d.key,
+ d.name,
+ d.platform,
+ serde_json::to_value(d.source)?.as_str(),
+ d.grant_id,
+ serde_json::to_string(&d.scopes)?,
+ d.lease_until,
+ d.created_at
+ ],
)?;
Ok(())
}
- pub fn remove_device(&self, ticket: &str) -> Result<()> {
- self.db.locked().execute("DELETE FROM devices WHERE ticket = ?1", [ticket])?;
+ /// Removes a device with its push and Live Activity tickets; false when it wasn't there.
+ 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])?;
+ tx.commit()?;
+ Ok(n > 0)
+ }
+
+ /// Extends an account device's lease (the cloud still lists its grant).
+ pub fn set_lease(&self, key: &str, until: i64) -> Result<()> {
+ let c = self.db.locked();
+ c.execute("UPDATE devices SET lease_until = ?2 WHERE key = ?1", params![key, until])?;
Ok(())
}
- pub fn devices(&self) -> Vec<String> {
+ pub fn touch_device(&self, key: &str) -> Result<()> {
let c = self.db.locked();
- let tickets = c
- .prepare("SELECT ticket FROM devices")
- .and_then(|mut st| st.query_map([], |r| r.get(0))?.collect::<rusqlite::Result<Vec<String>>>());
- logged("devices", tickets).unwrap_or_default()
+ c.execute("UPDATE devices SET last_seen_at = ?2 WHERE key = ?1", params![key, now_ms()])?;
+ Ok(())
+ }
+
+ pub fn add_push_ticket(
+ &self,
+ ticket: &str,
+ device_key: &str,
+ push_key: Option<&str>,
+ ctx: Option<&str>,
+ name: &str,
+ ) -> Result<()> {
+ let c = self.db.locked();
+ c.execute(
+ "INSERT INTO push_tickets(ticket, device_key, push_key, ctx, name, created_at) VALUES(?1, ?2, ?3, ?4, ?5, ?6)
+ ON CONFLICT(ticket) DO UPDATE SET device_key = ?2, push_key = ?3, ctx = ?4, name = ?5",
+ params![ticket, device_key, push_key, ctx, name, now_ms()],
+ )?;
+ Ok(())
+ }
+
+ pub fn remove_push_ticket(&self, ticket: &str) -> Result<()> {
+ self.db.locked().execute("DELETE FROM push_tickets WHERE ticket = ?1", [ticket])?;
+ Ok(())
+ }
+
+ pub fn push_tickets(&self) -> Vec<PushTicket> {
+ let c = self.db.locked();
+ let rows = c.prepare("SELECT ticket, push_key, ctx FROM push_tickets").and_then(|mut st| {
+ st.query_map([], |r| Ok(PushTicket { ticket: r.get(0)?, push_key: r.get(1)?, ctx: r.get(2)? }))?
+ .collect::<rusqlite::Result<Vec<_>>>()
+ });
+ logged("push tickets", rows).unwrap_or_default()
+ }
+
+ pub fn add_activity_ticket(&self, ticket: &str, bot_id: &str, device_key: &str) -> Result<()> {
+ let c = self.db.locked();
+ c.execute(
+ "INSERT INTO activity_tickets(ticket, bot_id, device_key, created_at) VALUES(?1, ?2, ?3, ?4)
+ ON CONFLICT(ticket) DO UPDATE SET bot_id = ?2, device_key = ?3",
+ params![ticket, bot_id, device_key, now_ms()],
+ )?;
+ Ok(())
+ }
+
+ pub fn activity_tickets(&self, bot_id: &str) -> Vec<String> {
+ let c = self.db.locked();
+ let rows = c
+ .prepare("SELECT ticket FROM activity_tickets WHERE bot_id = ?1")
+ .and_then(|mut st| st.query_map([bot_id], |r| r.get(0))?.collect::<rusqlite::Result<Vec<String>>>());
+ logged("activity tickets", rows).unwrap_or_default()
+ }
+
+ /// Forgets a bot's Live Activity tickets (its activity ended); returns them.
+ pub fn take_activity_tickets(&self, bot_id: &str) -> Vec<String> {
+ let tickets = self.activity_tickets(bot_id);
+ if let Err(error) = self.db.locked().execute("DELETE FROM activity_tickets WHERE bot_id = ?1", [bot_id]) {
+ tracing::warn!(%error, bot = bot_id, "couldn't forget Live Activity tickets");
+ }
+ tickets
}
}
@@ -497,6 +680,60 @@ mod tests {
assert_eq!(s.expire_pending().unwrap(), 0, "idempotent");
}
+ #[test]
+ fn removing_a_device_drops_its_tickets() {
+ let s = temp_store();
+ let d = Device {
+ key: "dk1".into(),
+ name: "Phone".into(),
+ platform: "ios".into(),
+ source: DeviceSource::Local,
+ grant_id: None,
+ scopes: vec![Scope::Control, Scope::Screen],
+ lease_until: None,
+ created_at: 1,
+ last_seen_at: None,
+ };
+ s.put_device(&d).unwrap();
+ s.put_device(&Device { key: "dk2".into(), ..d.clone() }).unwrap();
+ s.add_push_ticket("t1", "dk1", Some("pk"), Some("local"), "Phone").unwrap();
+ s.add_push_ticket("t2", "dk2", None, None, "Phone").unwrap();
+ s.add_activity_ticket("a1", "b1", "dk1").unwrap();
+ s.add_activity_ticket("a2", "b1", "dk2").unwrap();
+ let got = s.device("dk1").unwrap();
+ assert_eq!((got.source, got.scopes), (DeviceSource::Local, vec![Scope::Control, Scope::Screen]));
+
+ assert!(s.remove_device("dk1").unwrap());
+ assert!(!s.remove_device("dk1").unwrap());
+ assert!(s.device("dk1").is_none());
+ assert_eq!(s.push_tickets().iter().map(|t| t.ticket.as_str()).collect::<Vec<_>>(), ["t2"]);
+ assert_eq!(s.activity_tickets("b1"), ["a2"]);
+ assert_eq!(s.take_activity_tickets("b1"), ["a2"]);
+ assert!(s.activity_tickets("b1").is_empty());
+ }
+
+ #[test]
+ fn schema_3_replaces_the_old_ticket_table() {
+ let dir = std::env::temp_dir().join(format!("codync-test-{}", uuid::Uuid::new_v4()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let db = dir.join("t.db");
+ {
+ let c = Connection::open(&db).unwrap();
+ c.execute_batch(
+ "CREATE TABLE kv(k TEXT PRIMARY KEY, v TEXT NOT NULL);
+ CREATE TABLE devices(ticket TEXT PRIMARY KEY, name TEXT, created_at INTEGER NOT NULL);
+ INSERT INTO devices VALUES('old', 'iPhone', 1);",
+ )
+ .unwrap();
+ }
+ let s = Store::open(&db).unwrap();
+ assert!(s.devices().unwrap().is_empty());
+ assert_eq!(s.kv_get("schema").as_deref(), Some("3"));
+ drop(s);
+ let s = Store::open(&db).unwrap();
+ assert!(s.devices().unwrap().is_empty(), "reopening keeps the new table");
+ }
+
#[test]
fn permission_wire_values_round_trip() {
let p: Permission = serde_json::from_str("\"auto\"").unwrap();
diff --git a/host/tests/e2e.rs b/host/tests/e2e.rs
index 6163d7ab..3c284cad 100644
--- a/host/tests/e2e.rs
+++ b/host/tests/e2e.rs
@@ -3,6 +3,13 @@
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] // test code: failing loudly is the point
+/// The host's wire crypto doubles as this test's device implementation.
+#[path = "../src/crypto.rs"]
+#[allow(dead_code)]
+mod crypto;
+
+use ed25519_dalek::SigningKey;
+use futures::{SinkExt as _, StreamExt as _};
use serde_json::{Value, json};
use std::path::PathBuf;
use std::process::{Child, Command, Stdio};
@@ -33,6 +40,7 @@ async fn start_host() -> Host {
let child = Command::new(env!("CARGO_BIN_EXE_codync-host"))
.args(["serve", "--bind", "127.0.0.1", "--port", &port.to_string()])
.env("CODYNC_HOME", &home)
+ .env("CODYNC_CLOUD", "off")
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
@@ -139,3 +147,145 @@ async fn rejects_requests_without_the_token() {
.unwrap();
assert_eq!(res.status(), 401);
}
+
+type Ws = tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>;
+
+/// A phone talking to the host over the direct E2E channel.
+struct Phone {
+ ws: Ws,
+ sealer: crypto::Sealer,
+ opener: crypto::Opener,
+}
+
+enum Frame {
+ Inner(Value),
+ Closed(u16),
+}
+
+impl Phone {
+ /// Connects and completes the handshake, verifying the host against the pinned `sk`.
+ async fn connect(host: &Host, key: &SigningKey, sk: &[u8; 32], pair: bool) -> Self {
+ let url = format!("{}/channel?v=1", host.base.replace("http://", "ws://"));
+ let (mut ws, _) = tokio_tungstenite::connect_async(url).await.unwrap();
+ let cid = crypto::computer_id_raw(sk);
+ let dk = key.verifying_key().to_bytes();
+ let ek = x25519_dalek::StaticSecret::from(crypto::random::<32>());
+ let ek_pub = crypto::x25519_pub(&ek);
+ let n = crypto::random::<32>();
+ let sig = crypto::sign(key, &crypto::hs1_input(&cid, &dk, &ek_pub, &n));
+ let hello = json!({"t": "hello", "v": 1, "dk": crypto::b64(&dk), "ek": crypto::b64(&ek_pub),
+ "n": crypto::b64(&n), "sig": crypto::b64(&sig), "pair": pair});
+ ws.send(hello.to_string().into()).await.unwrap();
+ let welcome: Value = serde_json::from_str(ws.next().await.unwrap().unwrap().to_text().unwrap()).unwrap();
+ assert_eq!(welcome["t"], "welcome", "{welcome}");
+ let ek_h: [u8; 32] = crypto::unb64_n(welcome["ek"].as_str().unwrap()).unwrap();
+ let th = crypto::transcript_hash(&cid, &dk, &ek_pub, &n, &ek_h);
+ crypto::verify(sk, &th, &crypto::unb64_n(welcome["sig"].as_str().unwrap()).unwrap()).unwrap();
+ let keys = crypto::channel_keys(&crypto::x25519(&ek, &ek_h).unwrap(), &th);
+ Self { ws, sealer: crypto::Sealer::new(keys.d2h), opener: crypto::Opener::new(keys.h2d, 16 << 20) }
+ }
+
+ async fn send(&mut self, v: Value) {
+ for f in self.sealer.seal(v.to_string().as_bytes()).unwrap() {
+ self.ws.send(f.to_string().into()).await.unwrap();
+ }
+ }
+
+ async fn recv(&mut self) -> Frame {
+ use tokio_tungstenite::tungstenite::Message;
+ loop {
+ let msg = tokio::time::timeout(Duration::from_secs(20), self.ws.next()).await.expect("host answers");
+ match msg.unwrap().unwrap() {
+ Message::Text(t) => {
+ let f: Value = serde_json::from_str(t.as_str()).unwrap();
+ if let Some(bytes) = self.opener.open(&f).unwrap() {
+ return Frame::Inner(serde_json::from_slice(&bytes).unwrap());
+ }
+ }
+ Message::Close(c) => return Frame::Closed(c.map_or(1005, |c| c.code.into())),
+ _ => {}
+ }
+ }
+ }
+
+ async fn inner(&mut self) -> Value {
+ match self.recv().await {
+ Frame::Inner(v) => v,
+ Frame::Closed(code) => panic!("closed with {code}"),
+ }
+ }
+
+ async fn call(&mut self, id: u64, m: &str, b: Value) -> Value {
+ self.send(json!({"id": id, "m": m, "b": b})).await;
+ loop {
+ let v = self.inner().await;
+ if v["id"] == id && v.get("ev").is_none() {
+ assert!(v["ok"].is_object(), "{m}: {v}");
+ return v["ok"].clone();
+ }
+ }
+ }
+}
+
+fn query_param(url: &str, name: &str) -> String {
+ url.split(['?', '&']).find_map(|p| p.strip_prefix(&format!("{name}="))).unwrap().to_owned()
+}
+
+#[tokio::test]
+async fn phone_pairs_and_chats_over_the_direct_channel() {
+ if Command::new("python3").arg("--version").output().is_err() {
+ eprintln!("skipping: python3 not available");
+ return;
+ }
+ let host = start_host().await;
+ let old = tokio_tungstenite::connect_async(format!("{}/channel?v=2", host.base.replace("http://", "ws://"))).await;
+ let Err(tokio_tungstenite::tungstenite::Error::Http(res)) = old else {
+ panic!("an unknown version must be refused")
+ };
+ assert_eq!(res.status(), 426);
+
+ let qr = host.call("pairing", json!({})).await;
+ let url = qr["pairingUrl"].as_str().unwrap();
+ let sk: [u8; 32] = crypto::unb64_n(&query_param(url, "sk")).unwrap();
+ assert_eq!(query_param(url, "id"), crypto::computer_id(&sk));
+ let key = SigningKey::from_bytes(&crypto::random());
+
+ let mut phone = Phone::connect(&host, &key, &sk, true).await;
+ let code = query_param(url, "code");
+ phone.send(json!({"id": 1, "m": "pair", "b": {"code": code, "name": "Test iPhone", "platform": "ios"}})).await;
+ assert_eq!(phone.inner().await["ok"]["computerId"], crypto::computer_id(&sk));
+ assert!(matches!(phone.recv().await, Frame::Closed(4100)));
+
+ let mut phone = Phone::connect(&host, &key, &sk, false).await;
+ let hello = phone.call(1, "hello", json!({})).await;
+ assert_eq!(hello["boxKey"], query_param(url, "bk"));
+ let agent = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fake_agent.py");
+ let bot = phone
+ .call(
+ 2,
+ "createBot",
+ json!({
+ "name": "Tester", "backend": "custom", "command": format!("python3 '{}'", agent.display()),
+ "cwd": host.home.to_string_lossy(), "permission": "auto",
+ }),
+ )
+ .await["bot"]["id"]
+ .as_str()
+ .unwrap()
+ .to_owned();
+ phone.send(json!({"id": 3, "sub": "events", "b": {"since": 0, "client": "ios"}})).await;
+ assert_eq!(phone.inner().await["ev"]["type"], "hello");
+ phone.call(4, "send", json!({"botId": bot, "text": "go", "clientNonce": "n1"})).await;
+ loop {
+ let v = phone.inner().await;
+ let e = &v["ev"]["entry"];
+ if v["id"] == 3 && e["kind"] == "agent" && e["data"]["final"] == true {
+ assert!(e["data"]["text"].as_str().unwrap().starts_with("Done"), "{e}");
+ break;
+ }
+ }
+
+ let devices = host.call("devices", json!({})).await;
+ assert_eq!(devices["devices"][0]["name"], "Test iPhone");
+ assert_eq!(devices["devices"][0]["connected"], true);
+}
diff --git a/kit/Package.swift b/kit/Package.swift
index 0c9802dc..88e75913 100644
--- a/kit/Package.swift
+++ b/kit/Package.swift
@@ -27,5 +27,6 @@ let package = Package(
resources: [.process("Resources")]
),
.testTarget(name: "CodyncKitTests", dependencies: ["CodyncKit"], resources: [.copy("Fixtures")]),
+ .testTarget(name: "CodyncUITests", dependencies: ["CodyncUI", "CodyncKit"]),
]
)
diff --git a/kit/Sources/CodyncKit/Client/ChannelTransport.swift b/kit/Sources/CodyncKit/Client/ChannelTransport.swift
new file mode 100644
index 00000000..4fd02ee1
--- /dev/null
+++ b/kit/Sources/CodyncKit/Client/ChannelTransport.swift
@@ -0,0 +1,932 @@
+import CryptoKit
+import Foundation
+import Network
+import os
+
+private let log = Logger(subsystem: "com.pokai.Codync", category: "Channel")
+
+/// The end-to-end encrypted channel to one computer (§6, §7): direct WebSocket on the LAN when it
+/// answers within 1.5 s, otherwise the cloud relay. Inner RPC multiplexes calls and streams over
+/// one channel; the relay adds presence and the offline mailbox. Reconnects by itself until `shutdown()`.
+public actor ChannelTransport: RemoteTransport {
+ static let identityChanged = "This computer's identity changed. Pair it again to keep using it."
+
+ public private(set) var computer: Computer
+ /// The last connection attempt failed because this app or the computer is too old.
+ public private(set) var needsUpgrade = false
+ /// Gave up for good (revoked, identity changed, needs an update); only a new transport can recover.
+ public private(set) var isStopped = false
+
+ private let identity: DeviceIdentity
+ /// Pairing mode (§4.1): the only request allowed is `pair`; the host then closes with 4100.
+ private let pairingCode: String?
+ private let dial: Dialer
+ private let directBudget: Duration
+ private let watchesNetwork: Bool
+
+ private var state: LinkState = .connecting
+ private var lastSeen: Date?
+ private var link: Link?
+ private var linkGeneration = 0
+ private var closed = false
+ private var restartRequested = false
+ private var supervisor: Task<Void, Never>?
+ private var monitor: NWPathMonitor?
+ private var sawFirstPath = false
+ /// Relay upgrades refused with 403 since the last handshake. Right after a pairing or an
+ /// approval the device can reach the relay before the host's new ACL does, so a few are retried.
+ private var refusals = 0
+
+ private var nextRequestId: UInt32 = 0
+ private var calls: [UInt32: CheckedContinuation<Data, Error>] = [:]
+ private var streams: [UInt32: AsyncThrowingStream<Data, Error>.Continuation] = [:]
+ private var streamIds: [UUID: UInt32] = [:]
+ private var puts: [String: CheckedContinuation<Void, Error>] = [:]
+ private var cancels: [String: CheckedContinuation<MailboxCancel, Never>] = [:]
+ private var lists: [UUID: CheckedContinuation<[QueuedItem], Never>] = [:]
+ private var waiters: [UUID: CheckedContinuation<Void, Never>] = [:]
+
+ private var stateObservers: [UUID: AsyncStream<LinkState>.Continuation] = [:]
+ private var computerObservers: [UUID: AsyncStream<Computer>.Continuation] = [:]
+ private var mailboxObservers: [UUID: AsyncStream<MailboxEvent>.Continuation] = [:]
+
+ /// One open socket and, once the handshake is done, its channel keys.
+ private struct Link {
+ let socket: any ChannelSocket
+ let route: HostRoute
+ let generation: Int
+ let outbox: AsyncStream<String>.Continuation
+ var handshake: RelayCrypto.Handshake?
+ var sealer: RelayCrypto.FrameSealer?
+ var opener: RelayCrypto.FrameOpener?
+ var lastReceived = ContinuousClock.now
+ }
+
+ /// How one connection attempt ended.
+ private enum Outcome: Sendable {
+ /// Reconnect now (paired, rekey, network changed).
+ case again
+ case retry(String)
+ /// Retry with backoff while showing this state (a lapsed lease may come back).
+ case wait(LinkState)
+ /// Don't retry: revoked, identity changed, needs an update, pairing over.
+ case stop(LinkState)
+ }
+
+ public init(computer: Computer, identity: DeviceIdentity) {
+ self.init(computer: computer, identity: identity, pairingCode: nil)
+ }
+
+ init(computer: Computer, identity: DeviceIdentity, pairingCode: String?, dial: @escaping Dialer = URLSessionSocket.dial,
+ directBudget: Duration = .milliseconds(1500), watchesNetwork: Bool = true) {
+ self.computer = computer
+ self.identity = identity
+ self.pairingCode = pairingCode
+ self.dial = dial
+ self.directBudget = directBudget
+ self.watchesNetwork = watchesNetwork
+ }
+
+ func start() {
+ guard supervisor == nil, !closed else { return }
+ supervisor = Task { await self.run() }
+ guard watchesNetwork else { return }
+ // A new network path (Wi-Fi ↔ cellular) can make direct possible again, or dead.
+ let monitor = NWPathMonitor()
+ monitor.pathUpdateHandler = { [weak self] path in
+ guard path.status == .satisfied else { return }
+ Task { await self?.networkChanged() }
+ }
+ monitor.start(queue: .global(qos: .utility))
+ self.monitor = monitor
+ }
+
+ public func shutdown() {
+ guard !closed else { return }
+ closed = true
+ supervisor?.cancel()
+ monitor?.cancel()
+ link?.socket.close(code: 1000)
+ dropChannel(HostError.unreachable)
+ dropMailbox()
+ for (_, c) in waiters { c.resume() }
+ waiters = [:]
+ stateObservers.values.forEach { $0.finish() }
+ computerObservers.values.forEach { $0.finish() }
+ mailboxObservers.values.forEach { $0.finish() }
+ stateObservers = [:]
+ computerObservers = [:]
+ mailboxObservers = [:]
+ }
+
+ /// Reconnects from scratch (the app came back to the foreground, say).
+ public func reconnect() {
+ guard !closed else { return }
+ restartRequested = true
+ link?.socket.close(code: 1000)
+ wake()
+ }
+
+ private func networkChanged() {
+ // The monitor reports the current path right away; only later ones are changes.
+ guard sawFirstPath else { sawFirstPath = true; return }
+ reconnect()
+ }
+
+ /// Waits until the first attempt is decided (ready, offline, failed, unauthorized).
+ func settled(within limit: Duration) async -> LinkState {
+ let deadline = ContinuousClock.now + limit
+ while state == .connecting, !closed, ContinuousClock.now < deadline {
+ await stateChange(until: deadline)
+ }
+ return state
+ }
+
+ // MARK: state
+
+ private func setState(_ new: LinkState) {
+ guard new != state else { return }
+ state = new
+ for c in stateObservers.values { c.yield(new) }
+ wake()
+ }
+
+ private func wake() {
+ let w = waiters
+ waiters = [:]
+ for c in w.values { c.resume() }
+ }
+
+ /// Suspends until the state changes, `wake()` is called, or `deadline` passes.
+ private func stateChange(until deadline: ContinuousClock.Instant) async {
+ let key = UUID()
+ await withCheckedContinuation { (c: CheckedContinuation<Void, Never>) in
+ waiters[key] = c
+ Task {
+ try? await Task.sleep(until: deadline)
+ self.resumeWaiter(key)
+ }
+ }
+ }
+
+ private func resumeWaiter(_ key: UUID) {
+ waiters.removeValue(forKey: key)?.resume()
+ }
+
+ private func observeStates(_ key: UUID, _ c: AsyncStream<LinkState>.Continuation) {
+ guard !closed else { c.yield(state); c.finish(); return }
+ c.yield(state)
+ stateObservers[key] = c
+ }
+
+ private func observeComputer(_ key: UUID, _ c: AsyncStream<Computer>.Continuation) {
+ guard !closed else { c.finish(); return }
+ computerObservers[key] = c
+ }
+
+ private func observeMailbox(_ key: UUID, _ c: AsyncStream<MailboxEvent>.Continuation) {
+ guard !closed else { c.finish(); return }
+ mailboxObservers[key] = c
+ }
+
+ private func removeObserver(_ key: UUID) {
+ stateObservers[key] = nil
+ computerObservers[key] = nil
+ mailboxObservers[key] = nil
+ }
+
+ public nonisolated func states() -> AsyncStream<LinkState> {
+ AsyncStream { c in
+ let key = UUID()
+ Task { await self.observeStates(key, c) }
+ c.onTermination = { _ in Task { await self.removeObserver(key) } }
+ }
+ }
+
+ /// Every merged `Computer` after an inner `hello` (§7.5 step 5); persist it.
+ public nonisolated func computerUpdates() -> AsyncStream<Computer> {
+ AsyncStream { c in
+ let key = UUID()
+ Task { await self.observeComputer(key, c) }
+ c.onTermination = { _ in Task { await self.removeObserver(key) } }
+ }
+ }
+
+ public nonisolated func mailboxEvents() -> AsyncStream<MailboxEvent> {
+ AsyncStream { c in
+ let key = UUID()
+ Task { await self.observeMailbox(key, c) }
+ c.onTermination = { _ in Task { await self.removeObserver(key) } }
+ }
+ }
+
+ // MARK: connection loop (§7.5, §7.6)
+
+ private func run() async {
+ var backoff = Backoff()
+ while !closed, !Task.isCancelled {
+ if case .ready = state { setState(.connecting) }
+ let started = ContinuousClock.now
+ let outcome = await attempt()
+ guard !closed, !Task.isCancelled else { return }
+ if restartRequested {
+ restartRequested = false
+ backoff = Backoff()
+ continue
+ }
+ switch outcome {
+ case .again:
+ backoff = Backoff()
+ case let .stop(final):
+ log.info("channel stopped: \(String(describing: final), privacy: .public)")
+ isStopped = true
+ setState(final)
+ return
+ case .retry, .wait:
+ // Stable for a minute: the next failure starts the backoff over.
+ if ContinuousClock.now - started > .seconds(60) { backoff = Backoff() }
+ if case let .wait(shown) = outcome {
+ setState(shown)
+ } else if case let .retry(reason) = outcome {
+ // The relay said the computer is off: keep saying so rather than "can't reach".
+ if case .hostOffline = state {} else { setState(.failed(reason)) }
+ }
+ let deadline = ContinuousClock.now + backoff.next()
+ while !closed, !restartRequested, ContinuousClock.now < deadline {
+ await stateChange(until: deadline)
+ }
+ restartRequested = false
+ }
+ }
+ }
+
+ private func attempt() async -> Outcome {
+ let directURLs = computer.urls.compactMap(Self.channelURL)
+ if !directURLs.isEmpty {
+ switch await raceDirect(directURLs) {
+ case let .connected(socket, keys): return await serve(socket, route: .direct, keys: keys)
+ case let .outcome(end): return end
+ case let .rejected(end):
+ // A plaintext `reject` isn't signed: whatever answers at a saved LAN address can
+ // send one. With a relay, ask the pinned computer through it; without one, only a
+ // pairing (short-lived, user-driven) ends on it, a saved computer keeps retrying.
+ if computer.cloud != nil { break }
+ if pairingCode != nil {
+ if case .stop(.failed(HostError.upgradeRequired.localizedDescription)) = end { return upgrade() }
+ return end
+ }
+ if case let .stop(shown) = end { return .wait(shown) }
+ return end
+ case .none: break
+ }
+ }
+ guard let cloud = computer.cloud else { return .retry(HostError.unreachable.localizedDescription) }
+ let socket: any ChannelSocket
+ do {
+ socket = try await dial(.relay(relayRequest(cloud)))
+ } catch {
+ return .retry(HostError.unreachable.localizedDescription)
+ }
+ return await serve(socket, route: .relay, keys: nil)
+ }
+
+ /// `http://h:p` → `ws://h:p/channel?v=1`.
+ static func channelURL(_ base: String) -> URL? {
+ guard var comps = URLComponents(string: base), let scheme = comps.scheme else { return nil }
+ comps.scheme = scheme == "https" ? "wss" : "ws"
+ comps.path = "/channel"
+ comps.query = "v=1"
+ return comps.url
+ }
+
+ /// `GET {cloud}/v1/relay/device/{computerId}?v=1[&pair=<offerId>]`, signed with the device key.
+ private func relayRequest(_ cloud: URL) throws -> URLRequest {
+ var comps = URLComponents(url: cloud.appending(path: "v1/relay/device/\(computer.id)"), resolvingAgainstBaseURL: false)
+ var query = "v=1"
+ if let pairingCode, let code = Data(base64URL: pairingCode) { query += "&pair=\(RelayCrypto.offerId(code: code))" }
+ comps?.percentEncodedQuery = query
+ guard let url = comps?.url else { throw HostError.unreachable }
+ let header = try identity.signatureHeader(method: "GET", authority: RelayCrypto.authority(of: url),
+ pathAndQuery: RelayCrypto.pathAndQuery(of: url), body: Data())
+ comps?.scheme = url.scheme == "http" ? "ws" : "wss"
+ var req = URLRequest(url: comps?.url ?? url, timeoutInterval: 15)
+ req.setValue(header, forHTTPHeaderField: "Codync-Sig")
+ return req
+ }
+
+ private enum DirectResult: Sendable {
+ case connected(any ChannelSocket, RelayCrypto.ChannelKeys)
+ /// Authenticated (the pinned key signed it): the identity changed.
+ case outcome(Outcome)
+ /// An unauthenticated `reject` from some address.
+ case rejected(Outcome)
+ case none
+ }
+
+ /// Every direct candidate in parallel; the first finished handshake within the budget wins.
+ private func raceDirect(_ urls: [URL]) async -> DirectResult {
+ let computer = computer
+ let identity = identity
+ let pair = pairingCode != nil
+ let dial = dial
+ let budget = directBudget
+ enum Finish: Sendable { case attempt(DirectResult), timeout }
+ return await withTaskGroup(of: Finish.self) { group in
+ for url in urls {
+ group.addTask { .attempt(await Self.directHandshake(url, computer: computer, identity: identity, pair: pair, dial: dial)) }
+ }
+ group.addTask {
+ try? await Task.sleep(for: budget)
+ return .timeout
+ }
+ var winner = DirectResult.none
+ var rejection: Outcome?
+ var decided = false
+ var failed = 0
+ for await finish in group {
+ guard !decided else {
+ // A slower address that connected anyway: not needed.
+ if case let .attempt(.connected(socket, _)) = finish { socket.close(code: 1000) }
+ continue
+ }
+ switch finish {
+ case .timeout:
+ decided = true
+ case let .attempt(result):
+ // A reject only fails that address; another may be the real computer.
+ if case let .rejected(o) = result, rejection == nil { rejection = o }
+ switch result {
+ case .none, .rejected:
+ failed += 1
+ decided = failed == urls.count
+ default:
+ winner = result
+ decided = true
+ }
+ }
+ if decided { group.cancelAll() }
+ }
+ if case .none = winner, let rejection { return .rejected(rejection) }
+ return winner
+ }
+ }
+
+ private static func directHandshake(_ url: URL, computer: Computer, identity: DeviceIdentity, pair: Bool, dial: Dialer) async -> DirectResult {
+ let socket: any ChannelSocket
+ do { socket = try await dial(.direct(url)) } catch { return .none }
+ return await withTaskCancellationHandler {
+ do {
+ let hs = try RelayCrypto.Handshake(computer: computer, deviceKey: identity.deviceKey)
+ try await socket.send(try Self.helloMessage(hs, identity: identity, pair: pair))
+ while true {
+ let wire = try Self.decodeWire(try await socket.receive())
+ switch wire.t {
+ case "welcome":
+ guard let ek = wire.ek.flatMap(Data.init(base64URL:)), let sig = wire.sig.flatMap(Data.init(base64URL:)) else {
+ socket.close(code: 4002)
+ return .none
+ }
+ do {
+ return .connected(socket, try hs.finish(ekH: ek, sig: sig))
+ } catch {
+ socket.close(code: 4001)
+ return .outcome(.stop(.unauthorized(identityChanged)))
+ }
+ case "reject":
+ socket.close(code: 1000)
+ return Self.rejection(wire).map { .rejected($0) } ?? .none
+ default:
+ continue
+ }
+ }
+ } catch {
+ socket.close(code: 1000)
+ return .none
+ }
+ } onCancel: {
+ socket.close(code: 1000)
+ }
+ }
+
+ /// What a `reject` means, or nil when a plain retry may succeed (rate limits, clock skew).
+ private static func rejection(_ wire: Wire) -> Outcome? {
+ let message = wire.message.flatMap { $0.isEmpty ? nil : $0 }
+ switch wire.code {
+ case "unauthorized", "revoked":
+ return .stop(.unauthorized(message ?? "This device isn't allowed on that computer anymore."))
+ case "leaseExpired":
+ // The computer couldn't confirm the account's approval lately; it may again.
+ return .wait(.unauthorized(message ?? "Your computer couldn't confirm this device's access. Retrying."))
+ case "unsupportedVersion":
+ return .stop(.failed(HostError.upgradeRequired.localizedDescription))
+ case "pairingClosed":
+ return .stop(.failed(message ?? "This pairing code expired. Show a new one on the computer."))
+ default:
+ return nil
+ }
+ }
+
+ /// Runs one socket until it ends.
+ private func serve(_ socket: any ChannelSocket, route: HostRoute, keys: RelayCrypto.ChannelKeys?) async -> Outcome {
+ let (outbox, sink) = AsyncStream<String>.makeStream()
+ linkGeneration += 1
+ let generation = linkGeneration
+ link = Link(socket: socket, route: route, generation: generation, outbox: sink)
+ // One writer, so frames leave in counter order and a message's chunks never interleave.
+ let writer = Task {
+ for await text in outbox {
+ do { try await socket.send(text) } catch { socket.close(code: 1011); return }
+ }
+ }
+ let heartbeat = Task { await self.heartbeat(generation, route: route) }
+ if let keys { install(keys, route: route) }
+ if closed || restartRequested { socket.close(code: 1000) }
+
+ var end: Outcome
+ do {
+ while true {
+ let text = try await socket.receive()
+ if let outcome = handle(text, generation: generation) {
+ end = outcome
+ socket.close(code: 1000)
+ break
+ }
+ }
+ } catch let closedError as SocketClosed {
+ end = outcome(closeCode: closedError.code)
+ } catch let refused as SocketRefused {
+ end = outcome(httpStatus: refused.status)
+ } catch {
+ end = .retry(HostError.unreachable.localizedDescription)
+ }
+ writer.cancel()
+ heartbeat.cancel()
+ sink.finish()
+ link = nil
+ dropChannel(HostError.unreachable)
+ dropMailbox()
+ return end
+ }
+
+ private func outcome(closeCode code: Int) -> Outcome {
+ switch code {
+ case 4001, 4003:
+ .stop(.unauthorized("This device isn't allowed on \(computer.name) anymore."))
+ case 4410:
+ .stop(.failed("This pairing code expired. Show a new one on the computer."))
+ case 4400:
+ upgrade()
+ case 4100:
+ // Paired: pairing mode is done; otherwise reconnect normally.
+ pairingCode == nil ? .again : .stop(.failed("Paired."))
+ case 4011:
+ .again
+ default:
+ .retry(HostError.unreachable.localizedDescription)
+ }
+ }
+
+ private func outcome(httpStatus status: Int) -> Outcome {
+ switch status {
+ case 403:
+ refusals += 1
+ return refusals <= 3
+ ? .retry(HostError.unreachable.localizedDescription)
+ : .stop(.unauthorized("This device isn't allowed on \(computer.name) anymore."))
+ case 426: return upgrade()
+ default: return .retry(HostError.unreachable.localizedDescription)
+ }
+ }
+
+ private func upgrade() -> Outcome {
+ needsUpgrade = true
+ return .stop(.failed(HostError.upgradeRequired.localizedDescription))
+ }
+
+ private func heartbeat(_ generation: Int, route: HostRoute) async {
+ // Direct: the host pings every 15 s; relay: we ping the DO every 30 s.
+ let interval: Duration = route == .direct ? .seconds(15) : .seconds(30)
+ let limit: Duration = route == .direct ? .seconds(45) : .seconds(75)
+ while !Task.isCancelled {
+ try? await Task.sleep(for: interval)
+ guard !Task.isCancelled, let link, link.generation == generation else { return }
+ if ContinuousClock.now - link.lastReceived > limit {
+ log.info("channel silent, closing")
+ link.socket.close(code: 1011)
+ return
+ }
+ let socket = link.socket
+ Task {
+ try? await socket.ping()
+ if route == .direct { self.touch(generation) }
+ }
+ }
+ }
+
+ private func touch(_ generation: Int) {
+ if link?.generation == generation { link?.lastReceived = .now }
+ }
+
+ // MARK: incoming
+
+ struct Wire: Decodable {
+ var t: String
+ var ek: String?
+ var sig: String?
+ var code: String?
+ var message: String?
+ var c: UInt64?
+ var d: String?
+ var online: Bool?
+ var lastSeenAt: Int64?
+ var nonce: String?
+ var state: String?
+ var items: [QueuedItem]?
+ }
+
+ static func decodeWire(_ text: String) throws -> Wire {
+ try JSONDecoder().decode(Wire.self, from: Data(text.utf8))
+ }
+
+ static func helloMessage(_ hs: RelayCrypto.Handshake, identity: DeviceIdentity, pair: Bool) throws -> String {
+ struct Hello: Encodable { var t = "hello"; var v = 1; var dk: String; var ek: String; var n: String; var sig: String; var pair: Bool? }
+ let hello = Hello(dk: identity.publicKey, ek: hs.ekD.base64URL, n: hs.n.base64URL,
+ sig: try identity.sign(hs.signInput).base64URL, pair: pair ? true : nil)
+ return String(decoding: try JSONEncoder().encode(hello), as: UTF8.self)
+ }
+
+ /// Handles one socket message; returns an outcome when the socket must end.
+ private func handle(_ text: String, generation: Int) -> Outcome? {
+ guard link?.generation == generation else { return nil }
+ link?.lastReceived = .now
+ guard let wire = try? Self.decodeWire(text) else { return nil }
+ switch wire.t {
+ case "presence":
+ if wire.online == true {
+ // The host (re)joined: any previous channel is gone; start a fresh handshake.
+ dropChannel(HostError.unreachable)
+ return startHandshake(generation)
+ }
+ lastSeen = wire.lastSeenAt.map(Date.init(milliseconds:))
+ dropChannel(HostError.computerOffline(lastSeen: lastSeen))
+ link?.handshake = nil
+ link?.sealer = nil
+ link?.opener = nil
+ setState(.hostOffline(lastSeen: lastSeen))
+ case "welcome":
+ guard let hs = link?.handshake, let route = link?.route,
+ let ek = wire.ek.flatMap(Data.init(base64URL:)), let sig = wire.sig.flatMap(Data.init(base64URL:)) else {
+ return .retry(HostError.unreachable.localizedDescription)
+ }
+ link?.handshake = nil
+ do {
+ install(try hs.finish(ekH: ek, sig: sig), route: route)
+ } catch {
+ return .stop(.unauthorized(Self.identityChanged))
+ }
+ case "reject":
+ if wire.code == "unsupportedVersion" { return upgrade() }
+ return Self.rejection(wire) ?? .retry(wire.message ?? HostError.unreachable.localizedDescription)
+ case "f":
+ guard var opener = link?.opener, let c = wire.c, let d = wire.d.flatMap(Data.init(base64URL:)) else {
+ link?.socket.close(code: 4002)
+ return .retry("Protocol error")
+ }
+ do {
+ let message = try opener.open(c: c, d: d)
+ link?.opener = opener
+ if let message { handleInner(message) }
+ } catch RelayCryptoError.tooLarge {
+ link?.socket.close(code: 4013)
+ return .retry("Message too large")
+ } catch {
+ link?.socket.close(code: 4002)
+ return .retry("Protocol error")
+ }
+ case "mbox.ok":
+ if let nonce = wire.nonce { puts.removeValue(forKey: nonce)?.resume() }
+ case "mbox.err":
+ if let nonce = wire.nonce {
+ puts.removeValue(forKey: nonce)?.resume(throwing: wire.code == "hostOnline" ? MailboxError.hostOnline : MailboxError.rejected(wire.code ?? "invalid"))
+ }
+ case "mbox.cancelled":
+ if let nonce = wire.nonce { cancels.removeValue(forKey: nonce)?.resume(returning: .cancelled) }
+ case "mbox.gone":
+ if let nonce = wire.nonce { cancels.removeValue(forKey: nonce)?.resume(returning: wire.state == "delivering" ? .delivering : .unknown) }
+ case "mbox.items":
+ if let key = lists.keys.first { lists.removeValue(forKey: key)?.resume(returning: wire.items ?? []) }
+ case "mbox.delivered":
+ if let nonce = wire.nonce { broadcast(.delivered(nonce: nonce)) }
+ case "mbox.failed":
+ if let nonce = wire.nonce { broadcast(.failed(nonce: nonce, code: wire.code ?? "invalid")) }
+ case "mbox.expired":
+ if let nonce = wire.nonce { broadcast(.expired(nonce: nonce)) }
+ default:
+ break
+ }
+ return nil
+ }
+
+ private func startHandshake(_ generation: Int) -> Outcome? {
+ guard let link else { return nil }
+ do {
+ let hs = try RelayCrypto.Handshake(computer: computer, deviceKey: identity.deviceKey)
+ self.link?.handshake = hs
+ self.link?.sealer = nil
+ self.link?.opener = nil
+ if case .ready = state { setState(.connecting) }
+ if case .hostOffline = state { setState(.connecting) }
+ link.outbox.yield(try Self.helloMessage(hs, identity: identity, pair: pairingCode != nil))
+ } catch {
+ return .stop(.unauthorized(Self.identityChanged))
+ }
+ // No welcome within 10 s: give up on this socket.
+ Task {
+ try? await Task.sleep(for: .seconds(10))
+ self.handshakeDeadline(generation)
+ }
+ return nil
+ }
+
+ private func handshakeDeadline(_ generation: Int) {
+ guard let link, link.generation == generation, link.handshake != nil else { return }
+ link.socket.close(code: 1000)
+ }
+
+ private func install(_ keys: RelayCrypto.ChannelKeys, route: HostRoute) {
+ link?.sealer = RelayCrypto.FrameSealer(key: keys.d2h)
+ link?.opener = RelayCrypto.FrameOpener(key: keys.h2d)
+ refusals = 0
+ setState(.ready(route))
+ if pairingCode == nil {
+ Task { await self.refreshComputer() }
+ }
+ }
+
+ private func broadcast(_ event: MailboxEvent) {
+ for c in mailboxObservers.values { c.yield(event) }
+ }
+
+ /// Inner RPC (§6.5): `ok`/`err` answer calls, `ev`/`end`/`err` feed streams.
+ private func handleInner(_ message: Data) {
+ guard let obj = try? JSONSerialization.jsonObject(with: message) as? [String: Any],
+ let rawId = obj["id"] as? NSNumber else { return }
+ let id = rawId.uint32Value
+ if let ev = obj["ev"] {
+ if let data = try? JSONSerialization.data(withJSONObject: ev, options: .fragmentsAllowed) { streams[id]?.yield(data) }
+ } else if obj["end"] as? Bool == true {
+ streams.removeValue(forKey: id)?.finish()
+ streamIds = streamIds.filter { $0.value != id }
+ } else if let err = obj["err"] as? [String: Any] {
+ let status = (err["status"] as? NSNumber)?.intValue ?? 500
+ let error = HostError.http(status, err["message"] as? String ?? "Host error \(status)")
+ if let call = calls.removeValue(forKey: id) {
+ call.resume(throwing: error)
+ } else if let stream = streams.removeValue(forKey: id) {
+ stream.finish(throwing: error)
+ streamIds = streamIds.filter { $0.value != id }
+ }
+ } else if obj.keys.contains("ok") {
+ let data = (try? JSONSerialization.data(withJSONObject: obj["ok"] ?? NSNull(), options: .fragmentsAllowed)) ?? Data("null".utf8)
+ calls.removeValue(forKey: id)?.resume(returning: data)
+ }
+ }
+
+ /// Ends everything riding on the channel (not the mailbox, which lives on the relay socket).
+ private func dropChannel(_ error: Error) {
+ let c = calls
+ let s = streams
+ calls = [:]
+ streams = [:]
+ streamIds = [:]
+ for call in c.values { call.resume(throwing: error) }
+ // Route change or re-handshake: the store resubscribes from its own rev.
+ for stream in s.values { stream.finish(throwing: HostError.unreachable) }
+ }
+
+ private func dropMailbox() {
+ let p = puts, x = cancels, l = lists
+ puts = [:]
+ cancels = [:]
+ lists = [:]
+ for put in p.values { put.resume(throwing: HostError.unreachable) }
+ for cancel in x.values { cancel.resume(returning: .unknown) }
+ for list in l.values { list.resume(returning: []) }
+ }
+
+ // MARK: inner hello (§7.5 step 5)
+
+ private func refreshComputer() async {
+ guard let data = try? await perform("hello", body: Data(), timeout: 20),
+ let hello = try? JSONDecoder().decode(Hello.self, from: data) else { return }
+ merge(hello)
+ }
+
+ func merge(_ hello: Hello) {
+ // The welcome signature already proved the key; a hello naming another computer is ignored.
+ guard hello.computerId == nil || hello.computerId == computer.id,
+ hello.signKey == nil || hello.signKey == computer.signKey else {
+ log.error("hello names another computer")
+ return
+ }
+ var c = computer
+ if !hello.name.isEmpty { c.name = hello.name }
+ if let bk = hello.boxKey, Data(base64URL: bk)?.count == 32 { c.boxKey = bk }
+ if let urls = hello.urls { c.urls = urls.filter(Pairing.isDirectURL) }
+ c.cloud = hello.cloud.flatMap(URL.init(string:)).flatMap { Pairing.isCloudURL($0) ? $0 : nil }
+ if let device = hello.device { c.device = device }
+ guard c != computer else { return }
+ computer = c
+ for o in computerObservers.values { o.yield(c) }
+ }
+
+ // MARK: calls and streams
+
+ public nonisolated func call(_ method: String, body: Data, timeout: TimeInterval) async throws -> Data {
+ try await perform(method, body: body, timeout: timeout)
+ }
+
+ private func nextId() -> UInt32 {
+ nextRequestId = nextRequestId == .max ? 1 : nextRequestId + 1
+ return nextRequestId
+ }
+
+ /// Waits (bounded) while connecting; throws what the link state means otherwise.
+ private func ready(within limit: TimeInterval) async throws {
+ let deadline = ContinuousClock.now + .seconds(max(limit, 0))
+ while true {
+ if closed { throw HostError.unreachable }
+ switch state {
+ case .ready where link?.sealer != nil: return
+ case .ready, .connecting:
+ guard ContinuousClock.now < deadline else { throw HostError.unreachable }
+ await stateChange(until: deadline)
+ case let .hostOffline(lastSeen): throw HostError.computerOffline(lastSeen: lastSeen)
+ case let .unauthorized(message): throw HostError.unauthorized(message)
+ case .failed: throw needsUpgrade ? HostError.upgradeRequired : HostError.unreachable
+ }
+ }
+ }
+
+ private func perform(_ method: String, body: Data, timeout: TimeInterval) async throws -> Data {
+ try await ready(within: timeout)
+ let b: Any = body.isEmpty ? NSNull() : try JSONSerialization.jsonObject(with: body, options: .fragmentsAllowed)
+ let id = nextId()
+ let payload = try JSONSerialization.data(withJSONObject: ["id": id, "m": method, "b": b] as [String: Any])
+ return try await withTaskCancellationHandler {
+ try await withCheckedThrowingContinuation { (c: CheckedContinuation<Data, Error>) in
+ calls[id] = c
+ do {
+ try sendInner(payload)
+ } catch {
+ calls.removeValue(forKey: id)?.resume(throwing: error)
+ return
+ }
+ Task {
+ try? await Task.sleep(for: .seconds(timeout))
+ self.abandon(id, error: HostError.unreachable)
+ }
+ }
+ } onCancel: {
+ Task { await self.abandon(id, error: CancellationError()) }
+ }
+ }
+
+ /// Timed out or cancelled: the host drops the answer (an already started mutation still runs).
+ private func abandon(_ id: UInt32, error: Error) {
+ guard let c = calls.removeValue(forKey: id) else { return }
+ c.resume(throwing: error)
+ try? sendInner(JSONSerialization.data(withJSONObject: ["id": id, "cancel": true]))
+ }
+
+ private func sendInner(_ message: Data) throws {
+ guard var sealer = link?.sealer, let link else { throw HostError.unreachable }
+ let frames = try sealer.seal(message)
+ self.link?.sealer = sealer
+ for frame in frames {
+ link.outbox.yield(#"{"t":"f","c":\#(frame.c),"d":"\#(frame.d.base64URL)"}"#)
+ }
+ // Counters must never wrap: replace the channel (§3.5).
+ if sealer.exhausted {
+ restartRequested = true
+ link.socket.close(code: 4011)
+ }
+ }
+
+ public nonisolated func stream(_ request: HostStreamRequest) -> AsyncThrowingStream<Data, Error> {
+ AsyncThrowingStream { continuation in
+ let key = UUID()
+ let task = Task { await self.openStream(request, key: key, continuation) }
+ continuation.onTermination = { _ in
+ task.cancel()
+ Task { await self.closeStream(key) }
+ }
+ }
+ }
+
+ private func openStream(_ request: HostStreamRequest, key: UUID, _ continuation: AsyncThrowingStream<Data, Error>.Continuation) async {
+ do {
+ try await ready(within: 10)
+ // The consumer left while we waited: `closeStream` already ran and found nothing to stop.
+ try Task.checkCancellation()
+ let id = nextId()
+ let sub: [String: Any] = switch request {
+ case let .events(since, client): ["id": id, "sub": "events", "b": ["since": since, "client": client]]
+ case let .term(term): ["id": id, "sub": "term", "b": ["term": term]]
+ }
+ streams[id] = continuation
+ streamIds[key] = id
+ try sendInner(JSONSerialization.data(withJSONObject: sub))
+ } catch {
+ continuation.finish(throwing: error)
+ }
+ }
+
+ /// The consumer went away: stop the host's stream.
+ private func closeStream(_ key: UUID) {
+ guard let id = streamIds.removeValue(forKey: key), streams.removeValue(forKey: id) != nil else { return }
+ try? sendInner(JSONSerialization.data(withJSONObject: ["id": id, "cancel": true]))
+ }
+
+ // MARK: mailbox (§6.4, §7.4)
+
+ private func relaySocket() throws -> Link {
+ guard let link, link.route == .relay else { throw HostError.unreachable }
+ return link
+ }
+
+ public func enqueue(botId: String, text: String, clientNonce: String) async throws {
+ guard pairingCode == nil, let bk = computer.boxKey.flatMap(Data.init(base64URL:)), bk.count == 32 else {
+ throw HostError.computerOffline(lastSeen: lastSeen)
+ }
+ if case let .ready(route) = state, route == .direct { throw MailboxError.hostOnline }
+ let link = try relaySocket()
+ guard puts[clientNonce] == nil else { throw MailboxError.rejected("busy") }
+ struct Send: Encodable { var botId: String; var text: String; var clientNonce: String }
+ struct Inner: Encodable { var m = "send"; var b: Send; var ts: Int64 }
+ let inner = try JSONEncoder().encode(Inner(b: Send(botId: botId, text: text, clientNonce: clientNonce),
+ ts: Int64(Date.now.timeIntervalSince1970 * 1000)))
+ // A fresh ephemeral key on every seal, retries included (§6.4 MUST).
+ let sealed = try RelayCrypto.sealMailbox(inner, hostBoxKey: bk, computerId: computer.id, deviceKey: identity.deviceKey,
+ clientNonce: clientNonce, sign: identity.sign)
+ struct Put: Encodable { var t = "mbox.put"; var nonce: String; var d: String }
+ let put = String(decoding: try JSONEncoder().encode(Put(nonce: clientNonce, d: sealed.blob.base64URL)), as: UTF8.self)
+ try await withCheckedThrowingContinuation { (c: CheckedContinuation<Void, Error>) in
+ puts[clientNonce] = c
+ link.outbox.yield(put)
+ Task {
+ try? await Task.sleep(for: .seconds(15))
+ self.expirePut(clientNonce)
+ }
+ }
+ }
+
+ private func expirePut(_ nonce: String) {
+ puts.removeValue(forKey: nonce)?.resume(throwing: HostError.unreachable)
+ }
+
+ public func cancelQueued(clientNonce: String) async -> MailboxCancel {
+ guard let link = try? relaySocket(), cancels[clientNonce] == nil else { return .unknown }
+ let message = String(decoding: (try? JSONSerialization.data(withJSONObject: ["t": "mbox.cancel", "nonce": clientNonce])) ?? Data(), as: UTF8.self)
+ return await withCheckedContinuation { c in
+ cancels[clientNonce] = c
+ link.outbox.yield(message)
+ Task {
+ try? await Task.sleep(for: .seconds(10))
+ self.expireCancel(clientNonce)
+ }
+ }
+ }
+
+ private func expireCancel(_ nonce: String) {
+ cancels.removeValue(forKey: nonce)?.resume(returning: .unknown)
+ }
+
+ public func listQueued() async -> [QueuedItem] {
+ guard let link = try? relaySocket() else { return [] }
+ let key = UUID()
+ return await withCheckedContinuation { c in
+ lists[key] = c
+ link.outbox.yield(#"{"t":"mbox.list"}"#)
+ Task {
+ try? await Task.sleep(for: .seconds(10))
+ self.expireList(key)
+ }
+ }
+ }
+
+ private func expireList(_ key: UUID) {
+ lists.removeValue(forKey: key)?.resume(returning: [])
+ }
+}
+
+/// Reconnect delays: from 1 s doubling to 30 s, full jitter (§7.6).
+struct Backoff {
+ private var attempt = 0
+
+ mutating func next() -> Duration {
+ let cap = min(30.0, pow(2.0, Double(attempt)))
+ attempt += 1
+ return .milliseconds(Int(Double.random(in: 0...cap) * 1000))
+ }
+}
diff --git a/kit/Sources/CodyncKit/Client/CloudClient.swift b/kit/Sources/CodyncKit/Client/CloudClient.swift
new file mode 100644
index 00000000..adf609bd
--- /dev/null
+++ b/kit/Sources/CodyncKit/Client/CloudClient.swift
@@ -0,0 +1,184 @@
+import Foundation
+
+/// An error from the Codync cloud: `{"error":{"code","message"}}`.
+public struct CloudError: LocalizedError, Sendable, Equatable {
+ public var status: Int
+ /// `notFound`, `conflict`, `requestExpired`, … (spec §8.3).
+ public var code: String
+ public var message: String?
+
+ public init(status: Int, code: String, message: String? = nil) {
+ self.status = status
+ self.code = code
+ self.message = message
+ }
+
+ public var errorDescription: String? {
+ switch code {
+ case "requestExpired": "The request expired. Ask again."
+ case "accountDeleted": "This account was deleted."
+ case "rateLimited": "Too many requests. Try again in a little while."
+ default: message ?? "Codync cloud error (\(code))"
+ }
+ }
+}
+
+/// The user-facing `/v1` API (§8.4): account, devices, computers, access requests, claims.
+/// The Clerk session token comes from the app; kit doesn't depend on ClerkKit.
+public struct CloudClient: Sendable {
+ public let baseURL: URL
+ let identity: DeviceIdentity?
+ let token: @Sendable () async throws -> String
+ let session: URLSession
+ /// How often `requestAccess` polls for the host's nonce.
+ var pollInterval: Duration = .seconds(2)
+
+ public init(baseURL: URL, identity: DeviceIdentity?, token: @escaping @Sendable () async throws -> String) {
+ self.init(baseURL: baseURL, identity: identity, session: .shared, token: token)
+ }
+
+ init(baseURL: URL, identity: DeviceIdentity?, session: URLSession, token: @escaping @Sendable () async throws -> String) {
+ self.baseURL = baseURL
+ self.identity = identity
+ self.session = session
+ self.token = token
+ }
+
+ // MARK: account and devices
+
+ public func me() async throws -> CloudAccount { try await request("GET", "v1/me") }
+
+ /// Registers this device key with the account (Clerk + proof of the key).
+ public func registerDevice(name: String, platform: String) async throws {
+ struct Res: Decodable {}
+ let _: Res = try await request("POST", "v1/devices", body: ["name": name, "platform": platform], signed: true)
+ }
+
+ public func devices() async throws -> [CloudDevice] {
+ struct Res: Decodable { var devices: [CloudDevice] }
+ let res: Res = try await request("GET", "v1/devices")
+ return res.devices
+ }
+
+ public func revokeDevice(_ deviceId: String) async throws {
+ try await send("DELETE", "v1/devices/\(deviceId)")
+ }
+
+ // MARK: computers
+
+ /// With a device identity, each computer says whether this device has access.
+ public func computers() async throws -> [CloudComputer] {
+ struct Res: Decodable { var computers: [CloudComputer] }
+ let res: Res = try await request("GET", "v1/computers", signed: identity != nil)
+ return res.computers
+ }
+
+ public func renameComputer(_ id: ComputerID, name: String) async throws {
+ try await send("PATCH", "v1/computers/\(id)", body: ["name": name])
+ }
+
+ /// Removes the computer from the account; every device's access to it through the account ends.
+ public func removeComputer(_ id: ComputerID) async throws {
+ try await send("DELETE", "v1/computers/\(id)")
+ }
+
+ public func grants(_ id: ComputerID) async throws -> [CloudGrant] {
+ struct Res: Decodable { var grants: [CloudGrant] }
+ let res: Res = try await request("GET", "v1/computers/\(id)/grants")
+ return res.grants
+ }
+
+ public func revokeGrant(_ id: ComputerID, grantId: String) async throws {
+ try await send("DELETE", "v1/computers/\(id)/grants/\(grantId)")
+ }
+
+ // MARK: access requests (§4.2 B, commit-then-reveal SAS)
+
+ /// Commit → wait for the host's nonce → reveal. Returns once `code` can be shown.
+ /// The device nonce lives only in memory here, so a cloud can't learn it before the host committed.
+ public func requestAccess(_ id: ComputerID, signKey: String) async throws -> AccessTicket {
+ guard let identity else { throw CloudError(status: 0, code: "noDeviceKey", message: "Sign in again on this device.") }
+ guard let hostKey = Data(base64URL: signKey), hostKey.count == 32, RelayCrypto.computerId(signKey: hostKey) == id else {
+ throw CloudError(status: 0, code: "badSignKey", message: "This computer's key doesn't match its ID.")
+ }
+ let nD = Data.random(32)
+ let commit = RelayCrypto.sasCommit(deviceKey: identity.deviceKey, deviceNonce: nD).base64URL
+ struct Created: Decodable { var requestId: String; var expiresAt: Int64 }
+ let created: Created = try await request("POST", "v1/computers/\(id)/access-requests", body: ["commit": commit], signed: true)
+
+ var hostNonce: Data?
+ while hostNonce == nil {
+ let status = try await accessStatus(created.requestId)
+ guard status.status == .pending else {
+ throw CloudError(status: 0, code: status.status == .expired ? "requestExpired" : status.status.rawValue, message: "The computer didn't take the request.")
+ }
+ if let raw = status.hostNonce {
+ guard let n = Data(base64URL: raw), n.count == 32 else { throw CloudError(status: 0, code: "badNonce", message: nil) }
+ hostNonce = n
+ } else {
+ guard Int64(Date.now.timeIntervalSince1970 * 1000) < created.expiresAt else {
+ throw CloudError(status: 410, code: "requestExpired", message: nil)
+ }
+ try await Task.sleep(for: pollInterval)
+ }
+ }
+ try await send("POST", "v1/access-requests/\(created.requestId)/reveal", body: ["nonce": nD.base64URL], signed: true)
+ let code = RelayCrypto.sasCode(hostSignKey: hostKey, deviceKey: identity.deviceKey, deviceNonce: nD, hostNonce: hostNonce ?? Data())
+ return AccessTicket(requestId: created.requestId, expiresAt: created.expiresAt, code: code, computerId: id, signKey: signKey)
+ }
+
+ public func accessStatus(_ requestId: String) async throws -> AccessStatus {
+ try await request("GET", "v1/access-requests/\(requestId)")
+ }
+
+ public func cancelAccess(_ requestId: String) async throws {
+ try await send("DELETE", "v1/access-requests/\(requestId)")
+ }
+
+ // MARK: claims (§4.2 A)
+
+ public func createClaim() async throws -> ClaimChallenge { try await request("POST", "v1/claims", body: [String: String]()) }
+
+ public func completeClaim(_ claimId: String, signed: ClaimSignature) async throws -> CloudComputer {
+ struct Res: Decodable { var computer: CloudComputer }
+ let res: Res = try await request("POST", "v1/claims/\(claimId)/complete", body: signed)
+ return res.computer
+ }
+
+ // MARK: plumbing
+
+ private struct NoBody: Encodable {}
+ private struct Failure: Decodable {
+ struct Detail: Decodable { var code: String; var message: String? }
+ var error: Detail
+ }
+ private struct Ignored: Decodable {}
+
+ private func send(_ method: String, _ path: String, body: (some Encodable)? = NoBody?.none, signed: Bool = false) async throws {
+ let _: Ignored = try await request(method, path, body: body, signed: signed)
+ }
+
+ func request<T: Decodable>(_ method: String, _ path: String, body: (some Encodable)? = NoBody?.none, signed: Bool = false) async throws -> T {
+ let url = baseURL.appending(path: path)
+ var req = URLRequest(url: url, timeoutInterval: 20)
+ req.httpMethod = method
+ let data = try body.map { try JSONEncoder().encode($0) } ?? Data()
+ if body != nil {
+ req.httpBody = data
+ req.setValue("application/json", forHTTPHeaderField: "Content-Type")
+ }
+ req.setValue("Bearer \(try await token())", forHTTPHeaderField: "Authorization")
+ if signed, let identity {
+ let header = try identity.signatureHeader(method: method, authority: RelayCrypto.authority(of: url),
+ pathAndQuery: RelayCrypto.pathAndQuery(of: url), body: data)
+ req.setValue(header, forHTTPHeaderField: "Codync-Sig")
+ }
+ let (bytes, response) = try await session.data(for: req)
+ let status = (response as? HTTPURLResponse)?.statusCode ?? 0
+ guard (200..<300).contains(status) else {
+ let e = try? JSONDecoder().decode(Failure.self, from: bytes)
+ throw CloudError(status: status, code: e?.error.code ?? "http\(status)", message: e?.error.message)
+ }
+ return try JSONDecoder().decode(T.self, from: bytes.isEmpty ? Data("{}".utf8) : bytes)
+ }
+}
diff --git a/kit/Sources/CodyncKit/Client/DeviceIdentity.swift b/kit/Sources/CodyncKit/Client/DeviceIdentity.swift
new file mode 100644
index 00000000..55922af6
--- /dev/null
+++ b/kit/Sources/CodyncKit/Client/DeviceIdentity.swift
@@ -0,0 +1,140 @@
+import CryptoKit
+import Foundation
+import Security
+
+/// This app install's keys for one account context (§3.2): an Ed25519 device key that hosts
+/// authorize, and an X25519 push key that opens notification contents. Private keys stay in the Keychain.
+public struct DeviceIdentity: Sendable {
+ /// Ed25519, b64url.
+ public let publicKey: String
+ /// X25519, b64url (§6.7).
+ public let pushKey: String
+ let signing: Curve25519.Signing.PrivateKey
+ let push: Curve25519.KeyAgreement.PrivateKey
+
+ init(signing: Curve25519.Signing.PrivateKey, push: Curve25519.KeyAgreement.PrivateKey) {
+ self.signing = signing
+ self.push = push
+ publicKey = signing.publicKey.rawRepresentation.base64URL
+ pushKey = push.publicKey.rawRepresentation.base64URL
+ }
+
+ static let deviceService = "com.pokai.Codync.device-key"
+ static let pushService = "com.pokai.Codync.push-key"
+
+ /// Loads this context's keys, creating whichever is missing.
+ public static func load(context: SharedStore.Context) throws -> DeviceIdentity {
+ let signing = try Keychain.read(service: deviceService, account: context.id)
+ .map { try Curve25519.Signing.PrivateKey(rawRepresentation: $0) }
+ ?? Keychain.create(service: deviceService, account: context.id) { Curve25519.Signing.PrivateKey() }
+ let push = try Keychain.read(service: pushService, account: context.id)
+ .map { try Curve25519.KeyAgreement.PrivateKey(rawRepresentation: $0) }
+ ?? Keychain.create(service: pushService, account: context.id) { Curve25519.KeyAgreement.PrivateKey() }
+ return DeviceIdentity(signing: signing, push: push)
+ }
+
+ /// Signing out or removing an account: hosts and the cloud can no longer tie anything to it.
+ public static func delete(context: SharedStore.Context) {
+ Keychain.delete(service: deviceService, account: context.id)
+ Keychain.delete(service: pushService, account: context.id)
+ }
+
+ var deviceKey: Data { signing.publicKey.rawRepresentation }
+
+ func sign(_ data: Data) throws -> Data { try signing.signature(for: data) }
+
+ /// The `Codync-Sig` header value (§5).
+ public func signatureHeader(method: String, authority: String, pathAndQuery: String, body: Data) throws -> String {
+ try signatureHeader(method: method, authority: authority, pathAndQuery: pathAndQuery, body: body,
+ ts: Int64(Date.now.timeIntervalSince1970 * 1000), nonce: Data.random(16).base64URL)
+ }
+
+ func signatureHeader(method: String, authority: String, pathAndQuery: String, body: Data, ts: Int64, nonce: String) throws -> String {
+ let input = RelayCrypto.requestSigInput(method: method, authority: authority, pathAndQuery: pathAndQuery, ts: ts, nonce: nonce, body: body)
+ return "v=1,kid=\(publicKey),ts=\(ts),nonce=\(nonce),sig=\(try sign(input).base64URL)"
+ }
+
+ /// For the Notification Service Extension: opens §6.7's `sealed` with the push key of
+ /// `contextID`. Never creates keys; nil when anything doesn't check out.
+ public static func openPush(sealed: String, computerId: ComputerID, contextID: String) -> (title: String, body: String)? {
+ guard let raw = try? Keychain.read(service: pushService, account: contextID),
+ let key = try? Curve25519.KeyAgreement.PrivateKey(rawRepresentation: raw) else { return nil }
+ return openPush(sealed: sealed, computerId: computerId, key: key)
+ }
+
+ static func openPush(sealed: String, computerId: ComputerID, key: Curve25519.KeyAgreement.PrivateKey) -> (title: String, body: String)? {
+ struct Alert: Decodable { var title: String; var body: String }
+ guard let plain = try? RelayCrypto.openPush(sealed: sealed, computerId: computerId, pushPrivate: key),
+ let alert = try? JSONDecoder().decode(Alert.self, from: plain) else { return nil }
+ return (alert.title, alert.body)
+ }
+}
+
+/// Generic-password items holding 32-byte raw keys (§3.2): this device only, never synced,
+/// readable after first unlock (pushes arrive while locked). macOS uses the login keychain:
+/// the Mac app has no entitlements, so the data protection keychain would fail with -34018.
+enum Keychain {
+ struct Failure: LocalizedError {
+ let status: OSStatus
+ var errorDescription: String? { "Keychain error \(status)" }
+ }
+
+ /// iOS app, widgets and notification extension share `CodyncKeychainGroup` from Info.plist.
+ /// An unsigned build leaves `$(AppIdentifierPrefix)` empty; a group without the team prefix
+ /// would fail with -34018, so it is left unset there.
+ private static let accessGroup: String? = {
+ guard let group = Bundle.main.object(forInfoDictionaryKey: "CodyncKeychainGroup") as? String,
+ group.range(of: #"^[A-Z0-9]{10}\."#, options: .regularExpression) != nil else { return nil }
+ return group
+ }()
+
+ private static func query(service: String, account: String) -> [CFString: Any] {
+ var q: [CFString: Any] = [
+ kSecClass: kSecClassGenericPassword,
+ kSecAttrService: service,
+ kSecAttrAccount: account,
+ kSecAttrSynchronizable: false,
+ ]
+ if let accessGroup, !accessGroup.isEmpty { q[kSecAttrAccessGroup] = accessGroup }
+ return q
+ }
+
+ static func read(service: String, account: String) throws -> Data? {
+ var q = query(service: service, account: account)
+ q[kSecReturnData] = true
+ q[kSecMatchLimit] = kSecMatchLimitOne
+ var out: CFTypeRef?
+ switch SecItemCopyMatching(q as CFDictionary, &out) {
+ case errSecSuccess: return out as? Data
+ case errSecItemNotFound: return nil
+ case let status: throw Failure(status: status)
+ }
+ }
+
+ /// Stores a new key; if another process won the race, returns the one it stored.
+ static func create<K: RawKey>(service: String, account: String, _ make: () -> K) throws -> K {
+ let key = make()
+ var q = query(service: service, account: account)
+ q[kSecValueData] = key.rawRepresentation
+ q[kSecAttrAccessible] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
+ switch SecItemAdd(q as CFDictionary, nil) {
+ case errSecSuccess: return key
+ case errSecDuplicateItem:
+ guard let raw = try read(service: service, account: account) else { throw Failure(status: errSecItemNotFound) }
+ return try K(rawRepresentation: raw)
+ case let status: throw Failure(status: status)
+ }
+ }
+
+ static func delete(service: String, account: String) {
+ SecItemDelete(query(service: service, account: account) as CFDictionary)
+ }
+}
+
+protocol RawKey {
+ var rawRepresentation: Data { get }
+ init<D: ContiguousBytes>(rawRepresentation: D) throws
+}
+
+extension Curve25519.Signing.PrivateKey: RawKey {}
+extension Curve25519.KeyAgreement.PrivateKey: RawKey {}
diff --git a/kit/Sources/CodyncKit/Client/HostClient.swift b/kit/Sources/CodyncKit/Client/HostClient.swift
index 86e97f12..b843c898 100644
--- a/kit/Sources/CodyncKit/Client/HostClient.swift
+++ b/kit/Sources/CodyncKit/Client/HostClient.swift
@@ -1,50 +1,5 @@
import Foundation
-/// What `codync-host pair` encodes: `codync://pair?name=…&token=…&urls=a,b`.
-public struct Pairing: Codable, Hashable, Sendable {
- public var name: String
- public var token: String
- public var urls: [String]
- /// What the computer is (`Device` on the host), learned from `hello`; picks its icon.
- public var device: String?
- /// The badge color the user picked on this phone (an `AvatarPalette` id).
- public var color: String?
-
- public init(name: String, token: String, urls: [String]) {
- self.name = name
- self.token = token
- self.urls = urls
- }
-
- public init?(url: URL) {
- guard url.scheme == "codync", url.host() == "pair",
- let items = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems else { return nil }
- let q = Dictionary(items.map { ($0.name, $0.value ?? "") }, uniquingKeysWith: { a, _ in a })
- guard let token = q["token"], !token.isEmpty else { return nil }
- let urls = (q["urls"] ?? "").split(separator: ",").map(String.init).filter { URL(string: $0) != nil }
- guard !urls.isEmpty else { return nil }
- self.init(name: q["name"].flatMap { $0.isEmpty ? nil : $0 } ?? "My computer", token: token, urls: urls)
- }
-
- public init?(string: String) {
- guard let url = URL(string: string.trimmingCharacters(in: .whitespacesAndNewlines)) else { return nil }
- self.init(url: url)
- }
-}
-
-public enum HostError: LocalizedError, Sendable {
- case http(Int, String)
- case unreachable
-
- public var errorDescription: String? {
- switch self {
- case .http(401, _): "This phone isn't paired with the host anymore. Pair again."
- case let .http(_, message): message
- case .unreachable: "Can't reach your computer. Is it on, awake, and on Tailscale or the same Wi-Fi?"
- }
- }
-}
-
public enum HostEvent: Sendable {
case hello(hostId: String, rev: Int64, usage: Usage, screen: ScreenState?)
case bot(Bot)
@@ -52,6 +7,10 @@ public enum HostEvent: Sendable {
case entry(Entry)
case usage(Usage)
case screen(ScreenState)
+ /// Loopback only: devices asking this computer for access.
+ case accessRequests([AccessRequest])
+ /// Loopback only: the host's cloud connection.
+ case cloud(CloudStatus)
case resync
/// An event this app version couldn't decode (host newer/older than the app).
case undecodable(type: String)
@@ -68,69 +27,33 @@ public struct Empty: Codable, Sendable {
}
public struct HostClient: Sendable {
- public let baseURL: URL
- public let token: String
+ public let transport: any HostTransport
+
+ public init(transport: any HostTransport) {
+ self.transport = transport
+ }
+ /// Loopback: the Mac's own host, or one reached through an SSH tunnel.
public init(baseURL: URL, token: String) {
- self.baseURL = baseURL
- self.token = token
+ self.init(transport: LoopbackTransport(baseURL: baseURL, token: token))
}
static let decoder = JSONDecoder()
static let encoder = JSONEncoder()
- private var session: URLSession { .shared }
-
public func call<T: Decodable>(_ method: String, _ body: some Encodable = Empty(), timeout: TimeInterval = 20) async throws -> T {
- var req = URLRequest(url: baseURL.appending(path: "api/\(method)"), timeoutInterval: timeout)
- req.httpMethod = "POST"
- req.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
- req.setValue("application/json", forHTTPHeaderField: "Content-Type")
- req.httpBody = try Self.encoder.encode(body)
- let (data, response) = try await session.data(for: req)
- let status = (response as? HTTPURLResponse)?.statusCode ?? 0
- guard (200..<300).contains(status) else {
- let message = (try? JSONDecoder().decode([String: String].self, from: data))?["error"] ?? "Host error \(status)"
- throw HostError.http(status, message)
- }
+ let data = try await transport.call(method, body: try Self.encoder.encode(body), timeout: timeout)
return try Self.decoder.decode(T.self, from: data)
}
- public func healthy(timeout: TimeInterval = 4) async -> Bool {
- var req = URLRequest(url: baseURL.appending(path: "health"), timeoutInterval: timeout)
- req.cachePolicy = .reloadIgnoringLocalCacheData
- guard let (_, response) = try? await session.data(for: req) else { return false }
- return (response as? HTTPURLResponse)?.statusCode == 200
- }
-
- /// First address (in the pairing's preference order) that answers `/health`.
- public static func resolve(_ pairing: Pairing) async -> HostClient? {
- let candidates = pairing.urls.compactMap(URL.init(string:)).map { HostClient(baseURL: $0, token: pairing.token) }
- return await withTaskGroup(of: (Int, Bool).self) { group in
- for (i, c) in candidates.enumerated() {
- group.addTask { (i, await c.healthy()) }
- }
- var ok: [Int] = []
- for await (i, healthy) in group where healthy {
- ok.append(i)
- // The best-ranked address won; no need to wait for slower ones.
- if i == 0 { break }
- }
- group.cancelAll()
- return ok.min().map { candidates[$0] }
- }
- }
-
- /// Server-sent events: catch-up since `since`, then live updates.
+ /// Catch-up since `since`, then live updates.
public func events(since: Int64, client: String) -> AsyncThrowingStream<HostEvent, Error> {
- var comps = URLComponents(url: baseURL.appending(path: "events"), resolvingAgainstBaseURL: false)!
- comps.queryItems = [.init(name: "since", value: String(since)), .init(name: "client", value: client)]
- return sse(comps.url!, parse: Self.parseEvent)
+ map(transport.stream(.events(since: since, client: client)), Self.parseEvent)
}
/// A setup terminal's output: everything so far, then live, finishing after `.exit`.
public func termOutput(_ term: String) -> AsyncThrowingStream<TermEvent, Error> {
- sse(baseURL.appending(path: "term/\(term)")) { data in
+ map(transport.stream(.term(term))) { data in
struct Raw: Decodable { var type: String; var data: String?; var code: Int? }
guard let raw = try? Self.decoder.decode(Raw.self, from: data) else { return nil }
switch raw.type {
@@ -141,26 +64,12 @@ public struct HostClient: Sendable {
}
}
- private func sse<T: Sendable>(_ url: URL, parse: @escaping @Sendable (Data) -> T?) -> AsyncThrowingStream<T, Error> {
- // Idle timeout, not a total one: the host pings every 15 s, so silence this long means it's
- // gone (shut down, asleep, off the network) even if the socket never closed.
- var req = URLRequest(url: url, timeoutInterval: 45)
- req.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
- req.setValue("text/event-stream", forHTTPHeaderField: "Accept")
- let session = self.session
- let request = req
- return AsyncThrowingStream { continuation in
+ private func map<T: Sendable>(_ source: AsyncThrowingStream<Data, Error>, _ parse: @escaping @Sendable (Data) -> T?) -> AsyncThrowingStream<T, Error> {
+ AsyncThrowingStream { continuation in
let task = Task {
do {
- let (bytes, response) = try await session.bytes(for: request)
- let status = (response as? HTTPURLResponse)?.statusCode ?? 0
- guard status == 200 else { throw HostError.http(status, "Host error \(status)") }
- for try await line in bytes.lines {
- guard line.hasPrefix("data:") else { continue }
- let payload = Data(line.dropFirst(5).utf8)
- if let event = parse(payload) {
- continuation.yield(event)
- }
+ for try await data in source {
+ if let event = parse(data) { continuation.yield(event) }
}
continuation.finish()
} catch {
@@ -182,6 +91,8 @@ public struct HostClient: Sendable {
struct EntryWrap: Decodable { var entry: Entry }
struct UsageWrap: Decodable { var usage: Usage }
struct ScreenWrap: Decodable { var screen: ScreenState }
+ struct RequestsWrap: Decodable { var requests: [AccessRequest] }
+ struct CloudWrap: Decodable { var cloud: CloudStatus }
let d = decoder
guard let env = try? d.decode(Envelope.self, from: data) else { return nil }
switch env.type {
@@ -200,6 +111,10 @@ public struct HostClient: Sendable {
return (try? d.decode(UsageWrap.self, from: data)).map { .usage($0.usage) }
case "screen":
return (try? d.decode(ScreenWrap.self, from: data)).map { .screen($0.screen) }
+ case "accessRequests":
+ return (try? d.decode(RequestsWrap.self, from: data)).map { .accessRequests($0.requests) }
+ case "cloud":
+ return (try? d.decode(CloudWrap.self, from: data)).map { .cloud($0.cloud) }
case "resync":
return .resync
default:
@@ -263,8 +178,10 @@ public extension HostClient {
let _: Empty = try await call("respondPermission", Body(entryId: entryId, optionId: optionId))
}
- func registerDevice(ticket: String, relay: String, name: String) async throws {
- let _: Empty = try await call("registerDevice", ["ticket": ticket, "relay": relay, "name": name])
+ /// Push tickets are bound to this device's key; `pushKey` lets the host seal notification text (§6.7).
+ func registerDevice(ticket: String, relay: String, name: String, pushKey: String?, ctx: String) async throws {
+ struct Body: Encodable { var ticket: String; var relay: String; var name: String; var pushKey: String?; var ctx: String }
+ let _: Empty = try await call("registerDevice", Body(ticket: ticket, relay: relay, name: name, pushKey: pushKey, ctx: ctx))
}
func registerActivity(botId: String, ticket: String) async throws {
@@ -344,3 +261,48 @@ public struct ScreenAnswer: Codable, Sendable {
public var session: String
public var sdp: String
}
+
+// MARK: - Loopback-only: this computer's devices and account (Mac)
+
+public extension HostClient {
+ /// The host signs a claim so the cloud can make this computer part of `userId`'s account (§4.2 A).
+ func claimSign(claimId: String, nonce: String, userId: String) async throws -> ClaimSignature {
+ try await call("claimSign", ["claimId": claimId, "nonce": nonce, "userId": userId])
+ }
+
+ func accessRequests() async throws -> [AccessRequest] {
+ struct Res: Decodable { var requests: [AccessRequest] }
+ let res: Res = try await call("accessRequests")
+ return res.requests
+ }
+
+ func decideAccessRequest(_ id: String, approve: Bool) async throws {
+ struct Body: Encodable { var requestId: String; var approve: Bool }
+ let _: Empty = try await call("decideAccessRequest", Body(requestId: id, approve: approve), timeout: 30)
+ }
+
+ func devices() async throws -> [AuthorizedDevice] {
+ struct Res: Decodable { var devices: [AuthorizedDevice] }
+ let res: Res = try await call("devices")
+ return res.devices
+ }
+
+ func revokeDevice(_ key: String) async throws {
+ let _: Empty = try await call("revokeDevice", ["key": key])
+ }
+
+ func cloudStatus() async throws -> CloudStatus { try await call("cloudStatus") }
+
+ func setCloud(enabled: Bool) async throws -> CloudStatus {
+ try await call("setCloud", ["enabled": enabled], timeout: 30)
+ }
+
+ func setCloud(enabled: Bool, url: URL?) async throws -> CloudStatus {
+ struct Body: Encodable { var enabled: Bool; var url: String? }
+ return try await call("setCloud", Body(enabled: enabled, url: url?.absoluteString), timeout: 30)
+ }
+
+ func unclaim() async throws {
+ let _: Empty = try await call("unclaim", timeout: 30)
+ }
+}
diff --git a/kit/Sources/CodyncKit/Client/HostConnector.swift b/kit/Sources/CodyncKit/Client/HostConnector.swift
new file mode 100644
index 00000000..40a29285
--- /dev/null
+++ b/kit/Sources/CodyncKit/Client/HostConnector.swift
@@ -0,0 +1,114 @@
+import Foundation
+
+/// Opens channels to computers (§7.5) and pairs new ones from a QR (§4.1).
+public enum HostConnector {
+ /// Direct first (1.5 s), else the relay. The returned transport stays alive while the
+ /// computer is offline (presence, mailbox) and reconnects on its own; `shutdown()` ends it.
+ public static func connect(_ computer: Computer, identity: DeviceIdentity) async throws -> ChannelTransport {
+ let transport = ChannelTransport(computer: computer, identity: identity)
+ await transport.start()
+ let state = await transport.settled(within: .seconds(15))
+ guard await transport.isStopped else { return transport }
+ await transport.shutdown()
+ if await transport.needsUpgrade { throw HostError.upgradeRequired }
+ if case let .unauthorized(message) = state { throw HostError.unauthorized(message) }
+ throw HostError.unreachable
+ }
+
+ /// Proves the QR's one-time code inside a channel to the QR's host key; the host
+ /// then authorizes this device and closes with `4100 paired`.
+ public static func pair(_ pairing: Pairing, identity: DeviceIdentity, deviceName: String, platform: String) async throws -> Computer {
+ let transport = ChannelTransport(computer: pairing.computer, identity: identity, pairingCode: pairing.code)
+ await transport.start()
+ do {
+ struct Body: Encodable { var code: String; var name: String; var platform: String }
+ struct Res: Decodable { var computerId: ComputerID; var name: String? }
+ let data = try await transport.call("pair", body: JSONEncoder().encode(Body(code: pairing.code, name: deviceName, platform: platform)), timeout: 30)
+ await transport.shutdown()
+ let res = try JSONDecoder().decode(Res.self, from: data)
+ guard res.computerId == pairing.computer.id else { throw HostError.unauthorized(ChannelTransport.identityChanged) }
+ var computer = pairing.computer
+ if let name = res.name, !name.isEmpty { computer.name = name }
+ return computer
+ } catch {
+ await transport.shutdown()
+ throw await transport.needsUpgrade ? HostError.upgradeRequired : error
+ }
+ }
+}
+
+// MARK: - WebSocket
+
+/// A WebSocket as the channel sees it: text messages, close codes, and a liveness ping.
+protocol ChannelSocket: Sendable {
+ func send(_ text: String) async throws
+ /// Throws `SocketClosed` or `SocketRefused` when the socket ends.
+ func receive() async throws -> String
+ /// Direct: a WebSocket ping frame, returning on pong. Relay: `{"t":"ping"}` (the DO answers).
+ func ping() async throws
+ func close(code: Int)
+}
+
+struct SocketClosed: Error, Equatable { var code: Int }
+/// The upgrade was answered with this HTTP status instead of 101.
+struct SocketRefused: Error, Equatable { var status: Int }
+
+enum Endpoint: Sendable {
+ case direct(URL)
+ case relay(URLRequest)
+}
+
+typealias Dialer = @Sendable (Endpoint) async throws -> any ChannelSocket
+
+final class URLSessionSocket: ChannelSocket {
+ private let task: URLSessionWebSocketTask
+ private let relay: Bool
+
+ static let dial: Dialer = { endpoint in
+ switch endpoint {
+ case let .direct(url): URLSessionSocket(URLRequest(url: url, timeoutInterval: 10), relay: false)
+ case let .relay(request): URLSessionSocket(request, relay: true)
+ }
+ }
+
+ init(_ request: URLRequest, relay: Bool) {
+ task = URLSession.shared.webSocketTask(with: request)
+ // Chunks are ≤ 256 KiB before base64 and framing.
+ task.maximumMessageSize = 1 << 20
+ self.relay = relay
+ task.resume()
+ }
+
+ func send(_ text: String) async throws {
+ do { try await task.send(.string(text)) } catch { throw ended() }
+ }
+
+ func receive() async throws -> String {
+ let message: URLSessionWebSocketTask.Message
+ do { message = try await task.receive() } catch { throw ended() }
+ switch message {
+ case let .string(s): return s
+ case let .data(d): return String(decoding: d, as: UTF8.self)
+ @unknown default: throw SocketClosed(code: 1003)
+ }
+ }
+
+ func ping() async throws {
+ if relay { return try await send(#"{"t":"ping"}"#) }
+ try await withCheckedThrowingContinuation { (c: CheckedContinuation<Void, Error>) in
+ task.sendPing { error in
+ if let error { c.resume(throwing: error) } else { c.resume() }
+ }
+ }
+ }
+
+ func close(code: Int) {
+ task.cancel(with: URLSessionWebSocketTask.CloseCode(rawValue: code) ?? .normalClosure, reason: nil)
+ }
+
+ private func ended() -> Error {
+ if task.closeCode != .invalid { return SocketClosed(code: task.closeCode.rawValue) }
+ if let http = task.response as? HTTPURLResponse, http.statusCode != 101 { return SocketRefused(status: http.statusCode) }
+ return SocketClosed(code: 1006)
+ }
+}
diff --git a/kit/Sources/CodyncKit/Client/HostTransport.swift b/kit/Sources/CodyncKit/Client/HostTransport.swift
new file mode 100644
index 00000000..8f5f033f
--- /dev/null
+++ b/kit/Sources/CodyncKit/Client/HostTransport.swift
@@ -0,0 +1,138 @@
+import Foundation
+
+/// How a client reaches a host API: loopback HTTP (the Mac itself, an SSH tunnel), or the
+/// end-to-end encrypted channel, direct on the LAN or through the cloud relay.
+public enum HostRoute: Sendable, Equatable {
+ case loopback, direct, relay
+}
+
+public enum HostStreamRequest: Sendable {
+ case events(since: Int64, client: String)
+ case term(String)
+}
+
+public enum LinkState: Sendable, Equatable {
+ case connecting
+ case ready(HostRoute)
+ /// The relay says the computer isn't connected (asleep, off): the mailbox still works.
+ case hostOffline(lastSeen: Date?)
+ /// Revoked, lease expired, or the computer's identity changed: retrying won't help.
+ case unauthorized(String)
+ /// Can't reach the computer at all (neither directly nor through the relay).
+ case failed(String)
+}
+
+public protocol HostTransport: Sendable {
+ func call(_ method: String, body: Data, timeout: TimeInterval) async throws -> Data
+ /// Each element is one event's JSON (what SSE puts after `data:`).
+ func stream(_ request: HostStreamRequest) -> AsyncThrowingStream<Data, Error>
+ /// A new stream per call: the current state first, then every change.
+ func states() -> AsyncStream<LinkState>
+}
+
+/// A transport to a remote computer: learns its addresses and keys, and holds messages
+/// in the relay mailbox while it is offline. `ChannelTransport` is the real one.
+public protocol RemoteTransport: HostTransport {
+ func computerUpdates() -> AsyncStream<Computer>
+ func enqueue(botId: String, text: String, clientNonce: String) async throws
+ func cancelQueued(clientNonce: String) async -> MailboxCancel
+ func listQueued() async -> [QueuedItem]
+ func mailboxEvents() -> AsyncStream<MailboxEvent>
+ /// Stops for good: closes sockets and ends every stream.
+ func shutdown() async
+}
+
+public enum HostError: LocalizedError, Sendable, Equatable {
+ case http(Int, String)
+ case unreachable
+ case computerOffline(lastSeen: Date?)
+ case unauthorized(String)
+ case upgradeRequired
+
+ public var errorDescription: String? {
+ switch self {
+ case .http(401, _): "This device isn't allowed on that computer anymore."
+ case let .http(_, message): message
+ case .unreachable: "Can't reach your computer. Is it on and connected to the internet?"
+ case .computerOffline: "Your computer is offline."
+ case let .unauthorized(message): message
+ case .upgradeRequired: "Update Codync to connect to this computer."
+ }
+ }
+}
+
+/// Today's HTTP API on loopback: the Mac talking to its own host, or through an SSH tunnel.
+public struct LoopbackTransport: HostTransport {
+ public let baseURL: URL
+ let token: String
+
+ public init(baseURL: URL, token: String) {
+ self.baseURL = baseURL
+ self.token = token
+ }
+
+ private var session: URLSession { .shared }
+
+ public func call(_ method: String, body: Data, timeout: TimeInterval) async throws -> Data {
+ var req = URLRequest(url: baseURL.appending(path: "api/\(method)"), timeoutInterval: timeout)
+ req.httpMethod = "POST"
+ req.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
+ req.setValue("application/json", forHTTPHeaderField: "Content-Type")
+ req.httpBody = body.isEmpty ? Data("{}".utf8) : body
+ let data: Data
+ let response: URLResponse
+ do {
+ (data, response) = try await session.data(for: req)
+ } catch is URLError {
+ throw HostError.unreachable
+ }
+ let status = (response as? HTTPURLResponse)?.statusCode ?? 0
+ guard (200..<300).contains(status) else {
+ let message = (try? JSONDecoder().decode([String: String].self, from: data))?["error"] ?? "Host error \(status)"
+ throw HostError.http(status, message)
+ }
+ return data
+ }
+
+ public func stream(_ request: HostStreamRequest) -> AsyncThrowingStream<Data, Error> {
+ switch request {
+ case let .events(since, client):
+ var comps = URLComponents(url: baseURL.appending(path: "events"), resolvingAgainstBaseURL: false)
+ comps?.queryItems = [.init(name: "since", value: String(since)), .init(name: "client", value: client)]
+ return sse(comps?.url ?? baseURL.appending(path: "events"))
+ case let .term(id):
+ return sse(baseURL.appending(path: "term/\(id)"))
+ }
+ }
+
+ public func states() -> AsyncStream<LinkState> {
+ AsyncStream { $0.yield(.ready(.loopback)) }
+ }
+
+ private func sse(_ url: URL) -> AsyncThrowingStream<Data, Error> {
+ // Idle timeout, not a total one: the host pings every 15 s, so silence this long means it's gone.
+ var req = URLRequest(url: url, timeoutInterval: 45)
+ req.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
+ req.setValue("text/event-stream", forHTTPHeaderField: "Accept")
+ let session = self.session
+ let request = req
+ return AsyncThrowingStream { continuation in
+ let task = Task {
+ do {
+ let (bytes, response) = try await session.bytes(for: request)
+ let status = (response as? HTTPURLResponse)?.statusCode ?? 0
+ guard status == 200 else { throw HostError.http(status, "Host error \(status)") }
+ for try await line in bytes.lines where line.hasPrefix("data:") {
+ continuation.yield(Data(line.dropFirst(5).utf8))
+ }
+ continuation.finish()
+ } catch is URLError {
+ continuation.finish(throwing: HostError.unreachable)
+ } catch {
+ continuation.finish(throwing: error)
+ }
+ }
+ continuation.onTermination = { _ in task.cancel() }
+ }
+ }
+}
diff --git a/kit/Sources/CodyncKit/Client/Pairing.swift b/kit/Sources/CodyncKit/Client/Pairing.swift
new file mode 100644
index 00000000..425defb7
--- /dev/null
+++ b/kit/Sources/CodyncKit/Client/Pairing.swift
@@ -0,0 +1,83 @@
+import Foundation
+
+/// A scanned QR / pairing link (§4.1). Short-lived: only the resulting `Computer` is kept.
+/// `codync://pair?v=3&name=…&id=<computerId>&sk=…&bk=…&code=…&urls=a,b&cloud=…`
+public struct Pairing: Hashable, Sendable {
+ public var computer: Computer
+ public var code: String
+
+ public enum Problem: LocalizedError, Sendable, Equatable {
+ case notPairingLink
+ /// The computer runs a Codync that speaks another protocol version.
+ case outdatedHost
+ case invalid
+
+ public var errorDescription: String? {
+ switch self {
+ case .notPairingLink: "That isn't a Codync pairing code."
+ case .outdatedHost: "Update Codync on your computer, then show a new pairing code."
+ case .invalid: "This pairing code is damaged. Show a new one on your computer."
+ }
+ }
+ }
+
+ public init?(url: URL) {
+ guard let p = try? Self.parse(url) else { return nil }
+ self = p
+ }
+
+ public init?(string: String) {
+ guard let p = try? Self.parse(string) else { return nil }
+ self = p
+ }
+
+ public static func parse(_ string: String) throws(Problem) -> Pairing {
+ guard let url = URL(string: string.trimmingCharacters(in: .whitespacesAndNewlines)) else { throw .notPairingLink }
+ return try parse(url)
+ }
+
+ public static func parse(_ url: URL) throws(Problem) -> Pairing {
+ guard url.scheme == "codync", url.host() == "pair",
+ let items = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems else { throw .notPairingLink }
+ let q = Dictionary(items.map { ($0.name, $0.value ?? "") }, uniquingKeysWith: { a, _ in a })
+ guard q["v"] == "3" else { throw .outdatedHost }
+ guard let id = q["id"], let sk = q["sk"], let bk = q["bk"], let code = q["code"],
+ let skRaw = Data(base64URL: sk), skRaw.count == 32,
+ Data(base64URL: bk)?.count == 32,
+ Data(base64URL: code)?.count == 16,
+ RelayCrypto.computerId(signKey: skRaw) == id else { throw .invalid }
+ let urls = (q["urls"] ?? "").split(separator: ",").map(String.init).filter(Self.isDirectURL)
+ var cloud: URL?
+ if let raw = q["cloud"], !raw.isEmpty {
+ guard let u = URL(string: raw), Self.isCloudURL(u) else { throw .invalid }
+ cloud = u
+ }
+ guard !urls.isEmpty || cloud != nil else { throw .invalid }
+ let name = q["name"].flatMap { $0.isEmpty ? nil : $0 } ?? "My computer"
+ return Pairing(computer: Computer(id: id, name: name, signKey: sk, boxKey: bk, urls: urls, cloud: cloud), code: code)
+ }
+
+ init(computer: Computer, code: String) {
+ self.computer = computer
+ self.code = code
+ }
+
+ /// The relay's pairing socket parameter.
+ var offerId: String? { Data(base64URL: code).map(RelayCrypto.offerId(code:)) }
+
+ static func isDirectURL(_ s: String) -> Bool {
+ guard let u = URL(string: s), u.scheme == "http" || u.scheme == "https", u.host() != nil else { return false }
+ return true
+ }
+
+ /// https only; debug builds also allow a local dev cloud.
+ public static func isCloudURL(_ url: URL) -> Bool {
+ guard url.host() != nil else { return false }
+ if url.scheme == "https" { return true }
+ #if DEBUG
+ return url.scheme == "http" && ["127.0.0.1", "localhost"].contains(url.host())
+ #else
+ return false
+ #endif
+ }
+}
diff --git a/kit/Sources/CodyncKit/Client/RelayCrypto.swift b/kit/Sources/CodyncKit/Client/RelayCrypto.swift
new file mode 100644
index 00000000..67e345e1
--- /dev/null
+++ b/kit/Sources/CodyncKit/Client/RelayCrypto.swift
@@ -0,0 +1,290 @@
+import CryptoKit
+import Foundation
+
+// The relay protocol's cryptography (docs/remote-relay-spec.md §5, §6), checked field by field
+// against docs/remote-relay-vectors.json. Labels are ASCII without a trailing NUL.
+
+extension Data {
+ /// Strict base64url without padding (RFC 4648 §5).
+ init?(base64URL string: String) {
+ guard string.utf8.allSatisfy({ Data.urlAlphabet.contains($0) }), string.count % 4 != 1 else { return nil }
+ var s = string.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/")
+ s += String(repeating: "=", count: (4 - s.count % 4) % 4)
+ self.init(base64Encoded: s)
+ }
+
+ var base64URL: String {
+ base64EncodedString()
+ .replacingOccurrences(of: "+", with: "-")
+ .replacingOccurrences(of: "/", with: "_")
+ .replacingOccurrences(of: "=", with: "")
+ }
+
+ static func random(_ count: Int) -> Data {
+ var g = SystemRandomNumberGenerator()
+ return Data((0..<count).map { _ in UInt8.random(in: .min ... .max, using: &g) })
+ }
+
+ private static let urlAlphabet = Set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".utf8)
+}
+
+public enum RelayCryptoError: Error, Equatable {
+ case badKey
+ case zeroSharedSecret
+ case badSignature
+ case decryptFailed
+ case badCounter
+ case tooLarge
+ case malformed
+}
+
+public enum RelayCrypto {
+ /// Largest plaintext chunk per frame (§6.3).
+ static let chunkSize = 256 * 1024
+ /// Reassembly limit for host → device messages.
+ static let maxInbound = 16 * 1024 * 1024
+
+ static func sha256(_ parts: Data...) -> Data {
+ var h = SHA256()
+ for p in parts { h.update(data: p) }
+ return Data(h.finalize())
+ }
+
+ static func label(_ s: String) -> Data { Data(s.utf8) }
+
+ static func u64be(_ v: UInt64) -> Data { withUnsafeBytes(of: v.bigEndian) { Data($0) } }
+
+ // MARK: identifiers
+
+ public static func computerId(signKey: Data) -> ComputerID { computerIdRaw(signKey: signKey).base64URL }
+
+ static func computerIdRaw(signKey: Data) -> Data { sha256(signKey).prefix(16) }
+
+ /// The 16 raw bytes behind a computer ID, or nil when it isn't one.
+ static func computerIdRaw(_ id: ComputerID) -> Data? {
+ guard id.count == 22, let raw = Data(base64URL: id), raw.count == 16 else { return nil }
+ return raw
+ }
+
+ /// `offerId` of a pairing code (§4.1).
+ static func offerId(code: Data) -> String { sha256(label("codync/offer/v1"), code).prefix(16).base64URL }
+
+ // MARK: X25519 + HKDF
+
+ static func sharedSecret(_ priv: Curve25519.KeyAgreement.PrivateKey, _ pub: Data) throws -> Data {
+ guard pub.count == 32, let key = try? Curve25519.KeyAgreement.PublicKey(rawRepresentation: pub) else { throw RelayCryptoError.badKey }
+ let ss = try priv.sharedSecretFromKeyAgreement(with: key).withUnsafeBytes { Data($0) }
+ guard ss.contains(where: { $0 != 0 }) else { throw RelayCryptoError.zeroSharedSecret }
+ return ss
+ }
+
+ static func extract(salt: Data, ikm: Data) -> Data {
+ HKDF<SHA256>.extract(inputKeyMaterial: SymmetricKey(data: ikm), salt: salt).withUnsafeBytes { Data($0) }
+ }
+
+ static func expand(_ prk: Data, _ info: String) -> SymmetricKey {
+ HKDF<SHA256>.expand(pseudoRandomKey: prk, info: label(info), outputByteCount: 32)
+ }
+
+ // MARK: handshake (§6.2)
+
+ static func hs1Input(cid: Data, dk: Data, ekD: Data, n: Data) -> Data {
+ label("codync/hs1/v1") + cid + dk + ekD + n
+ }
+
+ static func transcriptHash(cid: Data, dk: Data, ekD: Data, n: Data, ekH: Data) -> Data {
+ sha256(label("codync/hs2/v1"), cid, dk, ekD, n, ekH)
+ }
+
+ struct ChannelKeys {
+ var prk: Data
+ var d2h: SymmetricKey
+ var h2d: SymmetricKey
+ }
+
+ static func channelKeys(sharedSecret ss: Data, transcriptHash th: Data) -> ChannelKeys {
+ let prk = extract(salt: th, ikm: ss)
+ return ChannelKeys(prk: prk, d2h: expand(prk, "codync/d2h/v1"), h2d: expand(prk, "codync/h2d/v1"))
+ }
+
+ /// The device's half of one handshake: fresh ephemeral key and nonce each connection.
+ struct Handshake {
+ let cid: Data
+ let dk: Data
+ let hostSignKey: Curve25519.Signing.PublicKey
+ let ephemeral: Curve25519.KeyAgreement.PrivateKey
+ let n: Data
+
+ init(computer: Computer, deviceKey: Data,
+ ephemeral: Curve25519.KeyAgreement.PrivateKey = .init(), n: Data = .random(32)) throws {
+ guard let sk = Data(base64URL: computer.signKey), sk.count == 32,
+ let hostKey = try? Curve25519.Signing.PublicKey(rawRepresentation: sk),
+ computerId(signKey: sk) == computer.id else { throw RelayCryptoError.badKey }
+ cid = computerIdRaw(signKey: sk)
+ dk = deviceKey
+ hostSignKey = hostKey
+ self.ephemeral = ephemeral
+ self.n = n
+ }
+
+ var ekD: Data { ephemeral.publicKey.rawRepresentation }
+ var signInput: Data { hs1Input(cid: cid, dk: dk, ekD: ekD, n: n) }
+
+ /// Checks `welcome.sig` against the pinned host key, then derives both directions' keys.
+ func finish(ekH: Data, sig: Data) throws -> ChannelKeys {
+ let th = transcriptHash(cid: cid, dk: dk, ekD: ekD, n: n, ekH: ekH)
+ guard hostSignKey.isValidSignature(sig, for: th) else { throw RelayCryptoError.badSignature }
+ return channelKeys(sharedSecret: try sharedSecret(ephemeral, ekH), transcriptHash: th)
+ }
+ }
+
+ // MARK: frames (§6.3)
+
+ static func frameNonce(_ c: UInt64) -> Data { Data(count: 4) + u64be(c) }
+ static func frameAAD(_ c: UInt64) -> Data { label("codync/frame/v1") + u64be(c) }
+
+ static func sealFrame(key: SymmetricKey, counter c: UInt64, final: Bool, chunk: Data) throws -> Data {
+ let box = try ChaChaPoly.seal(Data([final ? 0 : 1]) + chunk, using: key,
+ nonce: ChaChaPoly.Nonce(data: frameNonce(c)), authenticating: frameAAD(c))
+ return box.ciphertext + box.tag
+ }
+
+ static func openFrame(key: SymmetricKey, counter c: UInt64, d: Data) throws -> (final: Bool, chunk: Data) {
+ guard d.count >= 17 else { throw RelayCryptoError.malformed }
+ let box = try ChaChaPoly.SealedBox(nonce: ChaChaPoly.Nonce(data: frameNonce(c)), ciphertext: d.dropLast(16), tag: d.suffix(16))
+ guard let plain = try? ChaChaPoly.open(box, using: key, authenticating: frameAAD(c)),
+ let flag = plain.first, flag <= 1 else { throw RelayCryptoError.decryptFailed }
+ return (flag == 0, plain.dropFirst())
+ }
+
+ /// One direction's sender: every inner message becomes ≤ 256 KiB chunks with consecutive counters.
+ struct FrameSealer {
+ let key: SymmetricKey
+ private(set) var counter: UInt64 = 0
+
+ init(key: SymmetricKey) { self.key = key }
+
+ /// Past 2^32 frames the channel must be replaced (`4011 rekey`).
+ var exhausted: Bool { counter >= 1 << 32 }
+
+ mutating func seal(_ message: Data) throws -> [(c: UInt64, d: Data)] {
+ var out: [(UInt64, Data)] = []
+ var rest = message[...]
+ repeat {
+ let chunk = rest.prefix(RelayCrypto.chunkSize)
+ rest = rest.dropFirst(chunk.count)
+ out.append((counter, try sealFrame(key: key, counter: counter, final: rest.isEmpty, chunk: Data(chunk))))
+ counter += 1
+ } while !rest.isEmpty
+ return out
+ }
+ }
+
+ /// One direction's receiver: demands the exact next counter and reassembles chunks.
+ struct FrameOpener {
+ let key: SymmetricKey
+ let limit: Int
+ private(set) var counter: UInt64 = 0
+ private var buffer = Data()
+
+ init(key: SymmetricKey, limit: Int = RelayCrypto.maxInbound) {
+ self.key = key
+ self.limit = limit
+ }
+
+ /// A whole message once its last chunk arrived, else nil.
+ mutating func open(c: UInt64, d: Data) throws -> Data? {
+ guard c == counter else { throw RelayCryptoError.badCounter }
+ let (final, chunk) = try openFrame(key: key, counter: c, d: d)
+ counter += 1
+ guard buffer.count + chunk.count <= limit else { throw RelayCryptoError.tooLarge }
+ buffer += chunk
+ guard final else { return nil }
+ defer { buffer = Data() }
+ return buffer
+ }
+ }
+
+ // MARK: mailbox (§6.4)
+
+ struct Mailbox {
+ var epk: Data
+ var ciphertext: Data
+ var sig: Data
+ var blob: Data { epk + sig + ciphertext }
+ }
+
+ /// Seals one inner message for an offline host. A fresh ephemeral key every time (MUST):
+ /// the fixed nonce is only safe because the key is never reused.
+ static func sealMailbox(_ plaintext: Data, hostBoxKey: Data, computerId: ComputerID, deviceKey dk: Data, clientNonce: String,
+ sign: (Data) throws -> Data,
+ ephemeral: Curve25519.KeyAgreement.PrivateKey = .init()) throws -> Mailbox {
+ guard let cid = computerIdRaw(computerId) else { throw RelayCryptoError.badKey }
+ let epk = ephemeral.publicKey.rawRepresentation
+ let ss = try sharedSecret(ephemeral, hostBoxKey)
+ let prk = extract(salt: label("codync/mbox/v1") + cid + dk + epk, ikm: ss)
+ let box = try ChaChaPoly.seal(plaintext, using: expand(prk, "codync/mbox-key/v1"),
+ nonce: ChaChaPoly.Nonce(data: Data(count: 12)), authenticating: dk + Data(clientNonce.utf8))
+ let ct = box.ciphertext + box.tag
+ return Mailbox(epk: epk, ciphertext: ct, sig: try sign(label("codync/mbox/v1") + cid + epk + ct))
+ }
+
+ static func mailboxKey(sharedSecret ss: Data, cid: Data, dk: Data, epk: Data) -> SymmetricKey {
+ expand(extract(salt: label("codync/mbox/v1") + cid + dk + epk, ikm: ss), "codync/mbox-key/v1")
+ }
+
+ // MARK: push (§6.7)
+
+ static func pushKey(sharedSecret ss: Data, cid: Data, pushKey: Data, epk: Data) -> SymmetricKey {
+ expand(extract(salt: label("codync/push/v1") + cid + pushKey + epk, ikm: ss), "codync/push-key/v1")
+ }
+
+ /// Opens `sealed = b64url(epk ‖ ct)` with the device's push key.
+ static func openPush(sealed: String, computerId: ComputerID, pushPrivate: Curve25519.KeyAgreement.PrivateKey) throws -> Data {
+ guard let raw = Data(base64URL: sealed), raw.count > 32 + 16, let cid = computerIdRaw(computerId) else { throw RelayCryptoError.malformed }
+ let epk = raw.prefix(32)
+ let ct = raw.dropFirst(32)
+ let key = pushKey(sharedSecret: try sharedSecret(pushPrivate, Data(epk)), cid: cid,
+ pushKey: pushPrivate.publicKey.rawRepresentation, epk: Data(epk))
+ let box = try ChaChaPoly.SealedBox(nonce: ChaChaPoly.Nonce(data: Data(count: 12)), ciphertext: ct.dropLast(16), tag: ct.suffix(16))
+ guard let plain = try? ChaChaPoly.open(box, using: key, authenticating: cid) else { throw RelayCryptoError.decryptFailed }
+ return plain
+ }
+
+ // MARK: SAS (§4.2 B)
+
+ static func sasCommit(deviceKey dk: Data, deviceNonce nD: Data) -> Data {
+ sha256(label("codync/sascommit/v1"), dk, nD)
+ }
+
+ static func sasCode(hostSignKey: Data, deviceKey dk: Data, deviceNonce nD: Data, hostNonce nH: Data) -> String {
+ let h = sha256(label("codync/sas/v2"), hostSignKey, dk, nD, nH)
+ let v = h.prefix(4).reduce(UInt32(0)) { $0 << 8 | UInt32($1) }
+ let s = String(v % 1_000_000)
+ return String(repeating: "0", count: 6 - s.count) + s
+ }
+
+ // MARK: Codync-Sig (§5)
+
+ static func requestSigInput(method: String, authority: String, pathAndQuery: String, ts: Int64, nonce: String, body: Data) -> Data {
+ Data([
+ "codync-sig-v1", method.uppercased(), authority.lowercased(), pathAndQuery,
+ String(ts), nonce, sha256(body).base64URL,
+ ].joined(separator: "\n").utf8)
+ }
+
+ /// The `Host` header value of `url`: lowercased, with a non-default port.
+ static func authority(of url: URL) -> String {
+ let host = (url.host(percentEncoded: false) ?? "").lowercased()
+ let defaultPort = ["https": 443, "wss": 443, "http": 80, "ws": 80][url.scheme?.lowercased() ?? ""]
+ guard let port = url.port, port != defaultPort else { return host }
+ return "\(host):\(port)"
+ }
+
+ /// Path and query exactly as sent on the request line.
+ static func pathAndQuery(of url: URL) -> String {
+ let path = url.path(percentEncoded: true)
+ let query = url.query(percentEncoded: true).map { "?\($0)" } ?? ""
+ return (path.isEmpty ? "/" : path) + query
+ }
+}
diff --git a/kit/Sources/CodyncKit/Client/SharedStore.swift b/kit/Sources/CodyncKit/Client/SharedStore.swift
index 8f8e9456..aee64c5f 100644
--- a/kit/Sources/CodyncKit/Client/SharedStore.swift
+++ b/kit/Sources/CodyncKit/Client/SharedStore.swift
@@ -1,10 +1,11 @@
-import Foundation
import CryptoKit
+import Foundation
-/// Values shared between the iOS app and its widgets through the App Group.
+/// Values shared between the app, its widgets and its notification extension through the App Group,
+/// one namespace per account context so a signed-out account's data never shows in another.
public enum SharedStore {
public static let appGroup = "group.com.pokai.Codync"
- /// Codync push relay (relay/ in this repo).
+ /// The APNs push relay (relay/ in this repo).
public static let relayURL = "https://codync-relay.kevin2005ha.workers.dev"
private static var defaults: UserDefaults { UserDefaults(suiteName: appGroup) ?? .standard }
@@ -18,16 +19,20 @@ public enum SharedStore {
public static var activeContext: Context { Context(accountID: activeAccountID) }
- public struct Context {
+ public struct Context: Sendable {
+ /// The raw Clerk user ID; nil = the local (signed-out) context.
public let accountID: String?
- private let defaults: UserDefaults
+ /// The UserDefaults suite (the App Group; tests use their own).
+ private let suite: String
+ private var defaults: UserDefaults { UserDefaults(suiteName: suite) ?? .standard }
public var id: String { accountID.map { Self.digest($0) } ?? "local" }
- public init(accountID: String?, defaults: UserDefaults = UserDefaults(suiteName: SharedStore.appGroup) ?? .standard) {
+ public init(accountID: String?, suite: String = SharedStore.appGroup) {
self.accountID = accountID
- self.defaults = defaults
+ self.suite = suite
}
+ private static let names = ["computers", "bots", "usage", "lastComputerId"]
private func key(_ name: String) -> String { accountID == nil ? name : "account.\(id).\(name)" }
public static func digest(_ value: String) -> String {
SHA256.hash(data: Data(value.utf8)).map { String(format: "%02x", $0) }.joined()
@@ -38,75 +43,63 @@ public enum SharedStore {
private func write<T: Encodable>(_ value: T?, _ name: String) {
defaults.set(value.flatMap { try? JSONEncoder().encode($0) }, forKey: key(name))
}
- public var pairing: Pairing? {
- get { read(Pairing.self, "pairing") }
- nonmutating set { write(newValue, "pairing") }
- }
- public var computers: [Pairing] {
- get { read([Pairing].self, "computers") ?? pairing.map { [$0] } ?? [] }
+
+ /// Computers this context may reach (no secrets: pinned public keys and addresses).
+ public var computers: [Computer] {
+ get { read([Computer].self, "computers") ?? [] }
nonmutating set { write(newValue, "computers") }
}
- public var preferredURL: String? {
- get { defaults.string(forKey: key("preferredURL")) }
- nonmutating set { defaults.set(newValue, forKey: key("preferredURL")) }
+ /// The widgets' snapshot of every computer's bots.
+ public var bots: [BotSnapshot] {
+ get { read([BotSnapshot].self, "bots") ?? [] }
+ nonmutating set { write(newValue, "bots") }
}
- public var usage: Usage? {
- get { read(Usage.self, "usage") }
+ public var usage: [ComputerID: Usage] {
+ get { read([ComputerID: Usage].self, "usage") ?? [:] }
nonmutating set { write(newValue, "usage") }
}
- public var bots: [Bot] {
- get { read([Bot].self, "bots") ?? [] }
- nonmutating set { write(newValue, "bots") }
+ /// The most recently active computer; the Usage widget shows only this one.
+ public var lastComputerId: ComputerID? {
+ get { defaults.string(forKey: key("lastComputerId")) }
+ nonmutating set { defaults.set(newValue, forKey: key("lastComputerId")) }
}
- /// Deep links carry the storage scope captured when a widget/activity
- /// was created, so an old surface cannot open another account's bot.
- public func botURL(_ botID: String) -> URL {
+
+ /// Deep links carry the context they were made in, so an old widget or activity
+ /// can't open another account's bot: `codync://bot/<botId>?scope=<id>&computer=<computerId>`.
+ public func botURL(_ ref: BotReference) -> URL {
var url = URLComponents()
url.scheme = "codync"
url.host = "bot"
- url.path = "/" + botID
+ url.path = "/" + ref.botId
url.queryItems = [
URLQueryItem(name: "scope", value: id),
- URLQueryItem(name: "computer", value: Self.digest(pairing?.token ?? "unpaired"))
+ URLQueryItem(name: "computer", value: ref.computerId),
]
- return url.url!
+ return url.url ?? URL(string: "codync://bot")!
}
- public func acceptsBotURL(_ url: URL) -> Bool {
- guard url.scheme == "codync", url.host == "bot" else { return false }
- let items = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems ?? []
- guard let scope = items.first(where: { $0.name == "scope" })?.value else {
- return accountID == nil
- }
- return scope == id && items.first(where: { $0.name == "computer" })?.value == Self.digest(pairing?.token ?? "unpaired")
+
+ /// The bot a deep link points at, or nil when it belongs to another context or is malformed.
+ public func reference(from url: URL) -> BotReference? {
+ guard url.scheme == "codync", url.host() == "bot",
+ let items = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems,
+ items.first(where: { $0.name == "scope" })?.value == id,
+ let computer = items.first(where: { $0.name == "computer" })?.value,
+ RelayCrypto.computerIdRaw(computer) != nil else { return nil }
+ let botId = String(url.path(percentEncoded: false).dropFirst())
+ guard !botId.isEmpty, !botId.contains("/") else { return nil }
+ return BotReference(accountId: accountID, computerId: computer, botId: botId)
}
- public var orderedPairing: Pairing? {
- guard var p = pairing else { return nil }
- if let preferredURL, let i = p.urls.firstIndex(of: preferredURL) {
- p.urls.insert(p.urls.remove(at: i), at: 0)
+
+ /// Signing out or removing the account: device keys, computers, widget snapshot and caches go.
+ public func erase() {
+ for name in Self.names { defaults.removeObject(forKey: key(name)) }
+ DeviceIdentity.delete(context: self)
+ let caches = URL.cachesDirectory
+ let marker = "-\(id)-"
+ for file in (try? FileManager.default.contentsOfDirectory(atPath: caches.path())) ?? []
+ where file.hasPrefix("codync-mirror-") && file.contains(marker) {
+ try? FileManager.default.removeItem(at: caches.appending(path: file))
}
- return p
}
}
-
- public static var pairing: Pairing? {
- get { activeContext.pairing }
- set { activeContext.pairing = newValue }
- }
- public static var computers: [Pairing] {
- get { activeContext.computers }
- set { activeContext.computers = newValue }
- }
- public static var preferredURL: String? {
- get { activeContext.preferredURL }
- set { activeContext.preferredURL = newValue }
- }
- public static var usage: Usage? {
- get { activeContext.usage }
- set { activeContext.usage = newValue }
- }
- public static var bots: [Bot] {
- get { activeContext.bots }
- set { activeContext.bots = newValue }
- }
- public static var orderedPairing: Pairing? { activeContext.orderedPairing }
}
diff --git a/kit/Sources/CodyncKit/Models/BotActivity.swift b/kit/Sources/CodyncKit/Models/BotActivity.swift
index c7a3e634..e9b45eae 100644
--- a/kit/Sources/CodyncKit/Models/BotActivity.swift
+++ b/kit/Sources/CodyncKit/Models/BotActivity.swift
@@ -8,6 +8,7 @@ public struct BotActivityAttributes: ActivityAttributes {
public struct ContentState: Codable, Hashable, Sendable {
/// idle | working | needsInput | error
public var status: String
+ /// Always empty: pushes never carry free text (§6.7). Kept so the content state shape stays stable.
public var activity: String
public var startedAt: Date?
@@ -19,13 +20,15 @@ public struct BotActivityAttributes: ActivityAttributes {
}
public var link: URL?
+ public var computerId: ComputerID
public var botId: String
public var name: String
public var avatarShape: String
public var avatarColor: String
- public init(bot: Bot, link: URL? = nil) {
+ public init(bot: Bot, computerId: ComputerID, link: URL? = nil) {
self.link = link
+ self.computerId = computerId
botId = bot.id
name = bot.name
avatarShape = bot.avatarShape
diff --git a/kit/Sources/CodyncKit/Models/Cloud.swift b/kit/Sources/CodyncKit/Models/Cloud.swift
new file mode 100644
index 00000000..35b20680
--- /dev/null
+++ b/kit/Sources/CodyncKit/Models/Cloud.swift
@@ -0,0 +1,203 @@
+import Foundation
+
+// Wire types for the Codync cloud (`/v1`, cloud/src/api.ts), the host's loopback-only
+// account methods (host/src/api.rs) and the relay mailbox. Times are epoch milliseconds.
+// Decoding is lenient: unknown fields are ignored and anything the server may omit is optional.
+
+/// `GET /v1/me`.
+public struct CloudAccount: Codable, Hashable, Sendable {
+ public var userId: String
+ public var email: String?
+ public var createdAt: Int64?
+}
+
+/// A computer in the account (`GET /v1/computers`). Its `boxKey` is for display only.
+public struct CloudComputer: Codable, Hashable, Sendable, Identifiable {
+ public var computerId: ComputerID
+ public var name: String
+ public var platform: String?
+ public var device: String?
+ /// Delivered by the cloud: trusted only after the SAS matched (`AccessTicket.signKey`).
+ public var signKey: String
+ public var boxKey: String?
+ public var version: String?
+ public var online: Bool?
+ public var lastSeenAt: Int64?
+ public var claimedAt: Int64?
+ /// `none` · `pending` · `granted` (only when the request carried this device's signature).
+ public var access: String?
+
+ public var id: ComputerID { computerId }
+ public var isOnline: Bool { online ?? false }
+}
+
+/// A started access request, after both nonces were exchanged: `code` is ready to show.
+public struct AccessTicket: Codable, Hashable, Sendable, Identifiable {
+ public var requestId: String
+ public var expiresAt: Int64
+ /// The 6-digit SAS to compare with the one the computer shows.
+ public var code: String
+ public var computerId: ComputerID
+ /// The host key the SAS was computed with; pinned once the request is approved.
+ public var signKey: String
+ public var id: String { requestId }
+
+ public init(requestId: String, expiresAt: Int64, code: String, computerId: ComputerID, signKey: String) {
+ self.requestId = requestId
+ self.expiresAt = expiresAt
+ self.code = code
+ self.computerId = computerId
+ self.signKey = signKey
+ }
+}
+
+public enum AccessState: String, Codable, Sendable {
+ case pending, approved, denied, expired, cancelled
+
+ public init(from decoder: Decoder) throws {
+ // A state this version doesn't know is over as far as it can tell.
+ self = AccessState(rawValue: try decoder.singleValueContainer().decode(String.self)) ?? .expired
+ }
+}
+
+/// `GET /v1/access-requests/{id}`.
+public struct AccessStatus: Codable, Hashable, Sendable {
+ public var requestId: String
+ public var computerId: ComputerID?
+ public var status: AccessState
+ public var expiresAt: Int64?
+ public var hostNonce: String?
+ public var grantId: String?
+}
+
+/// A pending request as the computer shows it (loopback `accessRequests`).
+public struct AccessRequest: Codable, Hashable, Sendable, Identifiable {
+ public var requestId: String
+ public var deviceKey: String
+ public var deviceName: String
+ public var platform: String?
+ public var email: String?
+ /// The SAS; nil until the phone revealed its nonce (Approve stays disabled).
+ public var code: String?
+ public var createdAt: Int64?
+ public var expiresAt: Int64?
+ public var id: String { requestId }
+}
+
+/// A device the host authorized (loopback `devices`).
+public struct AuthorizedDevice: Codable, Hashable, Sendable, Identifiable {
+ public var key: String
+ public var name: String
+ public var platform: String?
+ /// `local` (QR) or `account`.
+ public var source: String
+ public var scopes: [String]?
+ public var leaseUntil: Int64?
+ public var createdAt: Int64?
+ public var lastSeenAt: Int64?
+ public var connected: Bool?
+ public var id: String { key }
+}
+
+public struct CloudOwner: Codable, Hashable, Sendable {
+ public var userId: String
+ public var email: String?
+}
+
+/// The host's cloud connection (loopback `cloudStatus`, `setCloud`, `cloud` events).
+public struct CloudStatus: Codable, Hashable, Sendable {
+ public var enabled: Bool
+ public var url: String?
+ public var registered: Bool?
+ public var connected: Bool?
+ public var owner: CloudOwner?
+ public var lastError: String?
+}
+
+/// `POST /v1/claims`.
+public struct ClaimChallenge: Codable, Hashable, Sendable {
+ public var claimId: String
+ public var nonce: String
+ public var expiresAt: Int64
+}
+
+/// What the host signs for a claim (loopback `claimSign`), passed on to `/v1/claims/{id}/complete`.
+public struct ClaimSignature: Codable, Hashable, Sendable {
+ public var computerId: ComputerID
+ public var signKey: String
+ public var boxKey: String
+ public var name: String
+ public var platform: String
+ public var device: String?
+ public var version: String
+ public var sig: String
+}
+
+/// `GET /v1/devices`.
+public struct CloudDevice: Codable, Hashable, Sendable, Identifiable {
+ public var deviceId: String
+ public var deviceKey: String
+ public var name: String
+ public var platform: String?
+ public var createdAt: Int64?
+ public var lastUsedAt: Int64?
+ public var revoked: Bool?
+ public var id: String { deviceId }
+}
+
+/// `GET /v1/computers/{id}/grants`.
+public struct CloudGrant: Codable, Hashable, Sendable, Identifiable {
+ public var grantId: String
+ public var deviceId: String
+ public var deviceName: String?
+ public var platform: String?
+ public var scopes: [String]?
+ public var createdAt: Int64?
+ public var id: String { grantId }
+}
+
+/// A message waiting in the relay mailbox for a computer that is offline.
+public struct QueuedItem: Codable, Hashable, Sendable, Identifiable {
+ public var nonce: String
+ public var exp: Int64?
+ /// `queued`, or `delivering` (handed to the computer, not acknowledged yet).
+ public var state: String
+ public var id: String { nonce }
+}
+
+public enum MailboxEvent: Sendable, Equatable {
+ case delivered(nonce: String)
+ case failed(nonce: String, code: String)
+ case expired(nonce: String)
+
+ public var nonce: String {
+ switch self {
+ case let .delivered(nonce), let .failed(nonce, _), let .expired(nonce): nonce
+ }
+ }
+}
+
+public enum MailboxCancel: Sendable, Equatable {
+ /// Removed before the computer saw it.
+ case cancelled
+ /// Already handed to the computer: it will run.
+ case delivering
+ /// The relay doesn't have it (delivered, expired, or not reachable right now).
+ case unknown
+}
+
+/// Why the relay refused a mailbox message.
+public enum MailboxError: LocalizedError, Sendable, Equatable {
+ /// The computer came online: send over the channel instead.
+ case hostOnline
+ case rejected(String)
+
+ public var errorDescription: String? {
+ switch self {
+ case .hostOnline: "Your computer just came online. Send again."
+ case .rejected("full"): "Too many messages are waiting for this computer."
+ case .rejected("tooLarge"): "This message is too long to hold while the computer is offline."
+ case let .rejected(code): "Couldn't hold the message for your computer (\(code))."
+ }
+ }
+}
diff --git a/kit/Sources/CodyncKit/Models/Computer.swift b/kit/Sources/CodyncKit/Models/Computer.swift
new file mode 100644
index 00000000..0b746b19
--- /dev/null
+++ b/kit/Sources/CodyncKit/Models/Computer.swift
@@ -0,0 +1,64 @@
+import Foundation
+
+/// `b64url(SHA-256(hostSignPub)[0..16])`: derived from the host's signing key, never assigned by the cloud.
+public typealias ComputerID = String
+
+/// A computer this device may talk to. Holds no secrets: only pinned public keys and addresses.
+public struct Computer: Codable, Hashable, Sendable, Identifiable {
+ public var id: ComputerID
+ public var name: String
+ /// Pinned host signing key: the QR's `sk`, or the account flow's key once its SAS matched.
+ public var signKey: String
+ /// Pinned mailbox key: only from the QR's `bk` or the E2E `hello`; nil = no mailbox yet.
+ public var boxKey: String?
+ /// Direct candidates (`http://ip:port`), tried before the relay.
+ public var urls: [String]
+ /// The cloud relay base URL; nil = the host has the cloud off.
+ public var cloud: URL?
+ /// laptop · macmini · … · linux, from `hello`; picks the icon.
+ public var device: String?
+ /// The badge color picked on this device (an `AvatarPalette` id).
+ public var color: String?
+
+ public init(id: ComputerID, name: String, signKey: String, boxKey: String? = nil, urls: [String] = [],
+ cloud: URL? = nil, device: String? = nil, color: String? = nil) {
+ self.id = id
+ self.name = name
+ self.signKey = signKey
+ self.boxKey = boxKey
+ self.urls = urls
+ self.cloud = cloud
+ self.device = device
+ self.color = color
+ }
+
+ /// `true` when `id` really is the computer ID of `signKey`.
+ public var isConsistent: Bool {
+ Data(base64URL: signKey).map { $0.count == 32 && RelayCrypto.computerId(signKey: $0) == id } ?? false
+ }
+}
+
+/// A bot on a computer in an account context: bot IDs are only unique per computer.
+public struct BotReference: Codable, Hashable, Sendable {
+ /// `SharedStore.Context.accountID` (raw Clerk user ID; nil = the local context).
+ public var accountId: String?
+ public var computerId: ComputerID
+ public var botId: String
+
+ public init(accountId: String?, computerId: ComputerID, botId: String) {
+ self.accountId = accountId
+ self.computerId = computerId
+ self.botId = botId
+ }
+}
+
+/// One bot as the widgets see it.
+public struct BotSnapshot: Codable, Hashable, Sendable {
+ public var computerId: ComputerID
+ public var bot: Bot
+
+ public init(computerId: ComputerID, bot: Bot) {
+ self.computerId = computerId
+ self.bot = bot
+ }
+}
diff --git a/kit/Sources/CodyncKit/Models/Models.swift b/kit/Sources/CodyncKit/Models/Models.swift
index c41d2240..9fc45c92 100644
--- a/kit/Sources/CodyncKit/Models/Models.swift
+++ b/kit/Sources/CodyncKit/Models/Models.swift
@@ -228,8 +228,15 @@ public struct Hello: Codable, Sendable {
public var rev: Int64
/// Missing from hosts that predate remote screen.
public var screen: ScreenState?
- /// The host's current addresses, so pairings pick up Tailscale set up after pairing.
+ /// The host's current direct addresses.
public var urls: [String]?
+ /// Channel identity (§9.4); missing only on loopback to an older host.
+ public var computerId: ComputerID?
+ public var signKey: String?
+ public var boxKey: String?
+ public var `protocol`: Int?
+ /// The cloud relay the host uses; nil = cloud off.
+ public var cloud: String?
}
/// The computer's remote screen: whether phones can view/control it, and who's in control.
@@ -285,9 +292,12 @@ public struct SyncResponse: Codable, Sendable {
public var usage: Usage
}
+/// A fresh pairing code to show as a QR on this computer (loopback `pairing`).
public struct PairingInfo: Codable, Sendable {
public var pairingUrl: String
public var urls: [String]
+ public var svg: String?
+ public var expiresAt: Int64?
}
public struct DirListing: Codable, Sendable {
diff --git a/kit/Sources/CodyncUI/Bots/BotRow.swift b/kit/Sources/CodyncUI/Bots/BotRow.swift
index b0e8f3d5..9468c411 100644
--- a/kit/Sources/CodyncUI/Bots/BotRow.swift
+++ b/kit/Sources/CodyncUI/Bots/BotRow.swift
@@ -113,37 +113,33 @@ public struct ConnectionBanner: View {
Label("Connecting to \(model.hostName)…", systemImage: "antenna.radiowaves.left.and.right")
.font(.footnote)
.foregroundStyle(Palette.secondary)
+ case let .computerOffline(lastSeen):
+ let seen = lastSeen.map { " Last seen \(RelativeTime.day($0))." } ?? ""
+ banner(icon: "moon.zzz", title: "\(model.hostName) is offline",
+ detail: (model.canQueue ? "Messages wait and go out when it's back online." : "It's asleep or turned off.") + seen,
+ retry: false)
case let .offline(reason):
- HStack(alignment: .top, spacing: 8) {
- Image(systemName: "wifi.exclamationmark").foregroundStyle(Palette.warning)
- VStack(alignment: .leading, spacing: 2) {
- Text("\(model.hostName) is offline").font(.footnote.weight(.semibold)).foregroundStyle(Palette.text)
- Text(reason).font(.footnote).foregroundStyle(Palette.secondary)
- #if os(iOS)
- if reason == HostError.unreachable.localizedDescription { tailscaleHint }
- #endif
- }
- Spacer()
- Button("Retry", systemImage: "arrow.clockwise") { model.restartStream() }
- .labelStyle(.iconOnly)
- .help("Retry")
- }
- .padding(10)
- .background(Palette.surface, in: RoundedRectangle(cornerRadius: 10))
+ banner(icon: "wifi.exclamationmark", title: "Can't reach \(model.hostName)", detail: reason, retry: true)
+ case let .unauthorized(reason):
+ banner(icon: "lock.slash", title: "No access to \(model.hostName)", detail: reason, retry: false)
}
}
- /// Away from home the phone needs Tailscale: say whether it's off here or not set up at all.
- @ViewBuilder private var tailscaleHint: some View {
- if model.pairing?.urls.contains(where: Tailscale.isAddress) == true {
- if !Tailscale.isConnected {
- Text("Tailscale is off on this iPhone. Turn it on to reach \(model.hostName) away from home.")
- .font(.footnote.weight(.medium))
- .foregroundStyle(Palette.warning)
+ private func banner(icon: String, title: String, detail: String, retry: Bool) -> some View {
+ HStack(alignment: .top, spacing: 8) {
+ Image(systemName: icon).foregroundStyle(Palette.warning)
+ VStack(alignment: .leading, spacing: 2) {
+ Text(title).font(.footnote.weight(.semibold)).foregroundStyle(Palette.text)
+ Text(detail).font(.footnote).foregroundStyle(Palette.secondary)
+ }
+ Spacer()
+ if retry {
+ Button("Retry", systemImage: "arrow.clockwise") { model.restartStream() }
+ .labelStyle(.iconOnly)
+ .help("Retry")
}
- } else {
- Link("Away from home? Set up Tailscale", destination: Tailscale.downloadURL)
- .font(.footnote.weight(.medium))
}
+ .padding(10)
+ .background(Palette.surface, in: RoundedRectangle(cornerRadius: 10))
}
}
diff --git a/kit/Sources/CodyncUI/ComputerBadge.swift b/kit/Sources/CodyncUI/ComputerBadge.swift
index 90f027c4..e73b68b8 100644
--- a/kit/Sources/CodyncUI/ComputerBadge.swift
+++ b/kit/Sources/CodyncUI/ComputerBadge.swift
@@ -4,10 +4,10 @@ import SwiftUI
/// A computer's icon showing what it is (laptop, Mac mini, Linux…), in the color picked for it:
/// the profile button and the rows that switch computers.
public struct ComputerBadge: View {
- let computer: Pairing?
+ let computer: Computer?
let size: CGFloat
- public init(_ computer: Pairing?, size: CGFloat = 36) {
+ public init(_ computer: Computer?, size: CGFloat = 36) {
self.computer = computer
self.size = size
}
diff --git a/kit/Sources/CodyncUI/Store/AccountStore.swift b/kit/Sources/CodyncUI/Store/AccountStore.swift
new file mode 100644
index 00000000..60d6f210
--- /dev/null
+++ b/kit/Sources/CodyncUI/Store/AccountStore.swift
@@ -0,0 +1,259 @@
+import CodyncKit
+import Foundation
+import Observation
+
+/// One bot across an account context's computers, for lists that mix them.
+public struct RosterItem: Identifiable, Sendable {
+ public var ref: BotReference
+ public var bot: Bot
+ public var computer: Computer
+ public var id: BotReference { ref }
+}
+
+/// Account → computers → bots: one `BotStore` per computer this context can reach
+/// (QR-paired, approved through the account, or attached over loopback / SSH on the Mac),
+/// plus the account's computers from the cloud that this device can still ask access to.
+@MainActor
+@Observable
+public final class AccountStore {
+ public let storage: SharedStore.Context
+ public var accountId: String? { storage.accountID }
+ /// Attached (loopback) computers first, then the saved ones.
+ public private(set) var computers: [Computer] = []
+ public private(set) var stores: [ComputerID: BotStore] = [:]
+ /// Everything in the account, including computers this device isn't authorized on yet.
+ public private(set) var cloudComputers: [CloudComputer] = []
+ /// Access requests waiting for approval on the computer, with the SAS to show.
+ public private(set) var pendingAccess: [ComputerID: AccessTicket] = [:]
+ public var lastError: String?
+ public var selection: BotReference? {
+ didSet { if let id = selection?.computerId, !retired { storage.lastComputerId = id } }
+ }
+
+ public var onBotUpdated: (@MainActor (BotReference, Bot) -> Void)?
+ public var onConnected: (@MainActor (BotStore) -> Void)?
+ public var onSent: (@MainActor (BotReference, Bot) -> Void)?
+
+ private let clientKind: String
+ private let cloud: CloudClient?
+ private let makeStore: @MainActor (Computer, BotStore.Route) -> BotStore
+ /// Persisted in the context (channel route).
+ private var saved: [Computer]
+ /// This session only: the Mac's own host and SSH tunnels.
+ private var attached: [Computer] = []
+ private var accessPolls: [ComputerID: Task<Void, Never>] = [:]
+ private var isActive = true
+ private var retired = false
+
+ public convenience init(storage: SharedStore.Context, clientKind: String, cloud: CloudClient?) {
+ self.init(storage: storage, clientKind: clientKind, cloud: cloud) { computer, route in
+ BotStore(computer: computer, route: route, clientKind: clientKind, storage: storage)
+ }
+ }
+
+ init(storage: SharedStore.Context, clientKind: String, cloud: CloudClient?,
+ makeStore: @escaping @MainActor (Computer, BotStore.Route) -> BotStore) {
+ self.storage = storage
+ self.clientKind = clientKind
+ self.cloud = cloud
+ self.makeStore = makeStore
+ saved = storage.computers.filter(\.isConsistent)
+ for computer in saved { open(computer, route: .channel) }
+ refreshList()
+ }
+
+ // MARK: derived
+
+ /// Every computer's visible bots, pinned first, then most recent activity.
+ public var roster: [RosterItem] {
+ computers.flatMap { computer -> [RosterItem] in
+ guard let store = stores[computer.id] else { return [] }
+ return store.roster.map {
+ RosterItem(ref: BotReference(accountId: accountId, computerId: computer.id, botId: $0.id), bot: $0, computer: store.computer)
+ }
+ }
+ .sorted {
+ if $0.bot.pinned != $1.bot.pinned { return $0.bot.pinned }
+ return $0.bot.lastAt > $1.bot.lastAt
+ }
+ }
+
+ public func store(for id: ComputerID) -> BotStore? { stores[id] }
+
+ // MARK: computers
+
+ /// QR pairing (§4.1); the computer is saved in this context and connected.
+ public func pair(_ pairing: Pairing, deviceName: String, platform: String) async throws -> Computer {
+ let identity = try DeviceIdentity.load(context: storage)
+ var computer = try await HostConnector.pair(pairing, identity: identity, deviceName: deviceName, platform: platform)
+ guard !retired else { throw CancellationError() }
+ computer.color = saved.first { $0.id == computer.id }?.color
+ save(computer)
+ if !attached.contains(where: { $0.id == computer.id }) { open(computer, route: .channel) }
+ return computer
+ }
+
+ /// The Mac's own host or an SSH tunnel: not saved, it lasts until `detach`.
+ public func attach(_ computer: Computer, route: BotStore.Route) {
+ guard !retired else { return }
+ attached.removeAll { $0.id == computer.id }
+ attached.append(computer)
+ open(computer, route: route)
+ refreshList()
+ }
+
+ /// Ends an attachment; a saved computer with the same ID goes back to the channel.
+ public func detach(_ id: ComputerID) {
+ attached.removeAll { $0.id == id }
+ close(id)
+ if let computer = saved.first(where: { $0.id == id }), !retired { open(computer, route: .channel) }
+ refreshList()
+ }
+
+ public func forget(_ id: ComputerID) {
+ attached.removeAll { $0.id == id }
+ saved.removeAll { $0.id == id }
+ persist()
+ close(id)
+ accessPolls.removeValue(forKey: id)?.cancel()
+ pendingAccess[id] = nil
+ if selection?.computerId == id { selection = nil }
+ refreshList()
+ }
+
+ public func setColor(_ id: ComputerID, _ color: String) {
+ if let i = saved.firstIndex(where: { $0.id == id }) {
+ saved[i].color = color
+ persist()
+ }
+ if let i = attached.firstIndex(where: { $0.id == id }) { attached[i].color = color }
+ stores[id]?.updateComputer { $0.color = color }
+ refreshList()
+ }
+
+ // MARK: account (§4.2 B)
+
+ public func refreshCloud() async {
+ guard let cloud, !retired else { return }
+ do {
+ let list = try await cloud.computers()
+ guard !retired else { return }
+ cloudComputers = list
+ } catch {
+ lastError = error.localizedDescription
+ }
+ }
+
+ /// Starts an access request; the returned `code` must match the one the computer shows.
+ /// Approval is then picked up in the background and the computer joins `stores`.
+ public func requestAccess(_ id: ComputerID) async throws -> AccessTicket {
+ guard let cloud, let target = cloudComputers.first(where: { $0.computerId == id }) else {
+ throw CloudError(status: 404, code: "notFound", message: "That computer isn't in your account.")
+ }
+ let ticket = try await cloud.requestAccess(id, signKey: target.signKey)
+ guard !retired else { throw CancellationError() }
+ pendingAccess[id] = ticket
+ accessPolls[id]?.cancel()
+ accessPolls[id] = Task { [weak self] in await self?.awaitApproval(ticket, target: target, cloud: cloud) }
+ return ticket
+ }
+
+ private func awaitApproval(_ ticket: AccessTicket, target: CloudComputer, cloud: CloudClient) async {
+ while !Task.isCancelled, !retired {
+ try? await Task.sleep(for: .seconds(2))
+ guard !Task.isCancelled, !retired else { return }
+ guard let status = try? await cloud.accessStatus(ticket.requestId) else { continue }
+ guard !retired, pendingAccess[ticket.computerId]?.requestId == ticket.requestId else { return }
+ switch status.status {
+ case .pending:
+ continue
+ case .approved:
+ pendingAccess[ticket.computerId] = nil
+ // Pin the key the SAS was computed with; the first hello brings its mailbox key and addresses.
+ let computer = Computer(id: ticket.computerId, name: target.name, signKey: ticket.signKey,
+ cloud: cloud.baseURL, device: target.device)
+ save(computer)
+ if !attached.contains(where: { $0.id == computer.id }) { open(computer, route: .channel) }
+ await refreshCloud()
+ return
+ case .denied, .expired, .cancelled:
+ pendingAccess[ticket.computerId] = nil
+ lastError = status.status == .denied ? "\(target.name) declined the request." : "The request expired. Ask again."
+ return
+ }
+ }
+ }
+
+ // MARK: lifecycle
+
+ public func setActive(_ active: Bool) {
+ guard !retired else { return }
+ isActive = active
+ for store in stores.values { store.setActive(active) }
+ }
+
+ /// Account switched or signed out: nothing from here writes into storage or calls back anymore.
+ public func retire() {
+ retired = true
+ for store in stores.values { store.retire() }
+ for poll in accessPolls.values { poll.cancel() }
+ accessPolls = [:]
+ onBotUpdated = nil
+ onConnected = nil
+ onSent = nil
+ selection = nil
+ }
+
+ // MARK: plumbing
+
+ private func open(_ computer: Computer, route: BotStore.Route) {
+ close(computer.id)
+ let store = makeStore(computer, route)
+ let id = computer.id
+ store.onBotUpdated = { [weak self] bot in
+ guard let self, !self.retired else { return }
+ self.onBotUpdated?(BotReference(accountId: self.accountId, computerId: id, botId: bot.id), bot)
+ }
+ store.onSent = { [weak self] bot in
+ guard let self, !self.retired else { return }
+ self.onSent?(BotReference(accountId: self.accountId, computerId: id, botId: bot.id), bot)
+ }
+ store.onConnected = { [weak self] store in
+ guard let self, !self.retired else { return }
+ self.onConnected?(store)
+ }
+ store.onComputerChanged = { [weak self] computer in self?.computerChanged(computer) }
+ stores[id] = store
+ if isActive { store.setActive(true) }
+ }
+
+ private func close(_ id: ComputerID) {
+ stores.removeValue(forKey: id)?.retire()
+ }
+
+ private func computerChanged(_ computer: Computer) {
+ guard !retired else { return }
+ if let i = saved.firstIndex(where: { $0.id == computer.id }), stores[computer.id]?.route == .channel {
+ saved[i] = computer
+ persist()
+ }
+ if let i = attached.firstIndex(where: { $0.id == computer.id }) { attached[i] = computer }
+ refreshList()
+ }
+
+ private func save(_ computer: Computer) {
+ saved.removeAll { $0.id == computer.id }
+ saved.insert(computer, at: 0)
+ persist()
+ refreshList()
+ }
+
+ private func persist() {
+ guard !retired else { return }
+ storage.computers = saved
+ }
+
+ private func refreshList() {
+ computers = attached + saved.filter { c in !attached.contains { $0.id == c.id } }
+ }
+}
diff --git a/kit/Sources/CodyncUI/Store/BotStore.swift b/kit/Sources/CodyncUI/Store/BotStore.swift
index 31fa4b95..1e272095 100644
--- a/kit/Sources/CodyncUI/Store/BotStore.swift
+++ b/kit/Sources/CodyncUI/Store/BotStore.swift
@@ -5,8 +5,6 @@ import os
private let log = Logger(subsystem: "com.pokai.Codync", category: "BotStore")
-/// Single source of truth for a Codync client (iPhone app, Mac window): mirrors
-/// the host's bots and transcripts via one SSE stream (catch-up since `rev`, then live).
/// Opens the screen viewer, optionally watching a bot that's using the computer.
public struct ScreenRequest: Identifiable, Hashable, Sendable {
public var watching: String?
@@ -14,6 +12,9 @@ public struct ScreenRequest: Identifiable, Hashable, Sendable {
public init(watching: String? = nil) { self.watching = watching }
}
+/// One computer's mirror (bots, transcripts) for a client (iPhone app, Mac window), kept by one
+/// events stream (catch-up since `rev`, then live) over loopback or the encrypted channel.
+/// `AccountStore` holds one per computer.
@MainActor
@Observable
public final class BotStore {
@@ -21,13 +22,26 @@ public final class BotStore {
case unpaired
case connecting
case online
+ /// The relay says the computer isn't connected; messages can wait in its mailbox.
+ case computerOffline(lastSeen: Date?)
+ /// Can't reach the computer at all (no direct route, no relay).
case offline(String)
+ /// Revoked, lease expired, or the computer's identity changed.
+ case unauthorized(String)
}
- public private(set) var pairing: Pairing?
- /// Computers this phone knows, most recently used first (the active one leads).
- public private(set) var computers: [Pairing] = []
- public private(set) var connection: Connection = .unpaired
+ /// How this store reaches its computer.
+ public enum Route: Sendable, Hashable {
+ /// The Mac's own host, or one through an SSH tunnel.
+ case loopback(baseURL: URL, token: String)
+ /// The end-to-end encrypted channel (direct or relay), with this context's device key.
+ case channel
+ }
+
+ public private(set) var computer: Computer
+ public let route: Route
+ public private(set) var connection: Connection = .connecting
+ public private(set) var hostRoute: HostRoute?
public private(set) var client: HostClient?
public private(set) var hello: Hello?
public private(set) var bots: [String: Bot] = [:]
@@ -35,6 +49,10 @@ public final class BotStore {
public private(set) var usage: Usage
/// The computer's remote screen (`nil`: the host predates it).
public private(set) var screen: ScreenState?
+ /// Devices asking this computer for access (loopback only: the Mac approves them).
+ public private(set) var accessRequests: [AccessRequest] = []
+ /// The host's cloud connection (loopback only).
+ public private(set) var cloud: CloudStatus?
/// Installed on the computer, for the Plugins screen and bot settings.
public private(set) var installedConnectors: [InstalledConnector] = []
public private(set) var installedSkills: [InstalledSkill] = []
@@ -51,49 +69,67 @@ public final class BotStore {
public var screenRequest: ScreenRequest?
// Platform hooks (push registration, Live Activities, widgets).
- public var onPaired: (@MainActor (BotStore) -> Void)?
+ /// Each time the channel (or loopback) becomes ready.
+ public var onConnected: (@MainActor (BotStore) -> Void)?
public var onBotUpdated: (@MainActor (Bot) -> Void)?
- public var onUsageChanged: (@MainActor (Usage) -> Void)?
+ public var onUsageChanged: (@MainActor (ComputerID, Usage) -> Void)?
public var onSent: (@MainActor (Bot) -> Void)?
+ /// The computer's addresses or keys changed (merged from its `hello`); persist it.
+ var onComputerChanged: (@MainActor (Computer) -> Void)?
/// `ios` clients suppress pushes while connected; others don't.
private let clientKind: String
- /// Whether pairing lives in the shared App Group (iPhone) or is supplied each launch (Mac).
- private let persistsPairing: Bool
public let storage: SharedStore.Context
+ private let makeTransport: @MainActor () async throws -> any HostTransport
+ private var transport: (any HostTransport)?
private var retired = false
private var rev: Int64 = 0
private var hostId: String?
private var streamTask: Task<Void, Never>?
+ private var eventsTask: Task<Void, Never>?
private var isActive = true
private var saveTask: Task<Void, Never>?
private var rewound = false
- public init(pairing: Pairing?, clientKind: String, persistsPairing: Bool, storage: SharedStore.Context? = nil) {
- let storage = storage ?? (persistsPairing ? SharedStore.activeContext : SharedStore.Context(accountID: nil))
- self.storage = storage
- usage = storage.usage ?? Usage()
- self.pairing = pairing
+ /// `.channel` loads this context's `DeviceIdentity` itself.
+ public convenience init(computer: Computer, route: Route, clientKind: String, storage: SharedStore.Context) {
+ let make: @MainActor () async throws -> any HostTransport = switch route {
+ case let .loopback(baseURL, token):
+ { LoopbackTransport(baseURL: baseURL, token: token) }
+ case .channel:
+ { try await HostConnector.connect(computer, identity: try DeviceIdentity.load(context: storage)) }
+ }
+ self.init(computer: computer, route: route, clientKind: clientKind, storage: storage, transport: make)
+ }
+
+ init(computer: Computer, route: Route, clientKind: String, storage: SharedStore.Context,
+ transport: @escaping @MainActor () async throws -> any HostTransport) {
+ self.computer = computer
+ self.route = route
self.clientKind = clientKind
- self.persistsPairing = persistsPairing
- computers = persistsPairing ? storage.computers : pairing.map { [$0] } ?? []
+ self.storage = storage
+ makeTransport = transport
+ usage = storage.usage[computer.id] ?? Usage()
loadCache()
- connection = pairing == nil ? .unpaired : .connecting
}
// MARK: derived
- private var orderedPairing: Pairing? {
- guard persistsPairing else { return pairing }
- return storage.orderedPairing ?? pairing
+ /// Offline in any way: the computer is off, unreachable, or refuses this device.
+ public var isOffline: Bool {
+ switch connection {
+ case .computerOffline, .offline, .unauthorized: true
+ default: false
+ }
}
- public var isOffline: Bool {
- if case .offline = connection { true } else { false }
+ /// Offline, but sends can wait in the relay mailbox until the computer is back.
+ public var canQueue: Bool {
+ if case .computerOffline = connection { computer.boxKey != nil && transport is any RemoteTransport } else { false }
}
- public var hostName: String { hello?.name ?? pairing?.name ?? "Computer" }
+ public var hostName: String { hello?.name ?? computer.name }
/// Roster order: pinned first (manual order not tracked yet), then most recent activity.
public var roster: [Bot] {
@@ -112,58 +148,17 @@ public final class BotStore {
public func thread(_ botId: String) -> [Entry] { entries[botId] ?? [] }
- // MARK: pairing
-
- public func pair(_ p: Pairing) {
- guard !retired else { return }
- let changedHost = pairing?.token != p.token
- pairing = p
- if persistsPairing {
- storage.pairing = p
- storage.preferredURL = nil
- }
- // Re-pairing the same computer (new token after a reset) replaces its old entry.
- computers = [p] + computers.filter { $0.token != p.token && $0.name != p.name }
- if persistsPairing { storage.computers = computers }
- if changedHost { resetMirror() }
- connection = .connecting
- restartStream()
- onPaired?(self)
- }
-
- /// Forgets a computer; forgetting the active one switches to the next, if any.
- public func forget(_ p: Pairing) {
- computers.removeAll { $0.token == p.token }
- if persistsPairing { storage.computers = computers }
- guard p.token == pairing?.token else { return }
- if let next = computers.first { pair(next) } else { unpair() }
- }
-
- public func setColor(_ p: Pairing, _ color: String) {
- updateComputer(p.token) { $0.color = color }
- }
-
- private func updateComputer(_ token: String, _ change: (inout Pairing) -> Void) {
- computers = computers.map { var c = $0; if c.token == token { change(&c) }; return c }
- if pairing?.token == token { change(&pairing!) }
- guard persistsPairing else { return }
- storage.computers = computers
- if storage.pairing?.token == token, var p = storage.pairing { change(&p); storage.pairing = p }
- }
-
- public func unpair() {
- streamTask?.cancel()
- pairing = nil
- client = nil
- hello = nil
- if persistsPairing { storage.pairing = nil }
- resetMirror()
- connection = .unpaired
+ func updateComputer(_ change: (inout Computer) -> Void) {
+ var c = computer
+ change(&c)
+ guard c != computer else { return }
+ computer = c
+ onComputerChanged?(c)
}
private func resetMirror() {
bots = [:]
- entries = [:]
+ entries = entries.mapValues { $0.filter { $0.id.hasPrefix("local-") } }.filter { !$0.value.isEmpty }
rev = 0
hostId = nil
historyComplete = []
@@ -173,16 +168,17 @@ public final class BotStore {
// MARK: lifecycle
- /// Permanently detach a store when the client changes accounts. Existing
- /// async callbacks retain this old store and its fixed storage namespace.
+ /// Permanently detach a store (account switch, computer removed). Late async
+ /// callbacks still hold it, but it writes nothing and calls no hooks anymore.
public func retire() {
setActive(false)
retired = true
saveTask?.cancel()
- onPaired = nil
+ onConnected = nil
onBotUpdated = nil
onUsageChanged = nil
onSent = nil
+ onComputerChanged = nil
client = nil
selection = nil
screenRequest = nil
@@ -197,45 +193,131 @@ public final class BotStore {
restartStream()
} else {
// Disconnect so the host knows we're gone and sends pushes instead.
- streamTask?.cancel()
- streamTask = nil
+ stopTransport()
saveCache()
}
}
public func restartStream() {
- streamTask?.cancel()
- guard pairing != nil, isActive, !retired else { return }
+ guard isActive, !retired else { return }
+ stopTransport()
if connection != .online { connection = .connecting }
streamTask = Task { [weak self] in await self?.runStream() }
}
+ private func stopTransport() {
+ streamTask?.cancel()
+ streamTask = nil
+ eventsTask?.cancel()
+ eventsTask = nil
+ if let remote = transport as? any RemoteTransport {
+ Task { await remote.shutdown() }
+ }
+ transport = nil
+ }
+
private func runStream() async {
var backoff: Double = 1
- while !Task.isCancelled {
- guard let pairing = orderedPairing else { return }
- guard let client = await HostClient.resolve(pairing) else {
+ var transport: any HostTransport
+ while true {
+ do {
+ transport = try await makeTransport()
+ break
+ } catch HostError.unauthorized(let message) {
+ if !Task.isCancelled, !retired { connection = .unauthorized(message) }
+ return
+ } catch {
guard !Task.isCancelled, !retired else { return }
- connection = .offline(HostError.unreachable.localizedDescription)
+ connection = .offline(error.localizedDescription)
try? await Task.sleep(for: .seconds(backoff))
- backoff = min(backoff * 2, 20)
- continue
+ backoff = min(backoff * 2, 30)
+ guard !Task.isCancelled else { return }
}
+ }
+ guard !Task.isCancelled, !retired else {
+ if let remote = transport as? any RemoteTransport { await remote.shutdown() }
+ return
+ }
+ self.transport = transport
+ let client = HostClient(transport: transport)
+ self.client = client
+ if let remote = transport as? any RemoteTransport { watch(remote) }
+ for await state in transport.states() {
guard !Task.isCancelled, !retired else { return }
- self.client = client
- if persistsPairing { storage.preferredURL = client.baseURL.absoluteString }
+ switch state {
+ case let .ready(route):
+ hostRoute = route
+ if eventsTask == nil {
+ if connection != .online { connection = .connecting }
+ eventsTask = Task { [weak self] in await self?.runEvents(client) }
+ // Mailbox outcomes that happened while this app wasn't listening (§10.2).
+ if let remote = transport as? any RemoteTransport {
+ Task { [weak self] in await self?.reconcileQueued(remote) }
+ }
+ }
+ onConnected?(self)
+ case .connecting:
+ stopEvents()
+ connection = .connecting
+ case let .hostOffline(lastSeen):
+ stopEvents()
+ connection = .computerOffline(lastSeen: lastSeen)
+ if let remote = transport as? any RemoteTransport {
+ Task { [weak self] in await self?.reconcileQueued(remote) }
+ }
+ case let .unauthorized(message):
+ stopEvents()
+ connection = .unauthorized(message)
+ case let .failed(message):
+ stopEvents()
+ connection = .offline(message)
+ }
+ }
+ }
+
+ private func stopEvents() {
+ eventsTask?.cancel()
+ eventsTask = nil
+ hostRoute = nil
+ }
+
+ /// The channel's side streams: merged computer info and mailbox outcomes.
+ private func watch(_ remote: any RemoteTransport) {
+ let updates = remote.computerUpdates()
+ let mailbox = remote.mailboxEvents()
+ Task { [weak self] in
+ for await computer in updates {
+ guard let self, !self.retired else { return }
+ // The color is picked on this device; the transport's copy may be older.
+ self.updateComputer { current in
+ let color = current.color
+ current = computer
+ current.color = color
+ }
+ }
+ }
+ Task { [weak self] in
+ for await event in mailbox {
+ guard let self, !self.retired else { return }
+ self.applyMailbox(event)
+ }
+ }
+ }
+
+ /// Events (catch-up since `rev`, then live) for as long as the link stays ready.
+ private func runEvents(_ client: HostClient) async {
+ var backoff: Double = 1
+ while !Task.isCancelled {
do {
if hello == nil || hello?.hostId != hostId {
let h = try await client.hello()
guard !Task.isCancelled, !retired else { return }
hello = h
- if let device = h.device, self.pairing?.device != device, let token = self.pairing?.token {
- updateComputer(token) { $0.device = device }
- }
- // Addresses the host gained since pairing (say, Tailscale installed later) join the list.
- if let urls = h.urls, let token = self.pairing?.token,
- let known = self.pairing?.urls, !Set(urls).isSubset(of: Set(known)) {
- updateComputer(token) { p in p.urls += urls.filter { !p.urls.contains($0) } }
+ if case .loopback = route {
+ updateComputer { c in
+ c.name = h.name
+ if let device = h.device { c.device = device }
+ }
}
// Host upgraded since the cache was written: its data may carry new fields.
if let stamp = cacheStamp, stamp != "\(Self.appBuild)/\(h.version)" {
@@ -243,6 +325,10 @@ public final class BotStore {
cacheStamp = nil
}
}
+ if case .loopback = route {
+ accessRequests = (try? await client.accessRequests()) ?? accessRequests
+ cloud = (try? await client.cloudStatus()) ?? cloud
+ }
for try await event in client.events(since: rev, client: clientKind) {
guard !Task.isCancelled, !retired else { return }
connection = .online
@@ -252,14 +338,20 @@ public final class BotStore {
} catch is CancellationError {
return
} catch {
- if Task.isCancelled { return }
+ if Task.isCancelled || retired { return }
log.info("stream ended: \(error.localizedDescription)")
- if case HostError.http(401, _) = error {
- connection = .offline(error.localizedDescription)
+ if case let HostError.unauthorized(message) = error {
+ connection = .unauthorized(message)
return
}
- // A dropped or timed-out stream means the computer went away; say so plainly.
- connection = .offline(error is URLError ? HostError.unreachable.localizedDescription : error.localizedDescription)
+ // On the channel the link state speaks for itself; loopback has no other signal.
+ if case .loopback = route {
+ if case HostError.http(401, _) = error {
+ connection = .offline(error.localizedDescription)
+ return
+ }
+ connection = .offline(error.localizedDescription)
+ }
}
try? await Task.sleep(for: .seconds(backoff))
backoff = min(backoff * 2, 20)
@@ -292,20 +384,31 @@ public final class BotStore {
setUsage(u)
case let .screen(s):
screen = s
+ case let .accessRequests(requests):
+ accessRequests = requests
+ case let .cloud(status):
+ cloud = status
case .resync:
- restartStream()
+ restartEvents()
case let .undecodable(type):
// Never skip past data we couldn't read: rewind once and fetch everything again.
log.error("undecodable \(type) event")
if !rewound {
rewound = true
rev = 0
- restartStream()
+ restartEvents()
}
}
scheduleSave()
}
+ /// Resubscribes from the current `rev` on the same link.
+ private func restartEvents() {
+ guard let client, eventsTask != nil else { return }
+ eventsTask?.cancel()
+ eventsTask = Task { [weak self] in await self?.runEvents(client) }
+ }
+
private func bump(_ r: Int64) { rev = max(rev, r) }
private func upsert(_ e: Entry) {
@@ -330,9 +433,10 @@ public final class BotStore {
}
private func setUsage(_ u: Usage) {
- guard u != usage else { return }
+ guard u != usage, !retired else { return }
usage = u
- onUsageChanged?(u)
+ storage.usage[computer.id] = u
+ onUsageChanged?(computer.id, u)
}
// MARK: actions
@@ -343,18 +447,30 @@ public final class BotStore {
}
public func send(_ text: String, to botId: String) {
+ send(text, to: botId, nonce: UUID().uuidString)
+ }
+
+ private func send(_ text: String, to botId: String, nonce: String) {
let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
- guard !trimmed.isEmpty else { return }
- let nonce = UUID().uuidString
+ guard !trimmed.isEmpty, !retired else { return }
let local = Entry(
id: "local-\(nonce)", seq: Int64.max, botId: botId, rev: 0, kind: "user",
turn: 0, data: EntryData(text: trimmed, status: "sending", clientNonce: nonce),
createdAt: Int64(Date.now.timeIntervalSince1970 * 1000), updatedAt: 0
)
upsert(local)
+ storage.lastComputerId = computer.id
+ if canQueue, let remote = transport as? any RemoteTransport {
+ enqueue(remote, text: trimmed, botId: botId, nonce: nonce)
+ return
+ }
+ deliver(trimmed, botId: botId, nonce: nonce)
+ }
+
+ private func deliver(_ text: String, botId: String, nonce: String) {
Task {
do {
- let e = try await require().send(botId: botId, text: trimmed, clientNonce: nonce)
+ let e = try await require().send(botId: botId, text: text, clientNonce: nonce)
upsert(e)
if let bot = bots[botId] { onSent?(bot) }
} catch {
@@ -363,10 +479,78 @@ public final class BotStore {
}
}
+ /// The computer is offline: the message waits, sealed for it, in the relay mailbox.
+ private func enqueue(_ remote: any RemoteTransport, text: String, botId: String, nonce: String) {
+ markLocal(nonce: nonce, botId: botId, status: "waiting")
+ saveCache()
+ Task {
+ do {
+ try await remote.enqueue(botId: botId, text: text, clientNonce: nonce)
+ if let bot = bots[botId] { onSent?(bot) }
+ } catch MailboxError.hostOnline {
+ // It came back meanwhile: send it the normal way once the link is up.
+ markLocal(nonce: nonce, botId: botId, status: "sending")
+ try? await Task.sleep(for: .seconds(2))
+ deliver(text, botId: botId, nonce: nonce)
+ } catch {
+ lastError = error.localizedDescription
+ markLocal(nonce: nonce, botId: botId, status: "failed")
+ }
+ saveCache()
+ }
+ }
+
+ /// Takes a waiting message back out of the mailbox, unless the computer already has it.
+ public func cancelQueued(_ entry: Entry) {
+ guard let nonce = entry.data.clientNonce, let remote = transport as? any RemoteTransport else { return }
+ Task {
+ switch await remote.cancelQueued(clientNonce: nonce) {
+ case .cancelled:
+ discard(entry)
+ case .delivering:
+ markLocal(nonce: nonce, botId: entry.botId, status: "delivering")
+ case .unknown:
+ lastError = "Couldn't take the message back. It may have been delivered already."
+ }
+ saveCache()
+ }
+ }
+
+ private func applyMailbox(_ event: MailboxEvent) {
+ guard let entry = entries.values.lazy.flatMap({ $0 }).first(where: { $0.id == "local-\(event.nonce)" }) else { return }
+ switch event {
+ // The events stream's own copy replaces it (matched by clientNonce).
+ case .delivered: markLocal(nonce: event.nonce, botId: entry.botId, status: "delivering")
+ case .failed, .expired: markLocal(nonce: event.nonce, botId: entry.botId, status: "failed")
+ }
+ saveCache()
+ }
+
+ /// Messages the relay no longer holds were delivered, refused or expired while we were away.
+ /// "Failed" is safe even if one was delivered: the events catch-up replaces it by clientNonce,
+ /// and a resend reuses that nonce, so the computer never runs it twice.
+ private func reconcileQueued(_ remote: any RemoteTransport) async {
+ let waiting = entries.values.flatMap { $0 }.filter { $0.data.status == "waiting" }
+ guard !waiting.isEmpty else { return }
+ let held = Dictionary(await remote.listQueued().map { ($0.nonce, $0.state) }, uniquingKeysWith: { a, _ in a })
+ guard !retired else { return }
+ for e in waiting {
+ guard let nonce = e.data.clientNonce else { continue }
+ switch held[nonce] {
+ case "queued": break
+ case .some: markLocal(nonce: nonce, botId: e.botId, status: "delivering")
+ case nil: markLocal(nonce: nonce, botId: e.botId, status: "failed")
+ }
+ }
+ saveCache()
+ }
+
public func retry(_ entry: Entry) {
guard let text = entry.data.text else { return }
entries[entry.botId]?.removeAll { $0.id == entry.id }
- send(text, to: entry.botId)
+ // The same clientNonce: if the computer got it after all, it won't run twice (the host
+ // skips a nonce it has). Every seal still takes a fresh ephemeral key (§6.4).
+ send(text, to: entry.botId, nonce: entry.data.clientNonce ?? UUID().uuidString)
}
public func discard(_ entry: Entry) {
@@ -526,14 +710,13 @@ public final class BotStore {
private static let appBuild = Bundle.main.infoDictionary?["CFBundleVersion"] as? String ?? "0"
private var cacheStamp: String?
+ /// Per app, context and computer (`SharedStore.Context.erase()` removes a context's files).
private var cacheURL: URL {
- let computer = SharedStore.Context.digest(pairing?.token ?? "unpaired")
- return URL.cachesDirectory.appending(path: "codync-mirror-\(Bundle.main.bundleIdentifier ?? "app")-\(storage.id)-\(computer).json")
+ URL.cachesDirectory.appending(path: "codync-mirror-\(Bundle.main.bundleIdentifier ?? "app")-\(storage.id)-\(computer.id).json")
}
private func loadCache() {
- guard pairing != nil,
- let data = try? Data(contentsOf: cacheURL),
+ guard let data = try? Data(contentsOf: cacheURL),
let cache = try? JSONDecoder().decode(Cache.self, from: data),
cache.stamp?.hasPrefix(Self.appBuild + "/") == true else { return }
cacheStamp = cache.stamp
@@ -554,8 +737,12 @@ public final class BotStore {
public func saveCache() {
guard !retired else { return }
- // Keep the newest 200 entries per bot; older ones page in from the host.
- let kept = entries.values.flatMap { $0.filter { !$0.id.hasPrefix("local-") }.suffix(200) }
+ // Keep the newest 200 entries per bot; older ones page in from the host. Messages waiting
+ // in the mailbox stay too, so they can still be seen and cancelled after a relaunch.
+ let kept = entries.values.flatMap { list in
+ list.filter { !$0.id.hasPrefix("local-") }.suffix(200)
+ + list.filter { $0.id.hasPrefix("local-") && ["waiting", "delivering"].contains($0.data.status) }
+ }
let cache = Cache(stamp: "\(Self.appBuild)/\(hello?.version ?? "")", hostId: hostId, rev: rev, bots: Array(bots.values), entries: kept)
if let data = try? JSONEncoder().encode(cache) {
try? data.write(to: cacheURL, options: .atomic)
diff --git a/kit/Sources/CodyncUI/Thread/ChatRows.swift b/kit/Sources/CodyncUI/Thread/ChatRows.swift
index 9dfd3b25..18bf2d2f 100644
--- a/kit/Sources/CodyncUI/Thread/ChatRows.swift
+++ b/kit/Sources/CodyncUI/Thread/ChatRows.swift
@@ -41,6 +41,17 @@ struct UserBubble: View {
.font(.caption2.bold())
case "cancelled":
Text("Not sent — stopped").font(.caption2).foregroundStyle(Palette.tertiary)
+ case "waiting":
+ HStack(spacing: 10) {
+ Text("Waiting for the computer to come online").foregroundStyle(Palette.tertiary)
+ Button("Cancel", systemImage: "xmark.circle") { model.cancelQueued(entry) }
+ .labelStyle(.iconOnly)
+ .help("Don't send")
+ .accessibilityLabel("Don't send")
+ }
+ .font(.caption2)
+ case "delivering":
+ Text("Delivered to the computer").font(.caption2).foregroundStyle(Palette.tertiary)
default:
#if os(macOS)
Text(entry.date, style: .time).font(.system(size: 10)).foregroundStyle(Palette.tertiary)
diff --git a/kit/Sources/CodyncUI/Thread/ThreadView.swift b/kit/Sources/CodyncUI/Thread/ThreadView.swift
index ecfe7b17..fa60c0ed 100644
--- a/kit/Sources/CodyncUI/Thread/ThreadView.swift
+++ b/kit/Sources/CodyncUI/Thread/ThreadView.swift
@@ -357,7 +357,8 @@ public struct ThreadView: View {
}
private var canSend: Bool {
- !draft.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && model.connection == .online
+ // Offline computers still take messages when the relay can hold them for it.
+ !draft.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && (model.connection == .online || model.canQueue)
}
private func submit() {
diff --git a/kit/Tests/CodyncKitTests/AccountStorageTests.swift b/kit/Tests/CodyncKitTests/AccountStorageTests.swift
deleted file mode 100644
index ba31b045..00000000
--- a/kit/Tests/CodyncKitTests/AccountStorageTests.swift
+++ /dev/null
@@ -1,53 +0,0 @@
-import Foundation
-import Testing
-@testable import CodyncKit
-
-@Test func accountPairingsStayIsolatedIncludingLateWrites() throws {
- let suite = "CodyncAccountTests.\(UUID().uuidString)"
- let defaults = try #require(UserDefaults(suiteName: suite))
- defer { defaults.removePersistentDomain(forName: suite) }
- let alice = SharedStore.Context(accountID: "user_alice", defaults: defaults)
- let bob = SharedStore.Context(accountID: "user_bob", defaults: defaults)
- let a = Pairing(name: "Same name", token: "alice-token", urls: ["https://alice.invalid"])
- let b = Pairing(name: "Same name", token: "bob-token", urls: ["https://bob.invalid"])
- alice.pairing = a
- alice.computers = [a]
- bob.pairing = b
- bob.computers = [b]
-
- // A retained store finishes work after the UI has selected Bob.
- alice.preferredURL = a.urls.first
- alice.usage = Usage()
- #expect(bob.pairing == b)
- #expect(bob.computers == [b])
- #expect(bob.preferredURL == nil)
- #expect(bob.usage == nil)
- #expect(alice.orderedPairing == a)
- #expect(alice.id != bob.id)
- #expect(SharedStore.Context(accountID: "user_alice", defaults: defaults).pairing == a)
-
- let oldWidget = alice.botURL("shared-bot-id")
- #expect(alice.acceptsBotURL(oldWidget))
- #expect(!bob.acceptsBotURL(oldWidget))
- #expect(!bob.acceptsBotURL(URL(string: "codync://bot/shared-bot-id")!))
- alice.pairing = b
- #expect(!alice.acceptsBotURL(oldWidget))
-}
-
-@Test func signingInDoesNotClaimLegacyLocalPairings() throws {
- let suite = "CodyncAccountTests.\(UUID().uuidString)"
- let defaults = try #require(UserDefaults(suiteName: suite))
- defer { defaults.removePersistentDomain(forName: suite) }
- let old = Pairing(name: "Legacy Mac", token: "local-token", urls: ["http://127.0.0.1:19222"])
- defaults.set(try JSONEncoder().encode(old), forKey: "pairing")
- let local = SharedStore.Context(accountID: nil, defaults: defaults)
- let signedIn = SharedStore.Context(accountID: "user_new", defaults: defaults)
-
- #expect(local.pairing == old)
- #expect(local.computers == [old])
- #expect(signedIn.pairing == nil)
- #expect(signedIn.computers.isEmpty)
- signedIn.pairing = old
- signedIn.pairing = nil
- #expect(local.pairing == old)
-}
diff --git a/kit/Tests/CodyncKitTests/ChannelTransportTests.swift b/kit/Tests/CodyncKitTests/ChannelTransportTests.swift
new file mode 100644
index 00000000..3cbe82e8
--- /dev/null
+++ b/kit/Tests/CodyncKitTests/ChannelTransportTests.swift
@@ -0,0 +1,355 @@
+import CryptoKit
+import Foundation
+import Testing
+@testable import CodyncKit
+
+private let v = Vectors.shared
+
+/// One direction of a fake WebSocket.
+actor Pipe {
+ private var items: [String] = []
+ private var waiters: [CheckedContinuation<String, Error>] = []
+ private var closedCode: Int?
+
+ func push(_ s: String) {
+ guard closedCode == nil else { return }
+ if waiters.isEmpty { items.append(s) } else { waiters.removeFirst().resume(returning: s) }
+ }
+
+ func pop() async throws -> String {
+ if !items.isEmpty { return items.removeFirst() }
+ if let closedCode { throw SocketClosed(code: closedCode) }
+ return try await withCheckedThrowingContinuation { waiters.append($0) }
+ }
+
+ func close(_ code: Int) {
+ guard closedCode == nil else { return }
+ closedCode = code
+ for w in waiters { w.resume(throwing: SocketClosed(code: code)) }
+ waiters = []
+ }
+}
+
+final class FakeSocket: ChannelSocket {
+ let endpoint: Endpoint
+ let toDevice = Pipe()
+ let toHost = Pipe()
+
+ init(_ endpoint: Endpoint) { self.endpoint = endpoint }
+
+ func send(_ text: String) async throws { await toHost.push(text) }
+ func receive() async throws -> String { try await toDevice.pop() }
+ func ping() async throws {}
+ func close(code: Int) {
+ Task {
+ await toDevice.close(code)
+ await toHost.close(code)
+ }
+ }
+}
+
+private func object(_ text: String) -> [String: Any] {
+ (try? JSONSerialization.jsonObject(with: Data(text.utf8)) as? [String: Any]) ?? [:]
+}
+
+private func text(_ obj: [String: Any]) -> String {
+ String(decoding: (try? JSONSerialization.data(withJSONObject: obj)) ?? Data(), as: UTF8.self)
+}
+
+/// The host (or, for DO messages, the relay) on the far end of a fake socket.
+struct HostSide {
+ let socket: FakeSocket
+ var sealer: RelayCrypto.FrameSealer?
+ var opener: RelayCrypto.FrameOpener?
+
+ init(_ socket: FakeSocket) { self.socket = socket }
+
+ /// Next message that isn't a relay ping.
+ func raw() async throws -> [String: Any] {
+ while true {
+ let o = object(try await socket.toHost.pop())
+ if o["t"] as? String != "ping" { return o }
+ }
+ }
+
+ func push(_ obj: [String: Any]) async { await socket.toDevice.push(text(obj)) }
+
+ /// Verifies the device's hello and answers with a welcome signed by `hostKey`.
+ @discardableResult
+ mutating func accept(hostKey: Curve25519.Signing.PrivateKey = v.hostSign) async throws -> [String: Any] {
+ let hello = try await raw()
+ #expect(hello["t"] as? String == "hello")
+ #expect(hello["v"] as? Int == 1)
+ let dk = Data(base64URL: hello["dk"] as? String ?? "") ?? Data()
+ let ekD = Data(base64URL: hello["ek"] as? String ?? "") ?? Data()
+ let n = Data(base64URL: hello["n"] as? String ?? "") ?? Data()
+ let cid = RelayCrypto.computerIdRaw(signKey: v.b64("keys", "hostSignPub"))
+ let sig = Data(base64URL: hello["sig"] as? String ?? "") ?? Data()
+ #expect(try Curve25519.Signing.PublicKey(rawRepresentation: dk)
+ .isValidSignature(sig, for: RelayCrypto.hs1Input(cid: cid, dk: dk, ekD: ekD, n: n)))
+ let ekH = Curve25519.KeyAgreement.PrivateKey()
+ let th = RelayCrypto.transcriptHash(cid: cid, dk: dk, ekD: ekD, n: n, ekH: ekH.publicKey.rawRepresentation)
+ await push(["t": "welcome", "v": 1, "ek": ekH.publicKey.rawRepresentation.base64URL, "sig": try hostKey.signature(for: th).base64URL])
+ let keys = RelayCrypto.channelKeys(sharedSecret: try RelayCrypto.sharedSecret(ekH, ekD), transcriptHash: th)
+ sealer = RelayCrypto.FrameSealer(key: keys.h2d)
+ opener = RelayCrypto.FrameOpener(key: keys.d2h)
+ return hello
+ }
+
+ /// Next inner message from the device.
+ mutating func receive() async throws -> [String: Any] {
+ while true {
+ let f = try await raw()
+ guard f["t"] as? String == "f", var o = opener else { continue }
+ let c = (f["c"] as? NSNumber)?.uint64Value ?? .max
+ let message = try o.open(c: c, d: Data(base64URL: f["d"] as? String ?? "") ?? Data())
+ opener = o
+ if let message { return (try JSONSerialization.jsonObject(with: message) as? [String: Any]) ?? [:] }
+ }
+ }
+
+ mutating func send(_ inner: [String: Any]) async throws {
+ guard var s = sealer else { return }
+ for frame in try s.seal(try JSONSerialization.data(withJSONObject: inner)) {
+ await push(["t": "f", "c": frame.c, "d": frame.d.base64URL])
+ }
+ sealer = s
+ }
+}
+
+/// A dialer handing each new fake socket to the test.
+private func fakeDialer() -> (Dialer, AsyncStream<FakeSocket>) {
+ let (sockets, sink) = AsyncStream<FakeSocket>.makeStream()
+ return ({ endpoint in
+ let s = FakeSocket(endpoint)
+ sink.yield(s)
+ return s
+ }, sockets)
+}
+
+private func helloBody() -> [String: Any] { [
+ "hostId": "h1", "name": "Studio", "version": "3.0.0", "os": "macos", "backends": [], "rev": 0,
+ "computerId": v.str("keys", "computerId"), "signKey": v.str("keys", "hostSignPub"), "boxKey": v.str("keys", "hostBoxPub"),
+ "urls": ["http://10.0.0.2:19222"], "cloud": "https://cloud.example.dev", "device": "macstudio", "protocol": 1,
+] }
+
+private func waitFor(_ states: AsyncStream<LinkState>, _ match: (LinkState) -> Bool) async -> LinkState? {
+ for await s in states where match(s) { return s }
+ return nil
+}
+
+@Test(.timeLimit(.minutes(1))) func directChannelMultiplexesCallsAndStreams() async throws {
+ let (dial, sockets) = fakeDialer()
+ var computer = v.computer
+ computer.boxKey = nil
+ computer.urls = ["http://127.0.0.1:1"]
+ let t = ChannelTransport(computer: computer, identity: v.identity, pairingCode: nil, dial: dial, watchesNetwork: false)
+ let a = t.states()
+ let b = t.states()
+ let updates = t.computerUpdates()
+ await t.start()
+ var socketIterator = sockets.makeAsyncIterator()
+ let socket = try #require(await socketIterator.next())
+ guard case let .direct(url) = socket.endpoint else { Issue.record("not direct"); return }
+ #expect(url.absoluteString == "ws://127.0.0.1:1/channel?v=1")
+ var host = HostSide(socket)
+ let h = try await host.accept()
+ #expect(h["pair"] == nil)
+
+ // Every consumer sees the same state.
+ #expect(await waitFor(a) { $0 == .ready(.direct) } == .ready(.direct))
+ #expect(await waitFor(b) { $0 == .ready(.direct) } == .ready(.direct))
+
+ // The transport asks for hello by itself and merges what it learns.
+ let first = try await host.receive()
+ #expect(first["m"] as? String == "hello")
+ try await host.send(["id": first["id"] ?? 0, "ok": helloBody()])
+ var updated = updates.makeAsyncIterator()
+ let merged = try #require(await updated.next())
+ #expect(merged.boxKey == v.str("keys", "hostBoxPub"))
+ #expect(merged.urls == ["http://10.0.0.2:19222"])
+ #expect(merged.cloud?.absoluteString == "https://cloud.example.dev")
+ #expect(merged.device == "macstudio" && merged.name == "Studio")
+
+ // Two calls in flight, answered out of order.
+ async let usage = t.call("usage", body: Data(#"{"refresh":false}"#.utf8), timeout: 10)
+ async let sync = t.call("sync", body: Data(#"{"since":7}"#.utf8), timeout: 10)
+ let r1 = try await host.receive()
+ let r2 = try await host.receive()
+ #expect(r1["id"] as? Int != r2["id"] as? Int)
+ for r in [r2, r1] { try await host.send(["id": r["id"] ?? 0, "ok": ["method": r["m"] ?? ""]]) }
+ #expect(object(String(decoding: try await usage, as: UTF8.self))["method"] as? String == "usage")
+ #expect(object(String(decoding: try await sync, as: UTF8.self))["method"] as? String == "sync")
+ let syncBody = [r1, r2].first { $0["m"] as? String == "sync" }?["b"] as? [String: Any]
+ #expect(syncBody?["since"] as? Int == 7)
+
+ // Errors keep their HTTP status.
+ let denied = Task { try await t.call("setScreenEnabled", body: Data(#"{"enabled":true}"#.utf8), timeout: 10) }
+ let r3 = try await host.receive()
+ try await host.send(["id": r3["id"] ?? 0, "err": ["status": 403, "message": "Only on the computer."]])
+ await #expect(throws: HostError.http(403, "Only on the computer.")) { _ = try await denied.value }
+
+ // A stream yields events until its consumer stops; the host is then told to cancel.
+ let reader = Task {
+ var got: [Data] = []
+ for try await d in t.stream(.events(since: 5, client: "ios")) {
+ got.append(d)
+ if got.count == 2 { break }
+ }
+ return got
+ }
+ let sub = try await host.receive()
+ #expect(sub["sub"] as? String == "events")
+ #expect((sub["b"] as? [String: Any])?["since"] as? Int == 5)
+ #expect((sub["b"] as? [String: Any])?["client"] as? String == "ios")
+ try await host.send(["id": sub["id"] ?? 0, "ev": ["type": "hello", "hostId": "h1", "rev": 9]])
+ try await host.send(["id": sub["id"] ?? 0, "ev": ["type": "resync"]])
+ let got = try await reader.value
+ #expect(got.count == 2 && object(String(decoding: got[1], as: UTF8.self))["type"] as? String == "resync")
+ let cancel = try await host.receive()
+ #expect(cancel["id"] as? Int == sub["id"] as? Int && cancel["cancel"] as? Bool == true)
+
+ // Revoked: no retry.
+ await socket.toDevice.close(4003)
+ guard case .unauthorized = await waitFor(t.states(), { if case .unauthorized = $0 { true } else { false } }) else {
+ Issue.record("expected unauthorized"); return
+ }
+ await #expect(throws: HostError.self) { _ = try await t.call("hello", body: Data(), timeout: 1) }
+ await t.shutdown()
+}
+
+@Test(.timeLimit(.minutes(1))) func changedHostIdentityIsNotRetried() async throws {
+ let (dial, sockets) = fakeDialer()
+ var computer = v.computer
+ computer.urls = ["http://127.0.0.1:1"]
+ let t = ChannelTransport(computer: computer, identity: v.identity, pairingCode: nil, dial: dial, watchesNetwork: false)
+ await t.start()
+ var it = sockets.makeAsyncIterator()
+ var host = HostSide(try #require(await it.next()))
+ try await host.accept(hostKey: Curve25519.Signing.PrivateKey())
+ #expect(await t.settled(within: .seconds(5)) == .unauthorized(ChannelTransport.identityChanged))
+ await t.shutdown()
+}
+
+@Test(.timeLimit(.minutes(1))) func directRejectFallsBackToTheRelay() async throws {
+ let (dial, sockets) = fakeDialer()
+ var computer = v.computer
+ computer.urls = ["http://192.168.1.20:19222"]
+ computer.cloud = URL(string: "https://cloud.example.dev")
+ let t = ChannelTransport(computer: computer, identity: v.identity, pairingCode: nil, dial: dial, watchesNetwork: false)
+ await t.start()
+ var it = sockets.makeAsyncIterator()
+ // Some other host now answers at the saved LAN address; its reject isn't signed.
+ let stranger = HostSide(try #require(await it.next()))
+ _ = try await stranger.raw()
+ await stranger.push(["t": "reject", "code": "unauthorized"])
+ let socket = try #require(await it.next())
+ guard case .relay = socket.endpoint else { Issue.record("expected the relay"); return }
+ var relay = HostSide(socket)
+ await relay.push(["t": "presence", "online": true, "lastSeenAt": NSNull()])
+ try await relay.accept()
+ #expect(await t.settled(within: .seconds(5)) == .ready(.relay))
+ #expect(await !t.isStopped)
+ await t.shutdown()
+}
+
+@Test(.timeLimit(.minutes(1))) func relayPresenceAndMailbox() async throws {
+ let (dial, sockets) = fakeDialer()
+ var computer = v.computer
+ computer.urls = []
+ computer.cloud = URL(string: "https://cloud.example.dev")
+ let t = ChannelTransport(computer: computer, identity: v.identity, pairingCode: nil, dial: dial, watchesNetwork: false)
+ let mailbox = t.mailboxEvents()
+ await t.start()
+ var it = sockets.makeAsyncIterator()
+ let socket = try #require(await it.next())
+ guard case let .relay(request) = socket.endpoint else { Issue.record("not relay"); return }
+ #expect(request.url?.absoluteString == "wss://cloud.example.dev/v1/relay/device/\(computer.id)?v=1")
+ let sig = request.value(forHTTPHeaderField: "Codync-Sig") ?? ""
+ #expect(sig.hasPrefix("v=1,kid=\(v.identity.publicKey),ts="))
+ var relay = HostSide(socket)
+
+ await relay.push(["t": "presence", "online": false, "lastSeenAt": 1_790_000_000_000])
+ let seen = Date(milliseconds: 1_790_000_000_000)
+ #expect(await t.settled(within: .seconds(5)) == .hostOffline(lastSeen: seen))
+ await #expect(throws: HostError.computerOffline(lastSeen: seen)) { _ = try await t.call("hello", body: Data(), timeout: 1) }
+
+ // Queue a message: it goes out sealed for the host's box key.
+ let nonce = "3F2504E0-4F89-11D3-9A0C-0305E82C3301"
+ async let queued: Void = t.enqueue(botId: "b1", text: "hi", clientNonce: nonce)
+ let put = try await relay.raw()
+ #expect(put["t"] as? String == "mbox.put" && put["nonce"] as? String == nonce)
+ let blob = try #require(Data(base64URL: put["d"] as? String ?? ""))
+ let epk = blob.prefix(32), mboxSig = blob.dropFirst(32).prefix(64), ct = blob.dropFirst(96)
+ let cid = RelayCrypto.computerIdRaw(signKey: v.b64("keys", "hostSignPub"))
+ #expect(v.deviceSign.publicKey.isValidSignature(mboxSig, for: RelayCrypto.label("codync/mbox/v1") + cid + epk + ct))
+ let key = RelayCrypto.mailboxKey(sharedSecret: try RelayCrypto.sharedSecret(v.hostBox, Data(epk)), cid: cid,
+ dk: v.b64("keys", "deviceSignPub"), epk: Data(epk))
+ let box = try ChaChaPoly.SealedBox(nonce: ChaChaPoly.Nonce(data: Data(count: 12)), ciphertext: ct.dropLast(16), tag: ct.suffix(16))
+ let inner = object(String(decoding: try ChaChaPoly.open(box, using: key, authenticating: v.b64("keys", "deviceSignPub") + Data(nonce.utf8)), as: UTF8.self))
+ #expect(inner["m"] as? String == "send")
+ #expect((inner["b"] as? [String: Any])?["clientNonce"] as? String == nonce)
+ #expect((inner["b"] as? [String: Any])?["text"] as? String == "hi")
+ await relay.push(["t": "mbox.ok", "nonce": nonce, "state": "queued"])
+ try await queued
+
+ // The relay refusing says why.
+ let refused = Task { try await t.enqueue(botId: "b1", text: "again", clientNonce: "n2") }
+ _ = try await relay.raw()
+ await relay.push(["t": "mbox.err", "nonce": "n2", "code": "full"])
+ await #expect(throws: MailboxError.rejected("full")) { try await refused.value }
+
+ async let listed = t.listQueued()
+ #expect(try await relay.raw()["t"] as? String == "mbox.list")
+ await relay.push(["t": "mbox.items", "items": [["nonce": nonce, "exp": 1, "state": "queued"]]])
+ #expect(await listed.map(\.nonce) == [nonce])
+
+ async let cancelled = t.cancelQueued(clientNonce: nonce)
+ #expect(try await relay.raw()["t"] as? String == "mbox.cancel")
+ await relay.push(["t": "mbox.cancelled", "nonce": nonce])
+ #expect(await cancelled == .cancelled)
+
+ async let gone = t.cancelQueued(clientNonce: "n3")
+ _ = try await relay.raw()
+ await relay.push(["t": "mbox.gone", "nonce": "n3", "state": "delivering"])
+ #expect(await gone == .delivering)
+
+ await relay.push(["t": "mbox.expired", "nonce": "n4"])
+ var events = mailbox.makeAsyncIterator()
+ #expect(await events.next() == .expired(nonce: "n4"))
+
+ // The host comes online: a fresh handshake through the relay.
+ await relay.push(["t": "presence", "online": true, "lastSeenAt": nil as Int? as Any])
+ try await relay.accept()
+ #expect(await waitFor(t.states()) { $0 == .ready(.relay) } == .ready(.relay))
+ await #expect(throws: MailboxError.self) {
+ async let online: Void = t.enqueue(botId: "b1", text: "x", clientNonce: "n5")
+ _ = try await relay.raw()
+ await relay.push(["t": "mbox.err", "nonce": "n5", "code": "hostOnline"])
+ try await online
+ }
+ await t.shutdown()
+}
+
+@Test(.timeLimit(.minutes(1))) func pairingSendsOnlyPairThenStopsOn4100() async throws {
+ let (dial, sockets) = fakeDialer()
+ var computer = v.computer
+ computer.urls = ["http://127.0.0.1:1"]
+ let code = v.str("pairing", "code")
+ let t = ChannelTransport(computer: computer, identity: v.identity, pairingCode: code, dial: dial, watchesNetwork: false)
+ await t.start()
+ var it = sockets.makeAsyncIterator()
+ let socket = try #require(await it.next())
+ var host = HostSide(socket)
+ let h = try await host.accept()
+ #expect(h["pair"] as? Bool == true)
+ async let paired = t.call("pair", body: Data(#"{"code":"\#(code)","name":"iPhone","platform":"ios"}"#.utf8), timeout: 10)
+ let first = try await host.receive()
+ #expect(first["m"] as? String == "pair")
+ #expect((first["b"] as? [String: Any])?["code"] as? String == code)
+ try await host.send(["id": first["id"] ?? 0, "ok": ["computerId": computer.id, "name": "Studio"]])
+ #expect(object(String(decoding: try await paired, as: UTF8.self))["name"] as? String == "Studio")
+ await socket.toDevice.close(4100)
+ #expect(await waitFor(t.states()) { if case .failed = $0 { true } else { false } } == .failed("Paired."))
+ await t.shutdown()
+}
diff --git a/kit/Tests/CodyncKitTests/CodyncKitTests.swift b/kit/Tests/CodyncKitTests/CodyncKitTests.swift
index 3fac73e9..42ca6f7a 100644
--- a/kit/Tests/CodyncKitTests/CodyncKitTests.swift
+++ b/kit/Tests/CodyncKitTests/CodyncKitTests.swift
@@ -19,14 +19,6 @@ import Testing
#expect(id == "b2")
}
-@Test func parsesPairingURL() throws {
- let p = try #require(Pairing(string: "codync://pair?name=Kevin%27s%20Mac&token=t0k&urls=http%3A%2F%2F100.1.2.3%3A19222%2Chttp%3A%2F%2Fa%3A1"))
- #expect(p.name == "Kevin's Mac")
- #expect(p.token == "t0k")
- #expect(p.urls == ["http://100.1.2.3:19222", "http://a:1"])
- #expect(Pairing(string: "codync://pair?token=") == nil)
-}
-
@Test func relativeTime() {
let now = Date(timeIntervalSince1970: 1_000_000)
#expect(RelativeTime.short(now.addingTimeInterval(-30), now: now) == "now")
diff --git a/kit/Tests/CodyncKitTests/PairingStorageTests.swift b/kit/Tests/CodyncKitTests/PairingStorageTests.swift
new file mode 100644
index 00000000..c76d5561
--- /dev/null
+++ b/kit/Tests/CodyncKitTests/PairingStorageTests.swift
@@ -0,0 +1,80 @@
+import Foundation
+import Testing
+@testable import CodyncKit
+
+private let v = Vectors.shared
+
+private func link(_ overrides: [String: String?] = [:]) -> String {
+ var q: [String: String?] = [
+ "v": "3", "name": "Kevin's Mac", "id": v.str("keys", "computerId"), "sk": v.str("keys", "hostSignPub"),
+ "bk": v.str("keys", "hostBoxPub"), "code": v.str("pairing", "code"),
+ "urls": "http://192.168.1.5:19222,http://100.64.1.2:19222", "cloud": "https://codync-cloud-staging.example.workers.dev",
+ ]
+ for (k, value) in overrides { q[k] = value }
+ var comps = URLComponents(string: "codync://pair")!
+ comps.queryItems = q.keys.sorted().compactMap { k in q[k]!.map { URLQueryItem(name: k, value: $0) } }
+ return comps.string!
+}
+
+@Test func parsesPairingV3() throws {
+ let p = try Pairing.parse(link())
+ #expect(p.computer.id == v.str("keys", "computerId"))
+ #expect(p.computer.name == "Kevin's Mac")
+ #expect(p.computer.signKey == v.str("keys", "hostSignPub"))
+ #expect(p.computer.boxKey == v.str("keys", "hostBoxPub"))
+ #expect(p.computer.urls == ["http://192.168.1.5:19222", "http://100.64.1.2:19222"])
+ #expect(p.computer.cloud?.absoluteString == "https://codync-cloud-staging.example.workers.dev")
+ #expect(p.code == v.str("pairing", "code"))
+ #expect(p.offerId == v.str("pairing", "offerId"))
+ #expect(Pairing(string: link()) == p)
+ // Either route alone is enough.
+ #expect(Pairing(string: link(["urls": nil])) != nil)
+ #expect(Pairing(string: link(["cloud": nil])) != nil)
+}
+
+@Test func rejectsBadPairingLinks() {
+ #expect(throws: Pairing.Problem.outdatedHost) { try Pairing.parse(link(["v": nil])) }
+ #expect(throws: Pairing.Problem.outdatedHost) { try Pairing.parse(link(["v": "2"])) }
+ #expect(throws: Pairing.Problem.invalid) { try Pairing.parse(link(["id": "AAAAAAAAAAAAAAAAAAAAAA"])) }
+ #expect(throws: Pairing.Problem.invalid) { try Pairing.parse(link(["code": nil])) }
+ #expect(throws: Pairing.Problem.invalid) { try Pairing.parse(link(["code": "short"])) }
+ #expect(throws: Pairing.Problem.invalid) { try Pairing.parse(link(["bk": nil])) }
+ #expect(throws: Pairing.Problem.invalid) { try Pairing.parse(link(["cloud": "http://evil.example.com"])) }
+ #expect(throws: Pairing.Problem.invalid) { try Pairing.parse(link(["urls": nil, "cloud": nil])) }
+ #expect(throws: Pairing.Problem.notPairingLink) { try Pairing.parse("https://example.com") }
+ // The old token-based link is not accepted.
+ #expect(throws: Pairing.Problem.outdatedHost) { try Pairing.parse("codync://pair?name=Mac&token=t0k&urls=http%3A%2F%2Fa%3A1") }
+}
+
+@Test func botLinksStayInTheirContext() throws {
+ let suite = "CodyncTests.\(UUID().uuidString)"
+ defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }
+ let alice = SharedStore.Context(accountID: "user_alice", suite: suite)
+ let bob = SharedStore.Context(accountID: "user_bob", suite: suite)
+ let local = SharedStore.Context(accountID: nil, suite: suite)
+ let ref = BotReference(accountId: "user_alice", computerId: v.str("keys", "computerId"), botId: "b1")
+
+ let url = alice.botURL(ref)
+ #expect(url.absoluteString == "codync://bot/b1?scope=\(alice.id)&computer=\(ref.computerId)")
+ #expect(alice.reference(from: url) == ref)
+ #expect(bob.reference(from: url) == nil)
+ #expect(local.reference(from: url) == nil)
+ #expect(alice.reference(from: URL(string: "codync://bot/b1")!) == nil)
+ #expect(alice.reference(from: URL(string: "codync://bot/b1?scope=\(alice.id)&computer=nope")!) == nil)
+ let localRef = BotReference(accountId: nil, computerId: ref.computerId, botId: "b1")
+ #expect(local.reference(from: local.botURL(localRef)) == localRef)
+}
+
+@Test func contextsAreIsolatedAndErasable() throws {
+ let suite = "CodyncTests.\(UUID().uuidString)"
+ defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }
+ let alice = SharedStore.Context(accountID: "user_alice", suite: suite)
+ let bob = SharedStore.Context(accountID: "user_bob", suite: suite)
+ alice.computers = [v.computer]
+ alice.usage = [v.computer.id: Usage()]
+ alice.lastComputerId = v.computer.id
+ #expect(bob.computers.isEmpty && bob.usage.isEmpty && bob.lastComputerId == nil)
+ #expect(SharedStore.Context(accountID: "user_alice", suite: suite).computers == [v.computer])
+ alice.erase()
+ #expect(alice.computers.isEmpty && alice.usage.isEmpty && alice.lastComputerId == nil)
+}
diff --git a/kit/Tests/CodyncKitTests/RelayVectorsTests.swift b/kit/Tests/CodyncKitTests/RelayVectorsTests.swift
new file mode 100644
index 00000000..5dd0dafe
--- /dev/null
+++ b/kit/Tests/CodyncKitTests/RelayVectorsTests.swift
@@ -0,0 +1,219 @@
+import CryptoKit
+import Foundation
+import Testing
+@testable import CodyncKit
+
+/// docs/remote-relay-vectors.json, the single source of truth shared with the host and the cloud.
+struct Vectors: Sendable {
+ let data: Data
+ var json: [String: Any] { (try? JSONSerialization.jsonObject(with: data) as? [String: Any]) ?? [:] }
+
+ static let shared = Vectors(data: (try? Data(contentsOf: URL(filePath: #filePath).deletingLastPathComponent()
+ .appending(path: "../../../docs/remote-relay-vectors.json").standardized)) ?? Data())
+
+ subscript(_ section: String) -> [String: Any] { json[section] as? [String: Any] ?? [:] }
+
+ func b64(_ section: String, _ key: String) -> Data { Data(base64URL: self[section][key] as? String ?? "") ?? Data() }
+ func str(_ section: String, _ key: String) -> String { self[section][key] as? String ?? "" }
+
+ var hostSign: Curve25519.Signing.PrivateKey { try! .init(rawRepresentation: b64("keys", "hostSignSeed")) }
+ var hostBox: Curve25519.KeyAgreement.PrivateKey { try! .init(rawRepresentation: b64("keys", "hostBoxPriv")) }
+ var deviceSign: Curve25519.Signing.PrivateKey { try! .init(rawRepresentation: b64("keys", "deviceSignSeed")) }
+ var computer: Computer {
+ Computer(id: str("keys", "computerId"), name: "Mac", signKey: str("keys", "hostSignPub"), boxKey: str("keys", "hostBoxPub"))
+ }
+ var identity: DeviceIdentity { DeviceIdentity(signing: deviceSign, push: try! .init(rawRepresentation: b64("push", "pushPriv"))) }
+}
+
+private let v = Vectors.shared
+private func raw(_ key: SymmetricKey) -> Data { key.withUnsafeBytes { Data($0) } }
+
+@Test func vectorFileLoads() {
+ #expect(!v.json.isEmpty)
+}
+
+@Test func base64URLIsStrict() {
+ #expect(Data([0xfb, 0xff]).base64URL == "-_8")
+ #expect(Data(base64URL: "-_8") == Data([0xfb, 0xff]))
+ #expect(Data(base64URL: "+/8") == nil)
+ #expect(Data(base64URL: "-_8=") == nil)
+ #expect(Data(base64URL: "A") == nil)
+}
+
+@Test func keysAndComputerId() {
+ #expect(v.hostSign.publicKey.rawRepresentation.base64URL == v.str("keys", "hostSignPub"))
+ #expect(v.hostBox.publicKey.rawRepresentation.base64URL == v.str("keys", "hostBoxPub"))
+ #expect(v.deviceSign.publicKey.rawRepresentation.base64URL == v.str("keys", "deviceSignPub"))
+ #expect(RelayCrypto.computerId(signKey: v.b64("keys", "hostSignPub")) == v.str("keys", "computerId"))
+ #expect(v.computer.isConsistent)
+ #expect(v.identity.publicKey == v.str("keys", "deviceSignPub"))
+ #expect(v.identity.pushKey == v.str("push", "pushPub"))
+}
+
+@Test func handshake() throws {
+ let ekD = try Curve25519.KeyAgreement.PrivateKey(rawRepresentation: v.b64("handshake", "deviceEphPriv"))
+ let ekH = try Curve25519.KeyAgreement.PrivateKey(rawRepresentation: v.b64("handshake", "hostEphPriv"))
+ #expect(ekD.publicKey.rawRepresentation == v.b64("handshake", "deviceEphPub"))
+ #expect(ekH.publicKey.rawRepresentation == v.b64("handshake", "hostEphPub"))
+ let hs = try RelayCrypto.Handshake(computer: v.computer, deviceKey: v.deviceSign.publicKey.rawRepresentation,
+ ephemeral: ekD, n: v.b64("handshake", "n"))
+ #expect(hs.signInput == v.b64("handshake", "hs1SignInput"))
+ // CryptoKit's Ed25519 signatures are randomized: check both verify rather than compare bytes.
+ #expect(v.deviceSign.publicKey.isValidSignature(v.b64("handshake", "hs1Sig"), for: hs.signInput))
+ #expect(v.deviceSign.publicKey.isValidSignature(try v.identity.sign(hs.signInput), for: hs.signInput))
+
+ let th = RelayCrypto.transcriptHash(cid: hs.cid, dk: hs.dk, ekD: hs.ekD, n: hs.n, ekH: ekH.publicKey.rawRepresentation)
+ #expect(th == v.b64("handshake", "transcriptHash"))
+ #expect(try RelayCrypto.sharedSecret(ekD, ekH.publicKey.rawRepresentation) == v.b64("handshake", "sharedSecret"))
+
+ let keys = try hs.finish(ekH: ekH.publicKey.rawRepresentation, sig: v.b64("handshake", "hs2Sig"))
+ #expect(keys.prk == v.b64("handshake", "prk"))
+ #expect(raw(keys.d2h) == v.b64("handshake", "kD2H"))
+ #expect(raw(keys.h2d) == v.b64("handshake", "kH2D"))
+
+ // A welcome signed by any other key is an attack, not a retry.
+ let forged = try Curve25519.Signing.PrivateKey().signature(for: th)
+ #expect(throws: RelayCryptoError.badSignature) { try hs.finish(ekH: ekH.publicKey.rawRepresentation, sig: forged) }
+}
+
+@Test func zeroSharedSecretIsRejected() throws {
+ let priv = Curve25519.KeyAgreement.PrivateKey()
+ #expect(throws: (any Error).self) { try RelayCrypto.sharedSecret(priv, Data(count: 32)) }
+}
+
+@Test func frames() throws {
+ let kD2H = SymmetricKey(data: v.b64("handshake", "kD2H"))
+ let kH2D = SymmetricKey(data: v.b64("handshake", "kH2D"))
+ let frames = v.json["frames"] as? [[String: Any]] ?? []
+ #expect(frames.count == 3)
+ for f in frames {
+ let c = UInt64(f["c"] as? Int ?? -1)
+ let final = f["final"] as? Bool ?? true
+ let message = Data((f["message"] as? String ?? "").utf8)
+ let d = Data(base64URL: f["d"] as? String ?? "") ?? Data()
+ #expect(Data([final ? 0 : 1]) + message == Data(base64URL: f["plaintext"] as? String ?? ""))
+ let key = f["dir"] as? String == "d2h" ? kD2H : kH2D
+ #expect(try RelayCrypto.sealFrame(key: key, counter: c, final: final, chunk: message) == d)
+ let opened = try RelayCrypto.openFrame(key: key, counter: c, d: d)
+ #expect(opened.final == final && opened.chunk == message)
+ }
+ // Device side: the first d2h message, then the h2d answer.
+ var sealer = RelayCrypto.FrameSealer(key: kD2H)
+ let first = try sealer.seal(Data("{\"id\":1,\"m\":\"hello\",\"b\":{}}".utf8))
+ #expect(first.count == 1 && first[0].c == 0 && first[0].d.base64URL == frames[0]["d"] as? String)
+ var opener = RelayCrypto.FrameOpener(key: kH2D)
+ let answer = try opener.open(c: 0, d: Data(base64URL: frames[1]["d"] as? String ?? "") ?? Data())
+ #expect(answer == Data("{\"id\":1,\"ok\":{\"name\":\"Mac\"}}".utf8))
+}
+
+@Test func chunkingReassemblesAndEnforcesOrderAndLimit() throws {
+ let key = SymmetricKey(size: .bits256)
+ let big = Data((0..<(600 * 1024)).map { UInt8($0 % 251) })
+ var sealer = RelayCrypto.FrameSealer(key: key)
+ let frames = try sealer.seal(big)
+ #expect(frames.map(\.c) == [0, 1, 2])
+ var opener = RelayCrypto.FrameOpener(key: key)
+ #expect(try opener.open(c: 0, d: frames[0].d) == nil)
+ #expect(try opener.open(c: 1, d: frames[1].d) == nil)
+ #expect(try opener.open(c: 2, d: frames[2].d) == big)
+
+ // Replayed or reordered frames close the channel.
+ var strict = RelayCrypto.FrameOpener(key: key)
+ #expect(throws: RelayCryptoError.badCounter) { try strict.open(c: 1, d: frames[1].d) }
+ var small = RelayCrypto.FrameOpener(key: key, limit: 300 * 1024)
+ _ = try small.open(c: 0, d: frames[0].d)
+ #expect(throws: RelayCryptoError.tooLarge) { try small.open(c: 1, d: frames[1].d) }
+ // Empty messages are still one final frame.
+ var empty = RelayCrypto.FrameSealer(key: key)
+ #expect(try empty.seal(Data()).count == 1)
+}
+
+@Test func sas() {
+ let dk = v.b64("keys", "deviceSignPub")
+ let nD = v.b64("sas", "deviceNonce")
+ #expect(RelayCrypto.sasCommit(deviceKey: dk, deviceNonce: nD) == v.b64("sas", "commit"))
+ #expect(RelayCrypto.sasCode(hostSignKey: v.b64("keys", "hostSignPub"), deviceKey: dk, deviceNonce: nD,
+ hostNonce: v.b64("sas", "hostNonce")) == v.str("sas", "code"))
+}
+
+@Test func claimAndACLSignaturesVerify() {
+ let host = v.hostSign.publicKey
+ #expect(host.isValidSignature(v.b64("claim", "sig"), for: Data(v.str("claim", "canonical").utf8)))
+ #expect(v.b64("acl", "d") == Data(v.str("acl", "json").utf8))
+ #expect(host.isValidSignature(v.b64("acl", "sig"), for: v.b64("acl", "d")))
+}
+
+@Test func offerId() {
+ #expect(RelayCrypto.offerId(code: v.b64("pairing", "code")) == v.str("pairing", "offerId"))
+}
+
+@Test func mailbox() throws {
+ let eph = try Curve25519.KeyAgreement.PrivateKey(rawRepresentation: v.b64("mailbox", "ephPriv"))
+ #expect(eph.publicKey.rawRepresentation == v.b64("mailbox", "ephPub"))
+ #expect(try RelayCrypto.sharedSecret(eph, v.b64("keys", "hostBoxPub")) == v.b64("mailbox", "sharedSecret"))
+ let cid = try #require(RelayCrypto.computerIdRaw(v.str("keys", "computerId")))
+ let dk = v.b64("keys", "deviceSignPub")
+ #expect(raw(RelayCrypto.mailboxKey(sharedSecret: v.b64("mailbox", "sharedSecret"), cid: cid, dk: dk, epk: eph.publicKey.rawRepresentation))
+ == v.b64("mailbox", "key"))
+ let sealed = try RelayCrypto.sealMailbox(Data(v.str("mailbox", "plaintext").utf8), hostBoxKey: v.b64("keys", "hostBoxPub"),
+ computerId: v.str("keys", "computerId"), deviceKey: dk,
+ clientNonce: v.str("mailbox", "clientNonce"), sign: v.identity.sign, ephemeral: eph)
+ #expect(sealed.ciphertext == v.b64("mailbox", "ciphertext"))
+ let signed = RelayCrypto.label("codync/mbox/v1") + cid + sealed.epk + sealed.ciphertext
+ #expect(v.deviceSign.publicKey.isValidSignature(sealed.sig, for: signed))
+ #expect(v.deviceSign.publicKey.isValidSignature(v.b64("mailbox", "sig"), for: signed))
+ #expect(sealed.epk + v.b64("mailbox", "sig") + sealed.ciphertext == v.b64("mailbox", "blob"))
+ #expect(sealed.blob.count == v.b64("mailbox", "blob").count)
+}
+
+@Test func mailboxNeverReusesEphemeralKeys() throws {
+ let seal = {
+ try RelayCrypto.sealMailbox(Data("same".utf8), hostBoxKey: v.b64("keys", "hostBoxPub"), computerId: v.str("keys", "computerId"),
+ deviceKey: v.b64("keys", "deviceSignPub"), clientNonce: "n", sign: v.identity.sign)
+ }
+ let a = try seal()
+ let b = try seal()
+ #expect(a.epk != b.epk)
+ #expect(a.ciphertext != b.ciphertext)
+}
+
+@Test func push() throws {
+ let pushPriv = try Curve25519.KeyAgreement.PrivateKey(rawRepresentation: v.b64("push", "pushPriv"))
+ let eph = try Curve25519.KeyAgreement.PrivateKey(rawRepresentation: v.b64("push", "ephPriv"))
+ #expect(eph.publicKey.rawRepresentation == v.b64("push", "ephPub"))
+ let ss = try RelayCrypto.sharedSecret(pushPriv, eph.publicKey.rawRepresentation)
+ #expect(ss == v.b64("push", "sharedSecret"))
+ let cid = try #require(RelayCrypto.computerIdRaw(v.str("keys", "computerId")))
+ #expect(raw(RelayCrypto.pushKey(sharedSecret: ss, cid: cid, pushKey: v.b64("push", "pushPub"), epk: eph.publicKey.rawRepresentation))
+ == v.b64("push", "key"))
+ #expect(try RelayCrypto.openPush(sealed: v.str("push", "sealed"), computerId: v.str("keys", "computerId"), pushPrivate: pushPriv)
+ == Data(v.str("push", "plaintext").utf8))
+ let alert = try #require(DeviceIdentity.openPush(sealed: v.str("push", "sealed"), computerId: v.str("keys", "computerId"), key: pushPriv))
+ #expect(alert.title == "Reviewer" && alert.body == "Run cargo test --all?")
+ // Bound to the computer (aad) and to this device's key.
+ #expect(DeviceIdentity.openPush(sealed: v.str("push", "sealed"), computerId: "AAAAAAAAAAAAAAAAAAAAAA", key: pushPriv) == nil)
+ #expect(DeviceIdentity.openPush(sealed: v.str("push", "sealed"), computerId: v.str("keys", "computerId"), key: .init()) == nil)
+}
+
+@Test func requestSignature() throws {
+ let input = RelayCrypto.requestSigInput(method: "get", authority: "Codync-Cloud-Staging.example.workers.dev",
+ pathAndQuery: v.str("requestSig", "pathAndQuery"), ts: 1_790_000_000_000,
+ nonce: v.str("requestSig", "nonce"), body: Data())
+ #expect(input == Data(v.str("requestSig", "canonical").utf8))
+ #expect(RelayCrypto.sha256(Data()).base64URL == v.str("requestSig", "bodySha256"))
+ #expect(v.deviceSign.publicKey.isValidSignature(v.b64("requestSig", "sig"), for: input))
+
+ let header = try v.identity.signatureHeader(method: "GET", authority: v.str("requestSig", "authority"),
+ pathAndQuery: v.str("requestSig", "pathAndQuery"), body: Data(),
+ ts: 1_790_000_000_000, nonce: v.str("requestSig", "nonce"))
+ let expected = v.str("requestSig", "header").replacingOccurrences(of: "Codync-Sig: ", with: "")
+ #expect(header.components(separatedBy: ",sig=")[0] == expected.components(separatedBy: ",sig=")[0])
+ let sig = try #require(Data(base64URL: header.components(separatedBy: ",sig=")[1]))
+ #expect(v.deviceSign.publicKey.isValidSignature(sig, for: input))
+
+ let url = try #require(URL(string: "https://Codync-Cloud-Staging.example.workers.dev/v1/relay/device/NHUPmL1Z_PyUbaRaqr6TOw?v=1"))
+ #expect(RelayCrypto.authority(of: url) == v.str("requestSig", "authority"))
+ #expect(RelayCrypto.pathAndQuery(of: url) == v.str("requestSig", "pathAndQuery"))
+ #expect(RelayCrypto.authority(of: URL(string: "http://127.0.0.1:8787/v1")!) == "127.0.0.1:8787")
+ #expect(RelayCrypto.authority(of: URL(string: "https://a.dev:443/v1")!) == "a.dev")
+}
diff --git a/kit/Tests/CodyncUITests/StoreTests.swift b/kit/Tests/CodyncUITests/StoreTests.swift
new file mode 100644
index 00000000..863491d0
--- /dev/null
+++ b/kit/Tests/CodyncUITests/StoreTests.swift
@@ -0,0 +1,228 @@
+import CryptoKit
+import Foundation
+import Testing
+@testable import CodyncKit
+@testable import CodyncUI
+
+/// A scripted transport: tests set its link state and push events; it records what the store asked.
+actor FakeRemote: RemoteTransport {
+ private var state: LinkState
+ private var stateSinks: [AsyncStream<LinkState>.Continuation] = []
+ private var eventSinks: [AsyncThrowingStream<Data, Error>.Continuation] = []
+ private var mailboxSinks: [AsyncStream<MailboxEvent>.Continuation] = []
+ private(set) var sent: [String] = []
+ private(set) var enqueued: [String] = []
+ var cancelResult = MailboxCancel.cancelled
+
+ init(_ state: LinkState) { self.state = state }
+
+ var subscribed: Bool { !eventSinks.isEmpty }
+
+ func set(_ new: LinkState) {
+ state = new
+ for s in stateSinks { s.yield(new) }
+ }
+
+ func emit(_ json: String) {
+ for s in eventSinks { s.yield(Data(json.utf8)) }
+ }
+
+ func emit(_ event: MailboxEvent) {
+ for s in mailboxSinks { s.yield(event) }
+ }
+
+ private func respond(_ method: String, _ body: Data) throws -> Data {
+ switch method {
+ case "hello":
+ return Data(#"{"hostId":"h1","name":"Mac","version":"3.0.0","os":"macos","backends":[],"rev":0}"#.utf8)
+ case "send":
+ let b = (try JSONSerialization.jsonObject(with: body) as? [String: String]) ?? [:]
+ sent.append(b["text"] ?? "")
+ let entry = #"{"id":"e\#(sent.count)","seq":\#(sent.count),"botId":"\#(b["botId"] ?? "")","rev":\#(sent.count),"kind":"user","turn":1,"data":{"text":"\#(b["text"] ?? "")","clientNonce":"\#(b["clientNonce"] ?? "")"},"createdAt":1,"updatedAt":1}"#
+ return Data(#"{"entry":\#(entry)}"#.utf8)
+ default:
+ return Data("{}".utf8)
+ }
+ }
+
+ nonisolated func call(_ method: String, body: Data, timeout: TimeInterval) async throws -> Data {
+ try await respond(method, body)
+ }
+
+ private func addEvents(_ c: AsyncThrowingStream<Data, Error>.Continuation) { eventSinks.append(c) }
+ private func addState(_ c: AsyncStream<LinkState>.Continuation) {
+ c.yield(state)
+ stateSinks.append(c)
+ }
+ private func addMailbox(_ c: AsyncStream<MailboxEvent>.Continuation) { mailboxSinks.append(c) }
+
+ nonisolated func stream(_ request: HostStreamRequest) -> AsyncThrowingStream<Data, Error> {
+ AsyncThrowingStream { c in Task { await self.addEvents(c) } }
+ }
+
+ nonisolated func states() -> AsyncStream<LinkState> {
+ AsyncStream { c in Task { await self.addState(c) } }
+ }
+
+ nonisolated func computerUpdates() -> AsyncStream<Computer> { AsyncStream { _ in } }
+
+ func enqueue(botId: String, text: String, clientNonce: String) async throws { enqueued.append(clientNonce) }
+ func cancelQueued(clientNonce: String) async -> MailboxCancel { cancelResult }
+ func listQueued() async -> [QueuedItem] { enqueued.map { QueuedItem(nonce: $0, exp: nil, state: "queued") } }
+
+ nonisolated func mailboxEvents() -> AsyncStream<MailboxEvent> {
+ AsyncStream { c in Task { await self.addMailbox(c) } }
+ }
+
+ func shutdown() async {
+ for s in eventSinks { s.finish() }
+ for s in stateSinks { s.finish() }
+ eventSinks = []
+ stateSinks = []
+ }
+}
+
+private func randomComputer(_ name: String) -> Computer {
+ let sk = Curve25519.Signing.PrivateKey().publicKey.rawRepresentation
+ return Computer(id: RelayCrypto.computerId(signKey: sk), name: name, signKey: sk.base64URLForTests,
+ boxKey: Curve25519.KeyAgreement.PrivateKey().publicKey.rawRepresentation.base64URLForTests,
+ cloud: URL(string: "https://cloud.example.dev"))
+}
+
+private extension Data {
+ var base64URLForTests: String {
+ base64EncodedString().replacingOccurrences(of: "+", with: "-").replacingOccurrences(of: "/", with: "_").replacingOccurrences(of: "=", with: "")
+ }
+}
+
+private func context() -> (SharedStore.Context, String) {
+ let suite = "CodyncUITests.\(UUID().uuidString)"
+ return (SharedStore.Context(accountID: "user_\(UUID().uuidString)", suite: suite), suite)
+}
+
+/// Polls until `condition` holds (2 s at most).
+@MainActor
+private func until(_ condition: @MainActor () async -> Bool) async -> Bool {
+ for _ in 0..<200 {
+ if await condition() { return true }
+ try? await Task.sleep(for: .milliseconds(10))
+ }
+ return false
+}
+
+private func botEvent(_ id: String, name: String, rev: Int) -> String {
+ #"{"type":"bot","bot":{"id":"\#(id)","name":"\#(name)","rev":\#(rev),"lastAt":\#(rev)}}"#
+}
+
+@MainActor @Test func offlineSendsWaitInTheMailbox() async throws {
+ let (storage, suite) = context()
+ defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }
+ let fake = FakeRemote(.hostOffline(lastSeen: nil))
+ let store = BotStore(computer: randomComputer("Mac"), route: .channel, clientKind: "ios", storage: storage) { fake }
+ store.setActive(true)
+ #expect(await until { store.connection == .computerOffline(lastSeen: nil) })
+ #expect(store.canQueue && store.isOffline)
+
+ store.send("hi", to: "b1")
+ #expect(await until { await fake.enqueued.count == 1 })
+ let waiting = try #require(store.thread("b1").first)
+ #expect(waiting.data.status == "waiting")
+ #expect(await fake.sent.isEmpty)
+
+ // Cancelled before the computer saw it: gone.
+ store.cancelQueued(waiting)
+ #expect(await until { store.thread("b1").isEmpty })
+
+ // Already handed over: it stays, marked delivered.
+ store.send("second", to: "b1")
+ #expect(await until { await fake.enqueued.count == 2 })
+ await fake.setCancelResult(.delivering)
+ let second = try #require(store.thread("b1").first)
+ store.cancelQueued(second)
+ #expect(await until { store.thread("b1").first?.data.status == "delivering" })
+
+ // Expired in the mailbox: failed, can be resent.
+ store.send("third", to: "b2")
+ #expect(await until { await fake.enqueued.count == 3 })
+ let third = try #require(store.thread("b2").first?.data.clientNonce)
+ await fake.emit(.expired(nonce: third))
+ #expect(await until { store.thread("b2").first?.data.status == "failed" })
+
+ // Back online: sends go straight to the computer, and its copy replaces the local one.
+ await fake.set(.ready(.relay))
+ #expect(await until { await fake.subscribed })
+ await fake.emit(botEvent("b1", name: "Rex", rev: 1))
+ #expect(await until { store.connection == .online })
+ store.send("live", to: "b3")
+ #expect(await until { store.thread("b3").first?.id == "e1" })
+ #expect(await fake.sent == ["live"])
+ store.retire()
+}
+
+@MainActor @Test func accountKeepsComputersApart() async throws {
+ let (storage, suite) = context()
+ defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }
+ let c1 = randomComputer("Mac")
+ let c2 = randomComputer("Linux box")
+ storage.computers = [c1, c2]
+ let fakes = [c1.id: FakeRemote(.ready(.direct)), c2.id: FakeRemote(.ready(.relay))]
+ let account = AccountStore(storage: storage, clientKind: "ios", cloud: nil) { computer, route in
+ BotStore(computer: computer, route: route, clientKind: "ios", storage: storage) { fakes[computer.id]! }
+ }
+ var updates: [BotReference] = []
+ account.onBotUpdated = { ref, _ in updates.append(ref) }
+ #expect(account.computers.map(\.id) == [c1.id, c2.id])
+ for fake in fakes.values { #expect(await until { await fake.subscribed }) }
+
+ // Same bot ID on both computers.
+ await fakes[c1.id]!.emit(botEvent("b1", name: "Mac bot", rev: 1))
+ await fakes[c2.id]!.emit(botEvent("b1", name: "Linux bot", rev: 2))
+ #expect(await until { account.roster.count == 2 })
+ let refs = account.roster.map(\.ref)
+ #expect(Set(refs).count == 2)
+ #expect(Set(refs.map(\.computerId)) == [c1.id, c2.id])
+ #expect(account.roster.first { $0.ref.computerId == c2.id }?.bot.name == "Linux bot")
+ #expect(Set(updates) == Set(refs))
+
+ // Routing by reference reaches only that computer.
+ let ref = try #require(refs.first { $0.computerId == c2.id })
+ account.store(for: ref.computerId)?.send("hello", to: ref.botId)
+ #expect(await until { await fakes[c2.id]!.sent == ["hello"] })
+ #expect(await fakes[c1.id]!.sent.isEmpty)
+ #expect(storage.lastComputerId == c2.id)
+
+ // After switching accounts, late events write nothing.
+ let old = account.store(for: c1.id)
+ account.retire()
+ await fakes[c1.id]!.emit(#"{"type":"usage","usage":{"providers":[{"id":"claude","name":"Claude","windows":[],"source":"x","updatedAt":1}]}}"#)
+ try? await Task.sleep(for: .milliseconds(100))
+ #expect(storage.usage[c1.id] == nil)
+ #expect(old?.usage.providers.isEmpty == true)
+ #expect(updates.count == 2)
+}
+
+@MainActor @Test func attachedComputersAreNotSaved() async throws {
+ let (storage, suite) = context()
+ defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }
+ let saved = randomComputer("Saved")
+ storage.computers = [saved]
+ let fake = FakeRemote(.ready(.loopback))
+ let account = AccountStore(storage: storage, clientKind: "mac", cloud: nil) { _, _ in
+ BotStore(computer: saved, route: .channel, clientKind: "mac", storage: storage) { fake }
+ }
+ let local = randomComputer("This Mac")
+ account.attach(local, route: .loopback(baseURL: URL(string: "http://127.0.0.1:19222")!, token: "t"))
+ #expect(account.computers.map(\.id) == [local.id, saved.id])
+ #expect(storage.computers.map(\.id) == [saved.id])
+ account.setColor(saved.id, "red")
+ #expect(storage.computers.first?.color == "red")
+ account.detach(local.id)
+ #expect(account.computers.map(\.id) == [saved.id])
+ account.forget(saved.id)
+ #expect(storage.computers.isEmpty && account.stores.isEmpty)
+ account.retire()
+}
+
+extension FakeRemote {
+ func setCancelResult(_ result: MailboxCancel) { cancelResult = result }
+}
diff --git a/project.yml b/project.yml
index 38c2545c..59a29d16 100644
--- a/project.yml
+++ b/project.yml
@@ -17,7 +17,7 @@ packages:
exactVersion: 153.0.0
settings:
base:
- MARKETING_VERSION: 2.1.0
+ MARKETING_VERSION: 3.0.0
CURRENT_PROJECT_VERSION: 17
SWIFT_VERSION: "6.0"
SWIFT_STRICT_CONCURRENCY: complete
@@ -126,6 +126,7 @@ targets:
- path: apps/ios
excludes:
- Widgets
+ - NotificationService
dependencies:
- package: Clerk
product: ClerkKit
@@ -135,6 +136,8 @@ targets:
product: CodyncUI
- target: Widgets
embed: true
+ - target: NotificationService
+ embed: true
settings:
base:
PRODUCT_NAME: Codync
@@ -176,3 +179,22 @@ targets:
INFOPLIST_KEY_CFBundleDisplayName: Codync
TARGETED_DEVICE_FAMILY: "1,2"
SKIP_INSTALL: YES
+ # Opens end-to-end sealed alert text (spec §6.7) with this account's push key from the shared Keychain.
+ NotificationService:
+ type: app-extension
+ platform: iOS
+ sources:
+ - apps/ios/NotificationService
+ dependencies:
+ - package: CodyncKit
+ product: CodyncKit
+ settings:
+ base:
+ PRODUCT_NAME: CodyncNotificationService
+ PRODUCT_BUNDLE_IDENTIFIER: com.pokai.Codync.ios.NotificationService
+ INFOPLIST_FILE: apps/ios/NotificationService/Info.plist
+ GENERATE_INFOPLIST_FILE: YES
+ CODE_SIGN_ENTITLEMENTS: apps/ios/NotificationService/NotificationService.entitlements
+ INFOPLIST_KEY_CFBundleDisplayName: Codync
+ TARGETED_DEVICE_FAMILY: "1,2"
+ SKIP_INSTALL: YES
diff --git a/relay/README.md b/relay/README.md
index 3c1d6c7d..fad65cde 100644
--- a/relay/README.md
+++ b/relay/README.md
@@ -23,6 +23,6 @@ Rotating `TICKET_KEY` invalidates every ticket; phones re-register on launch.
## Test
```bash
-npm test # ticket seal/open round trip
+npm test # ticket seal/open round trip, `mutableContent` → `mutable-content: 1`
npm run typecheck
```
diff --git a/relay/package.json b/relay/package.json
index 82bcacd9..ab9a0e91 100644
--- a/relay/package.json
+++ b/relay/package.json
@@ -6,7 +6,7 @@
"scripts": {
"deploy": "wrangler deploy",
"typecheck": "tsc",
- "test": "node --experimental-strip-types --no-warnings test/ticket.test.ts"
+ "test": "node --experimental-strip-types --no-warnings test/ticket.test.ts && node --experimental-strip-types --no-warnings test/push.test.ts"
},
"dependencies": {
"@fivesheepco/cloudflare-apns2": "^13.0.0"
diff --git a/relay/src/index.ts b/relay/src/index.ts
index 173fba1b..03d062b6 100644
--- a/relay/src/index.ts
+++ b/relay/src/index.ts
@@ -6,8 +6,11 @@
// one device — without ever learning the raw token or holding a shared secret.
//
// POST /register { token, env: "sandbox" | "production", kind: "alert" | "liveactivity" } -> { ticket }
-// POST /push { ticket, alert?: { title, body }, threadId?, category?, data?,
+// POST /push { ticket, alert?: { title, body }, threadId?, category?, data?, mutableContent?,
// liveActivity?: { event: "update" | "end", contentState } }
+//
+// `mutableContent: true` sets `mutable-content: 1` so the Notification Service Extension can replace the
+// generic alert with the host's end-to-end encrypted title/body (`data.sealed`).
import { ApnsClient, Notification, PushType, Priority } from "@fivesheepco/cloudflare-apns2";
@@ -96,15 +99,28 @@ async function register(req: Request, env: Env): Promise<Response> {
return json({ ticket: await sealTicket(env, { t: body.token, e, k }) });
}
-interface PushBody {
+export interface PushBody {
ticket?: string;
alert?: { title?: string; body?: string };
threadId?: string;
category?: string;
data?: Record<string, unknown>;
+ mutableContent?: boolean;
liveActivity?: { event?: "update" | "end"; contentState?: Record<string, unknown> };
}
+/** The `aps` dictionary for an alert push. */
+export function alertAps(body: PushBody & { alert: NonNullable<PushBody["alert"]> }): Record<string, unknown> {
+ const aps: Record<string, unknown> = {
+ alert: { title: (body.alert.title ?? "Codync").slice(0, 120), body: (body.alert.body ?? "").slice(0, 400) },
+ sound: "default",
+ "thread-id": body.threadId,
+ category: body.category,
+ };
+ if (body.mutableContent === true) aps["mutable-content"] = 1;
+ return aps;
+}
+
async function push(req: Request, env: Env): Promise<Response> {
const body = (await req.json().catch(() => null)) as PushBody | null;
const t = body?.ticket ? await openTicket(env, body.ticket) : null;
@@ -117,12 +133,7 @@ async function push(req: Request, env: Env): Promise<Response> {
new Notification(t.t, {
type: PushType.alert,
priority: Priority.immediate,
- aps: {
- alert: { title: (body.alert.title ?? "Codync").slice(0, 120), body: (body.alert.body ?? "").slice(0, 400) },
- sound: "default",
- "thread-id": body.threadId,
- category: body.category,
- },
+ aps: alertAps({ ...body, alert: body.alert }),
data: body.data ?? {},
}),
);
diff --git a/relay/test/push.test.ts b/relay/test/push.test.ts
new file mode 100644
index 00000000..f67e4df3
--- /dev/null
+++ b/relay/test/push.test.ts
@@ -0,0 +1,10 @@
+// Alert aps: `mutableContent` passes through as `mutable-content: 1`, and only when asked.
+import assert from "node:assert/strict";
+import { alertAps } from "../src/index.ts";
+
+const base = { alert: { title: "Codync", body: "Needs you" }, threadId: "b1", category: "needsInput" };
+assert.equal(alertAps({ ...base, mutableContent: true })["mutable-content"], 1);
+assert.equal("mutable-content" in alertAps(base), false);
+assert.equal("mutable-content" in alertAps({ ...base, mutableContent: false }), false);
+assert.deepEqual(alertAps(base).alert, { title: "Codync", body: "Needs you" });
+console.log("push tests ok");