Public/Start-GhostLocalSite.ps1

function Start-GhostLocalSite {
    <#
    .SYNOPSIS
        Installs and starts a Ghost site on this machine and returns how to connect to it.

    .DESCRIPTION
        Gives you a Ghost site of your own to write posts for, to develop a theme with, or to run tests
        against, without touching a live site. It follows https://docs.ghost.org/install/local and then does
        what that guide leaves to the browser, so that the site can be used right away, also on a build server:

        1. Installs Ghost with Ghost-CLI (ghost install local) in a folder of its own, with a SQLite database.
        2. Starts it. It runs in the background until it is stopped or the machine restarts.
        3. Creates the owner, the account you sign in to Ghost Admin with.
        4. Creates a custom integration and reads its Admin API key.
        5. Optionally links a theme into the site and activates it: a folder on this machine, or a git
           repository that is cloned first. A routes.yaml in the theme folder is given to the site as well.

        The command returns the address, the account and the key. It also puts the address and the key in the
        environment variables GHOST_ADMIN_API_URL and GHOST_ADMIN_API_KEY, which Connect-Ghost reads; in a GitHub
        workflow and in an Azure DevOps pipeline they are set for the steps that follow as well. With -Connect
        the module is connected to the site right away.

        The key in AdminApiKey is that of the integration, which may do on this site what an integration may do
        on a live site. StaffAccessToken is the token of the owner, which may do everything: list and delete
        themes, upload routes, import content. -Connect -AsOwner connects with that one.

        It can be run again at any time: what is already there is left alone. A site that is installed is
        started when it does not run, and the same account and key are returned.

        Needs Node.js 22 or 24 with npm, and git for -ThemeRepository. Ghost-CLI is run through npx, so nothing
        is installed for the whole machine. Without -Version the newest Ghost that the installed Node.js can run
        is installed; a warning says so when that is not the latest Ghost.

        A theme is linked, not copied: a change to a file of the theme shows on the site right away. Its name on
        the site is the name in its package.json. Keep the site out of the folder of the theme: Ghost reads
        everything in that folder as a part of the theme.

        The account and the key are kept in the file local-ghost.json in the folder of the site. They are only
        good for this site, which listens on this machine alone. Do not use the folder for anything you want to
        keep: Remove-GhostLocalSite deletes it.

    .EXAMPLE
        Start-GhostLocalSite -Connect

        Installs and starts Ghost in the folder .local-ghost of the current location, on http://localhost:2368,
        and connects the module to it. Get-GhostPost then returns the posts of that site.

    .EXAMPLE
        Start-GhostLocalSite -Path ../my-site -ThemePath ./my-theme

        Starts the site with the theme in the folder my-theme active, and with the routes of its routes.yaml.

    .EXAMPLE
        Start-GhostLocalSite -ThemeRepository https://dev.azure.com/my-org/my-project/_git/my-theme -Connect

        Clones the theme, or brings the clone of an earlier run up to date, and starts the site with it. git
        signs in the way it does for any other clone on this machine, so a private repository works when a plain
        git clone of it does.

    .EXAMPLE
        $site = Start-GhostLocalSite -Port 2370; Start-Process -FilePath $site.AdminUrl

        Starts a site on another port and opens Ghost Admin. The account to sign in with is in $site.Email and
        $site.Password.

    .LINK
        https://docs.ghost.org/install/local
    #>

    [CmdletBinding(SupportsShouldProcess)]
    [OutputType('Ghost.LocalSite')]
    param(
        # Folder of the site. Created when it is not there. Defaults to .local-ghost in the current location.
        [Parameter(Position = 0)]
        [string] $Path,

        # Ghost version to install, such as 6.75.0. Defaults to the newest version that the installed Node.js
        # can run. Only used when the site is installed.
        [string] $Version,

        # Port the site listens on. Only used when the site is installed.
        [ValidateRange(1024, 65535)]
        [int] $Port = 2368,

        # Title of the site. Only used when the site is set up.
        [string] $Title = 'Local Ghost',

        # Email address and password of the owner. Defaults to the account in local-ghost.json and, for a new
        # site, to ghost@example.com with a generated password. The password needs at least ten characters.
        [pscredential] $Credential,

        # Folder of a theme to link into the site and activate. It needs a package.json; the name in it is the
        # name of the theme on the site.
        [string] $ThemePath,

        # Address of a git repository that holds a theme, to use in the place of -ThemePath. It is cloned into
        # the folder theme-sources in the folder of the site and brought up to date on every run. That clone is
        # for running the theme, not for working on it: it goes when the site is removed.
        [string] $ThemeRepository,

        # Branch or tag of -ThemeRepository to use. Defaults to the default branch of the repository.
        [string] $ThemeBranch,

        # A routes.yaml to give the site. Defaults to the routes.yaml in the folder of the theme, when it has
        # one.
        [string] $RoutesPath,

        # Connect the module to the site, as Connect-Ghost does.
        [switch] $Connect,

        # With -Connect: connect as the owner of the site instead of as its integration. The owner may do
        # everything, such as Import-GhostContent. An integration may do what an integration may do on a live
        # site, which makes it the better stand-in for one.
        [switch] $AsOwner
    )

    try {
        # What happens is shown, because installing takes minutes. -InformationAction changes that.
        if (-not $PSBoundParameters.ContainsKey('InformationAction')) {
            $InformationPreference = 'Continue'
        }

        # The progress bar of the web cmdlets slows Windows PowerShell down considerably.
        $ProgressPreference = 'SilentlyContinue'

        $Path = Resolve-GhostLocalSitePath -Path $Path -ForNewSite
        $configPath = Join-Path -Path $Path -ChildPath 'config.development.json'
        $statePath = Join-Path -Path $Path -ChildPath 'local-ghost.json'
        $utf8 = [System.Text.UTF8Encoding]::new($false)

        # Ghost-CLI writes this file when it installs a site.
        $installed = Test-Path -LiteralPath (Join-Path -Path $Path -ChildPath '.ghost-cli')

        if (-not (Get-Command -Name 'node' -ErrorAction SilentlyContinue)) {
            throw 'Node.js is needed, version 22 or 24, with npm. Install it from https://nodejs.org/ and try again.'
        }
        if ($ThemeRepository -and $ThemePath) {
            throw 'Pass -ThemePath for a theme on this machine or -ThemeRepository for one to clone, not both.'
        }
        if ($ThemeRepository -and -not (Get-Command -Name 'git' -ErrorAction SilentlyContinue)) {
            throw 'git is needed to clone the theme of -ThemeRepository. Install it from https://git-scm.com/.'
        }
        if ($ThemePath) {
            if (-not (Test-Path -LiteralPath $ThemePath -PathType Container)) {
                throw "The folder of the theme, $ThemePath, does not exist."
            }

            # A site inside the folder of its own theme would be read by Ghost as a part of that theme.
            $separator = [System.IO.Path]::DirectorySeparatorChar
            $themeFolder = (Resolve-Path -LiteralPath $ThemePath).ProviderPath.TrimEnd('\', '/') + $separator
            $sitePath = $Path.TrimEnd('\', '/') + $separator
            $inside = $sitePath.StartsWith($themeFolder, [System.StringComparison]::OrdinalIgnoreCase)
            if ($inside) {
                throw "The site in $Path would lie inside the theme in $ThemePath. Pass -Path with a folder outside it."
            }

            # The same goes for a site that was put there earlier.
            $nestedSite = Get-ChildItem -LiteralPath $themeFolder -Directory -Force |
                Where-Object { Test-Path -LiteralPath (Join-Path -Path $_.FullName -ChildPath '.ghost-cli') } |
                Select-Object -First 1
            if ($nestedSite) {
                $reason = 'Ghost would read that site as a part of the theme and refuse the theme.'
                $remove = "Remove-GhostLocalSite -Path '$($nestedSite.FullName)'"
                $found = "The theme in $ThemePath has a Ghost site in it: $($nestedSite.FullName)."
                throw "$found $reason Remove it: $remove"
            }
        }

        if (-not $PSCmdlet.ShouldProcess($Path, 'Install and start a local Ghost site')) {
            return
        }

        if (-not $installed) {
            if ((Test-Path -LiteralPath $Path) -and @(Get-ChildItem -LiteralPath $Path -Force).Count -gt 0) {
                throw "$Path is not empty and holds no Ghost site. Ghost needs a folder of its own: pass another -Path."
            }

            # Something that already listens on the port would answer in the place of the new site.
            $client = [System.Net.Sockets.TcpClient]::new()
            try {
                $client.Connect('127.0.0.1', $Port)
                $taken = $true
            }
            catch {
                $taken = $false
            }
            finally {
                $client.Close()
            }
            if ($taken) {
                throw "Port $Port is in use, maybe by another Ghost site (ghost ls shows them). Pass another -Port."
            }

            if (-not $Version) {
                $Version = Get-GhostVersionForNode
            }

            Write-Information -MessageData "Installing Ghost $Version in $Path. This takes a few minutes."
            New-Item -Path $Path -ItemType Directory -Force | Out-Null
            $install = @(
                'install', $Version, '--local'
                '--dir', $Path
                '--port', $Port
                '--url', "http://localhost:$Port"
                '--no-start'
            )
            Invoke-GhostCli -Arguments $install
        }

        $config = ConvertFrom-Json -InputObject ([System.IO.File]::ReadAllText($configPath))
        $siteUrl = ([string] $config.url).TrimEnd('/')
        if ($installed -and $PSBoundParameters.ContainsKey('Port') -and ([uri] $siteUrl).Port -ne $Port) {
            Write-Warning -Message "The site is installed on $siteUrl and stays there. Remove it to change the port."
        }

        # Ghost emails a code when somebody signs in from a new device, and a local site cannot send email. A
        # local install has this turned off; an older Ghost-CLI did not do that.
        $security = $config.PSObject.Properties['security']
        $verification = if ($security) { $security.Value.PSObject.Properties['staffDeviceVerification'] }
        if (-not $verification -or $verification.Value -ne $false) {
            if (-not $security) {
                $config | Add-Member -NotePropertyName 'security' -NotePropertyValue ([pscustomobject]@{})
            }
            $config.security | Add-Member -NotePropertyName 'staffDeviceVerification' -NotePropertyValue $false -Force
            [System.IO.File]::WriteAllText($configPath, (ConvertTo-Json -InputObject $config -Depth 10), $utf8)

            # A site that runs has to read the setting again.
            if (Wait-GhostSite -SiteUrl $siteUrl -Timeout 0) {
                Invoke-GhostCli -Arguments 'stop', '--dir', $Path
            }
        }

        $site = Wait-GhostSite -SiteUrl $siteUrl -Timeout 0
        if (-not $site) {
            Write-Information -MessageData "Starting Ghost on $siteUrl."
            Invoke-GhostCli -Arguments 'start', '--dir', $Path
            $site = Wait-GhostSite -SiteUrl $siteUrl
            if (-not $site) {
                throw "Ghost was started but $siteUrl does not answer. See what it logged: ghost log --dir `"$Path`""
            }
        }

        # The owner.
        $state = $null
        if (Test-Path -LiteralPath $statePath) {
            $state = ConvertFrom-Json -InputObject ([System.IO.File]::ReadAllText($statePath))
        }

        $email = 'ghost@example.com'
        $password = [guid]::NewGuid().ToString('N')
        if ($Credential) {
            $email = $Credential.UserName
            $password = $Credential.GetNetworkCredential().Password
        }
        elseif ($state) {
            $email = $state.Email
            $password = $state.Password
        }

        $admin = @{
            SiteUrl = $siteUrl
            Session = [Microsoft.PowerShell.Commands.WebRequestSession]::new()
        }

        $isSetUp = (Invoke-GhostOwnerRequest @admin -Resource '/authentication/setup/').setup[0].status
        if (-not $isSetUp) {
            Write-Information -MessageData "Setting up the site with the owner $email."
            $owner = @{
                setup = @(
                    @{ name = 'Local Owner'; email = $email; password = $password; blogTitle = $Title }
                )
            }
            Invoke-GhostOwnerRequest @admin -Resource '/authentication/setup/' -Method 'Post' -Body $owner | Out-Null

            # Kept right away: when a later step fails, the account of the site is not lost with it.
            $account = [ordered]@{ Url = $siteUrl; Email = $email; Password = $password; AdminApiKey = $null }
            [System.IO.File]::WriteAllText($statePath, (ConvertTo-Json -InputObject $account), $utf8)
        }
        elseif (-not $Credential -and -not $state) {
            $advice = 'Pass the email address and the password of its owner with -Credential.'
            throw "The site in $Path was set up by hand: $statePath is not there. $advice"
        }

        $signIn = @{ username = $email; password = $password }
        Invoke-GhostOwnerRequest @admin -Resource '/session/' -Method 'Post' -Body $signIn | Out-Null

        # The token of the owner, which is used as a key and may do everything the owner may.
        $ownerKey = (Invoke-GhostOwnerRequest @admin -Resource '/users/me/token/').apiKey
        $staffAccessToken = [string] $ownerKey.secret
        if ($staffAccessToken -notmatch ':') {
            $staffAccessToken = '{0}:{1}' -f $ownerKey.id, $ownerKey.secret
        }

        # The Admin API key.
        $integrationName = 'Local development'
        $list = Invoke-GhostOwnerRequest @admin -Resource '/integrations/?include=api_keys&limit=all'
        $integration = $list.integrations | Where-Object { $_.name -eq $integrationName } | Select-Object -First 1
        if (-not $integration) {
            Write-Information -MessageData "Creating the integration '$integrationName'."
            $new = @{ integrations = @(@{ name = $integrationName }) }
            $create = @{ Resource = '/integrations/?include=api_keys'; Method = 'Post'; Body = $new }
            $created = Invoke-GhostOwnerRequest @admin @create
            $integration = $created.integrations[0]
        }
        $key = $integration.api_keys | Where-Object { $_.type -eq 'admin' } | Select-Object -First 1

        # A newer Ghost returns the key as it is used, <id>:<secret>. An older one returns the secret alone.
        $adminApiKey = [string] $key.secret
        if ($adminApiKey -notmatch ':') {
            $adminApiKey = '{0}:{1}' -f $key.id, $key.secret
        }

        # The theme.
        if ($ThemeRepository) {
            # The address can hold a password, which is kept out of what is written.
            $shownAddress = $ThemeRepository -replace '//[^/@]+@', '//'

            # The last part of the address, without .git, names the folder of the clone.
            $repositoryName = ($ThemeRepository.TrimEnd('/') -split '[/\\:]')[-1] -replace '\.git$'
            $repositoryName = $repositoryName -replace '[^A-Za-z0-9._-]', '-'
            $ThemePath = Join-Path -Path (Join-Path -Path $Path -ChildPath 'theme-sources') -ChildPath $repositoryName

            if (Test-Path -LiteralPath (Join-Path -Path $ThemePath -ChildPath '.git')) {
                $origin = [string] (& git -C $ThemePath remote get-url origin)
                if ($origin.TrimEnd('/') -ne $ThemeRepository.TrimEnd('/')) {
                    throw "$ThemePath is the clone of another repository. Remove that folder to clone $shownAddress."
                }

                Write-Information -MessageData "Bringing the clone of $shownAddress up to date."
                Invoke-GhostGit -Arguments '-C', $ThemePath, 'fetch', '--tags', 'origin'
                if ($ThemeBranch) {
                    Invoke-GhostGit -Arguments '-C', $ThemePath, 'checkout', $ThemeBranch
                }

                # A tag has nothing to pull. On a branch, only what does not conflict with a change in the clone.
                & git -C $ThemePath symbolic-ref --quiet HEAD | Out-Null
                if ($LASTEXITCODE -eq 0) {
                    Invoke-GhostGit -Arguments '-C', $ThemePath, 'pull', '--ff-only'
                }
            }
            else {
                Write-Information -MessageData "Cloning $shownAddress into $ThemePath."
                $clone = @('clone')
                if ($ThemeBranch) {
                    $clone += '--branch', $ThemeBranch
                }
                Invoke-GhostGit -Arguments ($clone + @($ThemeRepository, $ThemePath))
            }
        }

        $themeName = $null
        $themeSource = $null
        if ($ThemePath) {
            $themeSource = (Resolve-Path -LiteralPath $ThemePath).ProviderPath.TrimEnd('\', '/')
            $packagePath = Join-Path -Path $themeSource -ChildPath 'package.json'
            if (-not (Test-Path -LiteralPath $packagePath -PathType Leaf)) {
                $hint = ''
                if ($ThemeRepository) {
                    $hint = ' Is the repository empty, or is the theme in a folder of it?'
                }
                throw "$themeSource has no package.json, so it is not the folder of a Ghost theme.$hint"
            }

            # The name in package.json, as Ghost Admin and a theme that is uploaded use it. The folder can have
            # any name.
            $themeName = Split-Path -Path $themeSource -Leaf
            $package = ConvertFrom-Json -InputObject ([System.IO.File]::ReadAllText($packagePath))
            $packageName = $package.PSObject.Properties['name']
            if ($packageName -and $packageName.Value) {
                $themeName = [string] $packageName.Value
            }
            $link = Join-Path -Path (Join-Path -Path $Path -ChildPath 'content/themes') -ChildPath $themeName

            $existing = Get-Item -LiteralPath $link -Force -ErrorAction SilentlyContinue
            $isLink = $existing -and ($existing.Attributes -band [System.IO.FileAttributes]::ReparsePoint)
            if ($existing -and -not $isLink) {
                throw "The site already has a theme named '$themeName' that is not a link: $link. Rename or remove it."
            }
            if ($isLink -and @($existing.Target)[0].TrimEnd('\', '/') -ne $themeSource) {
                # A link to another folder with the same name. Deleting the link leaves that folder as it is.
                $existing.Delete()
                $existing = $null
            }
            if (-not $existing) {
                # A junction needs no special rights on Windows, where a symbolic link does.
                $linkType = if ($env:OS -eq 'Windows_NT') { 'Junction' } else { 'SymbolicLink' }
                New-Item -ItemType $linkType -Path $link -Value $themeSource | Out-Null

                # Ghost looks for themes when it starts.
                Write-Information -MessageData "Linked the theme '$themeName'. Restarting Ghost to load it."
                Invoke-GhostCli -Arguments 'restart', '--dir', $Path
                if (-not (Wait-GhostSite -SiteUrl $siteUrl)) {
                    throw "Ghost was restarted but $siteUrl does not answer. See its log: ghost log --dir `"$Path`""
                }
            }

            Invoke-GhostOwnerRequest @admin -Resource "/themes/$themeName/activate/" -Method 'Put' | Out-Null
            Write-Information -MessageData "The theme '$themeName' is active."
        }

        # The routes of a site are not part of its theme, but a theme with templates of its own for certain
        # addresses does not work without them. They are kept next to the theme and given to the site the way
        # Ghost Admin does it.
        if (-not $RoutesPath -and $themeSource) {
            $themeRoutes = Join-Path -Path $themeSource -ChildPath 'routes.yaml'
            if (Test-Path -LiteralPath $themeRoutes -PathType Leaf) {
                $RoutesPath = $themeRoutes
            }
        }

        $routesFile = $null
        if ($RoutesPath) {
            $routesFile = (Resolve-Path -LiteralPath $RoutesPath).ProviderPath
            $wanted = [System.IO.File]::ReadAllBytes($routesFile)
            $current = [string] (Invoke-GhostOwnerRequest @admin -Resource '/settings/routes/yaml/')

            # Compared as text, whatever the line endings: the routes are only sent when they differ.
            $normalize = { param($Text) ($Text -replace '\r\n?', "`n").Trim() }
            if ((& $normalize $current) -cne (& $normalize ([System.Text.Encoding]::UTF8.GetString($wanted)))) {
                $form = @{
                    FieldName       = 'routes'
                    FileName        = 'routes.yaml'
                    FileContent     = $wanted
                    FileContentType = 'application/x-yaml'
                }
                $form = ConvertTo-MultipartContent @form
                $upload = @{
                    Resource    = '/settings/routes/yaml/'
                    Method      = 'Post'
                    Content     = $form.Content
                    ContentType = $form.ContentType
                }
                Invoke-GhostOwnerRequest @admin @upload | Out-Null
                Write-Information -MessageData "The site uses the routes in $routesFile."
            }
        }

        # The result.
        $state = [ordered]@{
            Url              = $siteUrl
            Email            = $email
            Password         = $password
            AdminApiKey      = $adminApiKey
            StaffAccessToken = $staffAccessToken
        }
        [System.IO.File]::WriteAllText($statePath, (ConvertTo-Json -InputObject $state), $utf8)

        $env:GHOST_ADMIN_API_URL = $siteUrl
        $env:GHOST_ADMIN_API_KEY = $adminApiKey
        if ($env:GITHUB_ENV) {
            # For the steps of the workflow that follow, and out of its log.
            Write-Information -MessageData "::add-mask::$adminApiKey"
            Write-Information -MessageData "::add-mask::$password"
            $lines = "GHOST_ADMIN_API_URL=$siteUrl", "GHOST_ADMIN_API_KEY=$adminApiKey", ''
            [System.IO.File]::AppendAllText($env:GITHUB_ENV, ($lines -join "`n"), $utf8)
        }
        if ($env:TF_BUILD) {
            # For the steps of the Azure DevOps pipeline that follow. Not as a secret, which a step only gets
            # when it asks for it by name: the key is good for this site alone, and the site is gone when the job
            # is.
            Write-Information -MessageData "##vso[task.setvariable variable=GHOST_ADMIN_API_URL]$siteUrl"
            Write-Information -MessageData "##vso[task.setvariable variable=GHOST_ADMIN_API_KEY]$adminApiKey"
        }

        if ($Connect) {
            $connectKey = if ($AsOwner) { $staffAccessToken } else { $adminApiKey }
            $secureKey = [System.Net.NetworkCredential]::new('', $connectKey).SecurePassword
            Connect-Ghost -Url $siteUrl -AdminApiKey $secureKey | Out-Null
        }
        elseif ($AsOwner) {
            Write-Warning -Message '-AsOwner only has a meaning together with -Connect.'
        }

        Write-Information -MessageData "Ghost $($site.version) runs on $siteUrl. Sign in on $siteUrl/ghost as $email."
        [pscustomobject]@{
            PSTypeName       = 'Ghost.LocalSite'
            Url              = $siteUrl
            AdminUrl         = "$siteUrl/ghost"
            Version          = $site.version
            Path             = $Path
            Theme            = $themeName
            Routes           = $routesFile
            Email            = $email
            Password         = $password
            AdminApiKey      = $adminApiKey
            StaffAccessToken = $staffAccessToken
        }
    }
    catch {
        $PSCmdlet.ThrowTerminatingError($_)
    }
}