functions/sync.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169

function get-propertynames($obj) {
  # Measure-function "$($MyInvocation.MyCommand.Name)" {
        if ($obj -is [System.Collections.IDictionary]) {
            return $obj.keys
        }
        return $obj.psobject.Properties | select -ExpandProperty name
 # }
}

function ConvertTo-Hashtable([Parameter(ValueFromPipeline=$true)]$obj, [switch][bool]$recurse) {
 # Measure-function "$($MyInvocation.MyCommand.Name)" {

        $object =$obj
        if (!$recurse -and ($object -is [System.Collections.IDictionary] -or $object -is [array])) {
            return $object
        }
 
        if($object -is [array]) {
            if ($recurse) {
                for($i = 0; $i -lt $object.Length; $i++) {
                    $object[$i] = ConvertTo-Hashtable $object[$i] -recurse:$recurse
                }
            }
            return $object
        } 
        elseif ($object -is [System.Collections.IDictionary] -or  $object -is [System.Management.Automation.PSCustomObject] -or $true) {
            $h = @{}
            $props = get-propertynames $object
            foreach ($p in $props) {
                if ($recurse) {
                    $h[$p] = ConvertTo-Hashtable $object.$p -recurse:$recurse
                } else {
                    $h[$p] = $object.$p
                }
            }
            return $h
        } else {
            throw "could not convert object to hashtable"
            #return $object
        }
 # }
    
}



function get-syncdir() {
    if (test-path "HKCU:\Software\Microsoft\OneDrive") 
    {
        $prop = get-itemproperty "HKCU:\Software\Microsoft\OneDrive\" "UserFolder"
        if ($prop -ne $null) {
            $dir = $prop.userfolder
        }        
    }

    if ($dir -ne $null) {
        $syncdir = join-path $dir ".powershell-data"
        if (!(test-path $syncdir)) {
            $null = mkdir $syncdir
        }
        return $syncdir
    }
}


function set-globalpassword {
    Get-CredentialsCached -message "Global settings password" -reset -container "global-key"
}

function _getenckey { 
    [CmdletBinding()]
    param() 
    $pass = get-passwordcached -message "Global settings password" -container "global-key" -allowuserui
    $rfc = new-object System.Security.Cryptography.Rfc2898DeriveBytes $pass,@(1,2,3,4,5,6,7,8),1000            
    $enckey = $rfc.GetBytes(256/8);
    #write-verbose "key=$($enckey | convertto-base64) length=$($enckey.length)"
    return $enckey
} 

function new-credentials(
    [Parameter(Mandatory=$true)]$username, 
    [Parameter(Mandatory=$true)][securestring]$password) {
        return New-Object 'system.management.automation.pscredential' $username,$password
    }

function convertto-plaintext([Parameter(Mandatory=$true,ValueFromPipeline=$true,Position=1)][securestring]$password) {
    return (new-credentials $="dummy" $password).GetNetworkCredential().password
}

function import-settings {
    [CmdletBinding()]
    param ()
    $syncdir = get-syncdir
    if ($syncdir -eq $null) {
        write-warning "couldn't find OneDrive synced folder"
        return
    }
    $settings = import-cache -container "user-settings" -dir $syncdir | convertto-hashtable 
    
    
    if ($settings -eq $null) {
        $settings = @{}
    }

    $decrypted = @{}
    foreach($kvp in $settings.GetEnumerator()) {
        if ($kvp.value.startswith("enc:")) {
            try {
             $enckey = _getenckey
             $encvalue = $kvp.value.substring("enc:".length)
             $secvalue = convertto-securestring $encvalue -Key $enckey -ErrorAction stop
             $decrypted[$kvp.key] = $secvalue
             #$creds = new-object system.management.automation.pscredential ("dummy",$secvalue)
             #$pass = $creds.getnetworkcredential().password
            } catch {
                write-warning "failed to decode key $($kvp.key): $_"
                $decrypted[$kvp.key] = $kvp.value
            }
        }
        else {
            $decrypted[$kvp.key] = $kvp.value
        }
    }

    $settings = $decrypted
    write-verbose "imported $($settings.Count) settings from '$syncdir'"

    $global:settings = $settings

    return $settings
}

function export-setting {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true)] $key, 
        [Parameter(Mandatory=$true)] $value, 
        [Switch][bool]$force,
        [Alias("secure")][Switch][bool]$encrypt
        ) 
    $syncdir = get-syncdir
    if ($syncdir -eq $null) {
        write-warning "couldn't find OneDrive synced folder"
        return
    }
    $settings = import-cache -container "user-settings" -dir $syncdir | convertto-hashtable
    if ($settings -eq $null) { $settings = @{} }
    if ($settings[$key] -ne $null) {
        if (!$force) {
            write-warning "a setting with key $key already exists. Use -Force to override"
            return
        }
    }
    write-verbose "storing setting $key=$value at '$syncdir'"
    if ($encrypt) {
        $enckey = _getenckey
        $secvalue = convertto-securestring $value -asplaintext -force
        $encvalue = convertfrom-securestring $secvalue -key $enckey
        $settings[$key] = "enc:$encvalue"
    } else {
        $settings[$key] = "$value"
    }
    export-cache -data $settings -container "user-settings" -dir $syncdir
 
    import-settings
}