From 385d07decef0ff394b80ae6fab12caa4f4935aa1 Mon Sep 17 00:00:00 2001 From: hude Date: Thu, 3 Dec 2026 14:17:55 +0900 Subject: [PATCH 1/5] chore(ios): add manual-signing mode to testflight-upload, shared Swift/TS domain vectors, and fix VaultUITests MainActor warning --- mobile/ios/KinicUITests/VaultUITests.swift | 1 + .../KinicVaultCoreTests.swift | 41 +++++++ mobile/ios/scripts/check-sandbox-runtime.mjs | 9 ++ mobile/ios/scripts/testflight-upload.sh | 115 +++++++++++++++++- packages/vault-crypto/test/credential.test.ts | 23 ++++ shared/vault-domain-vectors.json | 44 +++++++ 6 files changed, 228 insertions(+), 5 deletions(-) create mode 100644 shared/vault-domain-vectors.json 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/Tests/KinicVaultCoreTests/KinicVaultCoreTests.swift b/mobile/ios/Packages/KinicVaultCore/Tests/KinicVaultCoreTests/KinicVaultCoreTests.swift index a401ebce5..180cd1666 100644 --- a/mobile/ios/Packages/KinicVaultCore/Tests/KinicVaultCoreTests/KinicVaultCoreTests.swift +++ b/mobile/ios/Packages/KinicVaultCore/Tests/KinicVaultCoreTests/KinicVaultCoreTests.swift @@ -550,6 +550,47 @@ struct KinicVaultCoreTests { #expect(VaultCredentialCodec.normalizeDomain("https://..example.com") == nil) } + @Test("Matches shared Swift/TypeScript domain normalization and matching vectors") + func matchesSharedDomainVectors() throws { + struct SharedDomainVectors: Decodable { + struct NormalizeCase: Decodable { + let input: String + let expected: String? + } + struct MatchCase: Decodable { + let domains: [String] + let queryHost: String + let expected: Bool + } + let normalizeDomain: [NormalizeCase] + let matchesDomain: [MatchCase] + } + + // File sits at mobile/ios/Packages/KinicVaultCore/Tests/KinicVaultCoreTests/KinicVaultCoreTests.swift + var repoRoot = URL(fileURLWithPath: #filePath) + for _ in 0..<7 { + repoRoot.deleteLastPathComponent() + } + let vectorsURL = repoRoot.appendingPathComponent("shared/vault-domain-vectors.json") + let data = try Data(contentsOf: vectorsURL) + let vectors = try JSONDecoder().decode(SharedDomainVectors.self, from: data) + + for tc in vectors.normalizeDomain { + #expect( + VaultCredentialCodec.normalizeDomain(tc.input) == tc.expected, + "normalizeDomain(\(tc.input))" + ) + } + for tc in vectors.matchesDomain { + #expect( + VaultCredentialCodec.matchesDomain(domains: tc.domains, queryHost: tc.queryHost) == tc.expected, + "matchesDomain(\(tc.domains), \(tc.queryHost))" + ) + let index = VaultDomainIndex(items: [tc.domains], domains: { $0 }) + #expect(!index.match(queryHost: tc.queryHost).isEmpty == tc.expected) + } + } + @Test("listCandidates prefilters with verified encrypted index and never drops incomplete manifests") func listCandidatesSkipsUnrelatedChunkDecryption() throws { let context = try makeTestContext() diff --git a/mobile/ios/scripts/check-sandbox-runtime.mjs b/mobile/ios/scripts/check-sandbox-runtime.mjs index 83dc0fd9d..5af925896 100644 --- a/mobile/ios/scripts/check-sandbox-runtime.mjs +++ b/mobile/ios/scripts/check-sandbox-runtime.mjs @@ -40,8 +40,17 @@ const testFlight = spawnSync( { cwd: repoRoot, encoding: "utf8", env: testFlightEnv } ); assert.match(testFlight.stdout, /distribution=internal-only/); +assert.match(testFlight.stdout, /signing_style=automatic/); assert.match(testFlight.stdout, new RegExp(`marketing_version=${projectMarketingVersion}`)); +const manualSigning = spawnSync( + "bash", + [testFlightScript, "--manual-signing", "--print-runtime-config"], + { cwd: repoRoot, encoding: "utf8", env: testFlightEnv } +); +assert.equal(manualSigning.status, 0, manualSigning.stderr); +assert.match(manualSigning.stdout, /signing_style=manual/); + 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..e95320639 100755 --- a/mobile/ios/scripts/testflight-upload.sh +++ b/mobile/ios/scripts/testflight-upload.sh @@ -24,6 +24,18 @@ 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_signing_style_set="${KINIC_IOS_SIGNING_STYLE+x}" +caller_signing_style="${KINIC_IOS_SIGNING_STYLE-}" +caller_signing_identity_set="${KINIC_IOS_SIGNING_IDENTITY+x}" +caller_signing_identity="${KINIC_IOS_SIGNING_IDENTITY-}" +caller_profile_app_set="${KINIC_IOS_PROFILE_APP+x}" +caller_profile_app="${KINIC_IOS_PROFILE_APP-}" +caller_profile_share_set="${KINIC_IOS_PROFILE_SHARE+x}" +caller_profile_share="${KINIC_IOS_PROFILE_SHARE-}" +caller_profile_widget_set="${KINIC_IOS_PROFILE_WIDGET+x}" +caller_profile_widget="${KINIC_IOS_PROFILE_WIDGET-}" +caller_profile_autofill_set="${KINIC_IOS_PROFILE_AUTOFILL+x}" +caller_profile_autofill="${KINIC_IOS_PROFILE_AUTOFILL-}" env_files=("$repo_root/mobile/ios/.env.local" "$repo_root/mobile/ios/.env.testflight.local") if [[ -n "${KINIC_IOS_ENV_FILE:-}" ]]; then @@ -46,6 +58,12 @@ done [[ -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" +[[ -z "$caller_signing_style_set" ]] || KINIC_IOS_SIGNING_STYLE="$caller_signing_style" +[[ -z "$caller_signing_identity_set" ]] || KINIC_IOS_SIGNING_IDENTITY="$caller_signing_identity" +[[ -z "$caller_profile_app_set" ]] || KINIC_IOS_PROFILE_APP="$caller_profile_app" +[[ -z "$caller_profile_share_set" ]] || KINIC_IOS_PROFILE_SHARE="$caller_profile_share" +[[ -z "$caller_profile_widget_set" ]] || KINIC_IOS_PROFILE_WIDGET="$caller_profile_widget" +[[ -z "$caller_profile_autofill_set" ]] || KINIC_IOS_PROFILE_AUTOFILL="$caller_profile_autofill" project="$repo_root/mobile/ios/Kinic.xcodeproj" project_spec="$repo_root/mobile/ios/project.yml" @@ -59,6 +77,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 +129,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 +154,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 +203,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[@]}" @@ -247,7 +281,48 @@ 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 +xcodeproj_patched=0 +cleanup() { + rm -f "$export_options" + if [[ "$xcodeproj_patched" == "1" ]]; then + "$repo_root/mobile/ios/scripts/ensure-xcodegen-project.sh" >/dev/null 2>&1 || true + fi +} +trap cleanup EXIT + +if [[ "$signing_style" == "manual" ]]; then + python3 - "$project/project.pbxproj" "$signing_identity" "$profile_app" "$profile_share" "$profile_widget" "$profile_autofill" <<'PY' +from pathlib import Path +import re +import sys + +pbx_path, signing_identity, p_app, p_share, p_widget, p_autofill = sys.argv[1:7] +pbx = Path(pbx_path) +text = pbx.read_text() + +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, +} + +def patch_block(m): + block = m.group(0) + for bundle_var, profile in profiles.items(): + if f'PRODUCT_BUNDLE_IDENTIFIER = "{bundle_var}";' in block or f'PRODUCT_BUNDLE_IDENTIFIER = {bundle_var};' in block: + block = block.replace( + 'PRODUCT_BUNDLE_IDENTIFIER =', + f'CODE_SIGN_IDENTITY = "{signing_identity}";\n\t\t\t\tCODE_SIGN_STYLE = Manual;\n\t\t\t\tPROVISIONING_PROFILE_SPECIFIER = "{profile}";\n\t\t\t\tPRODUCT_BUNDLE_IDENTIFIER =', + 1, + ) + break + return block + +pbx.write_text(re.sub(r'buildSettings = \{[^}]*\};', patch_block, text)) +PY + xcodeproj_patched=1 +fi mkdir -p "$(dirname "$archive_path")" "$export_path" @@ -263,11 +338,29 @@ cat >"$export_options" <method app-store-connect signingStyle - automatic + $signing_style teamID $team_id EOF +if [[ "$signing_style" == "manual" ]]; then + cat >>"$export_options" <signingCertificate + $signing_identity + provisioningProfiles + + xyz.kinic.ios.KinicWiki + $profile_app + xyz.kinic.ios.KinicWiki.ShareExtension + $profile_share + xyz.kinic.ios.KinicWiki.WorkItemsWidget + $profile_widget + xyz.kinic.ios.KinicWiki.VaultAutoFill + $profile_autofill + +EOF +fi + if [[ "$distribution" == "internal-only" ]]; then cat >>"$export_options" <testFlightInternalTestingOnly @@ -282,7 +375,14 @@ cat >>"$export_options" < EOF -printf 'Archiving %s %s (%s) for App Store Connect (%s)...\n' "$bundle_id" "$marketing_version" "$build_number" "$distribution" +archive_signing_flags=() +export_signing_flags=() +if [[ "$signing_style" == "automatic" ]]; then + archive_signing_flags+=(-allowProvisioningUpdates) + export_signing_flags+=(-allowProvisioningUpdates) +fi + +printf 'Archiving %s %s (%s) for App Store Connect (%s, %s signing)...\n' "$bundle_id" "$marketing_version" "$build_number" "$distribution" "$signing_style" xcodebuild archive \ -quiet \ -project "$project" \ @@ -290,11 +390,16 @@ xcodebuild archive \ -configuration "$configuration" \ -destination "generic/platform=iOS" \ -archivePath "$archive_path" \ - -allowProvisioningUpdates \ + "${archive_signing_flags[@]}" \ CURRENT_PROJECT_VERSION="$build_number" \ MARKETING_VERSION="$marketing_version" \ "${runtime_build_settings[@]}" +if [[ "$xcodeproj_patched" == "1" ]]; then + "$repo_root/mobile/ios/scripts/ensure-xcodegen-project.sh" + xcodeproj_patched=0 +fi + 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")" archive_build="$(plutil -extract ApplicationProperties.CFBundleVersion raw -o - "$archive_path/Info.plist")" @@ -317,7 +422,7 @@ xcodebuild -exportArchive \ -archivePath "$archive_path" \ -exportPath "$export_path" \ -exportOptionsPlist "$export_options" \ - -allowProvisioningUpdates + "${export_signing_flags[@]}" ipa_path="$export_path/KinicWiki.ipa" [[ -f "$ipa_path" ]] || fail "Exported IPA not found: $ipa_path" diff --git a/packages/vault-crypto/test/credential.test.ts b/packages/vault-crypto/test/credential.test.ts index b6a1e46ec..d5934820b 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,25 @@ 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 }>; + }; + + 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..47064b694 --- /dev/null +++ b/shared/vault-domain-vectors.json @@ -0,0 +1,44 @@ +{ + "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": "https://2130706433", "expected": "127.0.0.1" }, + { "input": "https://0177.0.0.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": "android://com.example.app", "expected": "com.example.app" }, + { "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 } + ] +} From 54e99a01cde43d43f26d19944d8a3d6299a9c047 Mon Sep 17 00:00:00 2001 From: hude Date: Thu, 3 Dec 2026 14:22:34 +0900 Subject: [PATCH 2/5] fix(ios): harden manual-signing script for Bash 3.2, isolated XML plist patching, and strengthen tests --- .../KinicVaultCoreTests.swift | 2 + mobile/ios/scripts/check-sandbox-runtime.mjs | 108 +++++++++- mobile/ios/scripts/testflight-upload.sh | 201 +++++++++--------- packages/vault-crypto/test/credential.test.ts | 3 + shared/vault-domain-vectors.json | 4 +- 5 files changed, 218 insertions(+), 100 deletions(-) diff --git a/mobile/ios/Packages/KinicVaultCore/Tests/KinicVaultCoreTests/KinicVaultCoreTests.swift b/mobile/ios/Packages/KinicVaultCore/Tests/KinicVaultCoreTests/KinicVaultCoreTests.swift index 180cd1666..c996c21df 100644 --- a/mobile/ios/Packages/KinicVaultCore/Tests/KinicVaultCoreTests/KinicVaultCoreTests.swift +++ b/mobile/ios/Packages/KinicVaultCore/Tests/KinicVaultCoreTests/KinicVaultCoreTests.swift @@ -574,6 +574,8 @@ struct KinicVaultCoreTests { let vectorsURL = repoRoot.appendingPathComponent("shared/vault-domain-vectors.json") let data = try Data(contentsOf: vectorsURL) let vectors = try JSONDecoder().decode(SharedDomainVectors.self, from: data) + #expect(!vectors.normalizeDomain.isEmpty) + #expect(!vectors.matchesDomain.isEmpty) for tc in vectors.normalizeDomain { #expect( diff --git a/mobile/ios/scripts/check-sandbox-runtime.mjs b/mobile/ios/scripts/check-sandbox-runtime.mjs index 5af925896..1385e6339 100644 --- a/mobile/ios/scripts/check-sandbox-runtime.mjs +++ b/mobile/ios/scripts/check-sandbox-runtime.mjs @@ -1,6 +1,6 @@ import assert from "node:assert/strict"; import { spawnSync } from "node:child_process"; -import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { chmodSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; @@ -14,6 +14,7 @@ const projectSpec = join(repoRoot, "mobile", "ios", "project.yml"); const projectMarketingVersion = readFileSync(projectSpec, "utf8").match(/^\s*MARKETING_VERSION:\s*"([^"]+)"\s*$/mu)?.[1]; assert.ok(projectMarketingVersion, "project MARKETING_VERSION is missing"); const testFlightEnv = { ...process.env, KINIC_IOS_MARKETING_VERSION: projectMarketingVersion }; +delete testFlightEnv.KINIC_IOS_SIGNING_STYLE; const required = [ "KINIC_DEPLOYMENT_ENVIRONMENT=sandbox", "KINIC_CANISTER_ID=3ryrw-kyaaa-aaaaf-qgxpq-cai", @@ -44,13 +45,114 @@ assert.match(testFlight.stdout, /signing_style=automatic/); assert.match(testFlight.stdout, new RegExp(`marketing_version=${projectMarketingVersion}`)); const manualSigning = spawnSync( - "bash", - [testFlightScript, "--manual-signing", "--print-runtime-config"], + "/bin/bash", + [testFlightScript, "--sandbox", "--manual-signing", "--print-runtime-config"], { cwd: repoRoot, encoding: "utf8", env: testFlightEnv } ); assert.equal(manualSigning.status, 0, manualSigning.stderr); +assert.match(manualSigning.stdout, /distribution=internal-only/); assert.match(manualSigning.stdout, /signing_style=manual/); +// Verify --manual-signing end-to-end under macOS /bin/bash (Bash 3.2) with stubbed xcodebuild/asc +// so empty-array expansion, isolated project patching, and plist escaping are exercised directly. +const stubDir = mkdtempSync(join(tmpdir(), "kinic-testflight-stub-")); +try { + const logFile = join(stubDir, "xcodebuild.log"); + const exportCopy = join(stubDir, "export-options.plist"); + const stubXcodebuild = join(stubDir, "xcodebuild"); + writeFileSync( + stubXcodebuild, + `#!/bin/sh +set -eu +printf '%s\\n' "$*" >> "${logFile}" +mode="$1" +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" + 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\./); + 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 e95320639..1ad3018c0 100755 --- a/mobile/ios/scripts/testflight-upload.sh +++ b/mobile/ios/scripts/testflight-upload.sh @@ -281,24 +281,33 @@ fi "$repo_root/mobile/ios/scripts/ensure-xcodegen-project.sh" export_options="$(mktemp "${TMPDIR:-/tmp}/kinic-testflight-export.XXXXXX.plist")" -xcodeproj_patched=0 +archive_project="$project" +manual_project="" cleanup() { rm -f "$export_options" - if [[ "$xcodeproj_patched" == "1" ]]; then - "$repo_root/mobile/ios/scripts/ensure-xcodegen-project.sh" >/dev/null 2>&1 || true + if [[ -n "$manual_project" ]]; then + rm -rf "$manual_project" fi } trap cleanup EXIT if [[ "$signing_style" == "manual" ]]; then - python3 - "$project/project.pbxproj" "$signing_identity" "$profile_app" "$profile_share" "$profile_widget" "$profile_autofill" <<'PY' -from pathlib import Path -import re + manual_project_base="$(mktemp -d "$repo_root/mobile/ios/.Kinic-manual.XXXXXX")" + manual_project="${manual_project_base}.xcodeproj" + rmdir "$manual_project_base" + cp -R "$project" "$manual_project" + archive_project="$manual_project" + + python3 - "$manual_project/project.pbxproj" "$configuration" "$signing_identity" "$profile_app" "$profile_share" "$profile_widget" "$profile_autofill" <<'PY' +import json +import plistlib +import subprocess import sys -pbx_path, signing_identity, p_app, p_share, p_widget, p_autofill = sys.argv[1:7] -pbx = Path(pbx_path) -text = pbx.read_text() +pbx_path, config_name, signing_identity, p_app, p_share, p_widget, p_autofill = sys.argv[1:8] +raw_json = subprocess.check_output(["plutil", "-convert", "json", "-o", "-", pbx_path]) +pbx = json.loads(raw_json) +objects = pbx.get("objects", {}) profiles = { "$(KINIC_APP_BUNDLE_ID)": p_app, @@ -307,98 +316,92 @@ profiles = { "$(KINIC_AUTOFILL_EXTENSION_BUNDLE_ID)": p_autofill, } -def patch_block(m): - block = m.group(0) - for bundle_var, profile in profiles.items(): - if f'PRODUCT_BUNDLE_IDENTIFIER = "{bundle_var}";' in block or f'PRODUCT_BUNDLE_IDENTIFIER = {bundle_var};' in block: - block = block.replace( - 'PRODUCT_BUNDLE_IDENTIFIER =', - f'CODE_SIGN_IDENTITY = "{signing_identity}";\n\t\t\t\tCODE_SIGN_STYLE = Manual;\n\t\t\t\tPROVISIONING_PROFILE_SPECIFIER = "{profile}";\n\t\t\t\tPRODUCT_BUNDLE_IDENTIFIER =', - 1, - ) - break - return block - -pbx.write_text(re.sub(r'buildSettings = \{[^}]*\};', patch_block, text)) +updated = set() +for obj in objects.values(): + if not isinstance(obj, dict) or obj.get("isa") != "XCBuildConfiguration": + continue + if obj.get("name") != config_name: + continue + settings = obj.get("buildSettings") + if not isinstance(settings, dict): + continue + bundle_var = settings.get("PRODUCT_BUNDLE_IDENTIFIER") + if bundle_var in profiles: + settings["CODE_SIGN_STYLE"] = "Manual" + settings["CODE_SIGN_IDENTITY"] = signing_identity + settings["PROVISIONING_PROFILE_SPECIFIER"] = profiles[bundle_var] + updated.add(bundle_var) + +missing = sorted(set(profiles.keys()) - 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) PY - xcodeproj_patched=1 fi mkdir -p "$(dirname "$archive_path")" "$export_path" -cat >"$export_options" < - - - - destination - export - manageAppVersionAndBuildNumber - - method - app-store-connect - signingStyle - $signing_style - teamID - $team_id -EOF - -if [[ "$signing_style" == "manual" ]]; then - cat >>"$export_options" <signingCertificate - $signing_identity - provisioningProfiles - - xyz.kinic.ios.KinicWiki - $profile_app - xyz.kinic.ios.KinicWiki.ShareExtension - $profile_share - xyz.kinic.ios.KinicWiki.WorkItemsWidget - $profile_widget - xyz.kinic.ios.KinicWiki.VaultAutoFill - $profile_autofill - -EOF -fi - -if [[ "$distribution" == "internal-only" ]]; then - cat >>"$export_options" <testFlightInternalTestingOnly - -EOF -fi +python3 - "$export_options" "$signing_style" "$team_id" "$distribution" "$signing_identity" "$profile_app" "$profile_share" "$profile_widget" "$profile_autofill" <<'PY' +import plistlib +import sys -cat >>"$export_options" <uploadSymbols - - - -EOF +( + out_path, + signing_style, + team_id, + distribution, + signing_identity, + p_app, + p_share, + p_widget, + p_autofill, +) = sys.argv[1:10] + +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) +PY -archive_signing_flags=() -export_signing_flags=() +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_signing_flags+=(-allowProvisioningUpdates) - export_signing_flags+=(-allowProvisioningUpdates) + archive_cmd+=(-allowProvisioningUpdates) fi - -printf 'Archiving %s %s (%s) for App Store Connect (%s, %s signing)...\n' "$bundle_id" "$marketing_version" "$build_number" "$distribution" "$signing_style" -xcodebuild archive \ - -quiet \ - -project "$project" \ - -scheme "$scheme" \ - -configuration "$configuration" \ - -destination "generic/platform=iOS" \ - -archivePath "$archive_path" \ - "${archive_signing_flags[@]}" \ - CURRENT_PROJECT_VERSION="$build_number" \ - MARKETING_VERSION="$marketing_version" \ +archive_cmd+=( + "CURRENT_PROJECT_VERSION=$build_number" + "MARKETING_VERSION=$marketing_version" "${runtime_build_settings[@]}" +) -if [[ "$xcodeproj_patched" == "1" ]]; then - "$repo_root/mobile/ios/scripts/ensure-xcodegen-project.sh" - xcodeproj_patched=0 -fi +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")" @@ -416,13 +419,19 @@ autofill_privacy="$archive_path/Products/Applications/KinicWiki.app/PlugIns/Kini [[ -f "$widget_privacy" ]] || fail "PrivacyInfo.xcprivacy missing from work items widget archive" [[ -f "$autofill_privacy" ]] || fail "PrivacyInfo.xcprivacy missing from Vault AutoFill Extension archive" +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" \ - "${export_signing_flags[@]}" +"${export_cmd[@]}" ipa_path="$export_path/KinicWiki.ipa" [[ -f "$ipa_path" ]] || fail "Exported IPA not found: $ipa_path" diff --git a/packages/vault-crypto/test/credential.test.ts b/packages/vault-crypto/test/credential.test.ts index d5934820b..7cc2b5e43 100644 --- a/packages/vault-crypto/test/credential.test.ts +++ b/packages/vault-crypto/test/credential.test.ts @@ -131,6 +131,9 @@ describe("credential schema and domain helpers", () => { 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); } diff --git a/shared/vault-domain-vectors.json b/shared/vault-domain-vectors.json index 47064b694..b3798e819 100644 --- a/shared/vault-domain-vectors.json +++ b/shared/vault-domain-vectors.json @@ -39,6 +39,8 @@ { "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": ["[::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 } ] } From 07c93f05e10fd8037870d78887bab067314d851e Mon Sep 17 00:00:00 2001 From: hude Date: Thu, 3 Dec 2026 14:41:58 +0900 Subject: [PATCH 3/5] fix(ios): rewrite scheme container for isolated manual xcodeproj, use unique mktemp dir, and forward non-archive stub xcodebuild calls --- .gitignore | 1 + mobile/ios/scripts/check-sandbox-runtime.mjs | 15 ++- mobile/ios/scripts/testflight-upload.sh | 103 +++++++++++-------- 3 files changed, 73 insertions(+), 46 deletions(-) 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/scripts/check-sandbox-runtime.mjs b/mobile/ios/scripts/check-sandbox-runtime.mjs index 1385e6339..daedb4d3a 100644 --- a/mobile/ios/scripts/check-sandbox-runtime.mjs +++ b/mobile/ios/scripts/check-sandbox-runtime.mjs @@ -13,7 +13,11 @@ const sandboxWorkerConfig = join(repoRoot, "workers", "payment", "wrangler.sandb const projectSpec = join(repoRoot, "mobile", "ios", "project.yml"); const projectMarketingVersion = readFileSync(projectSpec, "utf8").match(/^\s*MARKETING_VERSION:\s*"([^"]+)"\s*$/mu)?.[1]; assert.ok(projectMarketingVersion, "project MARKETING_VERSION is missing"); -const testFlightEnv = { ...process.env, KINIC_IOS_MARKETING_VERSION: projectMarketingVersion }; +const testFlightEnv = { + ...process.env, + KINIC_IOS_ENV_FILE: "/dev/null", + KINIC_IOS_MARKETING_VERSION: projectMarketingVersion, +}; delete testFlightEnv.KINIC_IOS_SIGNING_STYLE; const required = [ "KINIC_DEPLOYMENT_ENVIRONMENT=sandbox", @@ -64,8 +68,11 @@ try { stubXcodebuild, `#!/bin/sh set -eu +mode="\${1:-}" +if [ "$mode" != "archive" ] && [ "$mode" != "-exportArchive" ]; then + exec /usr/bin/xcodebuild "$@" +fi printf '%s\\n' "$*" >> "${logFile}" -mode="$1" if [ "$mode" = "archive" ]; then archive_path="" project_path="" @@ -77,6 +84,8 @@ if [ "$mode" = "archive" ]; then 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" @@ -146,7 +155,7 @@ esac assert.equal(manualRun.status, 0, `${manualRun.stdout}\n${manualRun.stderr}`); const log = readFileSync(logFile, "utf8"); assert.doesNotMatch(log, /-allowProvisioningUpdates/); - assert.match(log, /\.Kinic-manual\./); + assert.match(log, /Kinic-manual-.*\.xcodeproj/); const exportedOptions = readFileSync(exportCopy, "utf8"); assert.match(exportedOptions, /KinicWiki App & Store "2026"/); } finally { diff --git a/mobile/ios/scripts/testflight-upload.sh b/mobile/ios/scripts/testflight-upload.sh index 1ad3018c0..ef90ec2d4 100755 --- a/mobile/ios/scripts/testflight-upload.sh +++ b/mobile/ios/scripts/testflight-upload.sh @@ -280,11 +280,12 @@ fi "$repo_root/mobile/ios/scripts/ensure-xcodegen-project.sh" -export_options="$(mktemp "${TMPDIR:-/tmp}/kinic-testflight-export.XXXXXX.plist")" +tmp_dir="$(mktemp -d "${TMPDIR:-/tmp}/kinic-testflight.XXXXXX")" +export_options="$tmp_dir/ExportOptions.plist" archive_project="$project" manual_project="" cleanup() { - rm -f "$export_options" + rm -rf "$tmp_dir" if [[ -n "$manual_project" ]]; then rm -rf "$manual_project" fi @@ -292,53 +293,69 @@ cleanup() { trap cleanup EXIT if [[ "$signing_style" == "manual" ]]; then - manual_project_base="$(mktemp -d "$repo_root/mobile/ios/.Kinic-manual.XXXXXX")" - manual_project="${manual_project_base}.xcodeproj" - rmdir "$manual_project_base" - cp -R "$project" "$manual_project" - archive_project="$manual_project" - - python3 - "$manual_project/project.pbxproj" "$configuration" "$signing_identity" "$profile_app" "$profile_share" "$profile_widget" "$profile_autofill" <<'PY' + manual_project="$(python3 - "$project" "$configuration" "$signing_identity" "$profile_app" "$profile_share" "$profile_widget" "$profile_autofill" <<'PY' import json import plistlib +import shutil import subprocess import sys +import tempfile +from pathlib import Path + +src_project, config_name, signing_identity, p_app, p_share, p_widget, p_autofill = sys.argv[1:8] +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" + raw_json = subprocess.check_output(["plutil", "-convert", "json", "-o", "-", str(pbx_path)]) + pbx = json.loads(raw_json) + objects = pbx.get("objects", {}) + + 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, + } -pbx_path, config_name, signing_identity, p_app, p_share, p_widget, p_autofill = sys.argv[1:8] -raw_json = subprocess.check_output(["plutil", "-convert", "json", "-o", "-", pbx_path]) -pbx = json.loads(raw_json) -objects = pbx.get("objects", {}) - -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 objects.values(): - if not isinstance(obj, dict) or obj.get("isa") != "XCBuildConfiguration": - continue - if obj.get("name") != config_name: - continue - settings = obj.get("buildSettings") - if not isinstance(settings, dict): - continue - bundle_var = settings.get("PRODUCT_BUNDLE_IDENTIFIER") - if bundle_var in profiles: - settings["CODE_SIGN_STYLE"] = "Manual" - settings["CODE_SIGN_IDENTITY"] = signing_identity - settings["PROVISIONING_PROFILE_SPECIFIER"] = profiles[bundle_var] - updated.add(bundle_var) - -missing = sorted(set(profiles.keys()) - 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) + updated = set() + for obj in objects.values(): + if not isinstance(obj, dict) or obj.get("isa") != "XCBuildConfiguration": + continue + if obj.get("name") != config_name: + continue + settings = obj.get("buildSettings") + if not isinstance(settings, dict): + continue + bundle_var = settings.get("PRODUCT_BUNDLE_IDENTIFIER") + if bundle_var in profiles: + settings["CODE_SIGN_STYLE"] = "Manual" + settings["CODE_SIGN_IDENTITY"] = signing_identity + settings["PROVISIONING_PROFILE_SPECIFIER"] = profiles[bundle_var] + updated.add(bundle_var) + + missing = sorted(set(profiles.keys()) - 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 scheme_file in schemes_dir.glob("*.xcscheme"): + scheme_file.write_text( + scheme_file.read_text().replace(f"container:{src.name}", f"container:{dst.name}") + ) +except Exception: + shutil.rmtree(dst, ignore_errors=True) + raise + +print(dst) PY +)" + archive_project="$manual_project" fi mkdir -p "$(dirname "$archive_path")" "$export_path" From 8b2d5ee4ea3b6863e132e45d498339fcb876d8fd Mon Sep 17 00:00:00 2001 From: hude Date: Thu, 3 Dec 2026 14:56:02 +0900 Subject: [PATCH 4/5] perf(vault,ios): 139x Swift normalizeDomain fast-path, fix cross-platform parity counterexamples, add PBT, and trim testflight-upload.sh --- .../KinicVaultCore/VaultCredential.swift | 127 +++++++- .../KinicVaultCoreTests.swift | 93 +++++- mobile/ios/scripts/testflight-upload.sh | 277 ++++++------------ packages/vault-crypto/src/credential.ts | 65 +++- .../vault-crypto/test/credential.pbt.test.ts | 9 +- shared/vault-domain-vectors.json | 9 + 6 files changed, 359 insertions(+), 221 deletions(-) diff --git a/mobile/ios/Packages/KinicVaultCore/Sources/KinicVaultCore/VaultCredential.swift b/mobile/ios/Packages/KinicVaultCore/Sources/KinicVaultCore/VaultCredential.swift index 0446dd736..595d6ab4c 100644 --- a/mobile/ios/Packages/KinicVaultCore/Sources/KinicVaultCore/VaultCredential.swift +++ b/mobile/ios/Packages/KinicVaultCore/Sources/KinicVaultCore/VaultCredential.swift @@ -112,25 +112,92 @@ 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 + if let result = 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 + }) as Bool? { + return result + } + return false + } + 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 +223,11 @@ public enum VaultCredentialCodec { else { return nil } + let isHttp = scheme == nil || scheme == "http" || scheme == "https" if endsInNumber(host) { - return normalizeIPv4Host(host) + guard let normalized = normalizeIPv4Host(host) else { return nil } + if !isHttp && normalized != host { return nil } + return normalized } if host != "localhost" && !host.contains(".") { return nil @@ -269,13 +339,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) } @@ -283,11 +368,21 @@ public enum VaultCredentialCodec { guard let target = normalizeDomain(queryHost), let domains, !domains.isEmpty else { return false } - return domains.contains { raw in - guard let domain = normalizeDomain(raw) else { return false } + let targetUtf8 = target.utf8 + let targetLen = targetUtf8.count + for raw in domains { + guard let domain = normalizeDomain(raw) else { continue } if domain == target { return true } - return canMatchAsParentDomain(domain) && target.hasSuffix(".\(domain)") + let diff = targetLen - domain.utf8.count + if diff > 1, + targetUtf8[targetUtf8.index(targetUtf8.startIndex, offsetBy: diff - 1)] == 0x2E, + target.hasSuffix(domain), + canMatchAsParentDomain(domain) + { + return true + } } + return false } public static func parse(_ data: Data) -> VaultCredentialRecord { diff --git a/mobile/ios/Packages/KinicVaultCore/Tests/KinicVaultCoreTests/KinicVaultCoreTests.swift b/mobile/ios/Packages/KinicVaultCore/Tests/KinicVaultCoreTests/KinicVaultCoreTests.swift index c996c21df..352bde74b 100644 --- a/mobile/ios/Packages/KinicVaultCore/Tests/KinicVaultCoreTests/KinicVaultCoreTests.swift +++ b/mobile/ios/Packages/KinicVaultCore/Tests/KinicVaultCoreTests/KinicVaultCoreTests.swift @@ -534,20 +534,85 @@ 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.. { 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_json_stdin '(() => { const c = v?.data?.attributes?.version ?? v?.data?.attributes?.buildNumber ?? v?.attributes?.version ?? v?.version ?? v?.buildNumber; return /^\d+$/.test(String(c ?? "")) ? c : null; })()')" \ + || 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_json_stdin '(() => { const c = v?.data?.[0]?.attributes?.cfBundleVersion ?? "0"; return /^\d+$/.test(String(c)) ? c : null; })()')" \ + || fail "Could not parse the latest App Store Connect upload number" + printf '%s\n' "$(( (latest_upload > latest_build ? latest_upload : latest_build) + 1 ))" } if [[ "$sandbox_mode" == "1" || -z "$build_number" ]]; then @@ -292,89 +256,14 @@ cleanup() { } trap cleanup EXIT -if [[ "$signing_style" == "manual" ]]; then - manual_project="$(python3 - "$project" "$configuration" "$signing_identity" "$profile_app" "$profile_share" "$profile_widget" "$profile_autofill" <<'PY' -import json -import plistlib -import shutil -import subprocess -import sys -import tempfile -from pathlib import Path - -src_project, config_name, signing_identity, p_app, p_share, p_widget, p_autofill = sys.argv[1:8] -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" - raw_json = subprocess.check_output(["plutil", "-convert", "json", "-o", "-", str(pbx_path)]) - pbx = json.loads(raw_json) - objects = pbx.get("objects", {}) - - 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 objects.values(): - if not isinstance(obj, dict) or obj.get("isa") != "XCBuildConfiguration": - continue - if obj.get("name") != config_name: - continue - settings = obj.get("buildSettings") - if not isinstance(settings, dict): - continue - bundle_var = settings.get("PRODUCT_BUNDLE_IDENTIFIER") - if bundle_var in profiles: - settings["CODE_SIGN_STYLE"] = "Manual" - settings["CODE_SIGN_IDENTITY"] = signing_identity - settings["PROVISIONING_PROFILE_SPECIFIER"] = profiles[bundle_var] - updated.add(bundle_var) - - missing = sorted(set(profiles.keys()) - 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 scheme_file in schemes_dir.glob("*.xcscheme"): - scheme_file.write_text( - scheme_file.read_text().replace(f"container:{src.name}", f"container:{dst.name}") - ) -except Exception: - shutil.rmtree(dst, ignore_errors=True) - raise - -print(dst) -PY -)" - archive_project="$manual_project" -fi - mkdir -p "$(dirname "$archive_path")" "$export_path" -python3 - "$export_options" "$signing_style" "$team_id" "$distribution" "$signing_identity" "$profile_app" "$profile_share" "$profile_widget" "$profile_autofill" <<'PY' -import plistlib -import sys - -( - out_path, - signing_style, - team_id, - distribution, - signing_identity, - p_app, - p_share, - p_widget, - p_autofill, -) = sys.argv[1:10] +# 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 + +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] options = { "destination": "export", @@ -394,10 +283,48 @@ if signing_style == "manual": } 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 Exception: + shutil.rmtree(dst, ignore_errors=True) + raise + print(dst) PY +)" +if [[ -n "$manual_project" ]]; then + archive_project="$manual_project" +fi archive_cmd=( xcodebuild archive @@ -427,14 +354,14 @@ 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 @@ -467,18 +394,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_json_stdin '(() => { const r = v?.data ?? []; return r.length === 1 && typeof r[0]?.attributes?.state?.state === "string" ? r[0].attributes.state.state : null; })()')" \ + || 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..6b2b7cafa 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; } 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/shared/vault-domain-vectors.json b/shared/vault-domain-vectors.json index b3798e819..85d54b38d 100644 --- a/shared/vault-domain-vectors.json +++ b/shared/vault-domain-vectors.json @@ -9,11 +9,20 @@ { "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": "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 }, From 5ad197cee77aba3b359d618318bdfa0e751d4f92 Mon Sep 17 00:00:00 2001 From: hude Date: Thu, 3 Dec 2026 16:04:27 +0900 Subject: [PATCH 5/5] fix(vault,ios): address Codex review on Unicode matchesDomain parity, special-scheme IPv4, BaseException cleanup, and strict ASC JSON parser --- .../KinicVaultCore/VaultCredential.swift | 40 ++++++------------- .../KinicVaultCoreTests.swift | 25 +++--------- mobile/ios/scripts/testflight-upload.sh | 35 +++++++++++----- packages/vault-crypto/src/credential.ts | 32 +++++++-------- shared/vault-domain-vectors.json | 3 ++ 5 files changed, 60 insertions(+), 75 deletions(-) diff --git a/mobile/ios/Packages/KinicVaultCore/Sources/KinicVaultCore/VaultCredential.swift b/mobile/ios/Packages/KinicVaultCore/Sources/KinicVaultCore/VaultCredential.swift index 595d6ab4c..22894949d 100644 --- a/mobile/ios/Packages/KinicVaultCore/Sources/KinicVaultCore/VaultCredential.swift +++ b/mobile/ios/Packages/KinicVaultCore/Sources/KinicVaultCore/VaultCredential.swift @@ -117,7 +117,7 @@ public enum VaultCredentialCodec { @inline(__always) private static func isFastNormalizedHost(_ raw: String) -> Bool { var mutable = raw - if let result = mutable.withUTF8({ buf -> Bool in + return mutable.withUTF8 { buf -> Bool in let count = buf.count guard count >= 3, count <= 255 else { return false } var hasDot = false @@ -158,10 +158,7 @@ public enum VaultCredentialCodec { if restHex { return false } } return true - }) as Bool? { - return result } - return false } public static func normalizeDomain(_ raw: String) -> String? { @@ -223,10 +220,10 @@ public enum VaultCredentialCodec { else { return nil } - let isHttp = scheme == nil || scheme == "http" || scheme == "https" + let isSpecialScheme = scheme == nil || scheme == "http" || scheme == "https" || scheme == "ws" || scheme == "wss" || scheme == "ftp" if endsInNumber(host) { guard let normalized = normalizeIPv4Host(host) else { return nil } - if !isHttp && normalized != host { return nil } + if !isSpecialScheme && normalized != host { return nil } return normalized } if host != "localhost" && !host.contains(".") { @@ -368,21 +365,11 @@ public enum VaultCredentialCodec { guard let target = normalizeDomain(queryHost), let domains, !domains.isEmpty else { return false } - let targetUtf8 = target.utf8 - let targetLen = targetUtf8.count - for raw in domains { - guard let domain = normalizeDomain(raw) else { continue } + return domains.contains { raw in + guard let domain = normalizeDomain(raw) else { return false } if domain == target { return true } - let diff = targetLen - domain.utf8.count - if diff > 1, - targetUtf8[targetUtf8.index(targetUtf8.startIndex, offsetBy: diff - 1)] == 0x2E, - target.hasSuffix(domain), - canMatchAsParentDomain(domain) - { - return true - } + return canMatchAsParentDomain(domain) && target.hasSuffix(".\(domain)") } - return false } public static func parse(_ data: Data) -> VaultCredentialRecord { @@ -476,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 352bde74b..a66d7628d 100644 --- a/mobile/ios/Packages/KinicVaultCore/Tests/KinicVaultCoreTests/KinicVaultCoreTests.swift +++ b/mobile/ios/Packages/KinicVaultCore/Tests/KinicVaultCoreTests/KinicVaultCoreTests.swift @@ -593,26 +593,11 @@ struct KinicVaultCoreTests { #expect(index.match(queryHost: q) == expected, "index parity mismatch for \(q)") } - // 3. Fast-path performance verification against slow URLComponents path. - let benchHosts = [ - "github.com", "api.github.com", "sub.example.com", "app.kinic.xyz", - "vault.icme.io", "accounts.google.com", "docs.cloudflare.com", "gist.github.com", - ] - let iterations = 40_000 - let tSlow0 = CFAbsoluteTimeGetCurrent() - var slowHits = 0 - for i in 0.. { + 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" } @@ -214,13 +231,13 @@ resolve_next_build_number() { local build_json upload_json latest_build latest_upload 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_json_stdin '(() => { const c = v?.data?.attributes?.version ?? v?.data?.attributes?.buildNumber ?? v?.attributes?.version ?? v?.version ?? v?.buildNumber; return /^\d+$/.test(String(c ?? "")) ? c : null; })()')" \ + 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_json_stdin '(() => { const c = v?.data?.[0]?.attributes?.cfBundleVersion ?? "0"; return /^\d+$/.test(String(c)) ? c : null; })()')" \ + latest_upload="$(printf '%s' "$upload_json" | parse_asc_json upload)" \ || fail "Could not parse the latest App Store Connect upload number" - printf '%s\n' "$(( (latest_upload > latest_build ? latest_upload : latest_build) + 1 ))" + printf '%s\n' "$(( (10#$latest_upload > 10#$latest_build ? 10#$latest_upload : 10#$latest_build) + 1 ))" } if [[ "$sandbox_mode" == "1" || -z "$build_number" ]]; then @@ -316,7 +333,7 @@ if signing_style == "manual": 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 Exception: + except BaseException: shutil.rmtree(dst, ignore_errors=True) raise print(dst) @@ -394,7 +411,7 @@ 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" | parse_json_stdin '(() => { const r = v?.data ?? []; return r.length === 1 && typeof r[0]?.attributes?.state?.state === "string" ? r[0].attributes.state.state : null; })()')" \ +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 6b2b7cafa..6c1197a13 100644 --- a/packages/vault-crypto/src/credential.ts +++ b/packages/vault-crypto/src/credential.ts @@ -290,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/shared/vault-domain-vectors.json b/shared/vault-domain-vectors.json index 85d54b38d..fad4e4c48 100644 --- a/shared/vault-domain-vectors.json +++ b/shared/vault-domain-vectors.json @@ -16,6 +16,9 @@ { "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" },