Public/Connect-Ghost.ps1

function Connect-Ghost {
    <#
    .SYNOPSIS
        Connects to the Admin API of a Ghost site.

    .DESCRIPTION
        Stores the address of the site and the Admin API key for the other functions of this module, and
        verifies both by reading the site information and requesting a single post.

        The key is the Admin API key of a custom integration (Ghost Admin > Settings > Integrations) or a staff
        access token (your profile in Ghost Admin). Both have the form <id>:<secret>. The key itself is never
        sent to the site: every request is signed with a token that is derived from it and valid for five
        minutes.

        Without parameters the address and the key are read from the environment variables GHOST_ADMIN_API_URL
        and GHOST_ADMIN_API_KEY, which is the convenient way to connect from a pipeline.

        The connection lasts until Disconnect-Ghost is called or the module is removed. There is one connection
        per session; connecting again replaces it.

    .EXAMPLE
        Connect-Ghost -Url 'https://example.ghost.io' -AdminApiKey (Read-Host -Prompt 'Admin API key' -AsSecureString)

        Prompts for the key and connects to the site.

    .EXAMPLE
        Connect-Ghost

        Connects with the address and the key from GHOST_ADMIN_API_URL and GHOST_ADMIN_API_KEY.

    .LINK
        https://docs.ghost.org/admin-api#authentication
    #>

    [CmdletBinding()]
    [OutputType('Ghost.Connection')]
    param(
        # Address of the site, such as https://example.ghost.io. A trailing /ghost is ignored, so the address of
        # Ghost Admin works as well. Defaults to the environment variable GHOST_ADMIN_API_URL.
        [Parameter(Position = 0)]
        [string] $Url = $env:GHOST_ADMIN_API_URL,

        # Admin API key or staff access token, in the form <id>:<secret>. Defaults to the environment variable
        # GHOST_ADMIN_API_KEY.
        [Parameter(Position = 1)]
        [Alias('Key')]
        [securestring] $AdminApiKey,

        # Value of the Accept-Version header, such as v5.0: the API version the calls are written for. Defaults
        # to the version of the site.
        [ValidatePattern('^v\d+\.\d+$')]
        [string] $ApiVersion
    )

    try {
        if ([string]::IsNullOrWhiteSpace($Url)) {
            throw 'No site address. Pass -Url or set the environment variable GHOST_ADMIN_API_URL.'
        }
        if (-not $AdminApiKey) {
            if ([string]::IsNullOrWhiteSpace($env:GHOST_ADMIN_API_KEY)) {
                throw 'No Admin API key. Pass -AdminApiKey or set the environment variable GHOST_ADMIN_API_KEY.'
            }
            $AdminApiKey = [System.Net.NetworkCredential]::new('', $env:GHOST_ADMIN_API_KEY.Trim()).SecurePassword
        }

        $siteUrl = $Url.Trim()
        if ($siteUrl -notmatch '^https?://') {
            $siteUrl = 'https://{0}' -f $siteUrl
        }
        $siteUrl = $siteUrl.TrimEnd('/') -replace '/ghost(/api(/admin)?)?$'
        if (-not [uri]::IsWellFormedUriString($siteUrl, [System.UriKind]::Absolute)) {
            throw "'$Url' is not a valid site address. Use the form https://example.ghost.io."
        }

        $key = [System.Net.NetworkCredential]::new('', $AdminApiKey).Password
        if ($key -notmatch '^(?<id>[0-9a-fA-F]+):(?<secret>(?:[0-9a-fA-F]{2})+)$') {
            throw 'The Admin API key must have the form <id>:<secret>, both in hexadecimal characters.'
        }

        if ($PSVersionTable.PSEdition -eq 'Desktop') {
            # Windows PowerShell does not offer TLS 1.2 on every system, and Ghost requires it.
            $protocol = [System.Net.ServicePointManager]::SecurityProtocol -bor [System.Net.SecurityProtocolType]::Tls12
            [System.Net.ServicePointManager]::SecurityProtocol = $protocol
        }

        $previous = $script:GhostConnection
        $script:GhostConnection = @{
            Url          = $siteUrl
            ApiUrl       = '{0}/ghost/api/admin' -f $siteUrl
            KeyId        = $Matches['id']
            Secret       = [System.Net.NetworkCredential]::new('', $Matches['secret']).SecurePassword
            ApiVersion   = $ApiVersion
            Version      = $null
            Title        = $null
            Token        = $null
            TokenExpires = [datetimeoffset]::MinValue
        }

        try {
            $resources = Get-GhostAPIData -Endpoint $MyInvocation.MyCommand.Name
            $uri = New-URIString -Endpoint $resources.URI
            $result = Submit-Request -Uri $uri -Method $resources.Method -Success $resources.Success
            $site = @(Test-ReturnFormat -Result $result -Location $resources.Result)[0]

            # The site reports its version as <major>.<minor>, which is also the form of Accept-Version.
            $reported = $site.PSObject.Properties['version']
            if (-not $reported -or [string] $reported.Value -notmatch '^\d+\.\d+') {
                throw "The site at $siteUrl does not report a Ghost version."
            }
            $script:GhostConnection['Version'] = [version] $Matches[0]
            $title = $site.PSObject.Properties['title']
            $script:GhostConnection['Title'] = if ($title) { $title.Value }
            if (-not $ApiVersion) {
                $script:GhostConnection['ApiVersion'] = 'v{0}' -f $Matches[0]
            }

            # The site information is public. Request a post to find out whether the key is accepted.
            $null = Get-GhostPost -Limit 1 -Fields 'id'
        }
        catch {
            $script:GhostConnection = $previous
            throw
        }

        [pscustomobject]@{
            PSTypeName = 'Ghost.Connection'
            Url        = $script:GhostConnection['Url']
            Title      = $script:GhostConnection['Title']
            Version    = $script:GhostConnection['Version']
            ApiVersion = $script:GhostConnection['ApiVersion']
        }
    }
    catch {
        $PSCmdlet.ThrowTerminatingError($_)
    }
}