diff --git a/.gitignore b/.gitignore index cc99c67ba..3d7b5e540 100644 --- a/.gitignore +++ b/.gitignore @@ -11,6 +11,7 @@ AGENTS.md # Xcode / iOS local state /mobile/ios/Kinic.xcodeproj/ +/mobile/ios/Kinic-manual-*.xcodeproj/ **/DerivedData/ **/build/ **/xcuserdata/ diff --git a/mobile/ios/KinicUITests/VaultUITests.swift b/mobile/ios/KinicUITests/VaultUITests.swift index 9a5d5cc8f..80ea1f8ef 100644 --- a/mobile/ios/KinicUITests/VaultUITests.swift +++ b/mobile/ios/KinicUITests/VaultUITests.swift @@ -9,6 +9,7 @@ final class VaultUITests: XCTestCase { continueAfterFailure = false } + @MainActor private func launchVault(screen: String = "list", darkMode: Bool = true) -> XCUIApplication { let app = XCUIApplication() app.launchEnvironment["KINIC_SCREENSHOT_MODE"] = "vault" diff --git a/mobile/ios/Packages/KinicVaultCore/Sources/KinicVaultCore/VaultCredential.swift b/mobile/ios/Packages/KinicVaultCore/Sources/KinicVaultCore/VaultCredential.swift index 0446dd736..22894949d 100644 --- a/mobile/ios/Packages/KinicVaultCore/Sources/KinicVaultCore/VaultCredential.swift +++ b/mobile/ios/Packages/KinicVaultCore/Sources/KinicVaultCore/VaultCredential.swift @@ -112,25 +112,89 @@ public enum VaultCredentialCodec { "javascript", "data", "vbscript", "blob", "file", "about", "mailto", "tel", ] + /// Zero-allocation UTF-8 fast-path for already-normalized lowercase ASCII multi-label hostnames + /// (non-IPv4, non-punycode). Matches WHATWG URL `https://\(raw)` identically. + @inline(__always) + private static func isFastNormalizedHost(_ raw: String) -> Bool { + var mutable = raw + return mutable.withUTF8 { buf -> Bool in + let count = buf.count + guard count >= 3, count <= 255 else { return false } + var hasDot = false + var labelLen = 0 + var lastLabelStart = 0 + for i in 0..= 0x61 && b <= 0x7A + let isDigit = b >= 0x30 && b <= 0x39 + if !isLowerAlpha && !isDigit && b != 0x2D { + return false + } + if labelLen == 3 && b == 0x2D && buf[i &- 3] == 0x78 && buf[i &- 2] == 0x6E && buf[i &- 1] == 0x2D { + return false + } + labelLen &+= 1 + } + guard hasDot, labelLen > 0 else { return false } + var allDigits = true + for i in lastLabelStart.. 0x39 { allDigits = false; break } + } + if allDigits { return false } + if labelLen >= 2 && buf[lastLabelStart] == 0x30 && buf[lastLabelStart &+ 1] == 0x78 { + var restHex = true + for i in (lastLabelStart &+ 2)..= 0x30 && b <= 0x39) || (b >= 0x61 && b <= 0x66)) { restHex = false; break } + } + if restHex { return false } + } + return true + } + } + public static func normalizeDomain(_ raw: String) -> String? { + if isFastNormalizedHost(raw) { + return raw + } + return normalizeDomainSlow(raw) + } + + internal static func normalizeDomainSlow(_ raw: String) -> String? { let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines) guard !trimmed.isEmpty, trimmed.count <= 2048 else { return nil } + var scheme: String? + var hasSchemeSeparator = false if let colon = trimmed.firstIndex(of: ":") { - let prefix = String(trimmed[..= 0x41 && first <= 0x5A) || (first >= 0x61 && first <= 0x7A), + prefix.utf8.allSatisfy({ + ($0 >= 0x41 && $0 <= 0x5A) || ($0 >= 0x61 && $0 <= 0x7A) + || ($0 >= 0x30 && $0 <= 0x39) || $0 == 0x2B || $0 == 0x2E || $0 == 0x2D + }) + { + let lower = prefix.lowercased() + if blockedSchemes.contains(lower) { return nil } + hasSchemeSeparator = trimmed[trimmed.index(after: colon)...].hasPrefix("//") + if lower != "http" && lower != "https" && lower != "android" && !hasSchemeSeparator { return nil } + scheme = lower } } var candidate = trimmed - if !candidate.contains("://") { + if !hasSchemeSeparator { if candidate.rangeOfCharacter(from: .whitespacesAndNewlines) != nil { return nil } candidate = "https://\(candidate)" } @@ -156,8 +220,11 @@ public enum VaultCredentialCodec { else { return nil } + let isSpecialScheme = scheme == nil || scheme == "http" || scheme == "https" || scheme == "ws" || scheme == "wss" || scheme == "ftp" if endsInNumber(host) { - return normalizeIPv4Host(host) + guard let normalized = normalizeIPv4Host(host) else { return nil } + if !isSpecialScheme && normalized != host { return nil } + return normalized } if host != "localhost" && !host.contains(".") { return nil @@ -269,13 +336,28 @@ public enum VaultCredentialCodec { private static func isIpOrLocalhost(_ host: String) -> Bool { if host == "localhost" { return true } - if host.hasPrefix("[") && host.hasSuffix("]") { return true } - let parts = host.split(separator: ".", omittingEmptySubsequences: false) - return parts.count == 4 && parts.allSatisfy { !$0.isEmpty && $0.count <= 3 && $0.allSatisfy(\.isNumber) } + let utf8 = host.utf8 + if utf8.first == 0x5B && utf8.last == 0x5D { return true } // '[' ... ']' + var groups = 1 + var digits = 0 + for b in utf8 { + if b == 0x2E { // '.' + if digits == 0 || digits > 3 { return false } + groups += 1 + if groups > 4 { return false } + digits = 0 + } else if b >= 0x30 && b <= 0x39 { + digits += 1 + if digits > 3 { return false } + } else { + return false + } + } + return groups == 4 && digits >= 1 && digits <= 3 } fileprivate static func canMatchAsParentDomain(_ domain: String) -> Bool { - guard domain.contains("."), !isIpOrLocalhost(domain) else { return false } + guard domain.utf8.contains(0x2E), !isIpOrLocalhost(domain) else { return false } return !nonMatchableParentDomains.contains(domain) } @@ -381,16 +463,13 @@ public struct VaultDomainIndex { for (index, item) in items.enumerated() { let domains = getDomains(item) guard !domains.isEmpty else { continue } - var seenExact = Set() - var seenParent = Set() + var seen = Set() for raw in domains { - guard let domain = VaultCredentialCodec.normalizeDomain(raw) else { continue } - if seenExact.insert(domain).inserted { - exact[domain, default: []].append(index) - } - if VaultCredentialCodec.canMatchAsParentDomain(domain), - seenParent.insert(domain).inserted - { + guard let domain = VaultCredentialCodec.normalizeDomain(raw), + seen.insert(domain).inserted + else { continue } + exact[domain, default: []].append(index) + if VaultCredentialCodec.canMatchAsParentDomain(domain) { parent[domain, default: []].append(index) } } diff --git a/mobile/ios/Packages/KinicVaultCore/Tests/KinicVaultCoreTests/KinicVaultCoreTests.swift b/mobile/ios/Packages/KinicVaultCore/Tests/KinicVaultCoreTests/KinicVaultCoreTests.swift index a401ebce5..a66d7628d 100644 --- a/mobile/ios/Packages/KinicVaultCore/Tests/KinicVaultCoreTests/KinicVaultCoreTests.swift +++ b/mobile/ios/Packages/KinicVaultCore/Tests/KinicVaultCoreTests/KinicVaultCoreTests.swift @@ -534,20 +534,113 @@ struct KinicVaultCoreTests { ) } - @Test("normalizeDomain matches WHATWG URL behavior for IPv4, IPv6, and non-HTTP schemes") - func normalizeDomainMatchesWHATWG() { - #expect(VaultCredentialCodec.normalizeDomain("https://[::1]") == "[::1]") - #expect(VaultCredentialCodec.normalizeDomain("https://[2001:db8:0:0::1]:8080/a") == "[2001:db8::1]") - #expect(VaultCredentialCodec.normalizeDomain("https://127.1") == "127.0.0.1") - #expect(VaultCredentialCodec.normalizeDomain("https://0x7f.1") == "127.0.0.1") - #expect(VaultCredentialCodec.normalizeDomain("https://2130706433") == "127.0.0.1") - #expect(VaultCredentialCodec.normalizeDomain("https://0177.0.0.1") == "127.0.0.1") - #expect(VaultCredentialCodec.normalizeDomain("https://example.com.") == "example.com") - #expect(VaultCredentialCodec.normalizeDomain("android://jp.1") == nil) - #expect(VaultCredentialCodec.normalizeDomain("https://jp.1") == nil) - #expect(VaultCredentialCodec.normalizeDomain("https://1.2.3.4.5") == nil) - #expect(VaultCredentialCodec.normalizeDomain("https://256.0.0.1") == nil) - #expect(VaultCredentialCodec.normalizeDomain("https://..example.com") == nil) + @Test("Property-based invariants: normalizeDomain fast-path parity, idempotency, matchesDomain isolation, and VaultDomainIndex differential equivalence") + func domainPropertyBasedInvariants() { + var state: UInt64 = 0x2026_1203_CAFE_BABE + func nextUInt64() -> UInt64 { + state &+= 0x9E37_79B9_7F4A_7C15 + var z = state + z = (z ^ (z >> 30)) &* 0xBF58_476D_1CE4_E5B9 + z = (z ^ (z >> 27)) &* 0x94D0_49BB_1331_11EB + return z ^ (z >> 31) + } + func pick(_ arr: [T]) -> T { arr[Int(nextUInt64() % UInt64(arr.count))] } + + let labels = ["a", "sub", "example", "com", "co", "jp", "127", "0", "1", "0x7f", "0x1", "0x", "0177", "xn--b", "", "."] + let schemes = ["", "https://", "http://", "android://", "javascript:"] + + // 1. Fast-path == slow-path parity & idempotency across 600 generated inputs. + for _ in 0..<600 { + let scheme = pick(schemes) + let count = 1 + Int(nextUInt64() % 5) + let host = (0..> "${logFile}" +if [ "$mode" = "archive" ]; then + archive_path="" + project_path="" + while [ $# -gt 0 ]; do + case "$1" in + -archivePath) archive_path="$2"; shift 2 ;; + -project) project_path="$2"; shift 2 ;; + *) shift ;; + esac + done + test -f "$project_path/project.pbxproj" + /usr/bin/plutil -lint "$project_path/project.pbxproj" >/dev/null + grep -q "container:$(basename "$project_path")" "$project_path/xcshareddata/xcschemes/Kinic.xcscheme" + mkdir -p "$archive_path/Products/Applications/KinicWiki.app/PlugIns/KinicShareExtension.appex" + mkdir -p "$archive_path/Products/Applications/KinicWiki.app/PlugIns/KinicWorkItemsWidget.appex" + mkdir -p "$archive_path/Products/Applications/KinicWiki.app/PlugIns/KinicVaultAutoFill.appex" + touch "$archive_path/Products/Applications/KinicWiki.app/PrivacyInfo.xcprivacy" + touch "$archive_path/Products/Applications/KinicWiki.app/PlugIns/KinicShareExtension.appex/PrivacyInfo.xcprivacy" + touch "$archive_path/Products/Applications/KinicWiki.app/PlugIns/KinicWorkItemsWidget.appex/PrivacyInfo.xcprivacy" + touch "$archive_path/Products/Applications/KinicWiki.app/PlugIns/KinicVaultAutoFill.appex/PrivacyInfo.xcprivacy" + cat > "$archive_path/Info.plist" < + +ApplicationProperties +CFBundleIdentifierxyz.kinic.ios.KinicWiki +CFBundleShortVersionString${projectMarketingVersion} +CFBundleVersion999999 + +EOF +elif [ "$mode" = "-exportArchive" ]; then + export_path="" + export_plist="" + while [ $# -gt 0 ]; do + case "$1" in + -exportPath) export_path="$2"; shift 2 ;; + -exportOptionsPlist) export_plist="$2"; shift 2 ;; + *) shift ;; + esac + done + cp "$export_plist" "${exportCopy}" + /usr/bin/plutil -lint "$export_plist" >/dev/null + mkdir -p "$export_path" + touch "$export_path/KinicWiki.ipa" +fi +` + ); + chmodSync(stubXcodebuild, 0o755); + + const stubAsc = join(stubDir, "asc"); + writeFileSync( + stubAsc, + `#!/bin/sh +set -eu +case "$*" in + *"builds uploads list"*) + printf '{"data":[{"attributes":{"state":{"state":"COMPLETE"}}}]}' + ;; +esac +` + ); + chmodSync(stubAsc, 0o755); + + const manualRun = spawnSync( + "/bin/bash", + [testFlightScript, "--manual-signing"], + { + cwd: repoRoot, + encoding: "utf8", + env: { + ...testFlightEnv, + PATH: `${stubDir}:${process.env.PATH ?? ""}`, + ASC_PROFILE: "StubProfile", + KINIC_IOS_BUILD_NUMBER: "999999", + KINIC_IOS_ARCHIVE_PATH: join(stubDir, "KinicWiki.xcarchive"), + KINIC_IOS_EXPORT_PATH: join(stubDir, "export"), + KINIC_IOS_PROFILE_APP: "KinicWiki App & Store \"2026\"", + }, + } + ); + assert.equal(manualRun.status, 0, `${manualRun.stdout}\n${manualRun.stderr}`); + const log = readFileSync(logFile, "utf8"); + assert.doesNotMatch(log, /-allowProvisioningUpdates/); + assert.match(log, /Kinic-manual-.*\.xcodeproj/); + const exportedOptions = readFileSync(exportCopy, "utf8"); + assert.match(exportedOptions, /KinicWiki App & Store "2026"/); +} finally { + rmSync(stubDir, { recursive: true, force: true }); +} + const external = spawnSync( "bash", [testFlightScript, "--sandbox", "--external", "--print-runtime-config"], diff --git a/mobile/ios/scripts/testflight-upload.sh b/mobile/ios/scripts/testflight-upload.sh index 7e4878ae4..398b2e037 100755 --- a/mobile/ios/scripts/testflight-upload.sh +++ b/mobile/ios/scripts/testflight-upload.sh @@ -8,22 +8,25 @@ set -euo pipefail repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd)" # Shell values are explicit invocation inputs and take precedence over local defaults. -caller_asc_app_id_set="${ASC_APP_ID+x}" -caller_asc_app_id="${ASC_APP_ID-}" -caller_asc_profile_set="${ASC_PROFILE+x}" -caller_asc_profile="${ASC_PROFILE-}" -caller_build_number_set="${KINIC_IOS_BUILD_NUMBER+x}" -caller_build_number="${KINIC_IOS_BUILD_NUMBER-}" caller_marketing_version_set="${KINIC_IOS_MARKETING_VERSION+x}" -caller_marketing_version="${KINIC_IOS_MARKETING_VERSION-}" -caller_archive_path_set="${KINIC_IOS_ARCHIVE_PATH+x}" -caller_archive_path="${KINIC_IOS_ARCHIVE_PATH-}" -caller_export_path_set="${KINIC_IOS_EXPORT_PATH+x}" -caller_export_path="${KINIC_IOS_EXPORT_PATH-}" -caller_scheme_set="${KINIC_IOS_SCHEME+x}" -caller_scheme="${KINIC_IOS_SCHEME-}" -caller_configuration_set="${KINIC_IOS_CONFIGURATION+x}" -caller_configuration="${KINIC_IOS_CONFIGURATION-}" +caller_env_vars=( + ASC_APP_ID ASC_PROFILE KINIC_IOS_BUILD_NUMBER KINIC_IOS_MARKETING_VERSION + KINIC_IOS_ARCHIVE_PATH KINIC_IOS_EXPORT_PATH KINIC_IOS_SCHEME KINIC_IOS_CONFIGURATION + KINIC_IOS_SIGNING_STYLE KINIC_IOS_SIGNING_IDENTITY + KINIC_IOS_PROFILE_APP KINIC_IOS_PROFILE_SHARE KINIC_IOS_PROFILE_WIDGET KINIC_IOS_PROFILE_AUTOFILL +) +caller_env_set=() +caller_env_val=() +for _i in "${!caller_env_vars[@]}"; do + _v="${caller_env_vars[$_i]}" + if [[ -n "${!_v+x}" ]]; then + caller_env_set[$_i]=1 + caller_env_val[$_i]="${!_v}" + else + caller_env_set[$_i]=0 + caller_env_val[$_i]="" + fi +done env_files=("$repo_root/mobile/ios/.env.local" "$repo_root/mobile/ios/.env.testflight.local") if [[ -n "${KINIC_IOS_ENV_FILE:-}" ]]; then @@ -38,14 +41,11 @@ for env_file in "${env_files[@]}"; do fi done -[[ -z "$caller_asc_app_id_set" ]] || ASC_APP_ID="$caller_asc_app_id" -[[ -z "$caller_asc_profile_set" ]] || ASC_PROFILE="$caller_asc_profile" -[[ -z "$caller_build_number_set" ]] || KINIC_IOS_BUILD_NUMBER="$caller_build_number" -[[ -z "$caller_marketing_version_set" ]] || KINIC_IOS_MARKETING_VERSION="$caller_marketing_version" -[[ -z "$caller_archive_path_set" ]] || KINIC_IOS_ARCHIVE_PATH="$caller_archive_path" -[[ -z "$caller_export_path_set" ]] || KINIC_IOS_EXPORT_PATH="$caller_export_path" -[[ -z "$caller_scheme_set" ]] || KINIC_IOS_SCHEME="$caller_scheme" -[[ -z "$caller_configuration_set" ]] || KINIC_IOS_CONFIGURATION="$caller_configuration" +for _i in "${!caller_env_vars[@]}"; do + if [[ "${caller_env_set[$_i]}" == "1" ]]; then + printf -v "${caller_env_vars[$_i]}" '%s' "${caller_env_val[$_i]}" + fi +done project="$repo_root/mobile/ios/Kinic.xcodeproj" project_spec="$repo_root/mobile/ios/project.yml" @@ -59,6 +59,12 @@ marketing_version="${KINIC_IOS_MARKETING_VERSION:-}" archive_path_override="${KINIC_IOS_ARCHIVE_PATH:-}" export_path_override="${KINIC_IOS_EXPORT_PATH:-}" asc_profile="${ASC_PROFILE:-}" +signing_style="${KINIC_IOS_SIGNING_STYLE:-automatic}" +signing_identity="${KINIC_IOS_SIGNING_IDENTITY:-iPhone Distribution}" +profile_app="${KINIC_IOS_PROFILE_APP:-KinicWiki App Store 20261130}" +profile_share="${KINIC_IOS_PROFILE_SHARE:-KinicWiki Share App Store 20260930}" +profile_widget="${KINIC_IOS_PROFILE_WIDGET:-KinicWiki Widget App Store 20260930}" +profile_autofill="${KINIC_IOS_PROFILE_AUTOFILL:-KinicWiki Vault AutoFill App Store 20261130}" mode="upload" distribution="external" sandbox_mode=0 @@ -105,6 +111,7 @@ Options: --external Upload a build that can be assigned to external TestFlight groups. This is the default. --internal-only Upload an internal-only TestFlight build. --sandbox Use staging services and force an internal-only build. + --manual-signing Sign archive and export with local App Store provisioning profiles instead of Xcode automatic signing. --print-runtime-config Print the selected runtime settings without building. EOF } @@ -129,6 +136,10 @@ while [[ $# -gt 0 ]]; do distribution="internal-only" shift ;; + --manual-signing) + signing_style="manual" + shift + ;; --print-runtime-config) print_runtime_config=1 shift @@ -174,8 +185,13 @@ if [[ "$sandbox_mode" == "1" ]]; then ) fi +if [[ "$signing_style" != "automatic" && "$signing_style" != "manual" ]]; then + fail "KINIC_IOS_SIGNING_STYLE must be 'automatic' or 'manual' (got: $signing_style)" +fi + if [[ "$print_runtime_config" == "1" ]]; then printf 'distribution=%s\n' "$distribution" + printf 'signing_style=%s\n' "$signing_style" printf 'marketing_version=%s\n' "$marketing_version" printf 'build_number=%s\n' "${build_number:-auto}" printf '%s\n' "${runtime_build_settings[@]}" @@ -184,45 +200,44 @@ fi [[ -n "$asc_profile" ]] || fail "ASC_PROFILE is required" +parse_asc_json() { + node -e ' + const fs = require("fs"); + const mode = process.argv[1]; + const v = JSON.parse(fs.readFileSync(0, "utf8")); + const parseDecimal = (raw) => { + if (typeof raw !== "string" && typeof raw !== "number") return null; + const s = String(raw); + if (!/^\d+$/.test(s)) return null; + const n = BigInt(s); + if (n < 0n || n >= 9223372036854775807n) return null; + return n.toString(10); + }; + let out = null; + if (mode === "build") { + out = parseDecimal(v?.data?.attributes?.version ?? v?.data?.attributes?.buildNumber ?? v?.attributes?.version ?? v?.version ?? v?.buildNumber); + } else if (mode === "upload") { + out = parseDecimal(v?.data?.[0]?.attributes?.cfBundleVersion ?? "0"); + } else if (mode === "upload_state") { + const r = v?.data ?? []; + out = r.length === 1 && typeof r[0]?.attributes?.state?.state === "string" ? r[0].attributes.state.state : null; + } + if (out === null) process.exit(2); + process.stdout.write(out); + ' "$1" +} + resolve_next_build_number() { local build_json upload_json latest_build latest_upload - if ! build_json="$(asc --profile "$asc_profile" builds info \ - --app "$asc_app_id" --latest --platform IOS --output json)"; then - fail "Could not read the latest App Store Connect build with profile $asc_profile" - fi - latest_build="$(printf '%s' "$build_json" | node -e ' - let input = ""; - process.stdin.on("data", (chunk) => { input += chunk; }); - process.stdin.on("end", () => { - const value = JSON.parse(input); - const candidate = value?.data?.attributes?.version - ?? value?.data?.attributes?.buildNumber - ?? value?.attributes?.version - ?? value?.version - ?? value?.buildNumber; - if (!/^\d+$/.test(String(candidate ?? ""))) process.exit(2); - process.stdout.write(String(candidate)); - }); - ')" || fail "Could not parse the latest App Store Connect build number" - if ! upload_json="$(asc --profile "$asc_profile" builds uploads list \ - --app "$asc_app_id" --platform IOS --sort=-cfBundleVersion --limit 1 --output json)"; then - fail "Could not read the latest App Store Connect upload with profile $asc_profile" - fi - latest_upload="$(printf '%s' "$upload_json" | node -e ' - let input = ""; - process.stdin.on("data", (chunk) => { input += chunk; }); - process.stdin.on("end", () => { - const value = JSON.parse(input); - const candidate = value?.data?.[0]?.attributes?.cfBundleVersion ?? "0"; - if (!/^\d+$/.test(String(candidate))) process.exit(2); - process.stdout.write(String(candidate)); - }); - ')" || fail "Could not parse the latest App Store Connect upload number" - if (( latest_upload > latest_build )); then - printf '%s\n' "$((latest_upload + 1))" - else - printf '%s\n' "$((latest_build + 1))" - fi + build_json="$(asc --profile "$asc_profile" builds info --app "$asc_app_id" --latest --platform IOS --output json)" \ + || fail "Could not read the latest App Store Connect build with profile $asc_profile" + latest_build="$(printf '%s' "$build_json" | parse_asc_json build)" \ + || fail "Could not parse the latest App Store Connect build number" + upload_json="$(asc --profile "$asc_profile" builds uploads list --app "$asc_app_id" --platform IOS --sort=-cfBundleVersion --limit 1 --output json)" \ + || fail "Could not read the latest App Store Connect upload with profile $asc_profile" + latest_upload="$(printf '%s' "$upload_json" | parse_asc_json upload)" \ + || fail "Could not parse the latest App Store Connect upload number" + printf '%s\n' "$(( (10#$latest_upload > 10#$latest_build ? 10#$latest_upload : 10#$latest_build) + 1 ))" } if [[ "$sandbox_mode" == "1" || -z "$build_number" ]]; then @@ -246,54 +261,108 @@ fi "$repo_root/mobile/ios/scripts/ensure-xcodegen-project.sh" -export_options="$(mktemp "${TMPDIR:-/tmp}/kinic-testflight-export.XXXXXX.plist")" -trap 'rm -f "$export_options"' EXIT +tmp_dir="$(mktemp -d "${TMPDIR:-/tmp}/kinic-testflight.XXXXXX")" +export_options="$tmp_dir/ExportOptions.plist" +archive_project="$project" +manual_project="" +cleanup() { + rm -rf "$tmp_dir" + if [[ -n "$manual_project" ]]; then + rm -rf "$manual_project" + fi +} +trap cleanup EXIT mkdir -p "$(dirname "$archive_path")" "$export_path" -cat >"$export_options" < - - - - destination - export - manageAppVersionAndBuildNumber - - method - app-store-connect - signingStyle - automatic - teamID - $team_id -EOF +# Single Python invocation writes ExportOptions.plist and (in manual mode) creates the isolated signed xcodeproj. +manual_project="$(python3 - "$project" "$export_options" "$signing_style" "$team_id" "$distribution" "$configuration" "$signing_identity" "$profile_app" "$profile_share" "$profile_widget" "$profile_autofill" <<'PY' +import json, plistlib, shutil, subprocess, sys, tempfile +from pathlib import Path -if [[ "$distribution" == "internal-only" ]]; then - cat >>"$export_options" <testFlightInternalTestingOnly - -EOF -fi +src_project, out_path, signing_style, team_id, distribution, config_name, signing_identity, p_app, p_share, p_widget, p_autofill = sys.argv[1:12] -cat >>"$export_options" <uploadSymbols - - - -EOF +options = { + "destination": "export", + "manageAppVersionAndBuildNumber": False, + "method": "app-store-connect", + "signingStyle": signing_style, + "teamID": team_id, + "uploadSymbols": True, +} +if signing_style == "manual": + options["signingCertificate"] = signing_identity + options["provisioningProfiles"] = { + "xyz.kinic.ios.KinicWiki": p_app, + "xyz.kinic.ios.KinicWiki.ShareExtension": p_share, + "xyz.kinic.ios.KinicWiki.WorkItemsWidget": p_widget, + "xyz.kinic.ios.KinicWiki.VaultAutoFill": p_autofill, + } +if distribution == "internal-only": + options["testFlightInternalTestingOnly"] = True +with open(out_path, "wb") as f: + plistlib.dump(options, f, fmt=plistlib.FMT_XML) + +if signing_style == "manual": + src = Path(src_project) + dst = Path(tempfile.mkdtemp(prefix="Kinic-manual-", suffix=".xcodeproj", dir=src.parent)) + try: + shutil.copytree(src, dst, dirs_exist_ok=True) + pbx_path = dst / "project.pbxproj" + pbx = json.loads(subprocess.check_output(["plutil", "-convert", "json", "-o", "-", str(pbx_path)])) + profiles = { + "$(KINIC_APP_BUNDLE_ID)": p_app, + "$(KINIC_SHARE_EXTENSION_BUNDLE_ID)": p_share, + "$(KINIC_WIDGET_BUNDLE_ID)": p_widget, + "$(KINIC_AUTOFILL_EXTENSION_BUNDLE_ID)": p_autofill, + } + updated = set() + for obj in pbx.get("objects", {}).values(): + if isinstance(obj, dict) and obj.get("isa") == "XCBuildConfiguration" and obj.get("name") == config_name: + settings = obj.get("buildSettings") + bundle_var = settings.get("PRODUCT_BUNDLE_IDENTIFIER") if isinstance(settings, dict) else None + if bundle_var in profiles: + settings.update(CODE_SIGN_STYLE="Manual", CODE_SIGN_IDENTITY=signing_identity, PROVISIONING_PROFILE_SPECIFIER=profiles[bundle_var]) + updated.add(bundle_var) + missing = sorted(set(profiles) - updated) + if missing: + raise SystemExit(f"Failed to patch manual signing for {config_name} targets: {', '.join(missing)}") + with open(pbx_path, "wb") as f: + plistlib.dump(pbx, f, fmt=plistlib.FMT_XML) + schemes_dir = dst / "xcshareddata" / "xcschemes" + if schemes_dir.is_dir(): + for sf in schemes_dir.glob("*.xcscheme"): + sf.write_text(sf.read_text().replace(f"container:{src.name}", f"container:{dst.name}")) + except BaseException: + shutil.rmtree(dst, ignore_errors=True) + raise + print(dst) +PY +)" +if [[ -n "$manual_project" ]]; then + archive_project="$manual_project" +fi -printf 'Archiving %s %s (%s) for App Store Connect (%s)...\n' "$bundle_id" "$marketing_version" "$build_number" "$distribution" -xcodebuild archive \ - -quiet \ - -project "$project" \ - -scheme "$scheme" \ - -configuration "$configuration" \ - -destination "generic/platform=iOS" \ - -archivePath "$archive_path" \ - -allowProvisioningUpdates \ - CURRENT_PROJECT_VERSION="$build_number" \ - MARKETING_VERSION="$marketing_version" \ +archive_cmd=( + xcodebuild archive + -quiet + -project "$archive_project" + -scheme "$scheme" + -configuration "$configuration" + -destination "generic/platform=iOS" + -archivePath "$archive_path" +) +if [[ "$signing_style" == "automatic" ]]; then + archive_cmd+=(-allowProvisioningUpdates) +fi +archive_cmd+=( + "CURRENT_PROJECT_VERSION=$build_number" + "MARKETING_VERSION=$marketing_version" "${runtime_build_settings[@]}" +) + +printf 'Archiving %s %s (%s) for App Store Connect (%s, %s signing)...\n' "$bundle_id" "$marketing_version" "$build_number" "$distribution" "$signing_style" +"${archive_cmd[@]}" archive_bundle_id="$(plutil -extract ApplicationProperties.CFBundleIdentifier raw -o - "$archive_path/Info.plist")" archive_version="$(plutil -extract ApplicationProperties.CFBundleShortVersionString raw -o - "$archive_path/Info.plist")" @@ -302,22 +371,28 @@ archive_build="$(plutil -extract ApplicationProperties.CFBundleVersion raw -o - [[ "$archive_version" == "$marketing_version" ]] || fail "Archive version mismatch: $archive_version" [[ "$archive_build" == "$build_number" ]] || fail "Archive build mismatch: $archive_build" -app_privacy="$archive_path/Products/Applications/KinicWiki.app/PrivacyInfo.xcprivacy" -extension_privacy="$archive_path/Products/Applications/KinicWiki.app/PlugIns/KinicShareExtension.appex/PrivacyInfo.xcprivacy" -widget_privacy="$archive_path/Products/Applications/KinicWiki.app/PlugIns/KinicWorkItemsWidget.appex/PrivacyInfo.xcprivacy" -autofill_privacy="$archive_path/Products/Applications/KinicWiki.app/PlugIns/KinicVaultAutoFill.appex/PrivacyInfo.xcprivacy" -[[ -f "$app_privacy" ]] || fail "PrivacyInfo.xcprivacy missing from app archive" -[[ -f "$extension_privacy" ]] || fail "PrivacyInfo.xcprivacy missing from Share Extension archive" -[[ -f "$widget_privacy" ]] || fail "PrivacyInfo.xcprivacy missing from work items widget archive" -[[ -f "$autofill_privacy" ]] || fail "PrivacyInfo.xcprivacy missing from Vault AutoFill Extension archive" +for _rel in \ + "PrivacyInfo.xcprivacy" \ + "PlugIns/KinicShareExtension.appex/PrivacyInfo.xcprivacy" \ + "PlugIns/KinicWorkItemsWidget.appex/PrivacyInfo.xcprivacy" \ + "PlugIns/KinicVaultAutoFill.appex/PrivacyInfo.xcprivacy"; do + [[ -f "$archive_path/Products/Applications/KinicWiki.app/$_rel" ]] \ + || fail "PrivacyInfo.xcprivacy missing from archive ($_rel)" +done + +export_cmd=( + xcodebuild -exportArchive + -quiet + -archivePath "$archive_path" + -exportPath "$export_path" + -exportOptionsPlist "$export_options" +) +if [[ "$signing_style" == "automatic" ]]; then + export_cmd+=(-allowProvisioningUpdates) +fi printf 'Exporting signed IPA...\n' -xcodebuild -exportArchive \ - -quiet \ - -archivePath "$archive_path" \ - -exportPath "$export_path" \ - -exportOptionsPlist "$export_options" \ - -allowProvisioningUpdates +"${export_cmd[@]}" ipa_path="$export_path/KinicWiki.ipa" [[ -f "$ipa_path" ]] || fail "Exported IPA not found: $ipa_path" @@ -336,18 +411,8 @@ upload_json="$(asc --profile "$asc_profile" builds uploads list \ --cf-bundle-version "$build_number" \ --platform IOS \ --output json)" || fail "Could not verify the App Store Connect upload" -upload_state="$(printf '%s' "$upload_json" | node -e ' - let input = ""; - process.stdin.on("data", (chunk) => { input += chunk; }); - process.stdin.on("end", () => { - const value = JSON.parse(input); - const records = value?.data ?? []; - if (records.length !== 1) process.exit(2); - const state = records[0]?.attributes?.state?.state; - if (typeof state !== "string") process.exit(2); - process.stdout.write(state); - }); -')" || fail "Could not resolve the App Store Connect upload state" +upload_state="$(printf '%s' "$upload_json" | parse_asc_json upload_state)" \ + || fail "Could not resolve the App Store Connect upload state" [[ "$upload_state" == "COMPLETE" ]] \ || fail "App Store Connect rejected or has not completed the upload (state: $upload_state)" diff --git a/packages/vault-crypto/src/credential.ts b/packages/vault-crypto/src/credential.ts index 72e80e105..6c1197a13 100644 --- a/packages/vault-crypto/src/credential.ts +++ b/packages/vault-crypto/src/credential.ts @@ -64,17 +64,64 @@ function dedupeStrings(values: readonly string[], maxItems: number): string[] { // Fast-path for already-normalized lowercase ASCII multi-label hostnames // (non-IPv4, non-punycode). Matches WHATWG URL `https://${raw}` identically. -const FAST_NORMALIZED_HOST_RE = /^[a-z0-9-]+(?:\.[a-z0-9-]+)+$/; -const NUMERIC_FINAL_LABEL_RE = /\.\d+$/; +function isFastNormalizedHost(raw: string): boolean { + const len = raw.length; + if (len < 3 || len > 255) return false; + let hasDot = false; + let labelLen = 0; + let lastLabelStart = 0; + for (let i = 0; i < len; i++) { + const c = raw.charCodeAt(i); + if (c === 46) { // '.' + if (labelLen === 0) return false; + hasDot = true; + labelLen = 0; + lastLabelStart = i + 1; + continue; + } + const isLowerAlpha = c >= 97 && c <= 122; + const isDigit = c >= 48 && c <= 57; + if (!isLowerAlpha && !isDigit && c !== 45) return false; + // Reject punycode labels ("xn--...") so IDNA runs on the slow path. + if ( + labelLen === 3 && + c === 45 && + raw.charCodeAt(i - 3) === 120 && + raw.charCodeAt(i - 2) === 110 && + raw.charCodeAt(i - 1) === 45 + ) { + return false; + } + labelLen++; + } + if (!hasDot || labelLen === 0) return false; + // WHATWG "ends in a number" check: reject final labels that are all-digits + // or 0x[0-9a-f]* (including bare "0x"), routing them through URL(). + let allDigits = true; + for (let i = lastLabelStart; i < len; i++) { + const c = raw.charCodeAt(i); + if (c < 48 || c > 57) { + allDigits = false; + break; + } + } + if (allDigits) return false; + if (labelLen >= 2 && raw.charCodeAt(lastLabelStart) === 48 && raw.charCodeAt(lastLabelStart + 1) === 120) { + let restHex = true; + for (let i = lastLabelStart + 2; i < len; i++) { + const c = raw.charCodeAt(i); + if (!((c >= 48 && c <= 57) || (c >= 97 && c <= 102))) { + restHex = false; + break; + } + } + if (restHex) return false; + } + return true; +} export function normalizeDomain(raw: string): string | null { - if ( - raw.length > 0 && - raw.length <= 255 && - FAST_NORMALIZED_HOST_RE.test(raw) && - !NUMERIC_FINAL_LABEL_RE.test(raw) && - !raw.includes("xn--") - ) { + if (isFastNormalizedHost(raw)) { return raw; } @@ -243,28 +290,24 @@ export function createDomainIndex( for (let idx = 0; idx < items.length; idx++) { const domains = getDomains(items[idx]!); if (!domains?.length) continue; - const seenExact = new Set(); - const seenParent = new Set(); + const seen = new Set(); for (let j = 0; j < domains.length; j++) { const domain = normalizeDomain(domains[j]!); - if (!domain) continue; - if (!seenExact.has(domain)) { - seenExact.add(domain); - let bucket = exactMap.get(domain); - if (!bucket) { - bucket = []; - exactMap.set(domain, bucket); - } - bucket.push(idx); + if (!domain || seen.has(domain)) continue; + seen.add(domain); + let bucket = exactMap.get(domain); + if (!bucket) { + bucket = []; + exactMap.set(domain, bucket); } - if (canMatchAsParentDomain(domain) && !seenParent.has(domain)) { - seenParent.add(domain); - let bucket = parentMap.get(domain); - if (!bucket) { - bucket = []; - parentMap.set(domain, bucket); + bucket.push(idx); + if (canMatchAsParentDomain(domain)) { + let pBucket = parentMap.get(domain); + if (!pBucket) { + pBucket = []; + parentMap.set(domain, pBucket); } - bucket.push(idx); + pBucket.push(idx); } } } diff --git a/packages/vault-crypto/test/credential.pbt.test.ts b/packages/vault-crypto/test/credential.pbt.test.ts index 2fa0ab6b6..e1dfda7aa 100644 --- a/packages/vault-crypto/test/credential.pbt.test.ts +++ b/packages/vault-crypto/test/credential.pbt.test.ts @@ -58,9 +58,9 @@ describe("vault-crypto credential & domain property-based invariants", () => { expect(normalizeDomain(once)).toBe(once); } } - const labels = ["a", "sub", "example", "com", "co", "jp", "127", "0", "1", "", "."]; + const labels = ["a", "sub", "example", "com", "co", "jp", "127", "0", "1", "0x7f", "0x1", "0x", "0177", "xn--b", "", "."]; const schemes = ["", "https://", "http://", "android://", "javascript:"]; - for (let i = 0; i < 400; i++) { + for (let i = 0; i < 600; i++) { const scheme = schemes[Math.floor(rng() * schemes.length)]; const parts = Array.from( { length: 1 + Math.floor(rng() * 5) }, @@ -70,9 +70,14 @@ describe("vault-crypto credential & domain property-based invariants", () => { const once = normalizeDomain(raw); if (once !== null) { expect(normalizeDomain(once)).toBe(once); + expect(normalizeDomain(`https://${once}`)).toBe(once); expect(once).toBe(once.toLowerCase()); expect(once.endsWith(".")).toBe(false); } + // Fast-path parity: bare host without scheme must match `https://${raw}` identically. + if (scheme === "" && !raw.includes(":")) { + expect(normalizeDomain(raw), `scheme parity for ${raw}`).toBe(normalizeDomain(`https://${raw}`)); + } } }); diff --git a/packages/vault-crypto/test/credential.test.ts b/packages/vault-crypto/test/credential.test.ts index b6a1e46ec..7cc2b5e43 100644 --- a/packages/vault-crypto/test/credential.test.ts +++ b/packages/vault-crypto/test/credential.test.ts @@ -1,6 +1,8 @@ +import { readFileSync } from "node:fs"; import { describe, expect, it } from "vitest"; import { buildCredentialMetadata, + createDomainIndex, extractDomains, matchesDomain, matchesMetadataQuery, @@ -121,4 +123,28 @@ describe("credential schema and domain helpers", () => { expect(matchesMetadataQuery(meta, "dev")).toBe(true); expect(matchesMetadataQuery(meta, "other")).toBe(false); }); + + it("matches shared Swift/TypeScript domain normalization and matching vectors", () => { + const vectorsUrl = new URL("../../../shared/vault-domain-vectors.json", import.meta.url); + const vectors = JSON.parse(readFileSync(vectorsUrl, "utf8")) as { + normalizeDomain: Array<{ input: string; expected: string | null }>; + matchesDomain: Array<{ domains: string[]; queryHost: string; expected: boolean }>; + }; + + expect(vectors.normalizeDomain.length).toBeGreaterThan(0); + expect(vectors.matchesDomain.length).toBeGreaterThan(0); + + for (const tc of vectors.normalizeDomain) { + expect(normalizeDomain(tc.input), `normalizeDomain(${JSON.stringify(tc.input)})`).toBe(tc.expected); + } + + for (const tc of vectors.matchesDomain) { + expect( + matchesDomain(tc.domains, tc.queryHost), + `matchesDomain(${JSON.stringify(tc.domains)}, ${JSON.stringify(tc.queryHost)})`, + ).toBe(tc.expected); + const index = createDomainIndex([{ domains: tc.domains }], (item) => item.domains); + expect(index.match(tc.queryHost).length > 0).toBe(tc.expected); + } + }); }); diff --git a/shared/vault-domain-vectors.json b/shared/vault-domain-vectors.json new file mode 100644 index 000000000..fad4e4c48 --- /dev/null +++ b/shared/vault-domain-vectors.json @@ -0,0 +1,58 @@ +{ + "normalizeDomain": [ + { "input": "https://GitHub.COM/login", "expected": "github.com" }, + { "input": "github.com", "expected": "github.com" }, + { "input": "https://example.com.", "expected": "example.com" }, + { "input": "https://sub.example.com:8443/path?a=1", "expected": "sub.example.com" }, + { "input": "http://localhost:3000", "expected": "localhost" }, + { "input": "localhost", "expected": "localhost" }, + { "input": "https://127.0.0.1:8080/login", "expected": "127.0.0.1" }, + { "input": "https://127.1", "expected": "127.0.0.1" }, + { "input": "https://0x7f.1", "expected": "127.0.0.1" }, + { "input": "0x7f.0x1", "expected": "127.0.0.1" }, + { "input": "https://0x7f.0x1", "expected": "127.0.0.1" }, + { "input": "0x7f.0x", "expected": "127.0.0.0" }, + { "input": "foo.0x1", "expected": null }, + { "input": "https://foo.0x1", "expected": null }, + { "input": "https://2130706433", "expected": "127.0.0.1" }, + { "input": "https://0177.0.0.1", "expected": "127.0.0.1" }, + { "input": "ftp://127.1", "expected": "127.0.0.1" }, + { "input": "ws://127.1", "expected": "127.0.0.1" }, + { "input": "wss://127.1", "expected": "127.0.0.1" }, + { "input": "https://[::1]", "expected": "[::1]" }, + { "input": "https://[2001:db8:0:0::1]:8080/a", "expected": "[2001:db8::1]" }, + { "input": "example.com/a://b", "expected": "example.com" }, + { "input": "android://com.example.app", "expected": "com.example.app" }, + { "input": "android://12345", "expected": null }, + { "input": "android://127.1", "expected": null }, + { "input": "android://127.0.0.1", "expected": "127.0.0.1" }, + { "input": "android://jp.1", "expected": null }, + { "input": "https://jp.1", "expected": null }, + { "input": "https://1.2.3.4.5", "expected": null }, + { "input": "https://256.0.0.1", "expected": null }, + { "input": "https://..example.com", "expected": null }, + { "input": "https://example..com", "expected": null }, + { "input": "javascript:alert(1)", "expected": null }, + { "input": "data:text/html,hi", "expected": null }, + { "input": "mailto:alice@example.com", "expected": null }, + { "input": "intranet", "expected": null }, + { "input": "", "expected": null }, + { "input": " ", "expected": null } + ], + "matchesDomain": [ + { "domains": ["github.com"], "queryHost": "github.com", "expected": true }, + { "domains": ["github.com"], "queryHost": "api.github.com", "expected": true }, + { "domains": ["api.github.com"], "queryHost": "github.com", "expected": false }, + { "domains": ["github.com"], "queryHost": "evilgithub.com", "expected": false }, + { "domains": ["co.jp"], "queryHost": "example.co.jp", "expected": false }, + { "domains": ["github.io"], "queryHost": "user.github.io", "expected": false }, + { "domains": ["github.io"], "queryHost": "github.io", "expected": true }, + { "domains": ["icp0.io"], "queryHost": "abc.icp0.io", "expected": false }, + { "domains": ["localhost"], "queryHost": "sub.localhost", "expected": false }, + { "domains": ["localhost"], "queryHost": "localhost", "expected": true }, + { "domains": ["127.0.0.1"], "queryHost": "127.1", "expected": true }, + { "domains": ["[::1]"], "queryHost": "https://[::1]:3000", "expected": true }, + { "domains": ["other.example", "github.com"], "queryHost": "api.github.com", "expected": true }, + { "domains": ["other.example", "sub.example.com"], "queryHost": "example.com", "expected": false } + ] +}