源码快照 @ 2026-09-01 (source-only, 剔除非源码素材)
Publish Claude Code Binaries / Stage and publish binaries (push) Canceled after 0s
Publish Tutti App Runtime / Build darwin-arm64 (push) Canceled after 0s
Publish Tutti App Runtime / Build darwin-amd64 (push) Canceled after 0s
Publish Tutti App Runtime / Build linux-amd64 (push) Canceled after 0s
Publish Tutti App Runtime / Build windows-amd64 (push) Canceled after 0s
Sync Tutti Agent Skills / sync (push) Canceled after 0s
Windows Agent Adapters / Test Windows agent adapters (push) Canceled after 0s
Windows Daemon Adapters / Test Windows daemon adapters (push) Canceled after 0s
Publish Tutti App Runtime / Publish runtime catalog (push) Canceled after 0s

This commit is contained in:
agent-radar committed 2026-09-01 20:17:27 +08:00
commit 2ed3415fb7
8018 files changed
+1936476

No files matched your search

+3
View File
@@ -0,0 +1,3 @@
# This file is sourced by React Native build phases inside Xcode.
# Use .xcode.env.local for machine-specific overrides.
export NODE_BINARY=$(command -v node)
+34
View File
@@ -0,0 +1,34 @@
.PHONY: ios-bindings-check ios-framework ios-framework-check
GOMOBILE_GO_TOOLCHAIN ?= go1.26.0
GOMOBILE_LDFLAGS ?= -checklinkname=0
REPO_ROOT := $(abspath ../../..)
DEVICE_LINK_DIR := $(REPO_ROOT)/packages/device-link
FRAMEWORK_OUTPUT ?= $(CURDIR)/Frameworks/TuttiMobileGo.xcframework
OBJC_PREFIX := TUT
GOMOBILE_GO := env GOTOOLCHAIN=$(GOMOBILE_GO_TOOLCHAIN) go
ios-bindings-check:
@bind_tmp=$$(mktemp -d); \
trap 'rm -rf "$$bind_tmp"' EXIT; \
cd "$(DEVICE_LINK_DIR)" && DEVELOPER_DIR=/Library/Developer/CommandLineTools $(GOMOBILE_GO) tool gobind -lang=objc -prefix=$(OBJC_PREFIX) -outdir="$$bind_tmp" ./mobile ../agent/daemon/liveprotocol/mobile; \
test -f "$$bind_tmp/src/gobind/$(OBJC_PREFIX)Mobile.objc.h"; \
test -f "$$bind_tmp/src/gobind/$(OBJC_PREFIX)Liveprotocolmobile.objc.h"; \
grep -Fq 'TUTMobileNewLink' "$$bind_tmp/src/gobind/$(OBJC_PREFIX)Mobile.objc.h"; \
grep -Fq 'TUTLiveprotocolmobileNewSubscriber' "$$bind_tmp/src/gobind/$(OBJC_PREFIX)Liveprotocolmobile.objc.h"
ios-framework:
@xcode_path=$$(xcode-select -p 2>/dev/null); \
test -n "$$xcode_path" && test -d "$$xcode_path/Platforms/iPhoneOS.platform" || (echo "Full Xcode with the iOS SDK is required" >&2; exit 1)
@mkdir -p "$(dir $(FRAMEWORK_OUTPUT))"
@tool_tmp=$$(mktemp -d); \
trap 'rm -rf "$$tool_tmp"' EXIT; \
cd "$(DEVICE_LINK_DIR)" && GOBIN="$$tool_tmp" $(GOMOBILE_GO) install golang.org/x/mobile/cmd/gobind; \
cd "$(DEVICE_LINK_DIR)" && PATH="$$tool_tmp:$$PATH" $(GOMOBILE_GO) tool gomobile bind -target=ios,iossimulator -prefix=$(OBJC_PREFIX) -ldflags="$(GOMOBILE_LDFLAGS)" -o "$(FRAMEWORK_OUTPUT)" ./mobile ../agent/daemon/liveprotocol/mobile
@$(MAKE) ios-framework-check
ios-framework-check:
@test -d "$(FRAMEWORK_OUTPUT)" || (echo "XCFramework not found: $(FRAMEWORK_OUTPUT)" >&2; exit 1)
@test -f "$(FRAMEWORK_OUTPUT)/Info.plist"
@find "$(FRAMEWORK_OUTPUT)" -path '*/Headers/TUTMobile.objc.h' -print -quit | grep -q .
@find "$(FRAMEWORK_OUTPUT)" -path '*/Headers/TUTLiveprotocolmobile.objc.h' -print -quit | grep -q .
+39
View File
@@ -0,0 +1,39 @@
# Resolve React Native's Pod helpers through Node so pnpm hoisting is supported.
require Pod::Executable.execute_command('node', ['-p',
'require.resolve(
"react-native/scripts/react_native_pods.rb",
{paths: [process.argv[1]]},
)', __dir__]).strip
require_relative './cocoapods_pathname_workaround'
platform :ios, min_ios_version_supported
prepare_react_native_project!
target 'TuttiMobile' do
config = use_native_modules!
pod 'TuttiMobileGo', :path => '.'
use_react_native!(
:path => config[:reactNativePath],
:app_path => "#{Pod::Config.instance.installation_root}/.."
)
post_install do |installer|
react_native_post_install(
installer,
config[:reactNativePath],
:mac_catalyst_enabled => false
)
# React Native resolves pnpm symlinks to an absolute store path during
# installation. Keep the user project portable across workspaces.
installer.aggregate_targets.map(&:user_project).compact.uniq.each do |project|
project.build_configurations.each do |build_configuration|
build_configuration.build_settings['REACT_NATIVE_PATH'] =
'${SRCROOT}/../node_modules/react-native'
end
project.save
end
end
end
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,506 @@
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 54;
objects = {
/* Begin PBXBuildFile section */
0C80B921A6F3F58F76C31292 /* libPods-TuttiMobile.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 5DCACB8F33CDC322A6C60F78 /* libPods-TuttiMobile.a */; };
13B07FBF1A68108700A75B9A /* Images.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 13B07FB51A68108700A75B9A /* Images.xcassets */; };
761780ED2CA45674006654EE /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 761780EC2CA45674006654EE /* AppDelegate.swift */; };
81AB9BB82411601600AC10FF /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 81AB9BB72411601600AC10FF /* LaunchScreen.storyboard */; };
A10000000000000000000001 /* MobileSecurityModule.swift in Sources */ = {isa = PBXBuildFile; fileRef = A20000000000000000000001 /* MobileSecurityModule.swift */; };
A10000000000000000000002 /* MobileBrowserAuthBridge.swift in Sources */ = {isa = PBXBuildFile; fileRef = A20000000000000000000002 /* MobileBrowserAuthBridge.swift */; };
A10000000000000000000003 /* QRCodeScannerViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = A20000000000000000000003 /* QRCodeScannerViewController.swift */; };
A10000000000000000000004 /* MobileNativeModules.m in Sources */ = {isa = PBXBuildFile; fileRef = A20000000000000000000004 /* MobileNativeModules.m */; };
A10000000000000000000005 /* DeviceLinkModule.mm in Sources */ = {isa = PBXBuildFile; fileRef = A20000000000000000000005 /* DeviceLinkModule.mm */; settings = {COMPILER_FLAGS = "-fcxx-modules"; }; };
A10000000000000000000006 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = 13B07FB81A68108700A75B9A /* PrivacyInfo.xcprivacy */; };
A10000000000000000000007 /* Localizable.strings in Resources */ = {isa = PBXBuildFile; fileRef = A30000000000000000000001 /* Localizable.strings */; };
A10000000000000000000008 /* InfoPlist.strings in Resources */ = {isa = PBXBuildFile; fileRef = A30000000000000000000002 /* InfoPlist.strings */; };
A10000000000000000000009 /* AppLifecycleModule.swift in Sources */ = {isa = PBXBuildFile; fileRef = A20000000000000000000010 /* AppLifecycleModule.swift */; };
A10000000000000000000010 /* MobileWebAuthenticationSession.swift in Sources */ = {isa = PBXBuildFile; fileRef = A20000000000000000000011 /* MobileWebAuthenticationSession.swift */; };
A10000000000000000000011 /* MobilePreferencesModule.swift in Sources */ = {isa = PBXBuildFile; fileRef = A20000000000000000000012 /* MobilePreferencesModule.swift */; };
A10000000000000000000012 /* DeviceLinkRelayProbe.mm in Sources */ = {isa = PBXBuildFile; fileRef = A20000000000000000000013 /* DeviceLinkRelayProbe.mm */; settings = {COMPILER_FLAGS = "-fcxx-modules"; }; };
A10000000000000000000013 /* DeviceLinkFraming.mm in Sources */ = {isa = PBXBuildFile; fileRef = A20000000000000000000015 /* DeviceLinkFraming.mm */; settings = {COMPILER_FLAGS = "-fcxx-modules"; }; };
/* End PBXBuildFile section */
/* Begin PBXFileReference section */
13B07F961A680F5B00A75B9A /* TuttiMobile.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = TuttiMobile.app; sourceTree = BUILT_PRODUCTS_DIR; };
13B07FB51A68108700A75B9A /* Images.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Images.xcassets; path = TuttiMobile/Images.xcassets; sourceTree = "<group>"; };
13B07FB61A68108700A75B9A /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = Info.plist; path = TuttiMobile/Info.plist; sourceTree = "<group>"; };
13B07FB81A68108700A75B9A /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = PrivacyInfo.xcprivacy; path = TuttiMobile/PrivacyInfo.xcprivacy; sourceTree = "<group>"; };
3B4392A12AC88292D35C810B /* Pods-TuttiMobile.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-TuttiMobile.debug.xcconfig"; path = "Target Support Files/Pods-TuttiMobile/Pods-TuttiMobile.debug.xcconfig"; sourceTree = "<group>"; };
5709B34CF0A7D63546082F79 /* Pods-TuttiMobile.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-TuttiMobile.release.xcconfig"; path = "Target Support Files/Pods-TuttiMobile/Pods-TuttiMobile.release.xcconfig"; sourceTree = "<group>"; };
5DCACB8F33CDC322A6C60F78 /* libPods-TuttiMobile.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-TuttiMobile.a"; sourceTree = BUILT_PRODUCTS_DIR; };
761780EC2CA45674006654EE /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = AppDelegate.swift; path = TuttiMobile/AppDelegate.swift; sourceTree = "<group>"; };
81AB9BB72411601600AC10FF /* LaunchScreen.storyboard */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.storyboard; name = LaunchScreen.storyboard; path = TuttiMobile/LaunchScreen.storyboard; sourceTree = "<group>"; };
A20000000000000000000001 /* MobileSecurityModule.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = MobileSecurityModule.swift; path = TuttiMobile/MobileSecurityModule.swift; sourceTree = "<group>"; };
A20000000000000000000002 /* MobileBrowserAuthBridge.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = MobileBrowserAuthBridge.swift; path = TuttiMobile/MobileBrowserAuthBridge.swift; sourceTree = "<group>"; };
A20000000000000000000003 /* QRCodeScannerViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = QRCodeScannerViewController.swift; path = TuttiMobile/QRCodeScannerViewController.swift; sourceTree = "<group>"; };
A20000000000000000000004 /* MobileNativeModules.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = MobileNativeModules.m; path = TuttiMobile/MobileNativeModules.m; sourceTree = "<group>"; };
A20000000000000000000005 /* DeviceLinkModule.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; name = DeviceLinkModule.mm; path = TuttiMobile/DeviceLinkModule.mm; sourceTree = "<group>"; };
A20000000000000000000006 /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = en; path = TuttiMobile/en.lproj/Localizable.strings; sourceTree = "<group>"; };
A20000000000000000000007 /* zh-Hans */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = "zh-Hans"; path = "TuttiMobile/zh-Hans.lproj/Localizable.strings"; sourceTree = "<group>"; };
A20000000000000000000008 /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = en; path = TuttiMobile/en.lproj/InfoPlist.strings; sourceTree = "<group>"; };
A20000000000000000000009 /* zh-Hans */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = "zh-Hans"; path = "TuttiMobile/zh-Hans.lproj/InfoPlist.strings"; sourceTree = "<group>"; };
A20000000000000000000010 /* AppLifecycleModule.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = AppLifecycleModule.swift; path = TuttiMobile/AppLifecycleModule.swift; sourceTree = "<group>"; };
A20000000000000000000011 /* MobileWebAuthenticationSession.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = MobileWebAuthenticationSession.swift; path = TuttiMobile/MobileWebAuthenticationSession.swift; sourceTree = "<group>"; };
A20000000000000000000012 /* MobilePreferencesModule.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = MobilePreferencesModule.swift; path = TuttiMobile/MobilePreferencesModule.swift; sourceTree = "<group>"; };
A20000000000000000000013 /* DeviceLinkRelayProbe.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; name = DeviceLinkRelayProbe.mm; path = TuttiMobile/DeviceLinkRelayProbe.mm; sourceTree = "<group>"; };
A20000000000000000000014 /* DeviceLinkRelayProbe.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = DeviceLinkRelayProbe.h; path = TuttiMobile/DeviceLinkRelayProbe.h; sourceTree = "<group>"; };
A20000000000000000000015 /* DeviceLinkFraming.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; name = DeviceLinkFraming.mm; path = TuttiMobile/DeviceLinkFraming.mm; sourceTree = "<group>"; };
A20000000000000000000016 /* DeviceLinkFraming.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = DeviceLinkFraming.h; path = TuttiMobile/DeviceLinkFraming.h; sourceTree = "<group>"; };
ED297162215061F000B7C4FE /* JavaScriptCore.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = JavaScriptCore.framework; path = System/Library/Frameworks/JavaScriptCore.framework; sourceTree = SDKROOT; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
13B07F8C1A680F5B00A75B9A /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
0C80B921A6F3F58F76C31292 /* libPods-TuttiMobile.a in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
13B07FAE1A68108700A75B9A /* TuttiMobile */ = {
isa = PBXGroup;
children = (
13B07FB51A68108700A75B9A /* Images.xcassets */,
761780EC2CA45674006654EE /* AppDelegate.swift */,
A20000000000000000000010 /* AppLifecycleModule.swift */,
A20000000000000000000005 /* DeviceLinkModule.mm */,
A20000000000000000000013 /* DeviceLinkRelayProbe.mm */,
A20000000000000000000014 /* DeviceLinkRelayProbe.h */,
A20000000000000000000015 /* DeviceLinkFraming.mm */,
A20000000000000000000016 /* DeviceLinkFraming.h */,
A20000000000000000000002 /* MobileBrowserAuthBridge.swift */,
A20000000000000000000011 /* MobileWebAuthenticationSession.swift */,
A20000000000000000000012 /* MobilePreferencesModule.swift */,
A20000000000000000000004 /* MobileNativeModules.m */,
A20000000000000000000001 /* MobileSecurityModule.swift */,
A20000000000000000000003 /* QRCodeScannerViewController.swift */,
13B07FB61A68108700A75B9A /* Info.plist */,
A30000000000000000000002 /* InfoPlist.strings */,
A30000000000000000000001 /* Localizable.strings */,
81AB9BB72411601600AC10FF /* LaunchScreen.storyboard */,
13B07FB81A68108700A75B9A /* PrivacyInfo.xcprivacy */,
);
name = TuttiMobile;
sourceTree = "<group>";
};
2D16E6871FA4F8E400B85C8A /* Frameworks */ = {
isa = PBXGroup;
children = (
ED297162215061F000B7C4FE /* JavaScriptCore.framework */,
5DCACB8F33CDC322A6C60F78 /* libPods-TuttiMobile.a */,
);
name = Frameworks;
sourceTree = "<group>";
};
832341AE1AAA6A7D00B99B32 /* Libraries */ = {
isa = PBXGroup;
children = (
);
name = Libraries;
sourceTree = "<group>";
};
83CBB9F61A601CBA00E9B192 = {
isa = PBXGroup;
children = (
13B07FAE1A68108700A75B9A /* TuttiMobile */,
832341AE1AAA6A7D00B99B32 /* Libraries */,
83CBBA001A601CBA00E9B192 /* Products */,
2D16E6871FA4F8E400B85C8A /* Frameworks */,
BBD78D7AC51CEA395F1C20DB /* Pods */,
);
indentWidth = 2;
sourceTree = "<group>";
tabWidth = 2;
usesTabs = 0;
};
83CBBA001A601CBA00E9B192 /* Products */ = {
isa = PBXGroup;
children = (
13B07F961A680F5B00A75B9A /* TuttiMobile.app */,
);
name = Products;
sourceTree = "<group>";
};
BBD78D7AC51CEA395F1C20DB /* Pods */ = {
isa = PBXGroup;
children = (
3B4392A12AC88292D35C810B /* Pods-TuttiMobile.debug.xcconfig */,
5709B34CF0A7D63546082F79 /* Pods-TuttiMobile.release.xcconfig */,
);
path = Pods;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
13B07F861A680F5B00A75B9A /* TuttiMobile */ = {
isa = PBXNativeTarget;
buildConfigurationList = 13B07F931A680F5B00A75B9A /* Build configuration list for PBXNativeTarget "TuttiMobile" */;
buildPhases = (
C38B50BA6285516D6DCD4F65 /* [CP] Check Pods Manifest.lock */,
13B07F871A680F5B00A75B9A /* Sources */,
13B07F8C1A680F5B00A75B9A /* Frameworks */,
13B07F8E1A680F5B00A75B9A /* Resources */,
00DD1BFF1BD5951E006B06BC /* Bundle React Native code and images */,
00EEFC60759A1932668264C0 /* [CP] Embed Pods Frameworks */,
E235C05ADACE081382539298 /* [CP] Copy Pods Resources */,
);
buildRules = (
);
dependencies = (
);
name = TuttiMobile;
productName = TuttiMobile;
productReference = 13B07F961A680F5B00A75B9A /* TuttiMobile.app */;
productType = "com.apple.product-type.application";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
83CBB9F71A601CBA00E9B192 /* Project object */ = {
isa = PBXProject;
attributes = {
LastUpgradeCheck = 1210;
TargetAttributes = {
13B07F861A680F5B00A75B9A = {
LastSwiftMigration = 1120;
};
};
};
buildConfigurationList = 83CBB9FA1A601CBA00E9B192 /* Build configuration list for PBXProject "TuttiMobile" */;
compatibilityVersion = "Xcode 12.0";
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
"zh-Hans",
);
mainGroup = 83CBB9F61A601CBA00E9B192;
productRefGroup = 83CBBA001A601CBA00E9B192 /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
13B07F861A680F5B00A75B9A /* TuttiMobile */,
);
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
13B07F8E1A680F5B00A75B9A /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
81AB9BB82411601600AC10FF /* LaunchScreen.storyboard in Resources */,
13B07FBF1A68108700A75B9A /* Images.xcassets in Resources */,
A10000000000000000000006 /* PrivacyInfo.xcprivacy in Resources */,
A10000000000000000000007 /* Localizable.strings in Resources */,
A10000000000000000000008 /* InfoPlist.strings in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXShellScriptBuildPhase section */
00DD1BFF1BD5951E006B06BC /* Bundle React Native code and images */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
"$(SRCROOT)/.xcode.env.local",
"$(SRCROOT)/.xcode.env",
);
name = "Bundle React Native code and images";
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "set -e\n\nWITH_ENVIRONMENT=\"$REACT_NATIVE_PATH/scripts/xcode/with-environment.sh\"\nREACT_NATIVE_XCODE=\"$REACT_NATIVE_PATH/scripts/react-native-xcode.sh\"\n\n/bin/sh -c \"\\\"$WITH_ENVIRONMENT\\\" \\\"$REACT_NATIVE_XCODE\\\"\"\n";
};
00EEFC60759A1932668264C0 /* [CP] Embed Pods Frameworks */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-TuttiMobile/Pods-TuttiMobile-frameworks-${CONFIGURATION}-input-files.xcfilelist",
);
name = "[CP] Embed Pods Frameworks";
outputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-TuttiMobile/Pods-TuttiMobile-frameworks-${CONFIGURATION}-output-files.xcfilelist",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-TuttiMobile/Pods-TuttiMobile-frameworks.sh\"\n";
showEnvVarsInLog = 0;
};
C38B50BA6285516D6DCD4F65 /* [CP] Check Pods Manifest.lock */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
"${PODS_PODFILE_DIR_PATH}/Podfile.lock",
"${PODS_ROOT}/Manifest.lock",
);
name = "[CP] Check Pods Manifest.lock";
outputPaths = (
"$(DERIVED_FILE_DIR)/Pods-TuttiMobile-checkManifestLockResult.txt",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n";
showEnvVarsInLog = 0;
};
E235C05ADACE081382539298 /* [CP] Copy Pods Resources */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-TuttiMobile/Pods-TuttiMobile-resources-${CONFIGURATION}-input-files.xcfilelist",
);
name = "[CP] Copy Pods Resources";
outputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-TuttiMobile/Pods-TuttiMobile-resources-${CONFIGURATION}-output-files.xcfilelist",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-TuttiMobile/Pods-TuttiMobile-resources.sh\"\n";
showEnvVarsInLog = 0;
};
/* End PBXShellScriptBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
13B07F871A680F5B00A75B9A /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
761780ED2CA45674006654EE /* AppDelegate.swift in Sources */,
A10000000000000000000001 /* MobileSecurityModule.swift in Sources */,
A10000000000000000000002 /* MobileBrowserAuthBridge.swift in Sources */,
A10000000000000000000010 /* MobileWebAuthenticationSession.swift in Sources */,
A10000000000000000000011 /* MobilePreferencesModule.swift in Sources */,
A10000000000000000000003 /* QRCodeScannerViewController.swift in Sources */,
A10000000000000000000004 /* MobileNativeModules.m in Sources */,
A10000000000000000000009 /* AppLifecycleModule.swift in Sources */,
A10000000000000000000005 /* DeviceLinkModule.mm in Sources */,
A10000000000000000000012 /* DeviceLinkRelayProbe.mm in Sources */,
A10000000000000000000013 /* DeviceLinkFraming.mm in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXVariantGroup section */
A30000000000000000000001 /* Localizable.strings */ = {
isa = PBXVariantGroup;
children = (
A20000000000000000000006 /* en */,
A20000000000000000000007 /* zh-Hans */,
);
name = Localizable.strings;
sourceTree = "<group>";
};
A30000000000000000000002 /* InfoPlist.strings */ = {
isa = PBXVariantGroup;
children = (
A20000000000000000000008 /* en */,
A20000000000000000000009 /* zh-Hans */,
);
name = InfoPlist.strings;
sourceTree = "<group>";
};
/* End PBXVariantGroup section */
/* Begin XCBuildConfiguration section */
13B07F941A680F5B00A75B9A /* Debug */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 3B4392A12AC88292D35C810B /* Pods-TuttiMobile.debug.xcconfig */;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CURRENT_PROJECT_VERSION = 1;
ENABLE_BITCODE = NO;
INFOPLIST_FILE = TuttiMobile/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 15.1;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 0.1.0;
OTHER_LDFLAGS = (
"$(inherited)",
"-ObjC",
"-lc++",
);
PRODUCT_BUNDLE_IDENTIFIER = sh.tutti.mobile;
PRODUCT_NAME = TuttiMobile;
SUPPORTED_PLATFORMS = "iphoneos iphonesimulator";
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
VERSIONING_SYSTEM = "apple-generic";
};
name = Debug;
};
13B07F951A680F5B00A75B9A /* Release */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 5709B34CF0A7D63546082F79 /* Pods-TuttiMobile.release.xcconfig */;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CURRENT_PROJECT_VERSION = 1;
INFOPLIST_FILE = TuttiMobile/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 15.1;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 0.1.0;
OTHER_LDFLAGS = (
"$(inherited)",
"-ObjC",
"-lc++",
);
PRODUCT_BUNDLE_IDENTIFIER = sh.tutti.mobile;
PRODUCT_NAME = TuttiMobile;
SUPPORTED_PLATFORMS = "iphoneos iphonesimulator";
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
VERSIONING_SYSTEM = "apple-generic";
};
name = Release;
};
83CBBA201A601CBA00E9B192 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES;
CLANG_CXX_LANGUAGE_STANDARD = "c++20";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_UNREACHABLE_CODE = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
COPY_PHASE_STRIP = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
IPHONEOS_DEPLOYMENT_TARGET = 15.1;
MTL_ENABLE_DEBUG_INFO = YES;
ONLY_ACTIVE_ARCH = YES;
OTHER_CFLAGS = (
"$(inherited)",
"-DRCT_REMOVE_LEGACY_ARCH=1",
);
OTHER_CPLUSPLUSFLAGS = (
"$(inherited)",
"-DRCT_REMOVE_LEGACY_ARCH=1",
);
PODFILE_DIR = "$(SRCROOT)";
REACT_NATIVE_PATH = "${SRCROOT}/../node_modules/react-native";
SDKROOT = iphoneos;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) DEBUG";
SWIFT_ENABLE_EXPLICIT_MODULES = NO;
USE_HERMES = true;
};
name = Debug;
};
83CBBA211A601CBA00E9B192 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES;
CLANG_CXX_LANGUAGE_STANDARD = "c++20";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_UNREACHABLE_CODE = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
COPY_PHASE_STRIP = YES;
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_NO_COMMON_BLOCKS = YES;
IPHONEOS_DEPLOYMENT_TARGET = 15.1;
MTL_ENABLE_DEBUG_INFO = NO;
OTHER_CFLAGS = (
"$(inherited)",
"-DRCT_REMOVE_LEGACY_ARCH=1",
);
OTHER_CPLUSPLUSFLAGS = (
"$(inherited)",
"-DRCT_REMOVE_LEGACY_ARCH=1",
);
PODFILE_DIR = "$(SRCROOT)";
REACT_NATIVE_PATH = "${SRCROOT}/../node_modules/react-native";
SDKROOT = iphoneos;
SWIFT_ENABLE_EXPLICIT_MODULES = NO;
USE_HERMES = true;
VALIDATE_PRODUCT = YES;
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
13B07F931A680F5B00A75B9A /* Build configuration list for PBXNativeTarget "TuttiMobile" */ = {
isa = XCConfigurationList;
buildConfigurations = (
13B07F941A680F5B00A75B9A /* Debug */,
13B07F951A680F5B00A75B9A /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
83CBB9FA1A601CBA00E9B192 /* Build configuration list for PBXProject "TuttiMobile" */ = {
isa = XCConfigurationList;
buildConfigurations = (
83CBBA201A601CBA00E9B192 /* Debug */,
83CBBA211A601CBA00E9B192 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = 83CBB9F71A601CBA00E9B192 /* Project object */;
}
@@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme LastUpgradeVersion = "1210" version = "1.3">
<BuildAction parallelizeBuildables = "YES" buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry buildForTesting = "YES" buildForRunning = "YES" buildForProfiling = "YES" buildForArchiving = "YES" buildForAnalyzing = "YES">
<BuildableReference BuildableIdentifier = "primary" BlueprintIdentifier = "13B07F861A680F5B00A75B9A" BuildableName = "TuttiMobile.app" BlueprintName = "TuttiMobile" ReferencedContainer = "container:TuttiMobile.xcodeproj"/>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction buildConfiguration = "Debug" selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" shouldUseLaunchSchemeArgsEnv = "YES"/>
<LaunchAction buildConfiguration = "Debug" selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" launchStyle = "0" useCustomWorkingDirectory = "NO" ignoresPersistentStateOnLaunch = "NO" debugDocumentVersioning = "YES" debugServiceExtension = "internal" allowLocationSimulation = "YES">
<BuildableProductRunnable runnableDebuggingMode = "0">
<BuildableReference BuildableIdentifier = "primary" BlueprintIdentifier = "13B07F861A680F5B00A75B9A" BuildableName = "TuttiMobile.app" BlueprintName = "TuttiMobile" ReferencedContainer = "container:TuttiMobile.xcodeproj"/>
</BuildableProductRunnable>
</LaunchAction>
<ProfileAction buildConfiguration = "Release" shouldUseLaunchSchemeArgsEnv = "YES" savedToolIdentifier = "" useCustomWorkingDirectory = "NO" debugDocumentVersioning = "YES">
<BuildableProductRunnable runnableDebuggingMode = "0">
<BuildableReference BuildableIdentifier = "primary" BlueprintIdentifier = "13B07F861A680F5B00A75B9A" BuildableName = "TuttiMobile.app" BlueprintName = "TuttiMobile" ReferencedContainer = "container:TuttiMobile.xcodeproj"/>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction buildConfiguration = "Debug"/>
<ArchiveAction buildConfiguration = "Release" revealArchiveInOrganizer = "YES"/>
</Scheme>
@@ -0,0 +1,47 @@
import React
import ReactAppDependencyProvider
import React_RCTAppDelegate
import UIKit
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var reactNativeDelegate: ReactNativeDelegate?
var reactNativeFactory: RCTReactNativeFactory?
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
) -> Bool {
let delegate = ReactNativeDelegate()
let factory = RCTReactNativeFactory(delegate: delegate)
delegate.dependencyProvider = RCTAppDependencyProvider()
reactNativeDelegate = delegate
reactNativeFactory = factory
window = UIWindow(frame: UIScreen.main.bounds)
factory.startReactNative(
withModuleName: "TuttiMobile",
in: window,
launchOptions: launchOptions
)
return true
}
}
final class ReactNativeDelegate: RCTDefaultReactNativeFactoryDelegate {
override func sourceURL(for bridge: RCTBridge) -> URL? {
bundleURL()
}
override func bundleURL() -> URL? {
#if DEBUG
RCTBundleURLProvider.sharedSettings().jsBundleURL(forBundleRoot: "index")
#else
Bundle.main.url(forResource: "main", withExtension: "jsbundle")
#endif
}
}
@@ -0,0 +1,68 @@
import React
import UIKit
@objc(TuttiAppLifecycle)
final class AppLifecycleModule: RCTEventEmitter {
private var observing = false
@objc
override static func requiresMainQueueSetup() -> Bool {
true
}
override func supportedEvents() -> [String] {
[Self.eventName]
}
@objc
func isForeground() -> NSNumber {
if Thread.isMainThread {
return NSNumber(
value: UIApplication.shared.applicationState != .background
)
}
return DispatchQueue.main.sync {
NSNumber(value: UIApplication.shared.applicationState != .background)
}
}
override func startObserving() {
guard !observing else {
return
}
observing = true
NotificationCenter.default.addObserver(
self,
selector: #selector(applicationDidBecomeActive),
name: UIApplication.didBecomeActiveNotification,
object: nil
)
NotificationCenter.default.addObserver(
self,
selector: #selector(applicationDidEnterBackground),
name: UIApplication.didEnterBackgroundNotification,
object: nil
)
}
override func stopObserving() {
observing = false
NotificationCenter.default.removeObserver(self)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
@objc
private func applicationDidBecomeActive() {
sendEvent(withName: Self.eventName, body: true)
}
@objc
private func applicationDidEnterBackground() {
sendEvent(withName: Self.eventName, body: false)
}
private static let eventName = "TuttiAppLifecycleChanged"
}
@@ -0,0 +1,16 @@
#import <Foundation/Foundation.h>
#import <TuttiMobileGo/TUTMobile.objc.h>
NS_ASSUME_NONNULL_BEGIN
FOUNDATION_EXPORT BOOL TUTDeviceLinkWriteFully(TUTMobileStream *stream,
NSData *payload,
NSError **error);
FOUNDATION_EXPORT NSData *_Nullable
TUTDeviceLinkReadFully(TUTMobileStream *stream, NSUInteger size,
NSError **error);
FOUNDATION_EXPORT NSData *TUTDeviceLinkFrame(NSData *payload);
FOUNDATION_EXPORT NSUInteger TUTDeviceLinkReadFrameSize(
TUTMobileStream *stream, NSUInteger maximum, NSError **error);
NS_ASSUME_NONNULL_END
@@ -0,0 +1,85 @@
#import "DeviceLinkFraming.h"
static const NSUInteger TUTDeviceLinkFramingMaxReadChunk = 1 << 20;
static NSError *TUTDeviceLinkFramingError(NSString *code, NSString *message) {
return [NSError errorWithDomain:@"sh.tutti.mobile.device-link"
code:1
userInfo:@{
NSLocalizedDescriptionKey : message,
@"code" : code,
}];
}
BOOL TUTDeviceLinkWriteFully(TUTMobileStream *stream, NSData *payload,
NSError **error) {
NSUInteger offset = 0;
while (offset < payload.length) {
NSData *chunk = offset == 0
? payload
: [payload subdataWithRange:NSMakeRange(
offset, payload.length - offset)];
long written = 0;
if (![stream write:chunk ret0_:&written error:error]) {
return NO;
}
if (written <= 0 || (NSUInteger)written > chunk.length) {
if (error != NULL) {
*error = TUTDeviceLinkFramingError(
@"INVALID_WRITE",
@"DeviceLink stream returned an invalid write count");
}
return NO;
}
offset += (NSUInteger)written;
}
return YES;
}
NSData *TUTDeviceLinkReadFully(TUTMobileStream *stream, NSUInteger size,
NSError **error) {
NSMutableData *output = [NSMutableData dataWithCapacity:size];
while (output.length < size) {
NSUInteger remaining = size - output.length;
NSMutableData *chunk = [NSMutableData
dataWithLength:MIN(remaining, TUTDeviceLinkFramingMaxReadChunk)];
long count = [stream readInto:chunk];
if (count <= 0 || (NSUInteger)count > chunk.length) {
if (error != NULL) {
*error = TUTDeviceLinkFramingError(
@"INCOMPLETE_FRAME",
@"DeviceLink stream closed before the response completed");
}
return nil;
}
[output appendBytes:chunk.bytes length:(NSUInteger)count];
}
return output;
}
NSData *TUTDeviceLinkFrame(NSData *payload) {
uint32_t size = CFSwapInt32HostToBig((uint32_t)payload.length);
NSMutableData *framed =
[NSMutableData dataWithBytes:&size length:sizeof(size)];
[framed appendData:payload];
return framed;
}
NSUInteger TUTDeviceLinkReadFrameSize(TUTMobileStream *stream,
NSUInteger maximum, NSError **error) {
NSData *header = TUTDeviceLinkReadFully(stream, sizeof(uint32_t), error);
if (header == nil) {
return 0;
}
uint32_t encoded = 0;
[header getBytes:&encoded length:sizeof(encoded)];
NSUInteger size = (NSUInteger)CFSwapInt32BigToHost(encoded);
if (size == 0 || size > maximum) {
if (error != NULL) {
*error = TUTDeviceLinkFramingError(
@"INVALID_FRAME", @"DeviceLink frame size is invalid");
}
return 0;
}
return size;
}
@@ -0,0 +1,929 @@
#import <Foundation/Foundation.h>
#import <React/RCTBridgeModule.h>
#import <React/RCTEventEmitter.h>
#import <React/RCTLog.h>
#import <TuttiMobileGo/TUTLiveprotocolmobile.objc.h>
#import <TuttiMobileGo/TUTMobile.objc.h>
#import <UIKit/UIKit.h>
#import "DeviceLinkFraming.h"
#import "DeviceLinkRelayProbe.h"
static NSString *const TUTAgentLiveEventName = @"TuttiDeviceLinkAgentLive";
static const int64_t TUTAgentLiveOpenTimeoutMillis = 10000;
static const NSTimeInterval TUTBackgroundGraceSeconds = 15.0;
static const NSUInteger TUTMaxAgentLiveFrameBytes = 2 << 20;
static const NSUInteger TUTMaxReadChunk = 1 << 20;
static const NSUInteger TUTMaxRequestBodyBytes = 8 << 20;
static const NSUInteger TUTMaxResponseBodyBytes = 16 << 20;
static const NSUInteger TUTFrameEnvelopeBytes = 1 << 20;
static const NSUInteger TUTMaxRequestFrameBytes =
((TUTMaxRequestBodyBytes + 2) / 3 * 4) + TUTFrameEnvelopeBytes;
static const NSUInteger TUTMaxResponseFrameBytes =
((TUTMaxResponseBodyBytes + 2) / 3 * 4) + TUTFrameEnvelopeBytes;
static NSError *TUTDeviceLinkError(NSString *code, NSString *message) {
return [NSError errorWithDomain:@"sh.tutti.mobile.device-link"
code:1
userInfo:@{
NSLocalizedDescriptionKey : message,
@"code" : code,
}];
}
static NSData *TUTJSONData(id value, NSError **error) {
return [NSJSONSerialization dataWithJSONObject:value options:0 error:error];
}
static NSDictionary *TUTJSONObject(NSData *data, NSError **error) {
id value = [NSJSONSerialization JSONObjectWithData:data options:0 error:error];
if (![value isKindOfClass:[NSDictionary class]]) {
if (error != NULL && *error == nil) {
*error = TUTDeviceLinkError(@"INVALID_RESPONSE",
@"DeviceLink response is not an object");
}
return nil;
}
return value;
}
@interface TuttiDeviceLink : RCTEventEmitter <RCTBridgeModule>
@property(nonatomic, strong) TUTMobileLink *link;
@property(nonatomic, strong) TUTMobileStream *agentLiveStream;
@property(nonatomic, copy) NSString *relayEndpoint;
@property(nonatomic, copy) NSString *relayQueryJSON;
@property(nonatomic, copy) NSString *relayHeadersJSON;
@property(nonatomic, copy) NSString *relaySubprotocol;
@property(nonatomic, assign) int64_t linkGeneration;
@property(nonatomic, assign) int64_t agentLiveGeneration;
@property(nonatomic, strong) dispatch_queue_t operationQueue;
@property(nonatomic, strong) dispatch_queue_t closeQueue;
@property(nonatomic, strong) dispatch_queue_t agentLiveQueue;
@property(nonatomic, strong) dispatch_block_t backgroundClose;
@property(nonatomic, assign) BOOL observing;
@end
@implementation TuttiDeviceLink
RCT_EXPORT_MODULE(TuttiDeviceLink)
+ (BOOL)requiresMainQueueSetup {
return NO;
}
- (instancetype)init {
self = [super init];
if (self != nil) {
_operationQueue = dispatch_queue_create(
"sh.tutti.mobile.device-link.operations", DISPATCH_QUEUE_CONCURRENT);
_closeQueue = dispatch_queue_create("sh.tutti.mobile.device-link.close",
DISPATCH_QUEUE_SERIAL);
_agentLiveQueue = dispatch_queue_create(
"sh.tutti.mobile.device-link.agent-live", DISPATCH_QUEUE_SERIAL);
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(applicationDidEnterBackground)
name:UIApplicationDidEnterBackgroundNotification
object:nil];
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(applicationWillEnterForeground)
name:UIApplicationWillEnterForegroundNotification
object:nil];
}
return self;
}
- (NSArray<NSString *> *)supportedEvents {
return @[ TUTAgentLiveEventName ];
}
- (void)startObserving {
@synchronized(self) {
self.observing = YES;
}
}
- (void)stopObserving {
@synchronized(self) {
self.observing = NO;
}
}
RCT_REMAP_METHOD(probeEpoch,
probeEpochWithResolver:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject) {
resolve(@(TUTMobileProbeEpoch()));
}
RCT_REMAP_METHOD(protocolEpoch,
protocolEpochWithResolver:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject) {
resolve(@(TUTMobileProtocolEpoch()));
}
RCT_REMAP_METHOD(runLoopbackProbe,
runLoopbackProbe:(double)timeoutMillis
resolver:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject) {
dispatch_async(self.operationQueue, ^{
NSError *error = nil;
NSString *result =
TUTMobileRunLoopbackProbe((int64_t)timeoutMillis, &error);
if (error != nil) {
reject(@"DEVICE_LINK_PROBE_FAILED", @"DeviceLink probe failed", error);
return;
}
resolve(result);
});
}
RCT_REMAP_METHOD(prepareLink,
prepareLink:(NSString *)stunEndpointsJSON
timeoutMillis:(double)timeoutMillis
resolver:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject) {
(void)timeoutMillis;
int64_t generation = [self beginLinkOperation];
dispatch_async(self.operationQueue, ^{
NSError *error = nil;
TUTMobileLink *prepared = TUTMobileNewLink(stunEndpointsJSON, &error);
if (prepared == nil || error != nil) {
[self closeDetachedLink:[self cancelLinkOperation:generation]];
reject(@"DEVICE_LINK_PREPARE_FAILED", @"Unable to prepare DeviceLink",
error);
return;
}
NSString *description = [prepared startLocalDescription:&error];
if (description == nil || error != nil) {
[self closeDetachedLink:prepared];
[self closeDetachedLink:[self cancelLinkOperation:generation]];
reject(@"DEVICE_LINK_PREPARE_FAILED", @"Unable to prepare DeviceLink",
error);
return;
}
if (![self promoteLink:prepared generation:generation]) {
[self closeDetachedLink:prepared];
reject(@"DEVICE_LINK_PREPARE_FAILED",
@"DeviceLink prepare was cancelled",
TUTDeviceLinkError(@"CANCELLED",
@"DeviceLink prepare was cancelled"));
return;
}
resolve(@{
@"descriptionJSON" : description,
@"token" : @(generation),
});
});
}
RCT_REMAP_METHOD(nextCandidateExchangeAction,
nextCandidateExchangeAction:(double)token
timeoutMillis:(double)timeoutMillis
resolver:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject) {
TUTMobileLink *selected = [self linkSnapshotForGeneration:(int64_t)token];
if (selected == nil) {
reject(@"DEVICE_LINK_CANDIDATE_FAILED",
@"DeviceLink preparation is no longer current", nil);
return;
}
dispatch_async(self.operationQueue, ^{
NSError *error = nil;
NSString *action = [selected
nextCandidateExchangeAction:(int64_t)timeoutMillis
error:&error];
if (action == nil || error != nil) {
reject(@"DEVICE_LINK_CANDIDATE_FAILED",
@"Unable to read DeviceLink candidate action", error);
return;
}
resolve(action);
});
}
RCT_REMAP_METHOD(resolveCandidateExchangeAction,
resolveCandidateExchangeAction:(double)actionId
succeeded:(BOOL)succeeded
retryable:(BOOL)retryable
candidatesJSON:(NSString *)candidatesJSON
token:(double)token
resolver:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject) {
TUTMobileLink *selected = [self linkSnapshotForGeneration:(int64_t)token];
if (selected == nil) {
reject(@"DEVICE_LINK_CANDIDATE_FAILED",
@"DeviceLink preparation is no longer current", nil);
return;
}
dispatch_async(self.operationQueue, ^{
NSError *error = nil;
long added = 0;
BOOL resolved = [selected
resolveCandidateExchangeAction:(int64_t)actionId
succeeded:succeeded
retryable:retryable
candidatesJSON:candidatesJSON
ret0_:&added
error:&error];
if (!resolved || error != nil) {
reject(@"DEVICE_LINK_CANDIDATE_FAILED",
@"Unable to resolve DeviceLink candidate action", error);
return;
}
resolve(@(added));
});
}
RCT_REMAP_METHOD(notifyRemoteCandidateChange,
notifyRemoteCandidateChange:(double)token
resolver:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject) {
TUTMobileLink *selected = [self linkSnapshotForGeneration:(int64_t)token];
if (selected == nil) {
reject(@"DEVICE_LINK_CANDIDATE_FAILED",
@"DeviceLink preparation is no longer current", nil);
return;
}
NSError *error = nil;
if (![selected notifyRemoteCandidateChange:&error]) {
reject(@"DEVICE_LINK_CANDIDATE_FAILED",
@"Unable to notify DeviceLink candidate change", error);
return;
}
resolve(nil);
}
RCT_REMAP_METHOD(stopCandidateExchange,
stopCandidateExchange:(double)token
resolver:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject) {
TUTMobileLink *selected = [self linkSnapshotForGeneration:(int64_t)token];
if (selected != nil) {
[selected stopCandidateExchange];
}
resolve(nil);
}
RCT_REMAP_METHOD(cancelLink,
cancelLink:(double)token
resolver:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject) {
[self closeDetachedLink:[self cancelLinkOperation:(int64_t)token]];
resolve(nil);
}
RCT_REMAP_METHOD(connectLink,
connectLink:(NSString *)peerDescriptionJSON
caller:(BOOL)caller
token:(double)token
timeoutMillis:(double)timeoutMillis
resolver:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject) {
TUTMobileLink *selected = [self linkSnapshotForGeneration:(int64_t)token];
if (selected == nil) {
reject(@"DEVICE_LINK_CONNECT_FAILED",
@"DeviceLink preparation is no longer current", nil);
return;
}
dispatch_async(self.operationQueue, ^{
NSError *error = nil;
NSString *scope = [selected connect:peerDescriptionJSON
caller:caller
timeoutMillis:(int64_t)timeoutMillis
error:&error];
if (error != nil) {
reject(@"DEVICE_LINK_CONNECT_FAILED", @"Unable to connect DeviceLink",
error);
return;
}
resolve(scope);
});
}
RCT_REMAP_METHOD(configureRelay,
configureRelay:(NSString *)endpoint
queryJSON:(NSString *)queryJSON
headersJSON:(NSString *)headersJSON
subprotocol:(NSString *)subprotocol
resolver:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject) {
NSString *normalizedEndpoint =
[endpoint stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSString *normalizedSubprotocol =
[subprotocol stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if (normalizedEndpoint.length == 0 || normalizedSubprotocol.length == 0) {
reject(@"DEVICE_LINK_RELAY_CONFIG_FAILED",
@"Relay endpoint and subprotocol are required", nil);
return;
}
@synchronized(self) {
self.relayEndpoint = normalizedEndpoint;
self.relayQueryJSON = queryJSON ?: @"";
self.relayHeadersJSON = headersJSON ?: @"";
self.relaySubprotocol = normalizedSubprotocol;
}
resolve(nil);
}
RCT_REMAP_METHOD(probeRelay,
probeRelay:(double)timeoutMillis
resolver:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject) {
NSDictionary *relay = [self relaySnapshot];
if (relay == nil) {
reject(@"DEVICE_LINK_RELAY_PROBE_FAILED",
@"DeviceLink Relay is not configured", nil);
return;
}
int64_t timeout = MAX((int64_t)timeoutMillis, 1);
TUTDeviceLinkProbeRelay(
relay, timeout, self.operationQueue,
^NSDictionary *(TUTMobileStream *stream, int64_t requestTimeout,
NSError **error) {
return [self requestAgentHTTPWithStream:stream
method:@"GET"
path:@"/v1/preferences/desktop"
body:@""
timeoutMillis:requestTimeout
error:error];
},
^(NSError *error) {
if (error != nil) {
reject(@"DEVICE_LINK_RELAY_PROBE_FAILED", @"Relay peer handshake failed",
error);
return;
}
resolve(nil);
});
}
RCT_REMAP_METHOD(requestAgentHTTP,
requestAgentHTTP:(NSString *)method
path:(NSString *)path
body:(NSString *)body
timeoutMillis:(double)timeoutMillis
resolver:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject) {
TUTMobileLink *selected = [self linkSnapshot];
NSDictionary *relay = [self relaySnapshot];
if (selected == nil && relay == nil) {
reject(@"DEVICE_LINK_REQUEST_FAILED", @"DeviceLink is not prepared", nil);
return;
}
dispatch_async(self.operationQueue, ^{
NSError *error = nil;
NSDictionary *response = nil;
if (selected != nil) {
response = [self requestAgentHTTPWithLink:selected
relay:relay
method:method
path:path
body:body
timeoutMillis:(int64_t)timeoutMillis
error:&error];
} else if (relay != nil) {
NSError *relayError = nil;
TUTMobileStream *stream = TUTMobileDialRelay(
relay[@"endpoint"], relay[@"queryJSON"], relay[@"headersJSON"],
relay[@"subprotocol"], (int64_t)timeoutMillis, &relayError);
if (stream != nil && relayError == nil) {
response = [self requestAgentHTTPWithStream:stream
method:method
path:path
body:body
timeoutMillis:(int64_t)timeoutMillis
error:&relayError];
}
if (response != nil) {
error = nil;
} else {
error = relayError;
}
}
if (response == nil || error != nil) {
reject(@"DEVICE_LINK_REQUEST_FAILED", @"DeviceLink request failed",
error);
return;
}
resolve(response);
});
}
RCT_REMAP_METHOD(startAgentLive,
startAgentLive:(NSString *)workspaceID
subscriptionGeneration:(nonnull NSNumber *)subscriptionGeneration
resolver:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject) {
NSString *normalized =
[workspaceID stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if (normalized.length == 0) {
reject(@"AGENT_LIVE_SUBSCRIBE_FAILED",
@"Agent live workspace id is required", nil);
return;
}
if (subscriptionGeneration.longLongValue <= 0 ||
subscriptionGeneration.doubleValue !=
(double)subscriptionGeneration.longLongValue) {
reject(@"AGENT_LIVE_SUBSCRIBE_FAILED",
@"Agent live subscription generation must be a positive integer",
nil);
return;
}
TUTMobileLink *selected = [self linkSnapshot];
NSDictionary *relay = [self relaySnapshot];
if (selected == nil && relay == nil) {
reject(@"AGENT_LIVE_SUBSCRIBE_FAILED", @"DeviceLink is not prepared", nil);
return;
}
int64_t generation = [self beginAgentLiveOperation];
dispatch_async(self.agentLiveQueue, ^{
NSError *error = nil;
TUTMobileStream *stream = [self openAgentStream:selected
relay:relay
timeoutMillis:TUTAgentLiveOpenTimeoutMillis
error:&error];
if (stream == nil || error != nil) {
reject(@"AGENT_LIVE_SUBSCRIBE_FAILED",
@"Unable to start Agent live subscription", error);
return;
}
if (![self promoteAgentLiveStream:stream generation:generation]) {
[self closeDetachedStream:stream];
reject(@"AGENT_LIVE_SUBSCRIBE_FAILED",
@"Agent live subscription was cancelled", nil);
return;
}
TUTLiveprotocolmobileSubscriber *subscriber =
TUTLiveprotocolmobileNewSubscriber(0, 0, &error);
if (subscriber == nil || error != nil) {
[self clearAgentLiveStream:stream generation:generation];
[self closeDetachedStream:stream];
reject(@"AGENT_LIVE_SUBSCRIBE_FAILED",
@"Unable to create Agent live subscriber", error);
return;
}
NSDictionary *subscription = @{
@"protocolRevision" : TUTLiveprotocolmobileProtocolRevision(),
@"workspaceId" : normalized,
};
NSData *subscriptionData = TUTJSONData(subscription, &error);
if (subscriptionData == nil || error != nil) {
[self clearAgentLiveStream:stream generation:generation];
[self closeDetachedStream:stream];
reject(@"AGENT_LIVE_SUBSCRIBE_FAILED",
@"Unable to encode Agent live subscription", error);
return;
}
NSString *requestID = [NSUUID UUID].UUIDString;
NSDictionary *request = @{
@"protocolEpoch" : @(TUTMobileProtocolEpoch()),
@"service" : @"agent_live",
@"requestId" : requestID,
@"method" : @"SUBSCRIBE",
@"path" : [NSString
stringWithFormat:@"/v1/workspaces/%@/agent-live", normalized],
@"body" : [subscriptionData base64EncodedStringWithOptions:0],
};
NSData *requestData = TUTJSONData(request, &error);
if (requestData == nil || requestData.length > TUTMaxRequestFrameBytes ||
!TUTDeviceLinkWriteFully(stream, TUTDeviceLinkFrame(requestData),
&error)) {
[self clearAgentLiveStream:stream generation:generation];
[self closeDetachedStream:stream];
reject(@"AGENT_LIVE_SUBSCRIBE_FAILED",
@"Unable to start Agent live subscription", error);
return;
}
resolve(nil);
while ([self isAgentLiveCurrent:stream generation:generation]) {
NSUInteger size =
TUTDeviceLinkReadFrameSize(stream, TUTMaxAgentLiveFrameBytes,
&error);
if (size == 0) {
break;
}
NSData *frame = TUTDeviceLinkReadFully(stream, size, &error);
NSString *result =
frame == nil ? nil
: [subscriber apply:frame error:&error];
if (result == nil || error != nil) {
break;
}
if ([self isAgentLiveCurrent:stream generation:generation]) {
NSDictionary *delivery = @{
@"workspaceId" : normalized,
@"subscriptionGeneration" : subscriptionGeneration,
@"result" : [self objectFromJSONString:result] ?: @{},
};
NSData *encoded = TUTJSONData(delivery, nil);
NSString *payload =
[[NSString alloc] initWithData:encoded encoding:NSUTF8StringEncoding];
[self emitAgentLive:payload];
}
}
BOOL current =
[self isAgentLiveGenerationCurrent:generation];
[self clearAgentLiveStream:stream generation:generation];
[self closeDetachedStream:stream];
if (current) {
NSData *encoded = TUTJSONData(@{
@"workspaceId" : normalized,
@"subscriptionGeneration" : subscriptionGeneration,
@"status" : @"disconnected",
@"reason" : @"stream_closed",
}, nil);
[self emitAgentLive:[[NSString alloc] initWithData:encoded
encoding:NSUTF8StringEncoding]];
}
});
}
RCT_REMAP_METHOD(stopAgentLive,
stopAgentLiveWithResolver:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject) {
[self closeCurrentAgentLiveStream];
resolve(nil);
}
RCT_REMAP_METHOD(closeLink,
closeLinkWithResolver:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject) {
[self closeCurrentLink];
resolve(nil);
}
- (NSDictionary *)requestAgentHTTPWithLink:(TUTMobileLink *)link
relay:(NSDictionary *)relay
method:(NSString *)method
path:(NSString *)path
body:(NSString *)body
timeoutMillis:(int64_t)timeoutMillis
error:(NSError **)error {
int64_t timeout = MAX(timeoutMillis, 1);
TUTMobileStream *stream = nil;
if (relay != nil) {
stream = [link openStreamWithRelay:relay[@"endpoint"]
queryJSON:relay[@"queryJSON"]
headersJSON:relay[@"headersJSON"]
subprotocol:relay[@"subprotocol"]
timeoutMillis:timeout
error:error];
} else {
stream = [link openStream:timeout error:error];
}
if (stream == nil) {
return nil;
}
return [self requestAgentHTTPWithStream:stream
method:method
path:path
body:body
timeoutMillis:timeoutMillis
error:error];
}
- (NSDictionary *)requestAgentHTTPWithStream:(TUTMobileStream *)stream
method:(NSString *)method
path:(NSString *)path
body:(NSString *)body
timeoutMillis:(int64_t)timeoutMillis
error:(NSError **)error {
int64_t timeout = MAX(timeoutMillis, 1);
NSDate *deadline = [NSDate dateWithTimeIntervalSinceNow:timeout / 1000.0];
@try {
int64_t remaining =
MAX((int64_t)([deadline timeIntervalSinceNow] * 1000.0), 1);
if (![stream setDeadline:remaining error:error]) {
return nil;
}
NSData *bodyData = [body dataUsingEncoding:NSUTF8StringEncoding];
if (bodyData.length > TUTMaxRequestBodyBytes) {
if (error != NULL) {
*error = TUTDeviceLinkError(
@"REQUEST_TOO_LARGE",
@"DeviceLink request body exceeds the supported limit");
}
return nil;
}
NSString *requestID = [NSUUID UUID].UUIDString;
NSDictionary *request = @{
@"protocolEpoch" : @(TUTMobileProtocolEpoch()),
@"service" : @"agent_http",
@"requestId" : requestID,
@"method" : method,
@"path" : path,
@"headers" : @{
@"Accept" : @[ @"application/json" ],
@"Content-Type" : @[ @"application/json" ],
},
@"body" : [bodyData base64EncodedStringWithOptions:0],
};
NSData *payload = TUTJSONData(request, error);
if (payload == nil || payload.length > TUTMaxRequestFrameBytes) {
return nil;
}
if (!TUTDeviceLinkWriteFully(stream, TUTDeviceLinkFrame(payload), error)) {
return nil;
}
NSUInteger responseSize =
TUTDeviceLinkReadFrameSize(stream, TUTMaxResponseFrameBytes, error);
if (responseSize == 0) {
return nil;
}
NSData *responseData =
TUTDeviceLinkReadFully(stream, responseSize, error);
if (responseData == nil) {
return nil;
}
NSDictionary *response = TUTJSONObject(responseData, error);
if (response == nil ||
![response[@"requestId"] isEqualToString:requestID]) {
if (error != NULL && *error == nil) {
*error = TUTDeviceLinkError(
@"INVALID_RESPONSE",
@"DeviceLink response request id does not match");
}
return nil;
}
NSString *encodedBody =
[response[@"body"] isKindOfClass:[NSString class]]
? response[@"body"]
: @"";
NSData *decoded =
[[NSData alloc] initWithBase64EncodedString:encodedBody options:0];
NSString *responseBody =
decoded == nil
? @""
: [[NSString alloc] initWithData:decoded
encoding:NSUTF8StringEncoding] ?: @"";
return @{
@"protocolEpoch" : response[@"protocolEpoch"] ?: @0,
@"status" : response[@"status"] ?: @0,
@"body" : responseBody,
@"errorCode" : response[@"errorCode"] ?: @"",
@"headers" : [response[@"headers"] isKindOfClass:[NSDictionary class]]
? response[@"headers"]
: @{},
};
} @finally {
[stream close:nil];
}
}
- (NSDictionary *)relaySnapshot {
@synchronized(self) {
if (self.relayEndpoint.length == 0 ||
self.relaySubprotocol.length == 0) {
return nil;
}
return @{
@"endpoint" : self.relayEndpoint,
@"queryJSON" : self.relayQueryJSON ?: @"",
@"headersJSON" : self.relayHeadersJSON ?: @"",
@"subprotocol" : self.relaySubprotocol,
};
}
}
- (TUTMobileStream *)openAgentStream:(TUTMobileLink *)link
relay:(NSDictionary *)relay
timeoutMillis:(int64_t)timeoutMillis
error:(NSError **)error {
NSError *directError = nil;
if (link != nil) {
TUTMobileStream *stream = relay != nil
? [link openStreamWithRelay:
relay[@"endpoint"]
queryJSON:relay[@"queryJSON"]
headersJSON:relay[@"headersJSON"]
subprotocol:relay[@"subprotocol"]
timeoutMillis:MAX(timeoutMillis, 1)
error:&directError]
: [link openStream:MAX(timeoutMillis, 1)
error:&directError];
if (stream != nil) {
return stream;
}
if (relay != nil) {
if (error != NULL) {
*error = directError;
}
return nil;
}
}
if (relay != nil) {
NSError *relayError = nil;
TUTMobileStream *stream = TUTMobileDialRelay(
relay[@"endpoint"], relay[@"queryJSON"], relay[@"headersJSON"],
relay[@"subprotocol"], MAX(timeoutMillis, 1), &relayError);
if (stream != nil) {
return stream;
}
if (error != NULL) {
*error = relayError ?: directError;
}
return nil;
}
if (error != NULL) {
*error = directError;
}
return nil;
}
- (NSDictionary *)objectFromJSONString:(NSString *)json {
NSData *data = [json dataUsingEncoding:NSUTF8StringEncoding];
return data == nil ? nil : TUTJSONObject(data, nil);
}
- (int64_t)beginLinkOperation {
@synchronized(self) {
self.linkGeneration += 1;
return self.linkGeneration;
}
}
- (BOOL)promoteLink:(TUTMobileLink *)next generation:(int64_t)generation {
TUTMobileLink *previous = nil;
@synchronized(self) {
if (generation != self.linkGeneration) {
return NO;
}
previous = self.link;
self.link = next;
}
if (previous != nil && previous != next) {
[self closeDetachedLink:previous];
}
return YES;
}
- (TUTMobileLink *)linkSnapshot {
@synchronized(self) {
return self.link;
}
}
- (TUTMobileLink *)linkSnapshotForGeneration:(int64_t)generation {
@synchronized(self) {
return generation == self.linkGeneration ? self.link : nil;
}
}
- (void)closeCurrentLink {
[self closeCurrentAgentLiveStream];
TUTMobileLink *previous = nil;
@synchronized(self) {
self.linkGeneration += 1;
previous = self.link;
self.link = nil;
self.relayEndpoint = nil;
self.relayQueryJSON = nil;
self.relayHeadersJSON = nil;
self.relaySubprotocol = nil;
}
[self closeDetachedLink:previous];
}
- (TUTMobileLink *)cancelLinkOperation:(int64_t)generation {
@synchronized(self) {
if (generation != self.linkGeneration) {
return nil;
}
self.linkGeneration += 1;
TUTMobileLink *previous = self.link;
self.link = nil;
return previous;
}
}
- (void)closeDetachedLink:(TUTMobileLink *)link {
if (link == nil) {
return;
}
dispatch_async(self.closeQueue, ^{
[link close:nil];
});
}
- (int64_t)beginAgentLiveOperation {
TUTMobileStream *previous = nil;
int64_t generation = 0;
@synchronized(self) {
self.agentLiveGeneration += 1;
generation = self.agentLiveGeneration;
previous = self.agentLiveStream;
self.agentLiveStream = nil;
}
[self closeDetachedStream:previous];
return generation;
}
- (BOOL)promoteAgentLiveStream:(TUTMobileStream *)stream
generation:(int64_t)generation {
@synchronized(self) {
if (generation != self.agentLiveGeneration) {
return NO;
}
self.agentLiveStream = stream;
return YES;
}
}
- (BOOL)isAgentLiveCurrent:(TUTMobileStream *)stream
generation:(int64_t)generation {
@synchronized(self) {
return generation == self.agentLiveGeneration &&
self.agentLiveStream == stream;
}
}
- (BOOL)isAgentLiveGenerationCurrent:(int64_t)generation {
@synchronized(self) {
return generation == self.agentLiveGeneration;
}
}
- (void)clearAgentLiveStream:(TUTMobileStream *)stream
generation:(int64_t)generation {
@synchronized(self) {
if (generation == self.agentLiveGeneration &&
self.agentLiveStream == stream) {
self.agentLiveStream = nil;
}
}
}
- (void)closeCurrentAgentLiveStream {
TUTMobileStream *previous = nil;
@synchronized(self) {
self.agentLiveGeneration += 1;
previous = self.agentLiveStream;
self.agentLiveStream = nil;
}
[self closeDetachedStream:previous];
}
- (void)closeDetachedStream:(TUTMobileStream *)stream {
if (stream == nil) {
return;
}
dispatch_async(self.closeQueue, ^{
[stream close:nil];
});
}
- (void)emitAgentLive:(NSString *)payload {
if (payload.length == 0) {
return;
}
@synchronized(self) {
if (!self.observing) {
return;
}
}
dispatch_async(dispatch_get_main_queue(), ^{
[self sendEventWithName:TUTAgentLiveEventName body:payload];
});
}
- (void)applicationDidEnterBackground {
[self closeCurrentAgentLiveStream];
@synchronized(self) {
if (self.backgroundClose != nil) {
dispatch_block_cancel(self.backgroundClose);
}
__weak TuttiDeviceLink *weakSelf = self;
self.backgroundClose =
dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS, ^{
[weakSelf closeCurrentLink];
});
dispatch_after(
dispatch_time(DISPATCH_TIME_NOW,
(int64_t)(TUTBackgroundGraceSeconds * NSEC_PER_SEC)),
dispatch_get_main_queue(), self.backgroundClose);
}
}
- (void)applicationWillEnterForeground {
@synchronized(self) {
if (self.backgroundClose != nil) {
dispatch_block_cancel(self.backgroundClose);
self.backgroundClose = nil;
}
}
}
- (void)invalidate {
[[NSNotificationCenter defaultCenter] removeObserver:self];
[self applicationWillEnterForeground];
[self closeCurrentLink];
[super invalidate];
}
@end
@@ -0,0 +1,15 @@
#import <Foundation/Foundation.h>
#import <TuttiMobileGo/TUTMobile.objc.h>
NS_ASSUME_NONNULL_BEGIN
typedef NSDictionary *_Nullable (^TUTDeviceLinkRelayRequest)(
TUTMobileStream *stream, int64_t timeoutMillis, NSError **error);
typedef void (^TUTDeviceLinkRelayProbeCompletion)(NSError *_Nullable error);
FOUNDATION_EXPORT void TUTDeviceLinkProbeRelay(
NSDictionary *relay, int64_t timeoutMillis, dispatch_queue_t queue,
TUTDeviceLinkRelayRequest request,
TUTDeviceLinkRelayProbeCompletion completion);
NS_ASSUME_NONNULL_END
@@ -0,0 +1,42 @@
#import "DeviceLinkRelayProbe.h"
static NSError *TUTRelayProbeError(NSString *message) {
return [NSError errorWithDomain:@"sh.tutti.mobile.device-link.relay-probe"
code:1
userInfo:@{NSLocalizedDescriptionKey : message}];
}
void TUTDeviceLinkProbeRelay(
NSDictionary *relay, int64_t timeoutMillis, dispatch_queue_t queue,
TUTDeviceLinkRelayRequest request,
TUTDeviceLinkRelayProbeCompletion completion) {
dispatch_async(queue, ^{
NSError *error = nil;
TUTMobileStream *stream = TUTMobileDialRelay(
relay[@"endpoint"], relay[@"queryJSON"], relay[@"headersJSON"],
relay[@"subprotocol"], timeoutMillis, &error);
NSDictionary *response = nil;
if (stream != nil && error == nil) {
response = request(stream, timeoutMillis, &error);
}
if (response == nil || error != nil) {
completion(error ?: TUTRelayProbeError(@"Relay peer handshake failed"));
return;
}
NSNumber *protocolEpoch = response[@"protocolEpoch"];
if (![protocolEpoch isKindOfClass:[NSNumber class]] ||
protocolEpoch.longLongValue != TUTMobileProtocolEpoch()) {
completion(TUTRelayProbeError(
@"Relay peer uses an unsupported DeviceLink protocol epoch"));
return;
}
NSInteger status = [response[@"status"] integerValue];
if (status < 200 || status > 299) {
completion(TUTRelayProbeError([NSString stringWithFormat:
@"Relay peer control request returned HTTP %ld",
(long)status]));
return;
}
completion(nil);
});
}
@@ -0,0 +1,116 @@
{
"images": [
{
"filename": "AppIcon-20@2x.png",
"idiom": "iphone",
"scale": "2x",
"size": "20x20"
},
{
"filename": "AppIcon-20@3x.png",
"idiom": "iphone",
"scale": "3x",
"size": "20x20"
},
{
"filename": "AppIcon-29@2x.png",
"idiom": "iphone",
"scale": "2x",
"size": "29x29"
},
{
"filename": "AppIcon-29@3x.png",
"idiom": "iphone",
"scale": "3x",
"size": "29x29"
},
{
"filename": "AppIcon-40@2x.png",
"idiom": "iphone",
"scale": "2x",
"size": "40x40"
},
{
"filename": "AppIcon-40@3x.png",
"idiom": "iphone",
"scale": "3x",
"size": "40x40"
},
{
"filename": "AppIcon-60@2x.png",
"idiom": "iphone",
"scale": "2x",
"size": "60x60"
},
{
"filename": "AppIcon-60@3x.png",
"idiom": "iphone",
"scale": "3x",
"size": "60x60"
},
{
"filename": "AppIcon-20.png",
"idiom": "ipad",
"scale": "1x",
"size": "20x20"
},
{
"filename": "AppIcon-20@2x-ipad.png",
"idiom": "ipad",
"scale": "2x",
"size": "20x20"
},
{
"filename": "AppIcon-29.png",
"idiom": "ipad",
"scale": "1x",
"size": "29x29"
},
{
"filename": "AppIcon-29@2x-ipad.png",
"idiom": "ipad",
"scale": "2x",
"size": "29x29"
},
{
"filename": "AppIcon-40.png",
"idiom": "ipad",
"scale": "1x",
"size": "40x40"
},
{
"filename": "AppIcon-40@2x-ipad.png",
"idiom": "ipad",
"scale": "2x",
"size": "40x40"
},
{
"filename": "AppIcon-76.png",
"idiom": "ipad",
"scale": "1x",
"size": "76x76"
},
{
"filename": "AppIcon-76@2x.png",
"idiom": "ipad",
"scale": "2x",
"size": "76x76"
},
{
"filename": "AppIcon-83.5@2x.png",
"idiom": "ipad",
"scale": "2x",
"size": "83.5x83.5"
},
{
"filename": "AppIcon-1024.png",
"idiom": "ios-marketing",
"scale": "1x",
"size": "1024x1024"
}
],
"info": {
"author": "xcode",
"version": 1
}
}
@@ -0,0 +1,6 @@
{
"info": {
"author": "xcode",
"version": 1
}
}
+75
View File
@@ -0,0 +1,75 @@
<?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>CADisableMinimumFrameDurationOnPhone</key>
<true/>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleDisplayName</key>
<string>Tutti</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>$(MARKETING_VERSION)</string>
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLName</key>
<string>sh.tutti.mobile.auth</string>
<key>CFBundleURLSchemes</key>
<array>
<string>tutti</string>
</array>
</dict>
</array>
<key>CFBundleVersion</key>
<string>$(CURRENT_PROJECT_VERSION)</string>
<key>LSApplicationQueriesSchemes</key>
<array>
<string>https</string>
</array>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<false/>
<key>NSAllowsLocalNetworking</key>
<true/>
</dict>
<key>NSCameraUsageDescription</key>
<string>Scan the pairing QR code shown by your Tutti desktop</string>
<key>NSLocalNetworkUsageDescription</key>
<string>Connect to your paired Tutti desktop on the local network</string>
<key>RCTNewArchEnabled</key>
<true/>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIRequiredDeviceCapabilities</key>
<array>
<string>arm64</string>
</array>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
</array>
<key>UIViewControllerBasedStatusBarAppearance</key>
<false/>
</dict>
</plist>
@@ -0,0 +1,37 @@
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="15702" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="01J-lp-oVM">
<device id="retina6_1" orientation="portrait" appearance="light"/>
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="15704"/>
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<scene sceneID="EHf-IW-A2E">
<objects>
<viewController id="01J-lp-oVM" sceneMemberID="viewController">
<view key="view" contentMode="scaleToFill" id="Ze5-6b-2t3">
<rect key="frame" x="0.0" y="0.0" width="414" height="896"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<label opaque="NO" clipsSubviews="YES" userInteractionEnabled="NO" contentMode="left" text="Tutti" textAlignment="center" translatesAutoresizingMaskIntoConstraints="NO" id="GJd-Yh-RWb">
<rect key="frame" x="0.0" y="426" width="414" height="44"/>
<fontDescription key="fontDescription" type="boldSystem" pointSize="36"/>
<nil key="highlightedColor"/>
</label>
</subviews>
<color key="backgroundColor" systemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/>
<constraints>
<constraint firstItem="Bcu-3y-fUS" firstAttribute="centerX" secondItem="GJd-Yh-RWb" secondAttribute="centerX" id="Q3B-4B-g5h"/>
<constraint firstItem="GJd-Yh-RWb" firstAttribute="centerY" secondItem="Bcu-3y-fUS" secondAttribute="centerY" id="moa-c2-u7t"/>
<constraint firstItem="GJd-Yh-RWb" firstAttribute="leading" secondItem="Bcu-3y-fUS" secondAttribute="leading" id="x7j-FC-K8j"/>
</constraints>
<viewLayoutGuide key="safeArea" id="Bcu-3y-fUS"/>
</view>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="iYj-Kq-Ea1" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
</scene>
</scenes>
</document>
@@ -0,0 +1,838 @@
import Darwin
import Foundation
struct MobileBrowserAuthError: LocalizedError {
let code: String
let message: String
var errorDescription: String? { message }
}
final class MobileBrowserAuthBridge {
private let queue = DispatchQueue(
label: "sh.tutti.mobile.browser-auth",
qos: .userInitiated
)
private let lock = NSLock()
private var active: BrowserLoginAttempt?
private let webAuthenticationSession = MobileWebAuthenticationSession()
private var closed = false
private var starting = false
func start(
appID: String,
authLoginURL: String,
appCallbackURL: String,
deviceID: String,
deviceName: String,
clientVersion: String,
completion: @escaping (Result<[String: String], Error>) -> Void
) {
lock.lock()
guard !closed else {
lock.unlock()
completion(
.failure(
MobileBrowserAuthError(
code: "BROWSER_LOGIN_UNAVAILABLE",
message: "Browser login is unavailable"
)
)
)
return
}
guard !starting, active == nil else {
lock.unlock()
completion(
.failure(
MobileBrowserAuthError(
code: "BROWSER_LOGIN_BUSY",
message: "A browser login is already active"
)
)
)
return
}
starting = true
lock.unlock()
queue.async { [weak self] in
guard let self else { return }
do {
let server = try Self.bindLoopbackServer()
let attempt = try BrowserLoginAttempt.create(
server: server,
appID: appID,
authLoginURL: authLoginURL,
appCallbackURL: appCallbackURL,
deviceID: deviceID,
deviceName: deviceName,
clientVersion: clientVersion,
completion: completion
)
self.lock.lock()
guard !self.closed else {
self.starting = false
self.lock.unlock()
Self.closeSocket(server.fileDescriptor)
throw MobileBrowserAuthError(
code: "BROWSER_LOGIN_UNAVAILABLE",
message: "Browser login is unavailable"
)
}
self.starting = false
self.active = attempt
self.lock.unlock()
DispatchQueue.main.async {
self.openAuthenticationSession(attempt)
}
self.serve(attempt)
} catch {
self.lock.lock()
self.starting = false
self.lock.unlock()
DispatchQueue.main.async {
completion(.failure(error))
}
}
}
}
func close() {
lock.lock()
guard !closed else {
lock.unlock()
return
}
closed = true
starting = false
let attempt = active
active = nil
lock.unlock()
DispatchQueue.main.async {
self.webAuthenticationSession.cancel()
}
guard let attempt else { return }
Self.closeSocket(attempt.server.fileDescriptor)
DispatchQueue.main.async {
attempt.completion(
.failure(
MobileBrowserAuthError(
code: "BROWSER_LOGIN_UNAVAILABLE",
message: "Browser login was closed"
)
)
)
}
}
private func serve(_ attempt: BrowserLoginAttempt) {
while Date() < attempt.expiresAt, isActive(attempt) {
var descriptor = pollfd(
fd: attempt.server.fileDescriptor,
events: Int16(POLLIN),
revents: 0
)
let pollResult = Darwin.poll(&descriptor, 1, 1_000)
if pollResult == 0 {
continue
}
if pollResult < 0 {
if errno == EINTR { continue }
finish(
attempt,
result: .failure(
MobileBrowserAuthError(
code: "BROWSER_LOGIN_FAILED",
message: "Browser login bridge stopped unexpectedly"
)
)
)
return
}
var address = sockaddr_storage()
var addressLength = socklen_t(MemoryLayout<sockaddr_storage>.size)
let client = withUnsafeMutablePointer(to: &address) { addressPointer in
addressPointer.withMemoryRebound(to: sockaddr.self, capacity: 1) {
Darwin.accept(
attempt.server.fileDescriptor,
$0,
&addressLength
)
}
}
if client < 0 {
if errno == EINTR { continue }
continue
}
var noSignal: Int32 = 1
setsockopt(
client,
SOL_SOCKET,
SO_NOSIGPIPE,
&noSignal,
socklen_t(MemoryLayout<Int32>.size)
)
defer { Self.closeSocket(client) }
do {
switch try handleRequest(attempt, client: client) {
case .pending:
continue
case .completed(let transferCode):
finish(attempt, result: .success(transferCode))
return
case .failed(let error):
finish(attempt, result: .failure(error))
return
}
} catch {
continue
}
}
if isActive(attempt) {
finish(
attempt,
result: .failure(
MobileBrowserAuthError(
code: "BROWSER_LOGIN_TIMEOUT",
message: "Browser login timed out"
)
)
)
}
}
private func handleRequest(
_ attempt: BrowserLoginAttempt,
client: Int32
) throws -> BrowserRequestOutcome {
let request = try Self.readRequest(
client,
deadline: min(attempt.expiresAt, Date(timeIntervalSinceNow: 2))
)
guard request.parts.count >= 2 else {
try Self.sendJSON(client, status: 400, body: #"{"ok":false}"#)
return .pending
}
guard Self.allowedHost(request.headers["host"], port: attempt.server.port) else {
try Self.sendEmpty(client, status: 403)
return .pending
}
let method = request.parts[0].uppercased()
let target = request.parts[1]
guard
let components = URLComponents(string: "http://localhost\(target)")
else {
try Self.sendJSON(client, status: 400, body: #"{"ok":false}"#)
return .pending
}
guard let query = Self.queryValues(components.queryItems ?? []) else {
try Self.sendJSON(client, status: 400, body: #"{"ok":false}"#)
return .pending
}
let origin = request.headers["origin"]?
.trimmingCharacters(in: .whitespacesAndNewlines)
let corsOrigin = origin == attempt.authOrigin ? attempt.authOrigin : nil
if method == "OPTIONS" {
if let corsOrigin {
try Self.sendEmpty(client, status: 204, corsOrigin: corsOrigin)
} else {
try Self.sendEmpty(client, status: 403)
}
return .pending
}
if method == "GET", components.path == "/oauth/health" {
if let origin, !origin.isEmpty, corsOrigin == nil {
try Self.sendEmpty(client, status: 403)
return .pending
}
let matched =
query["attempt_id"] == attempt.attemptID
&& query["token"] == attempt.bridgeToken
&& isActive(attempt)
&& Date() < attempt.expiresAt
if !matched {
try Self.sendJSON(
client,
status: 401,
body: #"{"ok":false,"error":{"code":"INVALID_BRIDGE_ATTEMPT"}}"#,
corsOrigin: corsOrigin
)
return .pending
}
let expiresAt = Int64(attempt.expiresAt.timeIntervalSince1970 * 1_000)
let payload: [String: Any] = [
"ok": true,
"data": [
"attemptId": attempt.attemptID,
"status": "ready",
"expiresAt": expiresAt,
],
]
let body =
String(
data: try JSONSerialization.data(withJSONObject: payload),
encoding: .utf8
) ?? #"{"ok":true}"#
try Self.sendJSON(client, status: 200, body: body, corsOrigin: corsOrigin)
return .pending
}
if method == "GET", components.path == "/oauth/callback" {
guard query["state"] == attempt.state else {
try Self.sendRedirect(
client,
location: Self.bridgeResultURL(
attempt,
status: "error",
safeErrorCode: "invalidState"
)
)
return .failed(
MobileBrowserAuthError(
code: "BROWSER_LOGIN_INVALID_STATE",
message: "Browser login state is invalid"
)
)
}
let callbackError =
query["error"]?
.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
if !callbackError.isEmpty {
let cancelled = callbackError == "user_cancelled"
try Self.sendRedirect(
client,
location: Self.bridgeResultURL(
attempt,
status: "error",
safeErrorCode: cancelled ? "userCancelled" : "providerError"
)
)
return .failed(
MobileBrowserAuthError(
code: cancelled ? "BROWSER_LOGIN_CANCELLED" : "BROWSER_LOGIN_FAILED",
message: cancelled
? "Browser login was cancelled"
: "Browser login provider returned an error"
)
)
}
let transferCode =
query["transfer_code"]?
.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
guard !transferCode.isEmpty else {
try Self.sendRedirect(
client,
location: Self.bridgeResultURL(
attempt,
status: "error",
safeErrorCode: "missingTransferCode"
)
)
return .failed(
MobileBrowserAuthError(
code: "BROWSER_LOGIN_FAILED",
message: "Browser login transfer code is missing"
)
)
}
try Self.sendRedirect(
client,
location: Self.bridgeResultURL(attempt, status: "success")
)
return .completed(transferCode)
}
try Self.sendJSON(client, status: 404, body: #"{"ok":false}"#)
return .pending
}
private func finish(
_ attempt: BrowserLoginAttempt,
result: Result<String, Error>
) {
lock.lock()
guard active === attempt else {
lock.unlock()
return
}
active = nil
lock.unlock()
Self.closeSocket(attempt.server.fileDescriptor)
DispatchQueue.main.async {
switch result {
case .success(let transferCode):
attempt.completion(
.success([
"attemptId": attempt.attemptID,
"bridgeToken": attempt.bridgeToken,
"deviceId": attempt.deviceID,
"transferCode": transferCode,
])
)
case .failure(let error):
self.webAuthenticationSession.cancel()
attempt.completion(.failure(error))
}
}
}
private func openAuthenticationSession(_ attempt: BrowserLoginAttempt) {
guard isActive(attempt) else { return }
guard
let callbackScheme = URL(string: attempt.appCallbackURL)?.scheme,
!callbackScheme.isEmpty
else {
finish(
attempt,
result: .failure(
MobileBrowserAuthError(
code: "BROWSER_LOGIN_FAILED",
message: "Unable to present browser login"
)
)
)
return
}
let started = webAuthenticationSession.start(
url: attempt.loginURL,
callbackScheme: callbackScheme
) { [weak self, weak attempt] result in
guard let self, let attempt else { return }
guard result != .callback else { return }
let cancelled = result == .cancelled
self.finish(
attempt,
result: .failure(
MobileBrowserAuthError(
code: cancelled ? "BROWSER_LOGIN_CANCELLED" : "BROWSER_LOGIN_FAILED",
message: cancelled
? "Browser login was cancelled"
: "Browser authentication session failed"
)
)
)
}
guard started else {
finish(
attempt,
result: .failure(
MobileBrowserAuthError(
code: "BROWSER_LOGIN_FAILED",
message: "Unable to start browser authentication session"
)
)
)
return
}
}
private func isActive(_ attempt: BrowserLoginAttempt) -> Bool {
lock.lock()
defer { lock.unlock() }
return active === attempt && !closed
}
private static func bindLoopbackServer() throws -> LoopbackServer {
for port in 38_473...38_492 {
let descriptor = Darwin.socket(AF_INET, SOCK_STREAM, 0)
guard descriptor >= 0 else { continue }
var reuse: Int32 = 1
setsockopt(
descriptor,
SOL_SOCKET,
SO_REUSEADDR,
&reuse,
socklen_t(MemoryLayout<Int32>.size)
)
var address = sockaddr_in()
address.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
address.sin_family = sa_family_t(AF_INET)
address.sin_port = in_port_t(port).bigEndian
guard
"127.0.0.1".withCString({
inet_pton(AF_INET, $0, &address.sin_addr)
}) == 1
else {
closeSocket(descriptor)
continue
}
let bound = withUnsafePointer(to: &address) { addressPointer in
addressPointer.withMemoryRebound(to: sockaddr.self, capacity: 1) {
Darwin.bind(
descriptor,
$0,
socklen_t(MemoryLayout<sockaddr_in>.size)
)
}
}
guard bound == 0, Darwin.listen(descriptor, 8) == 0 else {
closeSocket(descriptor)
continue
}
return LoopbackServer(fileDescriptor: descriptor, port: port)
}
throw MobileBrowserAuthError(
code: "BROWSER_LOGIN_FAILED",
message: "Unable to allocate browser login port"
)
}
private static func readRequest(
_ client: Int32, deadline: Date
) throws -> BrowserHTTPRequest {
var bytes = Data()
var buffer = [UInt8](repeating: 0, count: 4_096)
while bytes.count < 32_768 {
let remaining = deadline.timeIntervalSinceNow
guard remaining > 0 else { throw invalidRequestError() }
var descriptor = pollfd(fd: client, events: Int16(POLLIN), revents: 0)
let timeout = Int32(max(1, min(2_000, Int(remaining * 1_000))))
let pollResult = Darwin.poll(&descriptor, 1, timeout)
if pollResult == 0 { throw invalidRequestError() }
if pollResult < 0 {
if errno == EINTR { continue }
throw invalidRequestError()
}
let count = Darwin.recv(client, &buffer, buffer.count, 0)
guard count > 0 else { throw invalidRequestError() }
bytes.append(contentsOf: buffer.prefix(count))
if bytes.range(of: Data("\r\n\r\n".utf8)) != nil {
break
}
}
guard
bytes.range(of: Data("\r\n\r\n".utf8)) != nil,
let raw = String(data: bytes, encoding: .utf8)
else { throw invalidRequestError() }
let lines = raw.components(separatedBy: "\r\n")
var headers: [String: String] = [:]
for line in lines.dropFirst() {
guard !line.isEmpty, let separator = line.firstIndex(of: ":") else {
continue
}
let name = String(line[..<separator])
.trimmingCharacters(in: .whitespaces)
.lowercased()
let value = String(line[line.index(after: separator)...])
.trimmingCharacters(in: .whitespaces)
headers[name] = value
}
return BrowserHTTPRequest(
parts: lines.first?.split(separator: " ", maxSplits: 2).map(String.init) ?? [],
headers: headers
)
}
private static func sendEmpty(
_ client: Int32,
status: Int,
corsOrigin: String? = nil
) throws {
try writeResponse(
client, status: status, headers: [:], body: "", corsOrigin: corsOrigin
)
}
private static func sendJSON(
_ client: Int32,
status: Int,
body: String,
corsOrigin: String? = nil
) throws {
try writeResponse(
client,
status: status,
headers: ["Content-Type": "application/json; charset=utf-8"],
body: body,
corsOrigin: corsOrigin
)
}
private static func sendRedirect(
_ client: Int32,
location: String
) throws {
try writeResponse(
client,
status: 302,
headers: ["Location": location],
body: "",
corsOrigin: nil
)
}
private static func writeResponse(
_ client: Int32,
status: Int,
headers: [String: String],
body: String,
corsOrigin: String?
) throws {
let bodyData = Data(body.utf8)
let reason: String
switch status {
case 200: reason = "OK"
case 204: reason = "No Content"
case 302: reason = "Found"
case 400: reason = "Bad Request"
case 401: reason = "Unauthorized"
case 403: reason = "Forbidden"
case 404: reason = "Not Found"
default: reason = "Error"
}
var head = "HTTP/1.1 \(status) \(reason)\r\n"
head += "Connection: close\r\n"
head += "Content-Length: \(bodyData.count)\r\n"
if let corsOrigin {
head += "Access-Control-Allow-Origin: \(corsOrigin)\r\n"
head += "Access-Control-Allow-Methods: GET, POST, OPTIONS\r\n"
head += "Access-Control-Allow-Headers: Content-Type\r\n"
head += "Access-Control-Allow-Private-Network: true\r\n"
head += "Vary: Origin\r\n"
}
for (name, value) in headers {
head += "\(name): \(value)\r\n"
}
head += "\r\n"
try sendAll(client, data: Data(head.utf8) + bodyData)
}
private static func sendAll(_ client: Int32, data: Data) throws {
try data.withUnsafeBytes { rawBuffer in
guard let base = rawBuffer.baseAddress else { return }
var offset = 0
while offset < rawBuffer.count {
let written = Darwin.send(
client,
base.advanced(by: offset),
rawBuffer.count - offset,
0
)
guard written > 0 else {
throw MobileBrowserAuthError(
code: "BROWSER_LOGIN_FAILED",
message: "Unable to reply to browser login"
)
}
offset += written
}
}
}
private static func bridgeResultURL(
_ attempt: BrowserLoginAttempt,
status: String,
safeErrorCode: String? = nil
) -> String {
var query = ["desktopBridgeStatus=\(percentEncode(status))"]
if let safeErrorCode, !safeErrorCode.isEmpty {
query.append("desktopBridgeError=\(percentEncode(safeErrorCode))")
}
if safeErrorCode != "userCancelled" {
var openAppParameters = ["desktopBridgeStatus=\(percentEncode(status))"]
if let safeErrorCode, !safeErrorCode.isEmpty {
openAppParameters.append(
"desktopBridgeError=\(percentEncode(safeErrorCode))"
)
}
let openAppURL =
"\(attempt.appCallbackURL)?\(openAppParameters.joined(separator: "&"))"
query.append("openAppUrl=\(percentEncode(openAppURL))")
}
return "\(attempt.authOrigin)/auth/login/callback?\(query.joined(separator: "&"))"
}
private static func percentEncode(_ value: String) -> String {
value.addingPercentEncoding(
withAllowedCharacters: .urlQueryAllowed.subtracting(
CharacterSet(charactersIn: "&+=?")
)
) ?? ""
}
private static func allowedHost(_ hostHeader: String?, port: Int) -> Bool {
let host =
hostHeader?
.trimmingCharacters(in: .whitespacesAndNewlines)
.lowercased() ?? ""
return host == "127.0.0.1:\(port)" || host == "localhost:\(port)"
}
private static func queryValues(_ items: [URLQueryItem]) -> [String: String]? {
var values: [String: String] = [:]
for item in items {
guard values[item.name] == nil else { return nil }
values[item.name] = item.value ?? ""
}
return values
}
private static func invalidRequestError() -> MobileBrowserAuthError {
MobileBrowserAuthError(
code: "BROWSER_LOGIN_FAILED",
message: "Browser login request is invalid"
)
}
private static func closeSocket(_ descriptor: Int32) {
guard descriptor >= 0 else { return }
Darwin.shutdown(descriptor, SHUT_RDWR)
Darwin.close(descriptor)
}
}
private final class BrowserLoginAttempt {
let appCallbackURL: String
let attemptID: String
let authOrigin: String
let bridgeToken: String
let completion: (Result<[String: String], Error>) -> Void
let deviceID: String
let expiresAt: Date
let loginURL: URL
let server: LoopbackServer
let state: String
private init(
appCallbackURL: String,
attemptID: String,
authOrigin: String,
bridgeToken: String,
completion: @escaping (Result<[String: String], Error>) -> Void,
deviceID: String,
expiresAt: Date,
loginURL: URL,
server: LoopbackServer,
state: String
) {
self.appCallbackURL = appCallbackURL
self.attemptID = attemptID
self.authOrigin = authOrigin
self.bridgeToken = bridgeToken
self.completion = completion
self.deviceID = deviceID
self.expiresAt = expiresAt
self.loginURL = loginURL
self.server = server
self.state = state
}
static func create(
server: LoopbackServer,
appID: String,
authLoginURL: String,
appCallbackURL: String,
deviceID: String,
deviceName: String,
clientVersion: String,
completion: @escaping (Result<[String: String], Error>) -> Void
) throws -> BrowserLoginAttempt {
guard
let authURL = URL(string: authLoginURL.trimmingCharacters(in: .whitespaces)),
authURL.scheme == "https",
let authHost = authURL.host
else {
throw MobileBrowserAuthError(
code: "BROWSER_LOGIN_FAILED",
message: "Browser login URL must use HTTPS"
)
}
let normalizedAppID = appID.trimmingCharacters(in: .whitespacesAndNewlines)
guard !normalizedAppID.isEmpty else {
throw MobileBrowserAuthError(
code: "BROWSER_LOGIN_FAILED",
message: "App id is required"
)
}
let normalizedCallback = appCallbackURL.trimmingCharacters(
in: .whitespacesAndNewlines
)
guard normalizedCallback == "tutti://auth/login" else {
throw MobileBrowserAuthError(
code: "BROWSER_LOGIN_FAILED",
message: "App callback URL is not allowed"
)
}
let attemptID = UUID().uuidString
let bridgeToken = UUID().uuidString
let authOrigin = "https://\(authHost)"
let localOrigin = "http://127.0.0.1:\(server.port)"
let stateObject: [String: Any] = [
"v": 1,
"flow": "desktop_bridge",
"attemptId": attemptID,
"localServerOrigin": localOrigin,
"bridgeToken": bridgeToken,
"appId": normalizedAppID,
"appCallbackUrl": normalizedCallback,
"deviceId": deviceID.trimmingCharacters(in: .whitespacesAndNewlines),
"deviceName": deviceName.trimmingCharacters(in: .whitespacesAndNewlines),
"clientVersion": clientVersion.trimmingCharacters(in: .whitespacesAndNewlines),
"hostname": deviceName.trimmingCharacters(in: .whitespacesAndNewlines),
]
let state = try JSONSerialization.data(withJSONObject: stateObject)
.browserAuthBase64URLString()
guard
let encodedState = state.addingPercentEncoding(
withAllowedCharacters: .urlQueryAllowed
),
let loginURL = URL(string: "\(authOrigin)/auth/login?state=\(encodedState)")
else {
throw MobileBrowserAuthError(
code: "BROWSER_LOGIN_FAILED",
message: "Unable to create browser login URL"
)
}
return BrowserLoginAttempt(
appCallbackURL: normalizedCallback,
attemptID: attemptID,
authOrigin: authOrigin,
bridgeToken: bridgeToken,
completion: completion,
deviceID: deviceID.trimmingCharacters(in: .whitespacesAndNewlines),
expiresAt: Date(timeIntervalSinceNow: 5 * 60),
loginURL: loginURL,
server: server,
state: state
)
}
}
private struct LoopbackServer {
let fileDescriptor: Int32
let port: Int
}
private struct BrowserHTTPRequest {
let parts: [String]
let headers: [String: String]
}
private enum BrowserRequestOutcome {
case pending
case completed(String)
case failed(MobileBrowserAuthError)
}
extension Data {
fileprivate func browserAuthBase64URLString() -> String {
base64EncodedString()
.replacingOccurrences(of: "+", with: "-")
.replacingOccurrences(of: "/", with: "_")
.replacingOccurrences(of: "=", with: "")
}
}
@@ -0,0 +1,69 @@
#import <React/RCTBridgeModule.h>
#import <React/RCTEventEmitter.h>
@interface RCT_EXTERN_MODULE(TuttiAppLifecycle, RCTEventEmitter)
RCT_EXTERN__BLOCKING_SYNCHRONOUS_METHOD(isForeground)
@end
@interface RCT_EXTERN_MODULE(TuttiMobileSecurity, NSObject)
RCT_EXTERN_METHOD(getOrCreateIdentity
: (RCTPromiseResolveBlock)resolve rejecter
: (RCTPromiseRejectBlock)reject)
RCT_EXTERN_METHOD(sign
: (NSString *)message resolver
: (RCTPromiseResolveBlock)resolve rejecter
: (RCTPromiseRejectBlock)reject)
RCT_EXTERN_METHOD(loadSession
: (RCTPromiseResolveBlock)resolve rejecter
: (RCTPromiseRejectBlock)reject)
RCT_EXTERN_METHOD(saveSession
: (NSString *)sessionId userId
: (NSString *)userId email
: (NSString *)email name
: (NSString *)name avatarURL
: (NSString *)avatarURL resolver
: (RCTPromiseResolveBlock)resolve rejecter
: (RCTPromiseRejectBlock)reject)
RCT_EXTERN_METHOD(clearSession
: (RCTPromiseResolveBlock)resolve rejecter
: (RCTPromiseRejectBlock)reject)
RCT_EXTERN_METHOD(clearLegacySessionCookie
: (NSString *)accountBaseURL resolver
: (RCTPromiseResolveBlock)resolve rejecter
: (RCTPromiseRejectBlock)reject)
RCT_EXTERN_METHOD(startBrowserLogin
: (NSString *)appId authLoginURL
: (NSString *)authLoginURL appCallbackURL
: (NSString *)appCallbackURL resolver
: (RCTPromiseResolveBlock)resolve rejecter
: (RCTPromiseRejectBlock)reject)
RCT_EXTERN_METHOD(scanQRCode
: (RCTPromiseResolveBlock)resolve rejecter
: (RCTPromiseRejectBlock)reject)
RCT_EXTERN_METHOD(cancelQRCodeScan
: (RCTPromiseResolveBlock)resolve rejecter
: (RCTPromiseRejectBlock)reject)
@end
@interface RCT_EXTERN_MODULE(TuttiMobilePreferences, NSObject)
RCT_EXTERN__BLOCKING_SYNCHRONOUS_METHOD(loadThemePreference)
RCT_EXTERN_METHOD(saveThemePreference
: (NSString *)preference resolver
: (RCTPromiseResolveBlock)resolve rejecter
: (RCTPromiseRejectBlock)reject)
@end
@@ -0,0 +1,57 @@
import Foundation
import React
@objc(TuttiMobilePreferences)
final class MobilePreferencesModule: NSObject {
private let defaults = UserDefaults.standard
@objc
static func requiresMainQueueSetup() -> Bool {
false
}
@objc
func loadThemePreference() -> String {
Self.normalizeThemePreference(
defaults.string(forKey: Self.themePreferenceKey)
)
}
@objc(saveThemePreference:resolver:rejecter:)
func saveThemePreference(
_ preference: String,
resolver resolve: RCTPromiseResolveBlock,
rejecter reject: RCTPromiseRejectBlock
) {
guard Self.supportedThemePreferences.contains(preference) else {
reject(
"INVALID_THEME_PREFERENCE",
"Unsupported Mobile theme preference",
nil
)
return
}
defaults.set(preference, forKey: Self.themePreferenceKey)
guard defaults.string(forKey: Self.themePreferenceKey) == preference else {
reject(
"THEME_PREFERENCE_WRITE_FAILED",
"Unable to save Mobile theme preference",
nil
)
return
}
resolve(nil)
}
private static let supportedThemePreferences: Set<String> = [
"system", "light", "dark",
]
private static let themePreferenceKey = "themePreference"
private static func normalizeThemePreference(_ value: String?) -> String {
guard let value, supportedThemePreferences.contains(value) else {
return "system"
}
return value
}
}
@@ -0,0 +1,445 @@
import CryptoKit
import Foundation
import React
import Security
import UIKit
@objc(TuttiMobileSecurity)
final class MobileSecurityModule: NSObject {
private let browserAuthBridge = MobileBrowserAuthBridge()
private let store = MobileSecureStore()
private var scannerActive = false
private var scannerCancellationResolvers: [RCTPromiseResolveBlock] = []
private weak var scannerViewController: QRCodeScannerViewController?
@objc
static func requiresMainQueueSetup() -> Bool {
true
}
@objc
func constantsToExport() -> [AnyHashable: Any] {
[
"clientVersion": Bundle.main.object(
forInfoDictionaryKey: "CFBundleShortVersionString"
) as? String ?? "0.0.0",
"localeIdentifier": Locale.current.identifier,
]
}
@objc(getOrCreateIdentity:rejecter:)
func getOrCreateIdentity(
_ resolve: RCTPromiseResolveBlock,
rejecter reject: RCTPromiseRejectBlock
) {
do {
let identity = try store.getOrCreateIdentity()
resolve([
"deviceId": identity.deviceID,
"publicKey": identity.publicKey,
"arch": deviceArchitecture(),
"deviceName": UIDevice.current.name.isEmpty ? "iPhone" : UIDevice.current.name,
])
} catch {
reject("IDENTITY_UNAVAILABLE", "Unable to load device identity", error)
}
}
@objc(sign:resolver:rejecter:)
func sign(
_ message: String,
resolver resolve: RCTPromiseResolveBlock,
rejecter reject: RCTPromiseRejectBlock
) {
do {
resolve(try store.sign(Data(message.utf8)))
} catch {
reject("SIGN_FAILED", "Unable to sign device proof", error)
}
}
@objc(loadSession:rejecter:)
func loadSession(
_ resolve: RCTPromiseResolveBlock,
rejecter reject: RCTPromiseRejectBlock
) {
do {
guard var session = try store.loadSession() else {
resolve(nil)
return
}
session["avatarURL"] = session["avatarURL"] ?? ""
resolve(session)
} catch {
reject("SESSION_READ_FAILED", "Unable to read account session", error)
}
}
@objc(saveSession:userId:email:name:avatarURL:resolver:rejecter:)
func saveSession(
_ sessionID: String,
userId: String,
email: String,
name: String,
avatarURL: String,
resolver resolve: RCTPromiseResolveBlock,
rejecter reject: RCTPromiseRejectBlock
) {
do {
try store.saveSession([
"sessionId": sessionID.trimmingCharacters(in: .whitespacesAndNewlines),
"userId": userId.trimmingCharacters(in: .whitespacesAndNewlines),
"email": email.trimmingCharacters(in: .whitespacesAndNewlines),
"name": name.trimmingCharacters(in: .whitespacesAndNewlines),
"avatarURL": avatarURL.trimmingCharacters(in: .whitespacesAndNewlines),
])
resolve(nil)
} catch {
reject("SESSION_WRITE_FAILED", "Unable to save account session", error)
}
}
@objc(clearSession:rejecter:)
func clearSession(
_ resolve: RCTPromiseResolveBlock,
rejecter reject: RCTPromiseRejectBlock
) {
do {
try store.clearSession()
resolve(nil)
} catch {
reject("SESSION_CLEAR_FAILED", "Unable to clear account session", error)
}
}
@objc(clearLegacySessionCookie:resolver:rejecter:)
func clearLegacySessionCookie(
_ accountBaseURL: String,
resolver resolve: RCTPromiseResolveBlock,
rejecter reject: RCTPromiseRejectBlock
) {
do {
let url = try validatedCookieURL(accountBaseURL)
for cookie in HTTPCookieStorage.shared.cookies(for: url) ?? []
where cookie.name == "session_id" {
HTTPCookieStorage.shared.deleteCookie(cookie)
}
resolve(nil)
} catch {
reject(
"SESSION_COOKIE_CLEAR_FAILED",
"Unable to clear legacy account session cookie",
error
)
}
}
@objc(startBrowserLogin:authLoginURL:appCallbackURL:resolver:rejecter:)
func startBrowserLogin(
_ appID: String,
authLoginURL: String,
appCallbackURL: String,
resolver resolve: @escaping RCTPromiseResolveBlock,
rejecter reject: @escaping RCTPromiseRejectBlock
) {
do {
let identity = try store.getOrCreateIdentity()
browserAuthBridge.start(
appID: appID,
authLoginURL: authLoginURL,
appCallbackURL: appCallbackURL,
deviceID: identity.deviceID,
deviceName: UIDevice.current.name.isEmpty ? "iPhone" : UIDevice.current.name,
clientVersion: constantsToExport()["clientVersion"] as? String ?? "0.0.0"
) { result in
switch result {
case .success(let completion):
resolve(completion)
case .failure(let error):
let bridgeError = error as? MobileBrowserAuthError
reject(
bridgeError?.code ?? "BROWSER_LOGIN_FAILED",
bridgeError?.message ?? "Unable to complete browser login",
error
)
}
}
} catch {
reject("BROWSER_LOGIN_FAILED", "Unable to start browser login", error)
}
}
@objc(scanQRCode:rejecter:)
func scanQRCode(
_ resolve: @escaping RCTPromiseResolveBlock,
rejecter reject: @escaping RCTPromiseRejectBlock
) {
#if targetEnvironment(simulator)
reject("SCANNER_UNAVAILABLE", "QR scanner is unavailable in Simulator", nil)
#else
DispatchQueue.main.async { [weak self] in
guard let self else {
reject("SCANNER_UNAVAILABLE", "QR scanner is unavailable", nil)
return
}
self.presentQRCodeScanner(resolve, rejecter: reject)
}
#endif
}
private func presentQRCodeScanner(
_ resolve: @escaping RCTPromiseResolveBlock,
rejecter reject: @escaping RCTPromiseRejectBlock
) {
guard !scannerActive else {
reject("SCANNER_BUSY", "A QR scan is already active", nil)
return
}
guard let presenter = topViewController() else {
reject("SCANNER_UNAVAILABLE", "No active iOS view controller", nil)
return
}
scannerActive = true
let scanner = QRCodeScannerViewController()
scannerViewController = scanner
scanner.modalPresentationStyle = .fullScreen
scanner.onCompletion = { result in
self.scannerActive = false
self.scannerViewController = nil
switch result {
case .success(.manual):
resolve(["kind": "manual"])
case .success(.scanned(let value)):
resolve(["kind": "scanned", "value": value])
case .failure(let error):
switch error {
case QRCodeScannerError.permissionDenied:
reject("SCANNER_PERMISSION_DENIED", "Camera permission is required", error)
case QRCodeScannerError.cancelled:
reject("SCAN_CANCELLED", "QR scan cancelled", error)
case QRCodeScannerError.emptyCode:
reject("EMPTY_QR_CODE", "The scanned QR code is empty", error)
default:
reject("SCANNER_UNAVAILABLE", "QR scanner is unavailable", error)
}
}
let cancellationResolvers = self.scannerCancellationResolvers
self.scannerCancellationResolvers.removeAll()
for resolveCancellation in cancellationResolvers {
resolveCancellation(nil)
}
}
presenter.present(scanner, animated: true)
}
@objc(cancelQRCodeScan:rejecter:)
func cancelQRCodeScan(
_ resolve: @escaping RCTPromiseResolveBlock,
rejecter _: @escaping RCTPromiseRejectBlock
) {
DispatchQueue.main.async { [weak self] in
guard let self, let scanner = self.scannerViewController else {
resolve(nil)
return
}
self.scannerCancellationResolvers.append(resolve)
scanner.cancelScanning()
}
}
@objc
func invalidate() {
browserAuthBridge.close()
DispatchQueue.main.async { [weak self] in
self?.scannerViewController?.cancelScanning()
}
}
private func topViewController() -> UIViewController? {
let scenes = UIApplication.shared.connectedScenes.compactMap {
$0 as? UIWindowScene
}
let root =
scenes
.flatMap(\.windows)
.first(where: \.isKeyWindow)?
.rootViewController
var current = root
while let presented = current?.presentedViewController {
current = presented
}
return current
}
private func validatedCookieURL(_ rawURL: String) throws -> URL {
guard
let url = URL(string: rawURL.trimmingCharacters(in: .whitespacesAndNewlines)),
url.scheme == "https",
url.host != nil
else {
throw MobileSecurityError.invalidAccountURL
}
return url
}
}
private struct MobileIdentity {
let deviceID: String
let publicKey: String
}
private enum MobileSecurityError: Error {
case invalidAccountURL
case invalidSession
case invalidStoredIdentity
case keychain(OSStatus)
}
private final class MobileSecureStore {
private let keychain = MobileKeychain()
func getOrCreateIdentity() throws -> MobileIdentity {
let deviceID: String
if let stored = try keychain.read(account: "device-id"),
let value = String(data: stored, encoding: .utf8),
!value.isEmpty
{
deviceID = value
} else {
deviceID = UUID().uuidString
try keychain.write(Data(deviceID.utf8), account: "device-id")
}
let privateKey = try signingKey()
return MobileIdentity(
deviceID: deviceID,
publicKey: privateKey.publicKey.rawRepresentation.base64URLEncodedString()
)
}
func sign(_ message: Data) throws -> String {
try signingKey().signature(for: message).base64EncodedString()
}
func loadSession() throws -> [String: String]? {
guard let raw = try keychain.read(account: "account-session") else {
return nil
}
guard
let object = try JSONSerialization.jsonObject(with: raw) as? [String: String],
object["sessionId"]?.isEmpty == false
else {
try? keychain.delete(account: "account-session")
return nil
}
return object
}
func saveSession(_ session: [String: String]) throws {
guard session["sessionId"]?.isEmpty == false else {
throw MobileSecurityError.invalidSession
}
try keychain.write(
JSONSerialization.data(withJSONObject: session),
account: "account-session"
)
}
func clearSession() throws {
try keychain.delete(account: "account-session")
}
private func signingKey() throws -> Curve25519.Signing.PrivateKey {
if let stored = try keychain.read(account: "signing-ed25519-v1") {
guard
let key = try? Curve25519.Signing.PrivateKey(rawRepresentation: stored)
else {
try keychain.delete(account: "signing-ed25519-v1")
throw MobileSecurityError.invalidStoredIdentity
}
return key
}
let key = Curve25519.Signing.PrivateKey()
try keychain.write(key.rawRepresentation, account: "signing-ed25519-v1")
return key
}
}
private final class MobileKeychain {
private let service =
(Bundle.main.bundleIdentifier ?? "sh.tutti.mobile") + ".secure-state"
func read(account: String) throws -> Data? {
var query = baseQuery(account: account)
query[kSecReturnData as String] = true
query[kSecMatchLimit as String] = kSecMatchLimitOne
var result: CFTypeRef?
let status = SecItemCopyMatching(query as CFDictionary, &result)
if status == errSecItemNotFound {
return nil
}
guard status == errSecSuccess else {
throw MobileSecurityError.keychain(status)
}
return result as? Data
}
func write(_ data: Data, account: String) throws {
let query = baseQuery(account: account)
let attributes: [String: Any] = [
kSecValueData as String: data,
kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly,
]
let updateStatus = SecItemUpdate(
query as CFDictionary,
attributes as CFDictionary
)
if updateStatus == errSecItemNotFound {
var insertion = query
for (key, value) in attributes {
insertion[key] = value
}
let addStatus = SecItemAdd(insertion as CFDictionary, nil)
guard addStatus == errSecSuccess else {
throw MobileSecurityError.keychain(addStatus)
}
} else if updateStatus != errSecSuccess {
throw MobileSecurityError.keychain(updateStatus)
}
}
func delete(account: String) throws {
let status = SecItemDelete(baseQuery(account: account) as CFDictionary)
guard status == errSecSuccess || status == errSecItemNotFound else {
throw MobileSecurityError.keychain(status)
}
}
private func baseQuery(account: String) -> [String: Any] {
[
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: service,
kSecAttrAccount as String: account,
]
}
}
private func deviceArchitecture() -> String {
var systemInfo = utsname()
uname(&systemInfo)
return withUnsafePointer(to: &systemInfo.machine) { pointer in
pointer.withMemoryRebound(to: CChar.self, capacity: 1) {
String(cString: $0)
}
}
}
extension Data {
fileprivate func base64URLEncodedString() -> String {
base64EncodedString()
.replacingOccurrences(of: "+", with: "-")
.replacingOccurrences(of: "/", with: "_")
.replacingOccurrences(of: "=", with: "")
}
}
@@ -0,0 +1,88 @@
import AuthenticationServices
import Foundation
import UIKit
enum MobileWebAuthenticationResult {
case callback
case cancelled
case failed
}
final class MobileWebAuthenticationSession: NSObject,
ASWebAuthenticationPresentationContextProviding
{
private var authenticationSession: ASWebAuthenticationSession?
private weak var presentationAnchor: ASPresentationAnchor?
func start(
url: URL,
callbackScheme: String,
completion: @escaping (MobileWebAuthenticationResult) -> Void
) -> Bool {
guard authenticationSession == nil, let anchor = Self.currentAnchor() else {
return false
}
let completionHandler: ASWebAuthenticationSession.CompletionHandler = {
[weak self] _, error in
self?.authenticationSession = nil
self?.presentationAnchor = nil
guard let error else {
completion(.callback)
return
}
let browserError = error as NSError
let cancelled =
browserError.domain == ASWebAuthenticationSessionError.errorDomain
&& browserError.code
== ASWebAuthenticationSessionError.Code.canceledLogin.rawValue
completion(cancelled ? .cancelled : .failed)
}
let session: ASWebAuthenticationSession
if #available(iOS 17.4, *) {
session = ASWebAuthenticationSession(
url: url,
callback: .customScheme(callbackScheme),
completionHandler: completionHandler
)
} else {
session = ASWebAuthenticationSession(
url: url,
callbackURLScheme: callbackScheme,
completionHandler: completionHandler
)
}
presentationAnchor = anchor
authenticationSession = session
session.presentationContextProvider = self
session.prefersEphemeralWebBrowserSession = false
guard session.start() else {
authenticationSession = nil
presentationAnchor = nil
return false
}
return true
}
func cancel() {
authenticationSession?.cancel()
authenticationSession = nil
presentationAnchor = nil
}
func presentationAnchor(
for _: ASWebAuthenticationSession
) -> ASPresentationAnchor {
presentationAnchor ?? ASPresentationAnchor()
}
private static func currentAnchor() -> ASPresentationAnchor? {
let scenes = UIApplication.shared.connectedScenes.compactMap {
$0 as? UIWindowScene
}
return scenes
.flatMap(\.windows)
.first(where: \.isKeyWindow)
?? scenes.flatMap(\.windows).first
}
}
@@ -0,0 +1,37 @@
<?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>NSPrivacyAccessedAPITypes</key>
<array>
<dict>
<key>NSPrivacyAccessedAPIType</key>
<string>NSPrivacyAccessedAPICategoryFileTimestamp</string>
<key>NSPrivacyAccessedAPITypeReasons</key>
<array>
<string>C617.1</string>
</array>
</dict>
<dict>
<key>NSPrivacyAccessedAPIType</key>
<string>NSPrivacyAccessedAPICategoryUserDefaults</string>
<key>NSPrivacyAccessedAPITypeReasons</key>
<array>
<string>CA92.1</string>
</array>
</dict>
<dict>
<key>NSPrivacyAccessedAPIType</key>
<string>NSPrivacyAccessedAPICategorySystemBootTime</string>
<key>NSPrivacyAccessedAPITypeReasons</key>
<array>
<string>35F9.1</string>
</array>
</dict>
</array>
<key>NSPrivacyCollectedDataTypes</key>
<array/>
<key>NSPrivacyTracking</key>
<false/>
</dict>
</plist>
@@ -0,0 +1,216 @@
import AVFoundation
import UIKit
enum QRCodeScannerError: Error {
case cancelled
case emptyCode
case permissionDenied
case unavailable
}
enum QRCodeScannerResult {
case manual
case scanned(String)
}
final class QRCodeScannerViewController: UIViewController,
AVCaptureMetadataOutputObjectsDelegate
{
var onCompletion: ((Result<QRCodeScannerResult, Error>) -> Void)?
private let captureSession = AVCaptureSession()
private let captureQueue = DispatchQueue(
label: "sh.tutti.mobile.qr-capture",
qos: .userInitiated
)
private let previewLayer = AVCaptureVideoPreviewLayer()
private var completed = false
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .black
previewLayer.session = captureSession
previewLayer.videoGravity = .resizeAspectFill
view.layer.addSublayer(previewLayer)
let titleLabel = UILabel()
titleLabel.translatesAutoresizingMaskIntoConstraints = false
titleLabel.text = NSLocalizedString("scanner.title", comment: "")
titleLabel.textColor = .white
titleLabel.font = .preferredFont(forTextStyle: .headline)
titleLabel.textAlignment = .center
titleLabel.numberOfLines = 0
view.addSubview(titleLabel)
let cancelButton = UIButton(type: .system)
cancelButton.translatesAutoresizingMaskIntoConstraints = false
cancelButton.setTitle(
NSLocalizedString("scanner.cancel", comment: ""),
for: .normal
)
cancelButton.setTitleColor(.white, for: .normal)
cancelButton.titleLabel?.font = .preferredFont(forTextStyle: .headline)
cancelButton.addTarget(self, action: #selector(cancel), for: .touchUpInside)
view.addSubview(cancelButton)
let manualButton = UIButton(type: .system)
manualButton.translatesAutoresizingMaskIntoConstraints = false
manualButton.setTitle(
NSLocalizedString("scanner.manual", comment: ""),
for: .normal
)
manualButton.setTitleColor(.white, for: .normal)
manualButton.titleLabel?.font = .preferredFont(forTextStyle: .headline)
manualButton.addTarget(self, action: #selector(manualEntry), for: .touchUpInside)
view.addSubview(manualButton)
NSLayoutConstraint.activate([
titleLabel.topAnchor.constraint(
equalTo: view.safeAreaLayoutGuide.topAnchor,
constant: 24
),
titleLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 88),
titleLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -24),
cancelButton.topAnchor.constraint(
equalTo: view.safeAreaLayoutGuide.topAnchor,
constant: 24
),
cancelButton.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 24),
manualButton.bottomAnchor.constraint(
equalTo: view.safeAreaLayoutGuide.bottomAnchor,
constant: -24
),
manualButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
])
configureCapture()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
previewLayer.frame = view.bounds
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
stopCapture()
}
func metadataOutput(
_ output: AVCaptureMetadataOutput,
didOutput metadataObjects: [AVMetadataObject],
from connection: AVCaptureConnection
) {
guard
let readable = metadataObjects.first as? AVMetadataMachineReadableCodeObject,
readable.type == .qr
else {
return
}
let value =
readable.stringValue?.trimmingCharacters(in: .whitespacesAndNewlines)
?? ""
complete(
value.isEmpty
? .failure(QRCodeScannerError.emptyCode)
: .success(.scanned(value))
)
}
private func configureCapture() {
#if targetEnvironment(simulator)
complete(.failure(QRCodeScannerError.unavailable), shouldDismiss: false)
return
#else
switch AVCaptureDevice.authorizationStatus(for: .video) {
case .authorized:
startCapture()
case .notDetermined:
AVCaptureDevice.requestAccess(for: .video) { [weak self] granted in
DispatchQueue.main.async {
guard let self else { return }
if granted {
self.startCapture()
} else {
self.complete(.failure(QRCodeScannerError.permissionDenied))
}
}
}
case .denied, .restricted:
complete(.failure(QRCodeScannerError.permissionDenied))
@unknown default:
complete(.failure(QRCodeScannerError.unavailable))
}
#endif
}
private func startCapture() {
guard !completed else { return }
guard
let camera = AVCaptureDevice.default(for: .video),
let input = try? AVCaptureDeviceInput(device: camera),
captureSession.canAddInput(input)
else {
complete(.failure(QRCodeScannerError.unavailable))
return
}
captureSession.addInput(input)
let output = AVCaptureMetadataOutput()
guard captureSession.canAddOutput(output) else {
complete(.failure(QRCodeScannerError.unavailable))
return
}
captureSession.addOutput(output)
output.setMetadataObjectsDelegate(self, queue: .main)
output.metadataObjectTypes = [.qr]
captureQueue.async { [session = captureSession] in
session.startRunning()
}
}
@objc private func cancel() {
complete(.failure(QRCodeScannerError.cancelled))
}
@objc private func manualEntry() {
complete(.success(.manual))
}
func cancelScanning() {
complete(.failure(QRCodeScannerError.cancelled))
}
private func complete(
_ result: Result<QRCodeScannerResult, Error>,
shouldDismiss: Bool = true
) {
guard !completed else { return }
completed = true
let completion = onCompletion
stopCapture { [weak self] in
guard let self else {
completion?(result)
return
}
if shouldDismiss {
self.dismiss(animated: true) {
completion?(result)
}
} else {
completion?(result)
}
}
}
private func stopCapture(completion: (() -> Void)? = nil) {
captureQueue.async { [session = captureSession] in
if session.isRunning {
session.stopRunning()
}
if let completion {
DispatchQueue.main.async(execute: completion)
}
}
}
}
@@ -0,0 +1,2 @@
"NSCameraUsageDescription" = "Scan the pairing QR code shown by your Tutti desktop";
"NSLocalNetworkUsageDescription" = "Connect to your paired Tutti desktop on the local network";
@@ -0,0 +1,3 @@
"scanner.title" = "Scan pairing QR code";
"scanner.cancel" = "Cancel";
"scanner.manual" = "Can't scan? Enter pairing code";
@@ -0,0 +1,2 @@
"NSCameraUsageDescription" = "扫描 Tutti 电脑端显示的配对二维码";
"NSLocalNetworkUsageDescription" = "通过本地网络连接已配对的 Tutti 电脑";
@@ -0,0 +1,3 @@
"scanner.title" = "扫描配对二维码";
"scanner.cancel" = "取消";
"scanner.manual" = "无法扫描?输入配对码";
+11
View File
@@ -0,0 +1,11 @@
Pod::Spec.new do |spec|
spec.name = 'TuttiMobileGo'
spec.version = '0.1.0'
spec.summary = 'Tutti Mobile DeviceLink and Agent live gomobile bindings'
spec.homepage = 'https://github.com/tutti-os/tutti'
spec.license = { :type => 'Apache-2.0' }
spec.author = 'Tutti'
spec.platform = :ios, '15.1'
spec.source = { :git => 'https://github.com/tutti-os/tutti.git', :tag => spec.version.to_s }
spec.vendored_frameworks = 'Frameworks/TuttiMobileGo.xcframework'
end
@@ -0,0 +1,46 @@
# CocoaPods intermittently fails while resolving pnpm-backed local Pod paths
# with `ArgumentError: pathname contains null byte`. Preserve CocoaPods'
# filesystem-group behavior without resolving those symlinks through
# Pathname#realdirpath.
module CocoaPodsPathnameWorkaround
def group_for_path_in_group(
absolute_pathname,
group,
reflect_file_system_structure,
base_path = nil
)
unless absolute_pathname.absolute?
raise ArgumentError, "Paths must be absolute #{absolute_pathname}"
end
unless base_path.nil? || base_path.absolute?
raise ArgumentError, "Paths must be absolute #{base_path}"
end
relative_base = base_path.nil? ? group.real_path : base_path.cleanpath
relative_pathname = absolute_pathname.relative_path_from(relative_base)
relative_dir = relative_pathname.dirname
if reflect_file_system_structure
path = relative_base
relative_dir.each_filename do |name|
break if name.to_s.downcase.include? '.lproj'
next if name == '.'
path += name
group = group.children.find { |child| child.display_name == name } ||
group.new_group(name, path)
end
end
if relative_dir.basename.to_s.downcase.include? '.lproj'
group_name = variant_group_name(absolute_pathname)
lproj_parent_dir = absolute_pathname.dirname.dirname
group = @variant_groups_by_path_and_name[[lproj_parent_dir, group_name]] ||=
group.new_variant_group(group_name, lproj_parent_dir)
end
group
end
end
Pod::Project.prepend(CocoaPodsPathnameWorkaround)