Private/BrowserSettings.ps1

# Browser-wide profile preferences (edge://settings/profiles/multiProfileSettings) that Edge keeps in
# 'Local State' instead of in a profile folder:
# - Default profile for external links profiles.edge.ext_link_open_behavior / ext_link_open_profile_path
# - Open external links in another profile when
# recommended by external applications profiles.edge.prioritize_m365_links_for_profile_selection
# - Custom site switch (sites -> profile) profiles.edge.guided_switch_pref
#
# Profiles are referenced by full folder path ("...\User Data\Default"). In the portable form those
# paths become "{{profile:<Key>}}" tokens, so the settings can be applied on another machine, user
# account or channel where the same profile lives in another folder. Settings whose profile cannot be
# found locally are left as they are (list entries such as site switches are dropped individually).
#
# Per-profile options on the same settings page (single sign-on for work or school sites, automatic
# sign-in) live in the profile's Preferences and travel with the Settings category. The automatic
# profile switching toggles (work/personal, shopping, intranet, IE mode) are usually set by policy
# (HKCU/HKLM\Software\Policies\Microsoft\Edge) and are not part of the user data.

$script:EdgeBrowserSettingPaths = @(
    'profiles.edge.ext_link_open_behavior'
    'profiles.edge.ext_link_open_profile_path'
    'profiles.edge.prioritize_m365_links_for_profile_selection'
    'profiles.edge.guided_switch_pref'
)
$script:EdgeBrowserSettingsFileName = 'browser-settings.json'
$script:EdgeProfileTokenPattern = '^\{\{profile:(?<key>[^}]+)\}\}(?<rest>.*)$'

function Get-EdgeJsonPathValue {
    # Returns @{ Found; Value } for a dotted path in nested hashtables.
    [CmdletBinding()]
    param([AllowNull()][object]$Object, [Parameter(Mandatory)][string]$Path)
    $node = $Object
    foreach ($part in $Path.Split('.')) {
        if ($node -isnot [System.Collections.IDictionary] -or -not $node.Contains($part)) { return @{ Found = $false; Value = $null } }
        $node = $node[$part]
    }
    @{ Found = $true; Value = $node }
}

function Set-EdgeJsonPathValue {
    # Sets a dotted path in nested hashtables, creating intermediate hashtables.
    [CmdletBinding()]
    param([Parameter(Mandatory)][System.Collections.IDictionary]$Object, [Parameter(Mandatory)][string]$Path, [AllowNull()][object]$Value)
    $parts = $Path.Split('.')
    $node = $Object
    for ($i = 0; $i -lt $parts.Count - 1; $i++) {
        $part = $parts[$i]
        if ($node[$part] -isnot [System.Collections.IDictionary]) { $node[$part] = [ordered]@{} }
        $node = $node[$part]
    }
    $node[$parts[-1]] = $Value
}

function ConvertTo-EdgeCanonicalJson {
    # JSON with sorted object keys at every level, so equal settings always give the same text.
    [CmdletBinding()]
    [OutputType([string])]
    param([AllowNull()][object]$InputObject)
    $sort = $null
    $sort = {
        param($v)
        if ($v -is [System.Collections.IDictionary]) {
            $o = [ordered]@{}
            foreach ($k in @($v.Keys | ForEach-Object { [string]$_ } | Sort-Object -Culture '' -CaseSensitive)) { $o[$k] = & $sort $v[$k] }
            return $o
        }
        if ($v -is [System.Collections.IList]) { return , @(foreach ($x in $v) { , (& $sort $x) }) }
        $v
    }
    ConvertTo-Json -InputObject (& $sort $InputObject) -Depth 100 -Compress
}

function ConvertTo-EdgePortableSettingValue {
    # Replaces profile folder paths below User Data with "{{profile:<Key>}}" (recursively). Records the
    # referenced keys and their source folder in -Hints. Paths of unknown profiles stay unchanged.
    [CmdletBinding()]
    param(
        [AllowNull()][object]$Value,
        [Parameter(Mandatory)][string]$UserDataPath,
        [Parameter(Mandatory)][hashtable]$DirectoryToKey,
        [Parameter(Mandatory)][System.Collections.IDictionary]$Hints
    )
    if ($Value -is [string]) {
        $root = [IO.Path]::GetFullPath($UserDataPath).TrimEnd('\') + '\'
        if ($Value.StartsWith($root, [StringComparison]::OrdinalIgnoreCase)) {
            $rel = $Value.Substring($root.Length)
            $dir, $rest = $rel.Split('\', 2)
            if ($DirectoryToKey.ContainsKey($dir)) {
                $key = $DirectoryToKey[$dir]
                $Hints[$key] = $dir
                return '{{profile:' + $key + '}}' + $(if ($rest) { '\' + $rest } else { '' })
            }
        }
        return $Value
    }
    if ($Value -is [System.Collections.IDictionary]) {
        $o = [ordered]@{}
        foreach ($k in $Value.Keys) { $o[$k] = ConvertTo-EdgePortableSettingValue -Value $Value[$k] -UserDataPath $UserDataPath -DirectoryToKey $DirectoryToKey -Hints $Hints }
        return $o
    }
    if ($Value -is [System.Collections.IList]) {
        return , @(foreach ($x in $Value) { , (ConvertTo-EdgePortableSettingValue -Value $x -UserDataPath $UserDataPath -DirectoryToKey $DirectoryToKey -Hints $Hints) })
    }
    $Value
}

function ConvertFrom-EdgePortableSettingValue {
    # Resolves "{{profile:<Key>}}" tokens to local profile paths. Returns @{ Ok; Value; Missing }.
    # A list keeps the entries that resolve; any other value fails as a whole when a token is unknown.
    [CmdletBinding()]
    param(
        [AllowNull()][object]$Value,
        [Parameter(Mandatory)][string]$UserDataPath,
        [Parameter(Mandatory)][hashtable]$KeyToDirectory
    )
    if ($Value -is [string]) {
        $m = [regex]::Match($Value, $script:EdgeProfileTokenPattern)
        if (-not $m.Success) { return @{ Ok = $true; Value = $Value; Missing = @() } }
        $key = $m.Groups['key'].Value
        if (-not $KeyToDirectory.ContainsKey($key)) { return @{ Ok = $false; Value = $null; Missing = @($key) } }
        return @{ Ok = $true; Value = (Join-Path $UserDataPath $KeyToDirectory[$key]) + $m.Groups['rest'].Value; Missing = @() }
    }
    if ($Value -is [System.Collections.IDictionary]) {
        $o = [ordered]@{}
        $missing = @()
        foreach ($k in $Value.Keys) {
            $r = ConvertFrom-EdgePortableSettingValue -Value $Value[$k] -UserDataPath $UserDataPath -KeyToDirectory $KeyToDirectory
            if (-not $r.Ok) { return @{ Ok = $false; Value = $null; Missing = @($r.Missing) } }
            $missing += $r.Missing
            $o[$k] = $r.Value
        }
        return @{ Ok = $true; Value = $o; Missing = @($missing) }
    }
    if ($Value -is [System.Collections.IList]) {
        $items = [System.Collections.Generic.List[object]]::new()
        $missing = @()
        foreach ($x in $Value) {
            $r = ConvertFrom-EdgePortableSettingValue -Value $x -UserDataPath $UserDataPath -KeyToDirectory $KeyToDirectory
            if ($r.Ok) { $items.Add($r.Value) }
            $missing += $r.Missing
        }
        return @{ Ok = $true; Value = $items.ToArray(); Missing = @($missing) }
    }
    @{ Ok = $true; Value = $Value; Missing = @() }
}

function Get-EdgeBrowserSettings {
    <#
    .SYNOPSIS
        Reads the browser-wide profile preferences of a channel from Local State in portable form.
    .OUTPUTS
        [ordered]@{ Settings = { <path> = <value> }; Profiles = { <Key> = <source Directory> } }, or $null
        when Local State does not exist or holds none of the settings.
    #>

    [CmdletBinding()]
    param(
        [string]$Channel = 'Stable',
        [string]$UserDataRoot
    )
    $info = Get-EdgeChannelInfo -Channel $Channel -UserDataRoot $UserDataRoot
    $localStatePath = Join-Path $info.UserDataPath 'Local State'
    if (-not (Test-Path -LiteralPath $localStatePath -PathType Leaf)) { return $null }
    $state = Read-EdgeJsonFile -Path $localStatePath

    $dirToKey = @{}
    foreach ($p in @(Get-EdgeLocalProfile -Channel $Channel -UserDataRoot $UserDataRoot)) { $dirToKey[$p.Directory] = $p.Key }

    $settings = [ordered]@{}
    $hints = [ordered]@{}
    foreach ($path in $script:EdgeBrowserSettingPaths) {
        $r = Get-EdgeJsonPathValue -Object $state -Path $path
        if (-not $r.Found) { continue }
        $settings[$path] = ConvertTo-EdgePortableSettingValue -Value $r.Value -UserDataPath $info.UserDataPath -DirectoryToKey $dirToKey -Hints $hints
    }
    if (-not $settings.Count) { return $null }
    [ordered]@{ Settings = $settings; Profiles = $hints }
}

function Get-EdgeBrowserSettingsFingerprint {
    # SHA256 of the canonical JSON of the Settings part (the folder hints do not count), or $null.
    [CmdletBinding()]
    [OutputType([string])]
    param([AllowNull()][object]$BrowserSettings)
    $settings = Get-EdgeSyncValue $BrowserSettings 'Settings'
    if ($settings -isnot [System.Collections.IDictionary] -or -not $settings.Count) { return $null }
    Get-EdgeSyncSha256 -Text (ConvertTo-EdgeCanonicalJson -InputObject $settings)
}

function Set-EdgeBrowserSettings {
    <#
    .SYNOPSIS
        Applies portable browser-wide profile preferences to Local State. Edge of the channel must be
        closed (caller's job): Edge rewrites Local State when it exits.
    .DESCRIPTION
        Profile tokens are resolved by Key against the local profiles. A key that does not exist locally
        falls back to 'Default' when it was the Default profile at the source as well (the main profile of
        each machine). Settings that still cannot be resolved are skipped; list entries (site switches)
        are dropped one by one. Local State is backed up to "Local State.edgeprofilesync.bak" first and
        only rewritten when something changes.
    .OUTPUTS
        [pscustomobject]@{ Applied (string[]); Unchanged (string[]); Skipped (string[] "<path>: <reason>"); Changed (bool) }
    #>

    [CmdletBinding(SupportsShouldProcess)]
    param(
        [Parameter(Mandatory)][object]$BrowserSettings,
        [string]$Channel = 'Stable',
        [string]$UserDataRoot,
        # Only compute what would change (Applied / Unchanged / Skipped); never writes and prints nothing.
        [switch]$Preview
    )
    $info = Get-EdgeChannelInfo -Channel $Channel -UserDataRoot $UserDataRoot
    $userData = $info.UserDataPath
    $localStatePath = Join-Path $userData 'Local State'
    $state = (Test-Path -LiteralPath $localStatePath -PathType Leaf) ? (Read-EdgeJsonFile -Path $localStatePath) : $null
    if ($state -isnot [System.Collections.IDictionary]) { $state = [ordered]@{} }

    $keyToDir = @{}
    foreach ($p in @(Get-EdgeLocalProfile -Channel $Channel -UserDataRoot $UserDataRoot)) { $keyToDir[$p.Key] = $p.Directory }
    $hints = Get-EdgeSyncValue $BrowserSettings 'Profiles'
    if ($hints -is [System.Collections.IDictionary] -and (Test-Path -LiteralPath (Join-Path $userData 'Default') -PathType Container)) {
        foreach ($k in $hints.Keys) {
            if (-not $keyToDir.ContainsKey([string]$k) -and [string]$hints[$k] -eq 'Default') { $keyToDir[[string]$k] = 'Default' }
        }
    }

    $applied = [System.Collections.Generic.List[string]]::new()
    $unchanged = [System.Collections.Generic.List[string]]::new()
    $skipped = [System.Collections.Generic.List[string]]::new()
    $settings = Get-EdgeSyncValue $BrowserSettings 'Settings'
    if ($settings -isnot [System.Collections.IDictionary]) { $settings = @{} }

    # External-link behaviour and its profile path belong together: apply both or neither.
    $pairBehavior = 'profiles.edge.ext_link_open_behavior'
    $pairPath = 'profiles.edge.ext_link_open_profile_path'
    $resolved = [ordered]@{}
    foreach ($path in $settings.Keys) {
        if ($path -notin $script:EdgeBrowserSettingPaths) { $skipped.Add("${path}: not a known browser setting"); continue }
        $r = ConvertFrom-EdgePortableSettingValue -Value $settings[$path] -UserDataPath $userData -KeyToDirectory $keyToDir
        if (-not $r.Ok) { $skipped.Add("${path}: profile '$(@($r.Missing)[0])' does not exist here"); continue }
        if (@($r.Missing).Count) { $skipped.Add("${path}: entries for missing profile(s) $((@($r.Missing) | Select-Object -Unique) -join ', ') left out") }
        $resolved[$path] = $r.Value
    }
    if ($settings.Contains($pairPath) -and -not $resolved.Contains($pairPath) -and $resolved.Contains($pairBehavior)) {
        $resolved.Remove($pairBehavior)
        $skipped.Add("${pairBehavior}: skipped together with $pairPath")
    }

    foreach ($path in $resolved.Keys) {
        $current = Get-EdgeJsonPathValue -Object $state -Path $path
        if ($current.Found -and (ConvertTo-EdgeCanonicalJson $current.Value) -eq (ConvertTo-EdgeCanonicalJson $resolved[$path])) { $unchanged.Add($path); continue }
        Set-EdgeJsonPathValue -Object $state -Path $path -Value $resolved[$path]
        $applied.Add($path)
    }

    $changed = $false
    if ($applied.Count -and -not $Preview -and $PSCmdlet.ShouldProcess($localStatePath, "Apply browser settings ($($applied -join ', '))")) {
        if (Test-Path -LiteralPath $localStatePath -PathType Leaf) {
            Copy-Item -LiteralPath $localStatePath -Destination (Join-Path $userData 'Local State.edgeprofilesync.bak') -Force
        }
        Write-EdgeJsonFile -Path $localStatePath -InputObject $state
        $changed = $true
    }
    [pscustomobject]@{
        Applied   = $applied.ToArray()
        Unchanged = $unchanged.ToArray()
        Skipped   = $skipped.ToArray()
        Changed   = $changed
    }
}

function Get-EdgeBrowserSettingsSummary {
    # One-line, human readable description of portable browser settings (for console output).
    [CmdletBinding()]
    [OutputType([string])]
    param([AllowNull()][object]$BrowserSettings)
    $settings = Get-EdgeSyncValue $BrowserSettings 'Settings'
    if ($settings -isnot [System.Collections.IDictionary] -or -not $settings.Count) { return 'none' }
    $parts = [System.Collections.Generic.List[string]]::new()
    $linkPath = [string]$settings['profiles.edge.ext_link_open_profile_path']
    $m = [regex]::Match($linkPath, $script:EdgeProfileTokenPattern)
    if ($m.Success) { $parts.Add("external links open in '$($m.Groups['key'].Value)'") }
    elseif ($settings.Contains('profiles.edge.ext_link_open_behavior')) { $parts.Add('external link behaviour') }
    if ($settings.Contains('profiles.edge.prioritize_m365_links_for_profile_selection')) {
        $parts.Add('app-recommended profile ' + ($settings['profiles.edge.prioritize_m365_links_for_profile_selection'] ? 'on' : 'off'))
    }
    if ($settings.Contains('profiles.edge.guided_switch_pref')) { $parts.Add("$(@($settings['profiles.edge.guided_switch_pref']).Count) custom site switch(es)") }
    $parts -join ', '
}

function Invoke-EdgeSyncBrowserSettings {
    <#
    .SYNOPSIS
        Syncs the browser-wide profile preferences of one channel through
        "<SyncRoot>\browser\<Channel>\browser-settings.json" (3-way, like a profile category).
    .DESCRIPTION
        The store file holds { Settings; Profiles; UpdatedUtc; Machine }. Fingerprints are taken over the
        portable Settings only, so the same settings on machines with different profile folders are equal.
        State item key: "<Channel>|*|BrowserSettings". Push is always allowed; pull writes Local State and
        needs Edge of the channel closed (Confirm-EdgeSyncChannelClosed, which may stop windowless Edge).
        Returns one result object (Profile '*', Category 'BrowserSettings').
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory)][object]$Context,
        [Parameter(Mandatory)][string]$SyncRoot,
        [string]$UserDataRoot
    )
    $ctx = $Context
    $ch = $ctx.Channel
    $newResult = {
        param([string]$Action, [string]$Reason)
        [pscustomobject]@{ Channel = $ch; Profile = '*'; Category = 'BrowserSettings'; Action = $Action; Reason = $Reason }
    }
    $declined = {
        param([string]$Action, [string]$Reason)
        if ($ctx.WhatIf) { & $newResult $Action "WhatIf: $Reason" } else { & $newResult 'Skipped' "Declined: $Reason" }
    }

    $storeFile = Join-Path $SyncRoot "browser\$ch\$script:EdgeBrowserSettingsFileName"
    $stateKey = '{0}|*|BrowserSettings' -f $ch
    $stateItem = Get-EdgeSyncStateItem -State $ctx.State -ItemKey $stateKey
    $B = [string](Get-EdgeSyncValue $stateItem 'Fingerprint')
    $LF = [string](Get-EdgeSyncValue $stateItem 'LocalFingerprint')

    $remote = (Test-Path -LiteralPath $storeFile -PathType Leaf) ? (Read-EdgeJsonFile -Path $storeFile) : $null
    $R = [string](Get-EdgeBrowserSettingsFingerprint -BrowserSettings $remote)
    $remoteMachine = [string](Get-EdgeSyncValue $remote 'Machine')
    $remoteTime = ConvertTo-EdgeSyncUtcDate (Get-EdgeSyncValue $remote 'UpdatedUtc')

    $local = Get-EdgeBrowserSettings -Channel $ch -UserDataRoot $UserDataRoot
    $L = [string](Get-EdgeBrowserSettingsFingerprint -BrowserSettings $local)
    $localStatePath = Join-Path (Get-EdgeChannelInfo -Channel $ch -UserDataRoot $UserDataRoot).UserDataPath 'Local State'
    $localTime = (Test-Path -LiteralPath $localStatePath -PathType Leaf) ? (Get-Item -LiteralPath $localStatePath -Force).LastWriteTimeUtc : $null

    # Unchanged since the last sync -> equal to the base (after a pull the local copy can legitimately
    # differ from the store, e.g. site switches for a profile that does not exist here).
    $effectiveL = if ($L -and $LF -and $B -and $L -eq $LF) { $B } else { $L }
    # Without sync history the store wins: a new machine must not overwrite the settings with its defaults.
    $decision = Get-EdgeSyncDecision -Local $effectiveL -Remote $R -Base $B -LocalTimeUtc $localTime -RemoteTimeUtc $remoteTime -PreferRemoteWithoutBase
    $target = "$ch/BrowserSettings"

    # A previous pull left settings out because their profile did not exist here (Pending). When the local
    # copy is still what that pull wrote and some of those settings resolve now, apply the store copy again.
    $pending = [bool](Get-EdgeSyncValue $stateItem 'Pending' $false)
    $retry = $false
    if ($decision -eq 'InSync' -and $pending -and $R -and $R -eq $B -and $L -eq $LF) {
        $preview = Set-EdgeBrowserSettings -BrowserSettings $remote -Channel $ch -UserDataRoot $UserDataRoot -Preview
        if ($preview.Applied.Count) { $decision = 'Pull'; $retry = $true }
    }
    $setState = {
        param([string]$Fingerprint, [string]$LocalFingerprint, [bool]$IsPending)
        Set-EdgeSyncStateItem -State $ctx.State -ItemKey $stateKey -Fingerprint $Fingerprint -LocalFingerprint $LocalFingerprint
        if ($IsPending) { $ctx.State.Items[$stateKey]['Pending'] = $true }
    }

    switch ($decision) {
        'None' { return & $newResult 'Skipped' 'No data locally or in the store.' }
        'InSync' {
            if (-not $ctx.WhatIf) { & $setState ($R ? $R : $L) $L ($pending -and $L -eq $LF) }
            return & $newResult 'InSync' 'Local copy and store copy are the same.'
        }
        { $_ -in 'Push', 'Conflict-Push' } {
            $reason = if ($decision -eq 'Conflict-Push') { "Changed on both sides; local copy is newer than store copy ($remoteTime, $remoteMachine)." }
            elseif ($R) { 'Local copy changed.' } else { 'Only the local copy exists.' }
            $reason += ' ' + (Get-EdgeBrowserSettingsSummary -BrowserSettings $local)
            if ($ctx.Mode -eq 'PullOnly') { return & $newResult 'Skipped' "Mode PullOnly: $reason" }
            if (-not $ctx.Cmdlet.ShouldProcess($target, 'Push to sync store')) { return & $declined $decision $reason }
            $doc = [ordered]@{
                Settings   = $local['Settings']
                Profiles   = $local['Profiles']
                UpdatedUtc = [datetime]::UtcNow.ToString('o')
                Machine    = $ctx.MachineId
            }
            Write-EdgeJsonFile -Path $storeFile -InputObject $doc
            Set-EdgeSyncStateItem -State $ctx.State -ItemKey $stateKey -Fingerprint $L -LocalFingerprint $L
            return & $newResult $decision $reason
        }
        { $_ -in 'Pull', 'Conflict-Pull' } {
            $reason = if ($decision -eq 'Conflict-Pull') { "Changed on both sides; store copy ($remoteTime, $remoteMachine) is newer. Previous Local State kept as 'Local State.edgeprofilesync.bak'." }
            elseif ($retry) { 'Settings left out earlier because their profile was missing can be applied now.' }
            elseif ($L) { "Store copy changed on $remoteMachine." } else { "Only the store copy exists ($remoteMachine)." }
            $reason += ' ' + (Get-EdgeBrowserSettingsSummary -BrowserSettings $remote)
            if ($ctx.Mode -eq 'PushOnly') { return & $newResult 'Skipped' "Mode PushOnly: $reason" }
            if (-not (Confirm-EdgeSyncChannelClosed -Context $ctx)) { return & $newResult 'Skipped' "Browser settings need Edge closed (Local State): $($ctx.Gate.Reason)" }
            if (-not $ctx.Cmdlet.ShouldProcess($target, 'Pull from sync store')) { return & $declined $decision $reason }
            $applied = Set-EdgeBrowserSettings -BrowserSettings $remote -Channel $ch -UserDataRoot $UserDataRoot -Confirm:$false
            if ($applied.Skipped.Count) { $reason += ' Not applied: ' + ($applied.Skipped -join '; ') + '.' }
            $newL = [string](Get-EdgeBrowserSettingsFingerprint -BrowserSettings (Get-EdgeBrowserSettings -Channel $ch -UserDataRoot $UserDataRoot))
            & $setState $R $newL ($applied.Skipped.Count -gt 0)
            return & $newResult $decision $reason
        }
        default { throw "Unexpected sync decision '$decision'." }
    }
}