Bundle: redb-identity / scripts (scripts.txt), 6 files Snapshot: development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Index: https://redbase.app/src/dev-2026-12-06/redb-identity/_index.txt ==== Path: redb-identity/scripts/dev-backchannel-secret.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/scripts/dev-backchannel-secret.ps1 ---- #requires -Version 7.0 <# .SYNOPSIS Provisions the W6-0 backchannel service-account secret for local development. .DESCRIPTION The Identity host (Tsak.Worker, context 'identity.core') and the Identity.Web BFF must share one client_credentials secret so that: • SeedBackchannelClientHostedService can register the OpenIddict application 'identity-backchannel' on host startup. • RevokedSidsPollHostedService (BFF) can mint a machine-token and poll /api/v1/identity/revoked-sids/since every minute. This script generates one 32-byte random base64 secret (or accepts a custom one) and sets THREE environment variables in User scope so both processes pick it up on next start: Tsak__Contexts__identity.core__Override__Identity__SeedBackchannelClient__ClientSecret → consumed by SeedBackchannelClientHostedService inside Tsak.Worker Identity__BackchannelClient__ClientId → consumed by BackchannelTokenProvider in redb.Identity.Web Identity__BackchannelClient__ClientSecret → consumed by BackchannelTokenProvider in redb.Identity.Web Idempotent: if the env-vars already exist and match, no changes are made. Use -Force to rotate (regenerates a fresh secret and overwrites both sides). .PARAMETER Secret Custom secret to use instead of a generated random one. Must be non-empty. .PARAMETER ClientId Backchannel client identifier. Default 'identity-backchannel' (matches the default in SeedBackchannelClientOptions and the canonical context.json). .PARAMETER Scope Environment-variable scope. Default 'User' (per-user, persists across sessions). 'Machine' requires elevation. 'Process' is volatile. .PARAMETER Force Regenerate the secret even if env-vars already exist. Use to rotate. .PARAMETER Clear Remove all three env-vars (cleanup). Other parameters are ignored. .EXAMPLE ./scripts/dev-backchannel-secret.ps1 # Idempotent: generates a new secret on first run, no-op on subsequent runs. .EXAMPLE ./scripts/dev-backchannel-secret.ps1 -Force # Rotates the secret. Both Tsak.Worker AND Identity.Web must be restarted. # If a stale 'identity-backchannel' OpenIddict app already exists with the # OLD secret, the host seeder will skip (idempotent on ClientId, not Secret) # — you must either delete the app via the management API or run with the # original secret. .EXAMPLE ./scripts/dev-backchannel-secret.ps1 -Secret 'my-explicit-dev-secret' # Use a known secret (e.g. shared between team members). .EXAMPLE ./scripts/dev-backchannel-secret.ps1 -Clear # Removes all three env-vars. Useful before switching to a different identity instance. #> [CmdletBinding()] param( [string]$Secret, [string]$ClientId = "identity-backchannel", [ValidateSet("User", "Machine", "Process")] [string]$Scope = "User", [switch]$Force, [switch]$Clear ) $ErrorActionPreference = "Stop" # Three variables that must move in lockstep. $HostSecretVar = "Tsak__Contexts__identity.core__Override__Identity__SeedBackchannelClient__ClientSecret" $BffClientIdVar = "Identity__BackchannelClient__ClientId" $BffSecretVar = "Identity__BackchannelClient__ClientSecret" function Get-Env([string]$name) { [Environment]::GetEnvironmentVariable($name, $Scope) } function Set-Env([string]$name, [string]$value) { [Environment]::SetEnvironmentVariable($name, $value, $Scope) # User/Machine scopes are only seen by NEW processes — also mirror into the # current process env so 'dotnet run' from THIS shell picks it up immediately. if ($Scope -ne "Process") { [Environment]::SetEnvironmentVariable($name, $value, "Process") } } function Remove-Env([string]$name) { [Environment]::SetEnvironmentVariable($name, $null, $Scope) if ($Scope -ne "Process") { [Environment]::SetEnvironmentVariable($name, $null, "Process") } } if ($Clear) { Write-Host "Clearing backchannel env-vars from $Scope scope..." -ForegroundColor Yellow Remove-Env $HostSecretVar Remove-Env $BffClientIdVar Remove-Env $BffSecretVar Write-Host " ✓ cleared" -ForegroundColor Green return } $existingHostSecret = Get-Env $HostSecretVar $existingBffId = Get-Env $BffClientIdVar $existingBffSecret = Get-Env $BffSecretVar $allSet = -not [string]::IsNullOrEmpty($existingHostSecret) ` -and -not [string]::IsNullOrEmpty($existingBffId) ` -and -not [string]::IsNullOrEmpty($existingBffSecret) $consistent = $allSet ` -and ($existingHostSecret -eq $existingBffSecret) ` -and ($existingBffId -eq $ClientId) if ($consistent -and -not $Force -and -not $Secret) { Write-Host "Backchannel secret already provisioned in $Scope scope:" -ForegroundColor Green Write-Host " $HostSecretVar" Write-Host " $BffClientIdVar = $existingBffId" Write-Host " $BffSecretVar" Write-Host "(use -Force to rotate, -Clear to remove)" -ForegroundColor DarkGray return } if ($allSet -and -not $consistent -and -not $Force -and -not $Secret) { Write-Warning "Existing env-vars are INCONSISTENT (host secret ≠ BFF secret, or ClientId mismatch)." Write-Warning "Re-run with -Force to overwrite, or with -Secret to set explicit value." exit 1 } if (-not $Secret) { $bytes = New-Object byte[] 32 [System.Security.Cryptography.RandomNumberGenerator]::Fill($bytes) $Secret = [Convert]::ToBase64String($bytes) Write-Host "Generated new random secret (32 bytes, base64-encoded)." -ForegroundColor Cyan } else { Write-Host "Using explicit secret from -Secret parameter." -ForegroundColor Cyan } Set-Env $HostSecretVar $Secret Set-Env $BffClientIdVar $ClientId Set-Env $BffSecretVar $Secret Write-Host "`nProvisioned backchannel credentials in $Scope scope:" -ForegroundColor Green Write-Host " $HostSecretVar" Write-Host " $BffClientIdVar = $ClientId" Write-Host " $BffSecretVar" Write-Host "`nNext steps:" -ForegroundColor Yellow Write-Host " 1. Restart Tsak.Worker (SeedBackchannelClientHostedService will create/verify the OpenIddict app)." Write-Host " 2. Restart redb.Identity.Web (RevokedSidsPollHostedService will start polling)." if ($Scope -ne "Process") { Write-Host " • THIS shell already sees the new env-vars (mirrored into Process scope)." Write-Host " • OTHER already-open shells need to be reopened — User-scope env-vars are loaded at process start." } Write-Host "" Write-Host "If you rotated the secret with -Force and the 'identity-backchannel' OpenIddict" -ForegroundColor DarkYellow Write-Host "application already exists, the host seeder is idempotent on ClientId and will NOT" -ForegroundColor DarkYellow Write-Host "update the stored secret. Either delete the app via management API and restart, or" -ForegroundColor DarkYellow Write-Host "use the original secret." -ForegroundColor DarkYellow Path: redb-identity/scripts/dev-certs.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/scripts/dev-certs.ps1 ---- #requires -Version 7.0 <# .SYNOPSIS Provisions a locally-trusted TLS certificate for redb.Identity.Web dev. .DESCRIPTION W6-1: HTTPS by default for the BFF in development. Two paths: 1. mkcert (preferred) — issues a cert chained to a per-user root CA that the OS already trusts. Output: ./certs/identity-web.pfx. Kestrel reads it via the Kestrel:Endpoints:Https:Certificate section in appsettings.Development.json. 2. dotnet dev-certs https --trust (fallback) — uses the ASP.NET Core developer cert. No file output; Kestrel picks it up implicitly when no explicit cert is configured. Choice is automatic: mkcert if on PATH, otherwise dev-certs. .PARAMETER PfxPassword Password for the generated PFX (mkcert path). Defaults to "redb-dev". The same value must appear in appsettings.Development.json under Kestrel:Endpoints:Https:Certificate:Password. .PARAMETER OutDir Output directory for the PFX. Defaults to ./certs at the repo root. .PARAMETER Force Re-issue even if the PFX already exists. .EXAMPLE pwsh ./redb.Identity/scripts/dev-certs.ps1 .EXAMPLE pwsh ./redb.Identity/scripts/dev-certs.ps1 -Force #> [CmdletBinding()] param( [string]$PfxPassword = 'redb-dev', [string]$OutDir = (Join-Path $PSScriptRoot '..' '..' 'certs'), [switch]$Force ) $ErrorActionPreference = 'Stop' function Write-Info($msg) { Write-Host "[dev-certs] $msg" -ForegroundColor Cyan } function Write-Ok($msg) { Write-Host "[dev-certs] $msg" -ForegroundColor Green } function Write-Warn2($msg) { Write-Host "[dev-certs] $msg" -ForegroundColor Yellow } $mkcert = Get-Command mkcert -ErrorAction SilentlyContinue if ($mkcert) { Write-Info "mkcert found: $($mkcert.Source)" if (-not (Test-Path $OutDir)) { New-Item -ItemType Directory -Path $OutDir -Force | Out-Null } $OutDir = (Resolve-Path $OutDir).Path $pfxPath = Join-Path $OutDir 'identity-web.pfx' if ((Test-Path $pfxPath) -and -not $Force) { Write-Ok "PFX already exists: $pfxPath (use -Force to re-issue)" } else { Write-Info 'Installing mkcert local CA (idempotent)...' & mkcert -install | Out-Null Push-Location $OutDir try { Write-Info 'Issuing cert for localhost / 127.0.0.1 / ::1 ...' & mkcert ` -pkcs12 ` -p12-file 'identity-web.pfx' ` localhost 127.0.0.1 ::1 } finally { Pop-Location } # mkcert -pkcs12 uses fixed password "changeit"; re-export with our password. Write-Info 'Re-exporting PFX with configured password...' $cert = Get-PfxData -FilePath $pfxPath -Password (ConvertTo-SecureString -String 'changeit' -AsPlainText -Force) $cert.EndEntityCertificates[0] | Export-PfxCertificate ` -FilePath $pfxPath ` -Password (ConvertTo-SecureString -String $PfxPassword -AsPlainText -Force) ` -Force | Out-Null Write-Ok "Wrote $pfxPath" } Write-Host '' Write-Ok 'mkcert provisioning done. Kestrel will load this PFX via appsettings.Development.json.' Write-Host ' Path: ' $pfxPath Write-Host ' Password: ' $PfxPassword Write-Host '' Write-Host 'Next:' Write-Host ' cd redb.Identity/src/redb.Identity.Web' Write-Host ' dotnet run' return } Write-Warn2 'mkcert not found on PATH — falling back to dotnet dev-certs.' Write-Warn2 'For a wider-compatibility cert (containers, multi-host names) install mkcert:' Write-Warn2 ' https://github.com/FiloSottile/mkcert' Write-Host '' Write-Info 'Trusting the ASP.NET Core developer certificate...' & dotnet dev-certs https --trust if ($LASTEXITCODE -ne 0) { throw "dotnet dev-certs failed with exit code $LASTEXITCODE" } Write-Ok 'ASP.NET Core dev certificate installed and trusted.' Write-Host 'Kestrel picks it up automatically — no PFX path needed in config.' Write-Host '' Write-Host 'Next:' Write-Host ' cd redb.Identity/src/redb.Identity.Web' Write-Host ' dotnet run --launch-profile https' Path: redb-identity/scripts/dev-certs.sh Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/scripts/dev-certs.sh ---- #!/usr/bin/env bash # W6-1: Provisions a locally-trusted TLS certificate for redb.Identity.Web dev. # # Two paths, chosen automatically: # 1. mkcert (preferred) — emits ./certs/identity-web.pfx, loaded by # Kestrel via appsettings.Development.json -> Kestrel:Endpoints:Https. # 2. dotnet dev-certs https --trust (fallback) — uses the ASP.NET Core # dev cert; Kestrel picks it up implicitly when no PFX is configured. # # Usage: # ./redb.Identity/scripts/dev-certs.sh # default password 'redb-dev' # PFX_PASSWORD=secret ./redb.Identity/scripts/dev-certs.sh # FORCE=1 ./redb.Identity/scripts/dev-certs.sh # re-issue PFX set -euo pipefail PFX_PASSWORD="${PFX_PASSWORD:-redb-dev}" SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" OUT_DIR="${OUT_DIR:-$SCRIPT_DIR/../../certs}" FORCE="${FORCE:-0}" info() { printf '\033[36m[dev-certs] %s\033[0m\n' "$*"; } ok() { printf '\033[32m[dev-certs] %s\033[0m\n' "$*"; } warn() { printf '\033[33m[dev-certs] %s\033[0m\n' "$*"; } if command -v mkcert >/dev/null 2>&1; then info "mkcert found: $(command -v mkcert)" mkdir -p "$OUT_DIR" OUT_DIR="$(cd "$OUT_DIR" && pwd)" PFX_PATH="$OUT_DIR/identity-web.pfx" if [ -f "$PFX_PATH" ] && [ "$FORCE" != "1" ]; then ok "PFX already exists: $PFX_PATH (set FORCE=1 to re-issue)" else info 'Installing mkcert local CA (idempotent)...' mkcert -install >/dev/null info 'Issuing cert for localhost / 127.0.0.1 / ::1 ...' ( cd "$OUT_DIR" mkcert \ -pkcs12 \ -p12-file 'identity-web.pfx' \ localhost 127.0.0.1 ::1 ) # mkcert -pkcs12 default password is 'changeit'. Re-export with the # configured password via openssl so Kestrel can load it directly. if command -v openssl >/dev/null 2>&1; then info 'Re-exporting PFX with configured password via openssl...' TMP_PEM="$(mktemp)" openssl pkcs12 -in "$PFX_PATH" -nodes -passin pass:changeit -out "$TMP_PEM" openssl pkcs12 -export -in "$TMP_PEM" -out "$PFX_PATH" -passout "pass:$PFX_PASSWORD" rm -f "$TMP_PEM" else warn "openssl not found — PFX password stays at mkcert default 'changeit'." warn "Update Kestrel:Endpoints:Https:Certificate:Password in appsettings.Development.json to match." PFX_PASSWORD='changeit' fi ok "Wrote $PFX_PATH" fi cat < param( [ValidateSet("Release", "Debug")] [string]$Configuration = "Release", [switch]$NoBuild, [ValidateSet("Contracts", "Core", "Http", "Grpc", "Soap", "All")] [string]$Module = "All", [string]$TsakModules, [switch]$NoCopy ) $ErrorActionPreference = "Stop" # ── Resolve paths ────────────────────────────────────────────────────── $ScriptRoot = Split-Path -Parent $MyInvocation.MyCommand.Path $IdentityRoot = Resolve-Path (Join-Path $ScriptRoot "..") $RepoRoot = Resolve-Path (Join-Path $IdentityRoot "..") $Solution = Join-Path $IdentityRoot "redb.Identity.slnx" $OutputDir = Join-Path $ScriptRoot "output" if (-not $TsakModules) { # modules\, not Libs\ — Libs is the deprecated drop directory. Libs\shared still holds the # host-provided framework DLLs and stays below as an exclude source, but nothing is dropped there. $TsakModules = Join-Path $RepoRoot "redb.Tsak\src\redb.Tsak.Worker\modules" } $TsakWorkerBinRelease = Join-Path $RepoRoot "redb.Tsak\src\redb.Tsak.Worker\bin\Release\net10.0" $TsakWorkerBinDebug = Join-Path $RepoRoot "redb.Tsak\src\redb.Tsak.Worker\bin\Debug\net10.0" $TsakLibsRoot = Join-Path $RepoRoot "redb.Tsak\src\redb.Tsak.Worker\Libs" $TsakSharedLibs = Join-Path $TsakLibsRoot "shared" if (-not (Test-Path $OutputDir)) { New-Item -ItemType Directory -Path $OutputDir | Out-Null } # ── Build ────────────────────────────────────────────────────────────── # CopyLocalLockFileAssemblies=true forces NuGet PackageReference assemblies (OpenIddict, # Argon2, Fido2, Otp.NET, MyCSharp.HttpUserAgentParser, …) to be copied into bin/. # Without it, library-SDK projects only emit own DLL + ProjectReference outputs, and # the .tpkg would be missing all third-party deps. # We pass via /p: instead of editing csproj to avoid bloating test-project bin folders. if (-not $NoBuild) { Write-Host "`n=== Building redb.Identity ($Configuration) ===" -ForegroundColor Cyan & dotnet build $Solution -c $Configuration --nologo /p:CopyLocalLockFileAssemblies=true if ($LASTEXITCODE -ne 0) { throw "Build failed (exit $LASTEXITCODE)" } } # ── Build EXCLUDE set (host-provided assemblies) ─────────────────────── $ExcludeSet = New-Object System.Collections.Generic.HashSet[string] ([System.StringComparer]::OrdinalIgnoreCase) # name -> the copy the HOST will actually load. First source wins, and the scan order below is the # runtime's own order (worker bin, then the shared layer, then the frameworks), so the recorded path # is the assembly a module really binds to. Read by the version gate in Pack-Module. $HostProvided = New-Object 'System.Collections.Generic.Dictionary[string,string]' ([System.StringComparer]::OrdinalIgnoreCase) function Add-Excludes-FromDir([string]$Dir) { if (-not (Test-Path $Dir)) { Write-Host "Exclude source skipped (missing): $Dir" -ForegroundColor DarkGray return } $before = $ExcludeSet.Count Get-ChildItem -Path $Dir -Filter *.dll -File -ErrorAction SilentlyContinue | ForEach-Object { [void]$ExcludeSet.Add($_.Name) if (-not $HostProvided.ContainsKey($_.Name)) { $HostProvided[$_.Name] = $_.FullName } } $added = $ExcludeSet.Count - $before Write-Host "Exclude source: $Dir (+$added)" -ForegroundColor DarkGray } # Worker bin: scan whichever Configuration actually built (Debug if Release missing). # Sometimes both exist if user has built both — scan both, union of names is what's host-resident. Add-Excludes-FromDir $TsakWorkerBinRelease Add-Excludes-FromDir $TsakWorkerBinDebug # Tpkg-side resolution: ALC reads Libs\ root + Libs\shared\. Anything sitting there is # host-provided to every loaded module — exclude both. Add-Excludes-FromDir $TsakLibsRoot Add-Excludes-FromDir $TsakSharedLibs # Shared frameworks: the runtime resolves these by name for the host, and ModuleAssemblyLoadContext # asks the Default ALC before probing the package - so a copy inside a .tpkg can never win a resolve. # It is dead weight, and until the Tsak fix (ca994106) LoadedAssemblyTracker byte-loaded it a second # time into the non-collectible Default context. BOTH frameworks must be scanned: Microsoft.Extensions # .Configuration / .Options / .Logging / .Diagnostics.HealthChecks ship in the ASP.NET framework, not # in the runtime one. These names were excluded by accident until 2026-09-18, when build-shared stopped # copying framework assemblies into Libs\shared; stating the rule here makes the package independent of # whatever that layer happens to contain. $WorkerTfm = Split-Path $TsakWorkerBinRelease -Leaf # net10.0 - the same constant the bin paths use if ($WorkerTfm -notmatch '^net(?\d+)\.') { throw "Cannot read the framework major from '$WorkerTfm' (expected netN.M). Fix `$TsakWorkerBinRelease." } $TfmMajor = [int]$Matches['major'] $DotnetRoot = if ($env:DOTNET_ROOT) { $env:DOTNET_ROOT } else { Split-Path (Get-Command dotnet -ErrorAction Stop).Source } foreach ($fwName in @("Microsoft.NETCore.App", "Microsoft.AspNetCore.App")) { $fwRoot = Join-Path $DotnetRoot "shared\$fwName" if (-not (Test-Path $fwRoot)) { throw "Shared framework $fwName is not installed under $DotnetRoot. Without it the exclude set is wrong and the packages would carry framework assemblies." } # Highest installed version of the worker's major. Sort as [version], never as text: # a string sort puts 9.0.20 above 10.0.8 and would pick the wrong framework. $fwDir = Get-ChildItem $fwRoot -Directory | Where-Object { ($_.Name -as [version]) -and ($_.Name -as [version]).Major -eq $TfmMajor } | Sort-Object { [version]$_.Name } -Descending | Select-Object -First 1 if (-not $fwDir) { throw "No $fwName $TfmMajor.x found under $fwRoot, but the worker targets $WorkerTfm. Install the matching runtime." } Add-Excludes-FromDir $fwDir.FullName } # Always-exclude (cosmetic / not transferred) @( "redb.Identity.Tests.dll" ) | ForEach-Object { [void]$ExcludeSet.Add($_) } # ── Version gate ─────────────────────────────────────────────────────── # There used to be a force-include list here (Microsoft.IdentityModel.*): those DLLs were packaged # even though the host had them, on the reasoning that the host shipped an older, incompatible major # and the module needed its own. That never worked and cannot work: ModuleAssemblyLoadContext asks # the Default ALC before probing the package - it must, or contract types would split - and since # Tsak's ca994106 LoadedAssemblyTracker prefers the host copy too. The packaged copies were 1.26 MB # the loader never looked at, plus a Troubleshooting entry advising a cure that cures nothing. # # The real hazard is not "the host has it" but "the host has a DIFFERENT major", and that used to be # silent: the module compiled against one version, the host loaded another, and the failure surfaced # far away as a FileNotFoundException inside OpenIddict. The gate below turns that divergence into a # packaging error naming both sides, so it is fixed by moving a pin rather than by shipping a copy # that will be ignored. function Get-AssemblyVersionOrNull([string]$Path) { try { return [System.Reflection.AssemblyName]::GetAssemblyName($Path).Version } catch [System.BadImageFormatException] { return $null # native or mixed-mode file - there is no managed identity to compare } catch { Write-Host (" version unreadable ({0}): {1}" -f $_.Exception.GetType().Name, $Path) -ForegroundColor DarkGray return $null } } Write-Host "Exclude set built: $($ExcludeSet.Count) host-provided DLLs" -ForegroundColor DarkGray # ── Pack one module ──────────────────────────────────────────────────── function Pack-Module { param( [string]$ModuleName, # "redb.Identity.Core" [string]$ProjectDir, # full path to project dir [string]$ConfigFileName, # "redb.Identity.Core.config.json" [string[]]$ExtraExcludes = @(), # additional DLL names to skip [string[]]$ContentDirs = @() # subdirectories of bin\ to ship whole (e.g. "Wsdl") ) Write-Host "`n=== Packing $ModuleName ===" -ForegroundColor Cyan $bin = Join-Path $ProjectDir "bin\$Configuration\net10.0" $manifest = Join-Path $ProjectDir "Module\manifest.json" $config = Join-Path $ProjectDir $ConfigFileName if (-not (Test-Path $bin)) { throw "Bin dir missing: $bin" } if (-not (Test-Path $manifest)) { throw "Manifest missing: $manifest" } if (-not (Test-Path $config)) { throw "Config missing: $config" } $staging = Join-Path $env:TEMP "tpkg-$ModuleName-$([guid]::NewGuid().ToString('N'))" New-Item -ItemType Directory -Path $staging | Out-Null try { Copy-Item $manifest -Destination $staging Copy-Item $config -Destination $staging $localExcludes = New-Object System.Collections.Generic.HashSet[string] ([System.StringComparer]::OrdinalIgnoreCase) foreach ($n in $ExcludeSet) { [void]$localExcludes.Add($n) } foreach ($n in $ExtraExcludes) { [void]$localExcludes.Add($n) } $included = @() $skipped = @() $divergedMajor = @() $divergedMinor = @() Get-ChildItem -Path $bin -Filter *.dll -File | ForEach-Object { $name = $_.Name $isExcluded = $localExcludes.Contains($name) if ($isExcluded) { $skipped += $name # Version gate. Only for names the HOST provides: ExtraExcludes are the sibling # package's assemblies (a facade skips what Core.Module ships), and those two DO # share one context by design, so there is nothing to diverge. if ($HostProvided.ContainsKey($name)) { $ourVer = Get-AssemblyVersionOrNull $_.FullName $hostVer = Get-AssemblyVersionOrNull $HostProvided[$name] if ($ourVer -and $hostVer -and $ourVer -ne $hostVer) { $line = " {0}: module {1}, host {2} [host copy: {3}]" -f $name, $ourVer, $hostVer, $HostProvided[$name] if ($ourVer.Major -ne $hostVer.Major) { $divergedMajor += $line } else { $divergedMinor += $line } } } } else { Copy-Item $_.FullName -Destination $staging $included += $name } } if ($divergedMajor.Count -gt 0) { $msg = "{0}: major version divergence with the host on {1} assembly(ies):" -f $ModuleName, $divergedMajor.Count $msg += [Environment]::NewLine + ($divergedMajor -join [Environment]::NewLine) + [Environment]::NewLine $msg += "The host wins at runtime - the module's load context asks the Default one first - so packaging our own copy cannot fix this. " $msg += "Move a pin instead: the module project under redb.Identity\src, and redb.Tsak\src\redb.Tsak.Worker\redb.Tsak.Worker.csproj " $msg += "(System.IdentityModel.Tokens.Jwt also comes from redb.Licensing)." throw $msg } foreach ($w in $divergedMinor) { Write-Warning ("{0}: minor version divergence with the host, the host copy is what loads.{1}{2}" -f $ModuleName, [Environment]::NewLine, $w) } Write-Host (" Included : {0} DLLs" -f $included.Count) -ForegroundColor Green Write-Host (" Excluded : {0} DLLs (host-provided)" -f $skipped.Count) -ForegroundColor DarkGray # Content that is not a DLL and lives in a subdirectory: the WS-Trust WSDL, and anything like it # later. The DLL loop above reads only the root of bin\, so without this such a file is silently # left out of the package — and the code that looks for it degrades quietly rather than failing, # which is exactly the combination that ships a module missing half its purpose. foreach ($dir in $ContentDirs) { $source = Join-Path $bin $dir if (-not (Test-Path $source)) { throw "Content directory missing: $source" } Copy-Item $source -Destination $staging -Recurse -Force $files = @(Get-ChildItem -Path $source -File -Recurse) Write-Host (" Content : {0}\ ({1} files)" -f $dir, $files.Count) -ForegroundColor Green } $tpkg = Join-Path $OutputDir "$ModuleName.tpkg" if (Test-Path $tpkg) { Remove-Item $tpkg -Force } Compress-Archive -Path (Join-Path $staging "*") -DestinationPath $tpkg -CompressionLevel Optimal -Force $size = (Get-Item $tpkg).Length Write-Host (" Created : {0} ({1:N1} KB)" -f $tpkg, ($size / 1KB)) -ForegroundColor Green if (-not $NoCopy) { if (-not (Test-Path $TsakModules)) { New-Item -ItemType Directory -Path $TsakModules | Out-Null } $dest = Join-Path $TsakModules "$ModuleName.tpkg" Copy-Item $tpkg -Destination $dest -Force (Get-Item $dest).LastWriteTime = Get-Date # touch → triggers Tsak hot-reload watcher Write-Host (" Copied : {0}" -f $dest) -ForegroundColor Green } return [pscustomobject]@{ Module = $ModuleName Included = $included.Count Excluded = $skipped.Count SizeKB = [math]::Round($size / 1KB, 1) Tpkg = $tpkg DllNames = $included } } finally { if (Test-Path $staging) { Remove-Item $staging -Recurse -Force -ErrorAction SilentlyContinue } } } # ── Run ──────────────────────────────────────────────────────────────── $results = @() if ($Module -in @("Contracts", "All")) { # The contracts CARRIER: an empty module whose payload is its companion, # redb.Identity.Contracts.dll — the one process-wide instance of the DTO assembly that every # Identity module resolves against. Packed FIRST and excluded from everyone else, so that # hot-reloading any single module (whose reload force-Replaces its own companions in the # tracker) never swaps the contracts out from under the others (Tsak F-12). # Reloading THIS package replaces the instance and must be followed by reloading every # Identity module — which a contract change requires semantically anyway. $results += Pack-Module ` -ModuleName "redb.Identity.Contracts" ` -ProjectDir (Join-Path $IdentityRoot "src\redb.Identity.Contracts.Module") ` -ConfigFileName "redb.Identity.Contracts.Module.config.json" } # Every later package excludes what the carrier ships, exactly as the facades exclude what # Core.Module ships. When only a subset is being packed the carrier result is absent — then the # carrier's own bin answers instead, so a lone `-Module Core` repack still excludes the contracts. $contractsResult = $results | Where-Object { $_.Module -eq "redb.Identity.Contracts" } | Select-Object -First 1 $contractsExcludes = @() if ($contractsResult) { $contractsExcludes = $contractsResult.DllNames } else { $contractsBin = Join-Path $IdentityRoot "src\redb.Identity.Contracts.Module\bin\$Configuration\net10.0" if (Test-Path $contractsBin) { $contractsExcludes = @(Get-ChildItem -Path $contractsBin -Filter *.dll -File | ForEach-Object { $_.Name }) } } if (-not ($contractsExcludes -contains "redb.Identity.Contracts.dll")) { # Refuse to build a core package that would smuggle its own contracts copy back in. throw "Contracts carrier not built — run with -Module Contracts (or All), or build src\redb.Identity.Contracts.Module first." } if ($Module -in @("Core", "All")) { # The Tsak entry-point project is the *thin* shim `redb.Identity.Core.Module`. # Its bin/ contains: # - redb.Identity.Core.Module.dll ← the EntryPoint (isolated per-package ALC) # - redb.Identity.Core.dll ← COMPANION (visible to facade .tpkg's via # LoadedAssemblyTracker / Default ALC) # - OpenIddict.*, Konscious.Argon2, Fido2, Otp.NET, MyCSharp.HttpUserAgentParser* # - all transitive NuGet runtime DLLs not already provided by Tsak host. # redb.Identity.Contracts.dll is deliberately NOT here — the carrier package above ships it. $results += Pack-Module ` -ModuleName "redb.Identity.Core.Module" ` -ProjectDir (Join-Path $IdentityRoot "src\redb.Identity.Core.Module") ` -ConfigFileName "redb.Identity.Core.Module.config.json" ` -ExtraExcludes $contractsExcludes } if ($Module -in @("Http", "All")) { # Http.tpkg must NOT carry anything that already lives in Core.tpkg — # Tsak loads dependencies first (manifest.Dependencies) so types come from Core's ALC. # If we duplicate transitive NuGet DLLs (OpenIddict, Argon2, Fido2, …) into Http.tpkg, # we get type-identity collisions across ALCs. # Http.tpkg gets the union of Core.Module's DllNames as ExtraExcludes — every DLL # already shipped as a Core.Module companion is dropped from Http.tpkg, so Http.tpkg # ends up containing only the HTTP-facade DLL (`redb.Identity.Http.dll`). # Type identity is preserved cross-ALC because the Tsak ModuleAssemblyLoadContext # delegates resolution to the Default ALC (LoadedAssemblyTracker) before probing # local probe paths — Core.Module's companions are loaded into Default ALC and # shared by Assembly identity. $httpExtraExcludes = @( "redb.Identity.Core.dll", "redb.Identity.Contracts.dll" ) $coreResult = $results | Where-Object { $_.Module -eq "redb.Identity.Core.Module" } | Select-Object -First 1 if ($coreResult) { $httpExtraExcludes += $coreResult.DllNames } $httpExtraExcludes += $contractsExcludes $results += Pack-Module ` -ModuleName "redb.Identity.Http" ` -ProjectDir (Join-Path $IdentityRoot "src\redb.Identity.Http") ` -ConfigFileName "redb.Identity.Http.config.json" ` -ExtraExcludes $httpExtraExcludes } if ($Module -in @("Grpc", "All")) { # Same rule as Http: a facade .tpkg must NOT duplicate anything Core.Module already ships. # Tsak loads dependencies first, so Core's companions live in the Default ALC and are shared by # assembly identity; duplicating them here would create type-identity collisions across ALCs. # The result is a tiny package carrying only redb.Identity.Grpc.dll. $grpcExtraExcludes = @( "redb.Identity.Core.dll", "redb.Identity.Contracts.dll" ) $coreResultForGrpc = $results | Where-Object { $_.Module -eq "redb.Identity.Core.Module" } | Select-Object -First 1 if ($coreResultForGrpc) { $grpcExtraExcludes += $coreResultForGrpc.DllNames } $grpcExtraExcludes += $contractsExcludes $results += Pack-Module ` -ModuleName "redb.Identity.Grpc" ` -ProjectDir (Join-Path $IdentityRoot "src\redb.Identity.Grpc") ` -ConfigFileName "redb.Identity.Grpc.config.json" ` -ExtraExcludes $grpcExtraExcludes } if ($Module -in @("Soap", "All")) { # Same rule as Http and Grpc: a facade .tpkg must NOT duplicate anything Core.Module already ships. # The result is a tiny package carrying redb.Identity.Soap.dll and the WSDL it publishes. $soapExtraExcludes = @( "redb.Identity.Core.dll", "redb.Identity.Contracts.dll" ) $coreResultForSoap = $results | Where-Object { $_.Module -eq "redb.Identity.Core.Module" } | Select-Object -First 1 if ($coreResultForSoap) { $soapExtraExcludes += $coreResultForSoap.DllNames } $soapExtraExcludes += $contractsExcludes $results += Pack-Module ` -ModuleName "redb.Identity.Soap" ` -ProjectDir (Join-Path $IdentityRoot "src\redb.Identity.Soap") ` -ConfigFileName "redb.Identity.Soap.config.json" ` -ExtraExcludes $soapExtraExcludes ` -ContentDirs @("Wsdl") # the contract, served on GET; without it the facade answers POST only } # ── Copy external context.json (Tsak Layer 3, devops-editable) ──────── # This single file replaces business defaults that previously lived inside each # .tpkg's {Module}.config.json. Tsak's TsakCoordinator.LoadModuleConfigFiles reads # {sourceDir}/context.json (sourceDir = folder where .tpkg lives = $TsakModules) and # merges it into EVERY module's effective config in that folder. Each context binds # only the sections it knows (Core → Identity:*, Http → IdentityTransport:*); shared # Redb:identity-pg is wired into both. The slim in-package {Module}.config.json now # carries only ContextName + AutoStart (module identity). # context.json is ALWAYS emitted into scripts/output alongside the two .tpkg so that # output/ is a self-contained, deployable bundle: { *.tpkg + context.json }. Whoever # drops these files into a Tsak host's module folder (e.g. dist worker\modules\) gets the # shared Layer-3 config too — without it the modules boot on in-tpkg stub defaults only # (AllowEphemeralKeys=false, UsePropsSigningKeyStore=false → "no signing credentials"). # When -not $NoCopy we ALSO copy into the dev Worker modules dir for hot-reload. $externalContext = Join-Path $IdentityRoot "context.json" if (Test-Path $externalContext) { Write-Host ("`n=== External context.json ===") -ForegroundColor Cyan Write-Host (" Source : {0}" -f $externalContext) -ForegroundColor DarkGray # (1) scripts/output — part of the shippable artifact set (ALWAYS) $outputContext = Join-Path $OutputDir "context.json" Copy-Item $externalContext -Destination $outputContext -Force $outCtxSize = (Get-Item $outputContext).Length Write-Host (" Output : {0} ({1:N1} KB)" -f $outputContext, ($outCtxSize / 1KB)) -ForegroundColor Green # (2) dev Worker Libs — hot-reload (gated by -NoCopy) if (-not $NoCopy) { $contextDest = Join-Path $TsakModules "context.json" Copy-Item $externalContext -Destination $contextDest -Force (Get-Item $contextDest).LastWriteTime = Get-Date # touch → triggers hot-reload Write-Host (" Copied : {0}" -f $contextDest) -ForegroundColor Green } } else { Write-Warning "External context.json not found at $externalContext — modules will run with stub defaults only." } # ── Summary ──────────────────────────────────────────────────────────── Write-Host "`n=== Summary ===" -ForegroundColor Cyan $results | Select-Object Module, Included, Excluded, SizeKB, Tpkg | Format-Table -AutoSize Write-Host "`nDone." -ForegroundColor Green if (-not $NoCopy) { Write-Host "Tsak Worker should hot-reload modules from: $TsakModules" -ForegroundColor Yellow Write-Host "Devops single source of truth: $TsakModules\context.json" -ForegroundColor Yellow } Path: redb-identity/scripts/seed-conformance-user.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/scripts/seed-conformance-user.ps1 ---- #requires -Version 7 <# .SYNOPSIS Seeds the End-User the OIDF conformance suite logs in as: `conform` / `Conform1234Pass!`, with a FULL OIDC §5.1 profile (every profile/email/phone/address claim populated). .DESCRIPTION The Basic OP scope tests (oidcc-scope-profile / -email / -address / -phone / -all) VERIFY that userinfo returns every standard claim implied by the requested scope. A user created with only login+email makes those tests WARN ("userinfo doesn't contain all scope items"), which looks like a server defect but is just missing data. This script fills the profile so they PASS. The conformance worker runs on a dev SQLite DB that is reset on a clean restart, so this user is NOT persistent — re-run this after any worker restart during a conformance session. Idempotent: re-registering an existing login returns success; the PUT /me overwrites the profile. .PARAMETER BaseUrl OP base. Default https://127.0.0.1:5002 (local conformance context). #> param([string]$BaseUrl = 'https://127.0.0.1:5002') $ErrorActionPreference = 'Stop' $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true # One password-grant client, reused to mint tokens for each seeded user. $reg = Invoke-RestMethod -Method Post "$BaseUrl/connect/register" -ContentType 'application/json' -Body (@{ client_name = 'seed-conform'; grant_types = @('password') scope = 'openid profile email phone address identity:account' } | ConvertTo-Json) function Token($login, $pass, $scope) { (Invoke-RestMethod -Method Post "$BaseUrl/connect/token" -ContentType 'application/x-www-form-urlencoded' -Body @{ grant_type = 'password'; username = $login; password = $pass client_id = $reg.client_id; client_secret = $reg.client_secret; scope = $scope }).access_token } # Fills a user's full OIDC §5.1 profile via PUT /me, then confirms userinfo carries the set. # The suite's scope tests (oidcc-scope-*) log in as whatever End-User you type on the OP form and # verify userinfo returns every claim the scope implies — so EVERY user you might log in as needs # a complete profile, not just one. function Seed-Profile($login, $pass, $display, $given, $family, $email, $phone) { Write-Host "[$login] register + full profile ..." -ForegroundColor Cyan try { Invoke-RestMethod -Method Post "$BaseUrl/api/v1/identity/account/register" -ContentType 'application/json' -Body (@{ login = $login; email = $email; password = $pass; displayName = $display } | ConvertTo-Json) | Out-Null } catch { } # already exists (e.g. bootstrap admin) — fine, we only need the profile filled $tok = Token $login $pass 'openid profile email phone address identity:account' Invoke-RestMethod -Method Put "$BaseUrl/api/v1/identity/me" -Headers @{ Authorization = "Bearer $tok" } ` -ContentType 'application/json' -Body (@{ email = $email; displayName = $display; givenName = $given; familyName = $family; middleName = 'Test' nickname = $login; preferredUsername = $login; profile = "https://example.com/$login" picture = "https://example.com/$login.png"; website = 'https://example.com'; gender = 'other' birthdate = '1990-01-01'; zoneInfo = 'Europe/Moscow'; locale = 'en-US'; phoneNumber = $phone address = @{ formatted = "1 Test St, Testville, TS 12345, US"; streetAddress = '1 Test St' locality = 'Testville'; region = 'TS'; postalCode = '12345'; country = 'US' } } | ConvertTo-Json -Depth 6) | Out-Null $ui = Invoke-RestMethod "$BaseUrl/connect/userinfo" -Headers @{ Authorization = (Token $login $pass 'openid profile email phone address' | ForEach-Object { "Bearer $_" }) } $want = 'name','given_name','family_name','birthdate','email','phone_number','address' $missing = $want | Where-Object { -not $ui.PSObject.Properties.Name.Contains($_) } if ($missing) { Write-Host " MISSING: $($missing -join ', ')" -ForegroundColor Red; exit 1 } Write-Host " $login ready (full §5.1 profile)." -ForegroundColor Green } # Both End-Users the suite might be driven with: # conform — the documented suite login; # admin — the dev bootstrap admin, which is what you actually type on the OP form out of habit. Seed-Profile 'conform' 'Conform1234Pass!' 'Conformance User' 'Conf' 'Ormance' 'conform@example.com' '+15551234567' Seed-Profile 'admin' 'admin' 'Admin User' 'Ad' 'Min' 'admin@example.com' '+15559876543' Path: redb-identity/scripts/test-gate.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/scripts/test-gate.ps1 ---- #!/usr/bin/env pwsh <# .SYNOPSIS The Identity test gate: every test project of redb.Identity, on one storage provider. .DESCRIPTION Runs the three test projects the solution carries - redb.Identity.Tests (the engine, provider matrix), redb.Identity.Client.Tests (the SDK, pure unit) and redb.Identity.Web.Tests (the BFF, pure unit) - and prints one summary. Client and Web tests do not touch storage; they are in the gate because a gate that runs one project out of three is how tests stay red for months without anyone noticing (RevokedSidsPollHostedServiceTests since 2026-07, SearchUsers_GETs_with_query since 2026-06, DevTlsContractTests since 2026-05). The provider matrix is three invocations of this script, one per -Provider, started in parallel the way the owner runs them. Brokers are shared between those processes; suites that need one isolate themselves per provider (see AuditIbmMqIntegrationTests). .PARAMETER Provider sqlite (default) | postgres | mssql - exported as REDB_PROVIDER for redb.Identity.Tests. .PARAMETER Filter Optional `dotnet test --filter` expression applied to redb.Identity.Tests only. .PARAMETER NoBuild Skip the build (the last build of each project is used). Only when you know it is fresh. .EXAMPLE pwsh redb.Identity/scripts/test-gate.ps1 -Provider postgres #> param( [ValidateSet("sqlite", "postgres", "mssql")] [string]$Provider = "sqlite", [string]$Filter, [switch]$NoBuild ) $ErrorActionPreference = "Stop" $root = Resolve-Path (Join-Path (Split-Path -Parent $MyInvocation.MyCommand.Path) "..") $env:REDB_PROVIDER = $Provider $env:DOTNET_CLI_UI_LANGUAGE = "en" $projects = @( @{ Name = "redb.Identity.Tests"; Path = "tests\redb.Identity.Tests\redb.Identity.Tests.csproj"; UsesFilter = $true }, @{ Name = "redb.Identity.Client.Tests"; Path = "tests\redb.Identity.Client.Tests\redb.Identity.Client.Tests.csproj"; UsesFilter = $false }, @{ Name = "redb.Identity.Web.Tests"; Path = "tests\redb.Identity.Web.Tests\redb.Identity.Web.Tests.csproj"; UsesFilter = $false } ) $results = @() $failed = $false foreach ($p in $projects) { $csproj = Join-Path $root $p.Path Write-Host "`n=== $($p.Name) [REDB_PROVIDER=$Provider] ===" -ForegroundColor Cyan if (-not $NoBuild) { dotnet build $csproj -c Debug --nologo -v q if ($LASTEXITCODE -ne 0) { throw "build failed: $($p.Name) (exit $LASTEXITCODE)" } } $args = @("test", $csproj, "--no-build", "--nologo") if ($Filter -and $p.UsesFilter) { $args += @("--filter", $Filter) } $output = & dotnet @args 2>&1 $exit = $LASTEXITCODE $output | Where-Object { $_ -match '^\s*Failed |Passed!|Failed!|Error Message|^\s+Expected' } | ForEach-Object { Write-Host $_ } $summary = ($output | Select-String -Pattern 'Passed:\s+(\d+).*Total:\s+(\d+)|Failed:\s+(\d+),\s+Passed:\s+(\d+)' | Select-Object -Last 1).Line $results += [pscustomobject]@{ Project = $p.Name; Exit = $exit; Summary = ($summary ?? "").Trim() } if ($exit -ne 0) { $failed = $true } } Write-Host "`n=== Gate summary [REDB_PROVIDER=$Provider] ===" -ForegroundColor Cyan $results | Format-Table -AutoSize | Out-String | Write-Host if ($failed) { Write-Host "GATE RED" -ForegroundColor Red; exit 1 } Write-Host "GATE GREEN" -ForegroundColor Green exit 0