源码快照 @ 2026-09-01 (source-only, 剔除非源码素材)
Publish Claude Code Binaries / Stage and publish binaries (push) Canceled after 0s
Publish Tutti App Runtime / Build darwin-arm64 (push) Canceled after 0s
Publish Tutti App Runtime / Build darwin-amd64 (push) Canceled after 0s
Publish Tutti App Runtime / Build linux-amd64 (push) Canceled after 0s
Publish Tutti App Runtime / Build windows-amd64 (push) Canceled after 0s
Sync Tutti Agent Skills / sync (push) Canceled after 0s
Windows Agent Adapters / Test Windows agent adapters (push) Canceled after 0s
Windows Daemon Adapters / Test Windows daemon adapters (push) Canceled after 0s
Publish Tutti App Runtime / Publish runtime catalog (push) Canceled after 0s
Publish Claude Code Binaries / Stage and publish binaries (push) Canceled after 0s
Publish Tutti App Runtime / Build darwin-arm64 (push) Canceled after 0s
Publish Tutti App Runtime / Build darwin-amd64 (push) Canceled after 0s
Publish Tutti App Runtime / Build linux-amd64 (push) Canceled after 0s
Publish Tutti App Runtime / Build windows-amd64 (push) Canceled after 0s
Sync Tutti Agent Skills / sync (push) Canceled after 0s
Windows Agent Adapters / Test Windows agent adapters (push) Canceled after 0s
Windows Daemon Adapters / Test Windows daemon adapters (push) Canceled after 0s
Publish Tutti App Runtime / Publish runtime catalog (push) Canceled after 0s
This commit is contained in:
commit
2ed3415fb7
8018 files changed
+1936476
No files matched your search
@@ -0,0 +1,137 @@
|
||||
# @tutti-os/desktop-update-admission
|
||||
|
||||
Shared daemon and Electron mechanics for minimum-version admission, forced
|
||||
desktop upgrades, and version-scoped feature availability.
|
||||
|
||||
The package provides:
|
||||
|
||||
- a Go daemon core for proactive policy checks, timeout, throttling,
|
||||
single-flight, strict response validation, and feature-only persistence
|
||||
- TypeScript contracts for daemon snapshots and refresh results
|
||||
- Electron startup admission, forced-updater lease, restricted IPC, preload
|
||||
API, shared React UI, and i18n resources
|
||||
- deterministic development policy/updater scenarios and a loopback mock
|
||||
server
|
||||
|
||||
Tutti integrates the Go core in `tuttid`; TSH integrates it in `desktopd`.
|
||||
Electron talks only to its authenticated local daemon and never calls the
|
||||
public policy endpoint directly.
|
||||
|
||||
Hosts may show their business UI before awaiting startup admission. When the
|
||||
startup result requires an upgrade, the Electron controller keeps the business
|
||||
window visible and presents the forced-upgrade window as its modal child. A
|
||||
slow policy check therefore does not create a blank startup, while a resolved
|
||||
block prevents further interaction with the parent business window.
|
||||
|
||||
## Daemon API
|
||||
|
||||
The product daemon exposes:
|
||||
|
||||
- `GET /v1/desktop-update-admission` — current snapshot, no remote side effect
|
||||
- `GET /v1/desktop-update-admission/startup` — waits for the proactive initial
|
||||
check
|
||||
- `POST /v1/desktop-update-admission/refresh` — sends a `foreground` or `retry`
|
||||
lifecycle trigger
|
||||
|
||||
The daemon owns the 3-second startup timeout, 10-second foreground timeout,
|
||||
30-minute foreground interval, request single-flight, and fail-open result.
|
||||
Resolved policy checks and invalid responses enter the foreground throttle
|
||||
window. Failed-open transport and timeout checks remain immediately eligible so
|
||||
a restored network can recover admission. Electron owns lifecycle signals,
|
||||
foreground recovery retries, and presentation.
|
||||
|
||||
## Development scenarios
|
||||
|
||||
Packaged applications ignore all development variables. Invalid enabled
|
||||
development configuration fails startup.
|
||||
|
||||
Client identity and updater fields:
|
||||
|
||||
| Variable | Meaning |
|
||||
| ------------------------------------------ | --------------------------------------------------------------------------- |
|
||||
| `DESKTOP_UPDATE_ADMISSION_DEV` | Enables an unpackaged development scenario. |
|
||||
| `DESKTOP_UPDATE_ADMISSION_CURRENT_VERSION` | One current version injected into both daemon admission and updater. |
|
||||
| `DESKTOP_UPDATE_ADMISSION_LATEST_VERSION` | Updater target for available/downloaded outcomes. |
|
||||
| `DESKTOP_UPDATE_ADMISSION_UPDATER` | `available`, `downloaded`, `unavailable`, `error`, or `targetBelowMinimum`. |
|
||||
| `DESKTOP_UPDATE_ADMISSION_DOWNLOAD` | `success` or `error`. |
|
||||
| `DESKTOP_UPDATE_ADMISSION_INSTALL` | `simulated` or `error`; neither invokes the production installer. |
|
||||
| `DESKTOP_UPDATE_ADMISSION_TRANSPORT` | `in-process` (default) or `loopback`. |
|
||||
| `DESKTOP_UPDATE_ADMISSION_MOCK_SERVER_URL` | Exact `http://127.0.0.1:<port>` origin used by the daemon in loopback mode. |
|
||||
|
||||
Daemon-owned in-process policy fields:
|
||||
|
||||
| Variable | Meaning |
|
||||
| ------------------------------------------------- | -------------------------------------------------------------------------- |
|
||||
| `DESKTOP_UPDATE_ADMISSION_MINIMUM_VERSION` | Default minimum for policy steps that require one. |
|
||||
| `DESKTOP_UPDATE_ADMISSION_POLICY` | One policy outcome. |
|
||||
| `DESKTOP_UPDATE_ADMISSION_POLICY_SEQUENCE` | Per-request sequence such as `upgradeRequired@1.1.0,minimumNotConfigured`. |
|
||||
| `DESKTOP_UPDATE_ADMISSION_SCENARIO` | Named coordinated policy/updater scenario. |
|
||||
| `DESKTOP_UPDATE_ADMISSION_FEATURE_KEYS` | Comma-separated feature keys returned by the in-process policy checker. |
|
||||
| `DESKTOP_UPDATE_ADMISSION_FOREGROUND_INTERVAL_MS` | Daemon foreground interval override; integer at least 100. |
|
||||
|
||||
The shortest in-process forced-upgrade scenario is:
|
||||
|
||||
```bash
|
||||
DESKTOP_UPDATE_ADMISSION_DEV=1 \
|
||||
DESKTOP_UPDATE_ADMISSION_CURRENT_VERSION=1.0.0 \
|
||||
DESKTOP_UPDATE_ADMISSION_POLICY=upgradeRequired \
|
||||
DESKTOP_UPDATE_ADMISSION_MINIMUM_VERSION=1.1.0 \
|
||||
DESKTOP_UPDATE_ADMISSION_LATEST_VERSION=1.2.0 \
|
||||
DESKTOP_UPDATE_ADMISSION_UPDATER=available
|
||||
```
|
||||
|
||||
Named scenarios:
|
||||
|
||||
- `startup-force-success`
|
||||
- `startup-policy-timeout`
|
||||
- `startup-updater-unavailable`
|
||||
- `startup-target-below-minimum`
|
||||
- `startup-download-error`
|
||||
- `retry-policy-released`
|
||||
- `foreground-upgrade-required`
|
||||
|
||||
For a complete HTTP test, start the server in a separate process containing all
|
||||
server-owned policy fields:
|
||||
|
||||
```bash
|
||||
DESKTOP_UPDATE_ADMISSION_DEV=1 \
|
||||
DESKTOP_UPDATE_ADMISSION_POLICY=upgradeRequired \
|
||||
DESKTOP_UPDATE_ADMISSION_MINIMUM_VERSION=1.4.0 \
|
||||
DESKTOP_UPDATE_ADMISSION_FEATURE_KEYS=workspace.example \
|
||||
DESKTOP_UPDATE_ADMISSION_MOCK_SERVER_PORT=43210 \
|
||||
pnpm exec desktop-update-admission-mock-server
|
||||
```
|
||||
|
||||
Then start the client without policy fields:
|
||||
|
||||
```bash
|
||||
DESKTOP_UPDATE_ADMISSION_DEV=1 \
|
||||
DESKTOP_UPDATE_ADMISSION_CURRENT_VERSION=1.0.0 \
|
||||
DESKTOP_UPDATE_ADMISSION_TRANSPORT=loopback \
|
||||
DESKTOP_UPDATE_ADMISSION_MOCK_SERVER_URL=http://127.0.0.1:43210
|
||||
```
|
||||
|
||||
Add `DESKTOP_UPDATE_ADMISSION_UPDATER=available` and a
|
||||
`DESKTOP_UPDATE_ADMISSION_LATEST_VERSION` to the client process to exercise the
|
||||
forced updater. Policy variables in a loopback client are rejected, preventing
|
||||
a second policy authority.
|
||||
|
||||
## Feature availability
|
||||
|
||||
A valid `featureAvailability.keys` envelope replaces the daemon's
|
||||
exact-identity cache. Missing or invalid feature data retains the prior cache
|
||||
without changing a valid admission decision. The cache stores only identity,
|
||||
feature keys, policy revision, and fetch time; it never stores a minimum version
|
||||
or admission decision. The daemon always serializes `keys` as a JSON array,
|
||||
including `[]` when no feature keys are available.
|
||||
|
||||
Electron keeps only an in-memory projection for trusted renderer IPC:
|
||||
|
||||
```ts
|
||||
const snapshot = await desktopApi.featureAvailability.getSnapshot();
|
||||
const enabled = await desktopApi.featureAvailability.isSupported(
|
||||
"workspace.exampleFeature"
|
||||
);
|
||||
```
|
||||
|
||||
Renderer code does not read environment variables or access daemon cache files.
|
||||
@@ -0,0 +1,117 @@
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
)
|
||||
|
||||
const featureCacheSchemaVersion = "tutti.desktop-update-admission-feature-cache.v1"
|
||||
|
||||
type featureCacheDocument struct {
|
||||
SchemaVersion string `json:"schemaVersion"`
|
||||
Identity Identity `json:"identity"`
|
||||
PolicyRevision string `json:"policyRevision"`
|
||||
FetchedAt time.Time `json:"fetchedAt"`
|
||||
Keys []string `json:"keys"`
|
||||
}
|
||||
|
||||
type FeatureCache interface {
|
||||
Load(Identity) (FeatureAvailabilitySnapshot, error)
|
||||
Save(Identity, FeatureAvailabilitySnapshot) error
|
||||
}
|
||||
|
||||
type FileFeatureCache struct {
|
||||
Path string
|
||||
}
|
||||
|
||||
func (cache FileFeatureCache) Load(identity Identity) (FeatureAvailabilitySnapshot, error) {
|
||||
raw, err := os.ReadFile(cache.Path)
|
||||
if err != nil {
|
||||
return FeatureAvailabilitySnapshot{}, err
|
||||
}
|
||||
var document featureCacheDocument
|
||||
if err := json.Unmarshal(raw, &document); err != nil {
|
||||
return FeatureAvailabilitySnapshot{}, fmt.Errorf("decode feature availability cache: %w", err)
|
||||
}
|
||||
if document.SchemaVersion != featureCacheSchemaVersion {
|
||||
return FeatureAvailabilitySnapshot{}, errors.New("feature availability cache schema is unsupported")
|
||||
}
|
||||
if document.Identity != identity {
|
||||
return FeatureAvailabilitySnapshot{}, errors.New("feature availability cache identity does not match")
|
||||
}
|
||||
if document.PolicyRevision == "" || document.FetchedAt.IsZero() {
|
||||
return FeatureAvailabilitySnapshot{}, errors.New("feature availability cache metadata is invalid")
|
||||
}
|
||||
keys, err := parseFeatureAvailability(mustJSON(map[string]any{"keys": document.Keys}))
|
||||
if err != nil {
|
||||
return FeatureAvailabilitySnapshot{}, err
|
||||
}
|
||||
revision := document.PolicyRevision
|
||||
fetchedAt := document.FetchedAt.UTC()
|
||||
return FeatureAvailabilitySnapshot{
|
||||
Keys: keys,
|
||||
Source: "cache",
|
||||
PolicyRevision: &revision,
|
||||
FetchedAt: &fetchedAt,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (cache FileFeatureCache) Save(identity Identity, snapshot FeatureAvailabilitySnapshot) error {
|
||||
if cache.Path == "" {
|
||||
return errors.New("feature availability cache path is empty")
|
||||
}
|
||||
if snapshot.PolicyRevision == nil || snapshot.FetchedAt == nil {
|
||||
return errors.New("feature availability snapshot is not persistable")
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(cache.Path), 0o700); err != nil {
|
||||
return fmt.Errorf("create feature availability cache directory: %w", err)
|
||||
}
|
||||
document := featureCacheDocument{
|
||||
SchemaVersion: featureCacheSchemaVersion,
|
||||
Identity: identity,
|
||||
PolicyRevision: *snapshot.PolicyRevision,
|
||||
FetchedAt: snapshot.FetchedAt.UTC(),
|
||||
Keys: cloneFeatureKeys(snapshot.Keys),
|
||||
}
|
||||
raw, err := json.Marshal(document)
|
||||
if err != nil {
|
||||
return fmt.Errorf("encode feature availability cache: %w", err)
|
||||
}
|
||||
temporary, err := os.CreateTemp(filepath.Dir(cache.Path), ".desktop-update-admission-*.tmp")
|
||||
if err != nil {
|
||||
return fmt.Errorf("create feature availability cache temporary file: %w", err)
|
||||
}
|
||||
temporaryPath := temporary.Name()
|
||||
defer os.Remove(temporaryPath)
|
||||
if err := temporary.Chmod(0o600); err != nil {
|
||||
_ = temporary.Close()
|
||||
return fmt.Errorf("protect feature availability cache temporary file: %w", err)
|
||||
}
|
||||
if _, err := temporary.Write(append(raw, '\n')); err != nil {
|
||||
_ = temporary.Close()
|
||||
return fmt.Errorf("write feature availability cache temporary file: %w", err)
|
||||
}
|
||||
if err := temporary.Sync(); err != nil {
|
||||
_ = temporary.Close()
|
||||
return fmt.Errorf("sync feature availability cache temporary file: %w", err)
|
||||
}
|
||||
if err := temporary.Close(); err != nil {
|
||||
return fmt.Errorf("close feature availability cache temporary file: %w", err)
|
||||
}
|
||||
if err := os.Rename(temporaryPath, cache.Path); err != nil {
|
||||
return fmt.Errorf("replace feature availability cache: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func mustJSON(value any) []byte {
|
||||
raw, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return raw
|
||||
}
|
||||
@@ -0,0 +1,398 @@
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
developmentEnabledEnvironment = "DESKTOP_UPDATE_ADMISSION_DEV"
|
||||
developmentFeatureKeysEnvironment = "DESKTOP_UPDATE_ADMISSION_FEATURE_KEYS"
|
||||
developmentForegroundIntervalEnvironment = "DESKTOP_UPDATE_ADMISSION_FOREGROUND_INTERVAL_MS"
|
||||
developmentMinimumVersionEnvironment = "DESKTOP_UPDATE_ADMISSION_MINIMUM_VERSION"
|
||||
developmentMockServerURLEnvironment = "DESKTOP_UPDATE_ADMISSION_MOCK_SERVER_URL"
|
||||
developmentPolicyEnvironment = "DESKTOP_UPDATE_ADMISSION_POLICY"
|
||||
developmentPolicySequenceEnvironment = "DESKTOP_UPDATE_ADMISSION_POLICY_SEQUENCE"
|
||||
developmentScenarioEnvironment = "DESKTOP_UPDATE_ADMISSION_SCENARIO"
|
||||
developmentTransportEnvironment = "DESKTOP_UPDATE_ADMISSION_TRANSPORT"
|
||||
)
|
||||
|
||||
type DevelopmentResolution struct {
|
||||
Enabled bool
|
||||
Transport string
|
||||
MockServerURL string
|
||||
ForegroundInterval time.Duration
|
||||
Checker Checker
|
||||
}
|
||||
|
||||
type developmentPolicyStep struct {
|
||||
outcome string
|
||||
minimumVersion string
|
||||
}
|
||||
|
||||
type developmentChecker struct {
|
||||
featureKeys []string
|
||||
steps []developmentPolicyStep
|
||||
mu sync.Mutex
|
||||
indexes map[Identity]int
|
||||
}
|
||||
|
||||
func ResolveDevelopment(env map[string]string, identity Identity) (DevelopmentResolution, error) {
|
||||
enabled, err := parseDevelopmentBoolean(env[developmentEnabledEnvironment])
|
||||
if err != nil {
|
||||
return DevelopmentResolution{}, err
|
||||
}
|
||||
if !enabled {
|
||||
return DevelopmentResolution{}, nil
|
||||
}
|
||||
if !semverPattern.MatchString(identity.CurrentVersion) {
|
||||
return DevelopmentResolution{}, invalidDevelopmentError(
|
||||
fmt.Sprintf("current version %q must be valid SemVer", identity.CurrentVersion),
|
||||
)
|
||||
}
|
||||
interval := defaultForegroundInterval
|
||||
if raw := strings.TrimSpace(env[developmentForegroundIntervalEnvironment]); raw != "" {
|
||||
milliseconds, err := strconv.ParseInt(raw, 10, 64)
|
||||
if err != nil || milliseconds < 100 {
|
||||
return DevelopmentResolution{}, invalidDevelopmentError(
|
||||
developmentForegroundIntervalEnvironment + " must be an integer greater than or equal to 100",
|
||||
)
|
||||
}
|
||||
interval = time.Duration(milliseconds) * time.Millisecond
|
||||
}
|
||||
transport := strings.TrimSpace(env[developmentTransportEnvironment])
|
||||
if transport == "" {
|
||||
transport = "in-process"
|
||||
}
|
||||
switch transport {
|
||||
case "loopback":
|
||||
for _, name := range []string{
|
||||
developmentFeatureKeysEnvironment,
|
||||
developmentMinimumVersionEnvironment,
|
||||
developmentPolicyEnvironment,
|
||||
developmentPolicySequenceEnvironment,
|
||||
developmentScenarioEnvironment,
|
||||
} {
|
||||
if strings.TrimSpace(env[name]) != "" {
|
||||
return DevelopmentResolution{}, invalidDevelopmentError(
|
||||
name + " belongs to the loopback mock server, not the client daemon",
|
||||
)
|
||||
}
|
||||
}
|
||||
mockServerURL, err := validateDevelopmentLoopbackURL(env[developmentMockServerURLEnvironment])
|
||||
if err != nil {
|
||||
return DevelopmentResolution{}, err
|
||||
}
|
||||
return DevelopmentResolution{
|
||||
Enabled: true,
|
||||
Transport: transport,
|
||||
MockServerURL: mockServerURL,
|
||||
ForegroundInterval: interval,
|
||||
}, nil
|
||||
case "in-process":
|
||||
checker, err := resolveDevelopmentChecker(env, identity)
|
||||
if err != nil {
|
||||
return DevelopmentResolution{}, err
|
||||
}
|
||||
return DevelopmentResolution{
|
||||
Enabled: true,
|
||||
Transport: transport,
|
||||
ForegroundInterval: interval,
|
||||
Checker: checker,
|
||||
}, nil
|
||||
default:
|
||||
return DevelopmentResolution{}, invalidDevelopmentError(
|
||||
developmentTransportEnvironment + " must be in-process or loopback",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func parseDevelopmentBoolean(raw string) (bool, error) {
|
||||
switch strings.ToLower(strings.TrimSpace(raw)) {
|
||||
case "", "0", "false", "no", "off":
|
||||
return false, nil
|
||||
case "1", "true", "yes", "on":
|
||||
return true, nil
|
||||
default:
|
||||
return false, invalidDevelopmentError(
|
||||
developmentEnabledEnvironment + " must be a boolean flag",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func validateDevelopmentLoopbackURL(raw string) (string, error) {
|
||||
parsed, err := url.Parse(strings.TrimSpace(raw))
|
||||
if err != nil || parsed.Scheme != "http" || parsed.Hostname() != "127.0.0.1" ||
|
||||
parsed.User != nil || parsed.RawQuery != "" || parsed.Fragment != "" ||
|
||||
(parsed.Path != "" && parsed.Path != "/") || parsed.Port() == "" {
|
||||
return "", invalidDevelopmentError(
|
||||
developmentMockServerURLEnvironment + " must be an http://127.0.0.1 origin",
|
||||
)
|
||||
}
|
||||
return strings.TrimRight(parsed.String(), "/"), nil
|
||||
}
|
||||
|
||||
func resolveDevelopmentChecker(env map[string]string, identity Identity) (Checker, error) {
|
||||
featureKeys := []string{}
|
||||
if raw := strings.TrimSpace(env[developmentFeatureKeysEnvironment]); raw != "" {
|
||||
values := strings.Split(raw, ",")
|
||||
for index := range values {
|
||||
values[index] = strings.TrimSpace(values[index])
|
||||
}
|
||||
envelope, err := json.Marshal(map[string]any{"keys": values})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
keys, err := parseFeatureAvailability(envelope)
|
||||
if err != nil {
|
||||
return nil, invalidDevelopmentError(err.Error())
|
||||
}
|
||||
featureKeys = keys
|
||||
}
|
||||
steps, err := resolveDevelopmentPolicySteps(env)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, step := range steps {
|
||||
if err := validateDevelopmentStep(identity.CurrentVersion, step); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return &developmentChecker{
|
||||
featureKeys: featureKeys,
|
||||
steps: steps,
|
||||
indexes: make(map[Identity]int),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func resolveDevelopmentPolicySteps(env map[string]string) ([]developmentPolicyStep, error) {
|
||||
minimum := strings.TrimSpace(env[developmentMinimumVersionEnvironment])
|
||||
named := strings.TrimSpace(env[developmentScenarioEnvironment])
|
||||
policy := strings.TrimSpace(env[developmentPolicyEnvironment])
|
||||
sequence := strings.TrimSpace(env[developmentPolicySequenceEnvironment])
|
||||
if named != "" {
|
||||
if policy != "" || sequence != "" {
|
||||
return nil, invalidDevelopmentError(
|
||||
developmentScenarioEnvironment + " is mutually exclusive with configured policy outcomes",
|
||||
)
|
||||
}
|
||||
switch named {
|
||||
case "startup-force-success", "startup-updater-unavailable",
|
||||
"startup-target-below-minimum", "startup-download-error":
|
||||
return []developmentPolicyStep{{outcome: "upgradeRequired", minimumVersion: minimum}}, nil
|
||||
case "startup-policy-timeout":
|
||||
return []developmentPolicyStep{{outcome: "timeout"}}, nil
|
||||
case "retry-policy-released":
|
||||
return []developmentPolicyStep{
|
||||
{outcome: "upgradeRequired", minimumVersion: minimum},
|
||||
{outcome: "minimumNotConfigured"},
|
||||
}, nil
|
||||
case "foreground-upgrade-required":
|
||||
return []developmentPolicyStep{
|
||||
{outcome: "allowed", minimumVersion: "requestCurrentVersion"},
|
||||
{outcome: "upgradeRequired", minimumVersion: minimum},
|
||||
}, nil
|
||||
default:
|
||||
return nil, invalidDevelopmentError("unknown named scenario " + strconv.Quote(named))
|
||||
}
|
||||
}
|
||||
if policy != "" && sequence != "" {
|
||||
return nil, invalidDevelopmentError(
|
||||
developmentPolicyEnvironment + " and " + developmentPolicySequenceEnvironment + " are mutually exclusive",
|
||||
)
|
||||
}
|
||||
rawSteps := []string{}
|
||||
switch {
|
||||
case sequence != "":
|
||||
rawSteps = strings.Split(sequence, ",")
|
||||
case policy != "":
|
||||
rawSteps = []string{policy}
|
||||
default:
|
||||
return nil, invalidDevelopmentError(
|
||||
developmentPolicyEnvironment + " or " + developmentPolicySequenceEnvironment + " is required",
|
||||
)
|
||||
}
|
||||
steps := make([]developmentPolicyStep, 0, len(rawSteps))
|
||||
for _, raw := range rawSteps {
|
||||
parts := strings.Split(strings.TrimSpace(raw), "@")
|
||||
if len(parts) > 2 || strings.TrimSpace(parts[0]) == "" {
|
||||
return nil, invalidDevelopmentError("invalid policy step " + strconv.Quote(raw))
|
||||
}
|
||||
outcome := strings.TrimSpace(parts[0])
|
||||
switch outcome {
|
||||
case "allowed", "upgradeRequired":
|
||||
version := minimum
|
||||
if len(parts) == 2 {
|
||||
version = strings.TrimSpace(parts[1])
|
||||
}
|
||||
steps = append(steps, developmentPolicyStep{outcome: outcome, minimumVersion: version})
|
||||
case "minimumNotConfigured", "unsupported", "unmanagedPrerelease", "error", "timeout":
|
||||
if len(parts) == 2 {
|
||||
return nil, invalidDevelopmentError("policy outcome " + outcome + " must not include a minimum version")
|
||||
}
|
||||
steps = append(steps, developmentPolicyStep{outcome: outcome})
|
||||
default:
|
||||
return nil, invalidDevelopmentError("unknown policy outcome " + strconv.Quote(outcome))
|
||||
}
|
||||
}
|
||||
return steps, nil
|
||||
}
|
||||
|
||||
func validateDevelopmentStep(currentVersion string, step developmentPolicyStep) error {
|
||||
managedChannel := developmentManagedChannel(currentVersion)
|
||||
switch step.outcome {
|
||||
case "unmanagedPrerelease":
|
||||
if managedChannel != "unmanaged" {
|
||||
return invalidDevelopmentError("unmanagedPrerelease requires an unmanaged currentVersion")
|
||||
}
|
||||
return nil
|
||||
case "minimumNotConfigured", "unsupported":
|
||||
if managedChannel == "unmanaged" {
|
||||
return invalidDevelopmentError(step.outcome + " requires a managed currentVersion")
|
||||
}
|
||||
return nil
|
||||
case "allowed", "upgradeRequired":
|
||||
if managedChannel == "unmanaged" {
|
||||
return invalidDevelopmentError(step.outcome + " requires a managed currentVersion")
|
||||
}
|
||||
minimum := step.minimumVersion
|
||||
if minimum == "requestCurrentVersion" {
|
||||
minimum = currentVersion
|
||||
}
|
||||
if !semverPattern.MatchString(minimum) || developmentManagedChannel(minimum) != managedChannel {
|
||||
return invalidDevelopmentError(
|
||||
developmentMinimumVersionEnvironment + " must use the " + managedChannel + " channel",
|
||||
)
|
||||
}
|
||||
compared := compareDevelopmentVersions(currentVersion, minimum)
|
||||
if step.outcome == "allowed" && compared < 0 {
|
||||
return invalidDevelopmentError("allowed requires currentVersion to meet minimumVersion")
|
||||
}
|
||||
if step.outcome == "upgradeRequired" && compared >= 0 {
|
||||
return invalidDevelopmentError("upgradeRequired requires currentVersion below minimumVersion")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (checker *developmentChecker) Check(ctx context.Context, identity Identity) ([]byte, error) {
|
||||
checker.mu.Lock()
|
||||
index := checker.indexes[identity]
|
||||
if index >= len(checker.steps) {
|
||||
index = len(checker.steps) - 1
|
||||
}
|
||||
step := checker.steps[index]
|
||||
checker.indexes[identity]++
|
||||
checker.mu.Unlock()
|
||||
|
||||
switch step.outcome {
|
||||
case "timeout":
|
||||
<-ctx.Done()
|
||||
return nil, ctx.Err()
|
||||
case "error":
|
||||
return nil, errors.New("development minimum-version policy check failed")
|
||||
}
|
||||
|
||||
channel := developmentManagedChannel(identity.CurrentVersion)
|
||||
response := map[string]any{
|
||||
"channel": channel,
|
||||
"featureAvailability": map[string]any{"keys": checker.featureKeys},
|
||||
"policyRevision": fmt.Sprintf("development-policy-%d", index+1),
|
||||
}
|
||||
switch step.outcome {
|
||||
case "allowed":
|
||||
minimum := step.minimumVersion
|
||||
if minimum == "requestCurrentVersion" {
|
||||
minimum = identity.CurrentVersion
|
||||
}
|
||||
response["decision"] = "allowed"
|
||||
response["minimumVersion"] = minimum
|
||||
response["reason"] = "meetsMinimum"
|
||||
case "upgradeRequired":
|
||||
response["decision"] = "upgradeRequired"
|
||||
response["minimumVersion"] = step.minimumVersion
|
||||
response["reason"] = "belowMinimum"
|
||||
case "minimumNotConfigured":
|
||||
response["decision"] = "allowed"
|
||||
response["reason"] = "minimumNotConfigured"
|
||||
case "unsupported":
|
||||
response["decision"] = "notApplicable"
|
||||
response["reason"] = "unsupportedRelease"
|
||||
case "unmanagedPrerelease":
|
||||
response["channel"] = "unmanaged"
|
||||
response["decision"] = "notApplicable"
|
||||
response["reason"] = "unmanagedPrerelease"
|
||||
}
|
||||
return json.Marshal(response)
|
||||
}
|
||||
|
||||
func developmentManagedChannel(version string) string {
|
||||
switch {
|
||||
case stableVersionPattern.MatchString(version):
|
||||
return "stable"
|
||||
case rcVersionPattern.MatchString(version):
|
||||
return "rc"
|
||||
default:
|
||||
return "unmanaged"
|
||||
}
|
||||
}
|
||||
|
||||
func compareDevelopmentVersions(left string, right string) int {
|
||||
leftParts := parseDevelopmentVersionParts(left)
|
||||
rightParts := parseDevelopmentVersionParts(right)
|
||||
for index := 0; index < 3; index++ {
|
||||
if compared := compareDevelopmentNumericIdentifier(
|
||||
leftParts.core[index],
|
||||
rightParts.core[index],
|
||||
); compared != 0 {
|
||||
return compared
|
||||
}
|
||||
}
|
||||
if leftParts.stable != rightParts.stable {
|
||||
if leftParts.stable {
|
||||
return 1
|
||||
}
|
||||
return -1
|
||||
}
|
||||
return compareDevelopmentNumericIdentifier(leftParts.rc, rightParts.rc)
|
||||
}
|
||||
|
||||
type developmentVersionParts struct {
|
||||
core [3]string
|
||||
rc string
|
||||
stable bool
|
||||
}
|
||||
|
||||
func parseDevelopmentVersionParts(version string) developmentVersionParts {
|
||||
baseAndPrerelease := strings.SplitN(version, "-", 2)
|
||||
core := strings.Split(baseAndPrerelease[0], ".")
|
||||
parts := developmentVersionParts{stable: len(baseAndPrerelease) == 1}
|
||||
for index := 0; index < 3; index++ {
|
||||
parts.core[index] = core[index]
|
||||
}
|
||||
if len(baseAndPrerelease) == 2 {
|
||||
parts.rc = strings.TrimPrefix(baseAndPrerelease[1], "rc.")
|
||||
}
|
||||
return parts
|
||||
}
|
||||
|
||||
func compareDevelopmentNumericIdentifier(left string, right string) int {
|
||||
if len(left) < len(right) {
|
||||
return -1
|
||||
}
|
||||
if len(left) > len(right) {
|
||||
return 1
|
||||
}
|
||||
return strings.Compare(left, right)
|
||||
}
|
||||
|
||||
func invalidDevelopmentError(message string) error {
|
||||
return errors.New("invalid desktop update development scenario: " + message)
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestDevelopmentInProcessSequenceIsOwnedByDaemon(t *testing.T) {
|
||||
resolution, err := ResolveDevelopment(map[string]string{
|
||||
developmentEnabledEnvironment: "1",
|
||||
developmentFeatureKeysEnvironment: "workspace.example,agent.preview",
|
||||
developmentPolicySequenceEnvironment: "upgradeRequired@1.1.0,minimumNotConfigured",
|
||||
}, testIdentity())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if resolution.Transport != "in-process" || resolution.Checker == nil {
|
||||
t.Fatalf("resolution = %#v", resolution)
|
||||
}
|
||||
first, err := resolution.Checker.Check(context.Background(), testIdentity())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
parsedFirst, err := ParseRemoteResponse(first)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if parsedFirst.Policy.Decision != "upgradeRequired" ||
|
||||
len(parsedFirst.Feature) != 2 ||
|
||||
parsedFirst.Feature[0] != "agent.preview" {
|
||||
t.Fatalf("first response = %#v", parsedFirst)
|
||||
}
|
||||
second, err := resolution.Checker.Check(context.Background(), testIdentity())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
parsedSecond, err := ParseRemoteResponse(second)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if parsedSecond.Policy.Reason != "minimumNotConfigured" {
|
||||
t.Fatalf("second response = %#v", parsedSecond)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDevelopmentLoopbackRejectsClientPolicySource(t *testing.T) {
|
||||
_, err := ResolveDevelopment(map[string]string{
|
||||
developmentEnabledEnvironment: "1",
|
||||
developmentTransportEnvironment: "loopback",
|
||||
developmentMockServerURLEnvironment: "http://127.0.0.1:43210",
|
||||
developmentPolicyEnvironment: "upgradeRequired",
|
||||
}, testIdentity())
|
||||
if err == nil {
|
||||
t.Fatal("expected loopback policy ownership error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDevelopmentForegroundIntervalIsDaemonOwned(t *testing.T) {
|
||||
resolution, err := ResolveDevelopment(map[string]string{
|
||||
developmentEnabledEnvironment: "1",
|
||||
developmentPolicyEnvironment: "minimumNotConfigured",
|
||||
developmentForegroundIntervalEnvironment: "3000",
|
||||
}, testIdentity())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if resolution.ForegroundInterval != 3*time.Second {
|
||||
t.Fatalf("foreground interval = %s", resolution.ForegroundInterval)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDevelopmentRetryPolicyReleasedHasReachableSecondStep(t *testing.T) {
|
||||
resolution, err := ResolveDevelopment(map[string]string{
|
||||
developmentEnabledEnvironment: "1",
|
||||
developmentMinimumVersionEnvironment: "1.1.0",
|
||||
developmentScenarioEnvironment: "retry-policy-released",
|
||||
}, testIdentity())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
first, err := resolution.Checker.Check(context.Background(), testIdentity())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
firstParsed, err := ParseRemoteResponse(first)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
second, err := resolution.Checker.Check(context.Background(), testIdentity())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
secondParsed, err := ParseRemoteResponse(second)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if firstParsed.Policy.Decision != "upgradeRequired" ||
|
||||
secondParsed.Policy.Reason != "minimumNotConfigured" {
|
||||
t.Fatalf("steps = %#v then %#v", firstParsed.Policy, secondParsed.Policy)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDevelopmentVersionComparisonDoesNotLoseNumericPrecision(t *testing.T) {
|
||||
if compared := compareDevelopmentVersions(
|
||||
"900719925474099312345.0.0",
|
||||
"900719925474099312344.999.999",
|
||||
); compared <= 0 {
|
||||
t.Fatalf("comparison = %d, want positive", compared)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const maximumPolicyResponseBytes = 64 * 1024
|
||||
|
||||
type Checker interface {
|
||||
Check(context.Context, Identity) ([]byte, error)
|
||||
}
|
||||
|
||||
type HTTPChecker struct {
|
||||
Client *http.Client
|
||||
Endpoint string
|
||||
UserAgent string
|
||||
}
|
||||
|
||||
func (checker HTTPChecker) Check(ctx context.Context, identity Identity) ([]byte, error) {
|
||||
if checker.Client == nil {
|
||||
return nil, errors.New("desktop update admission HTTP client is not configured")
|
||||
}
|
||||
if strings.TrimSpace(checker.Endpoint) == "" {
|
||||
return nil, errors.New("desktop update admission endpoint is not configured")
|
||||
}
|
||||
body, err := json.Marshal(identity)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("encode desktop update admission request: %w", err)
|
||||
}
|
||||
request, err := http.NewRequestWithContext(ctx, http.MethodPost, checker.Endpoint, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create desktop update admission request: %w", err)
|
||||
}
|
||||
request.Header.Set("Accept", "application/json")
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
if checker.UserAgent != "" {
|
||||
request.Header.Set("User-Agent", checker.UserAgent)
|
||||
}
|
||||
response, err := checker.Client.Do(request)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("send desktop update admission request: %w", err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode < 200 || response.StatusCode >= 300 {
|
||||
_, _ = io.Copy(io.Discard, io.LimitReader(response.Body, maximumPolicyResponseBytes))
|
||||
return nil, fmt.Errorf("desktop update admission request returned HTTP %d", response.StatusCode)
|
||||
}
|
||||
raw, err := io.ReadAll(io.LimitReader(response.Body, maximumPolicyResponseBytes+1))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read desktop update admission response: %w", err)
|
||||
}
|
||||
if len(raw) > maximumPolicyResponseBytes {
|
||||
return nil, errors.New("desktop update admission response exceeds size limit")
|
||||
}
|
||||
return raw, nil
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var (
|
||||
semverPattern = regexp.MustCompile(`^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$`)
|
||||
stableVersionPattern = regexp.MustCompile(`^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$`)
|
||||
rcVersionPattern = regexp.MustCompile(`^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)-rc\.(0|[1-9]\d*)$`)
|
||||
featureKeyPattern = regexp.MustCompile(`^[A-Za-z][A-Za-z0-9]*(?:[._-][A-Za-z0-9]+)*$`)
|
||||
)
|
||||
|
||||
type parsedRemoteResponse struct {
|
||||
Policy PolicyResponse
|
||||
Feature []string
|
||||
FeaturePresent bool
|
||||
FeatureValid bool
|
||||
FeatureParseError error
|
||||
}
|
||||
|
||||
func ParseRemoteResponse(raw []byte) (parsedRemoteResponse, error) {
|
||||
var fields map[string]json.RawMessage
|
||||
if err := decodeOneJSONValue(raw, &fields); err != nil {
|
||||
return parsedRemoteResponse{}, err
|
||||
}
|
||||
for field := range fields {
|
||||
switch field {
|
||||
case "channel", "minimumVersion", "decision", "reason", "policyRevision", "featureAvailability":
|
||||
default:
|
||||
return parsedRemoteResponse{}, fmt.Errorf(
|
||||
"desktop update admission response contains unknown field %q",
|
||||
field,
|
||||
)
|
||||
}
|
||||
}
|
||||
var envelope struct {
|
||||
Channel json.RawMessage `json:"channel"`
|
||||
MinimumVersion json.RawMessage `json:"minimumVersion"`
|
||||
Decision json.RawMessage `json:"decision"`
|
||||
Reason json.RawMessage `json:"reason"`
|
||||
PolicyRevision json.RawMessage `json:"policyRevision"`
|
||||
FeatureAvailability json.RawMessage `json:"featureAvailability"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &envelope); err != nil {
|
||||
return parsedRemoteResponse{}, fmt.Errorf("decode desktop update admission response: %w", err)
|
||||
}
|
||||
|
||||
policy := PolicyResponse{}
|
||||
if err := decodeRequiredString(envelope.Channel, "channel", &policy.Channel); err != nil {
|
||||
return parsedRemoteResponse{}, err
|
||||
}
|
||||
if err := decodeRequiredString(envelope.Decision, "decision", &policy.Decision); err != nil {
|
||||
return parsedRemoteResponse{}, err
|
||||
}
|
||||
if err := decodeRequiredString(envelope.Reason, "reason", &policy.Reason); err != nil {
|
||||
return parsedRemoteResponse{}, err
|
||||
}
|
||||
if err := decodeRequiredString(envelope.PolicyRevision, "policyRevision", &policy.PolicyRevision); err != nil {
|
||||
return parsedRemoteResponse{}, err
|
||||
}
|
||||
if len(envelope.MinimumVersion) > 0 {
|
||||
if err := json.Unmarshal(envelope.MinimumVersion, &policy.MinimumVersion); err != nil || strings.TrimSpace(policy.MinimumVersion) == "" {
|
||||
return parsedRemoteResponse{}, errors.New("minimumVersion must be a non-empty string when present")
|
||||
}
|
||||
}
|
||||
if err := validatePolicyResponse(policy); err != nil {
|
||||
return parsedRemoteResponse{}, err
|
||||
}
|
||||
|
||||
result := parsedRemoteResponse{Policy: policy}
|
||||
if len(envelope.FeatureAvailability) == 0 {
|
||||
return result, nil
|
||||
}
|
||||
result.FeaturePresent = true
|
||||
keys, err := parseFeatureAvailability(envelope.FeatureAvailability)
|
||||
if err != nil {
|
||||
result.FeatureParseError = err
|
||||
return result, nil
|
||||
}
|
||||
result.Feature = keys
|
||||
result.FeatureValid = true
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func decodeOneJSONValue(raw []byte, target any) error {
|
||||
decoder := json.NewDecoder(bytes.NewReader(raw))
|
||||
if err := decoder.Decode(target); err != nil {
|
||||
return fmt.Errorf("decode desktop update admission response: %w", err)
|
||||
}
|
||||
var trailing json.RawMessage
|
||||
if err := decoder.Decode(&trailing); !errors.Is(err, io.EOF) {
|
||||
return errors.New("desktop update admission response contains trailing JSON")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func decodeRequiredString(raw json.RawMessage, field string, target *string) error {
|
||||
if len(raw) == 0 {
|
||||
return fmt.Errorf("%s is required", field)
|
||||
}
|
||||
if err := json.Unmarshal(raw, target); err != nil || strings.TrimSpace(*target) == "" {
|
||||
return fmt.Errorf("%s must be a non-empty string", field)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validatePolicyResponse(response PolicyResponse) error {
|
||||
hasMinimum := response.MinimumVersion != ""
|
||||
validMinimum := func(pattern *regexp.Regexp) bool {
|
||||
return hasMinimum && pattern.MatchString(response.MinimumVersion)
|
||||
}
|
||||
|
||||
switch {
|
||||
case response.Channel == "unmanaged" &&
|
||||
response.Decision == "notApplicable" &&
|
||||
response.Reason == "unmanagedPrerelease" &&
|
||||
!hasMinimum:
|
||||
return nil
|
||||
case (response.Channel == "stable" || response.Channel == "rc") &&
|
||||
response.Decision == "notApplicable" &&
|
||||
response.Reason == "unsupportedRelease" &&
|
||||
!hasMinimum:
|
||||
return nil
|
||||
case (response.Channel == "stable" || response.Channel == "rc") &&
|
||||
response.Decision == "allowed" &&
|
||||
response.Reason == "minimumNotConfigured" &&
|
||||
!hasMinimum:
|
||||
return nil
|
||||
case response.Channel == "stable" &&
|
||||
response.Decision == "allowed" &&
|
||||
response.Reason == "meetsMinimum" &&
|
||||
validMinimum(stableVersionPattern):
|
||||
return nil
|
||||
case response.Channel == "rc" &&
|
||||
response.Decision == "allowed" &&
|
||||
response.Reason == "meetsMinimum" &&
|
||||
validMinimum(rcVersionPattern):
|
||||
return nil
|
||||
case response.Channel == "stable" &&
|
||||
response.Decision == "upgradeRequired" &&
|
||||
response.Reason == "belowMinimum" &&
|
||||
validMinimum(stableVersionPattern):
|
||||
return nil
|
||||
case response.Channel == "rc" &&
|
||||
response.Decision == "upgradeRequired" &&
|
||||
response.Reason == "belowMinimum" &&
|
||||
validMinimum(rcVersionPattern):
|
||||
return nil
|
||||
default:
|
||||
return errors.New("desktop update admission response has an invalid policy combination")
|
||||
}
|
||||
}
|
||||
|
||||
func parseFeatureAvailability(raw json.RawMessage) ([]string, error) {
|
||||
var fields map[string]json.RawMessage
|
||||
if err := json.Unmarshal(raw, &fields); err != nil {
|
||||
return nil, errors.New("featureAvailability must be an object")
|
||||
}
|
||||
for field := range fields {
|
||||
if field != "keys" {
|
||||
return nil, fmt.Errorf(
|
||||
"featureAvailability contains unknown field %q",
|
||||
field,
|
||||
)
|
||||
}
|
||||
}
|
||||
var envelope struct {
|
||||
Keys json.RawMessage `json:"keys"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &envelope); err != nil {
|
||||
return nil, errors.New("featureAvailability must be an object")
|
||||
}
|
||||
if len(envelope.Keys) == 0 {
|
||||
return nil, errors.New("featureAvailability.keys is required")
|
||||
}
|
||||
var values []string
|
||||
if err := json.Unmarshal(envelope.Keys, &values); err != nil {
|
||||
return nil, errors.New("featureAvailability.keys must be a string array")
|
||||
}
|
||||
if len(values) > 256 {
|
||||
return nil, errors.New("featureAvailability.keys exceeds 256 entries")
|
||||
}
|
||||
unique := make(map[string]struct{}, len(values))
|
||||
for _, key := range values {
|
||||
if len(key) > 128 || !featureKeyPattern.MatchString(key) {
|
||||
return nil, fmt.Errorf("featureAvailability contains invalid key %q", key)
|
||||
}
|
||||
if _, exists := unique[key]; exists {
|
||||
return nil, fmt.Errorf("featureAvailability contains duplicate key %q", key)
|
||||
}
|
||||
unique[key] = struct{}{}
|
||||
}
|
||||
keys := make([]string, 0, len(unique))
|
||||
for key := range unique {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
return keys, nil
|
||||
}
|
||||
|
||||
func validateIdentity(identity Identity, checksEnabled bool) error {
|
||||
switch identity.Product {
|
||||
case ProductTSHDesktop, ProductTuttiDesktop:
|
||||
default:
|
||||
return fmt.Errorf("unsupported desktop product %q", identity.Product)
|
||||
}
|
||||
switch identity.Platform {
|
||||
case PlatformMacOS, PlatformWindows, PlatformLinux:
|
||||
default:
|
||||
return fmt.Errorf("unsupported desktop platform %q", identity.Platform)
|
||||
}
|
||||
switch identity.Architecture {
|
||||
case ArchitectureARM64, ArchitectureX64:
|
||||
default:
|
||||
return fmt.Errorf("unsupported desktop architecture %q", identity.Architecture)
|
||||
}
|
||||
if strings.TrimSpace(identity.CurrentVersion) == "" {
|
||||
return errors.New("desktop current version is required")
|
||||
}
|
||||
if checksEnabled && !semverPattern.MatchString(identity.CurrentVersion) {
|
||||
return fmt.Errorf("desktop current version %q is not valid SemVer", identity.CurrentVersion)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package daemon
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestParseRemoteResponseRejectsUnknownPolicyFields(t *testing.T) {
|
||||
_, err := ParseRemoteResponse([]byte(
|
||||
`{"channel":"stable","decision":"allowed","reason":"minimumNotConfigured","policyRevision":"v1","policySource":"appconfig"}`,
|
||||
))
|
||||
if err == nil {
|
||||
t.Fatal("expected unknown policy field error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseRemoteResponseRetainsPolicyWhenFeatureEnvelopeIsInvalid(t *testing.T) {
|
||||
parsed, err := ParseRemoteResponse([]byte(
|
||||
`{"channel":"stable","decision":"allowed","reason":"minimumNotConfigured","policyRevision":"v1","featureAvailability":{"keys":["workspace.example"],"extra":true}}`,
|
||||
))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !parsed.FeaturePresent || parsed.FeatureValid || parsed.FeatureParseError == nil {
|
||||
t.Fatalf("parsed = %#v", parsed)
|
||||
}
|
||||
if parsed.Policy.Decision != "allowed" {
|
||||
t.Fatalf("policy = %#v", parsed.Policy)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseRemoteResponseRejectsDuplicateFeatureKeys(t *testing.T) {
|
||||
parsed, err := ParseRemoteResponse([]byte(
|
||||
`{"channel":"stable","decision":"allowed","reason":"minimumNotConfigured","policyRevision":"v1","featureAvailability":{"keys":["workspace.example","workspace.example"]}}`,
|
||||
))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if parsed.FeatureValid || parsed.FeatureParseError == nil {
|
||||
t.Fatalf("parsed = %#v", parsed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseRemoteResponseRejectsTrailingJSON(t *testing.T) {
|
||||
_, err := ParseRemoteResponse([]byte(
|
||||
`{"channel":"stable","decision":"allowed","reason":"minimumNotConfigured","policyRevision":"v1"} {}`,
|
||||
))
|
||||
if err == nil {
|
||||
t.Fatal("expected trailing JSON error")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,401 @@
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"os"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultStartupTimeout = 3 * time.Second
|
||||
defaultForegroundTimeout = 10 * time.Second
|
||||
defaultForegroundInterval = 30 * time.Minute
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Identity Identity
|
||||
ChecksEnabled bool
|
||||
Checker Checker
|
||||
FeatureCache FeatureCache
|
||||
Logger *slog.Logger
|
||||
StartupTimeout time.Duration
|
||||
ForegroundTimeout time.Duration
|
||||
ForegroundInterval time.Duration
|
||||
Now func() time.Time
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
config Config
|
||||
mu sync.Mutex
|
||||
snapshot Snapshot
|
||||
started bool
|
||||
initialDone chan struct{}
|
||||
initialOnce sync.Once
|
||||
active chan struct{}
|
||||
lifecycle context.Context
|
||||
cancel context.CancelFunc
|
||||
closed bool
|
||||
}
|
||||
|
||||
func New(config Config) (*Service, error) {
|
||||
if err := validateIdentity(config.Identity, config.ChecksEnabled); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if config.ChecksEnabled && config.Checker == nil {
|
||||
return nil, errors.New("desktop update admission checker is required when checks are enabled")
|
||||
}
|
||||
if config.Logger == nil {
|
||||
config.Logger = slog.Default()
|
||||
}
|
||||
if config.Now == nil {
|
||||
config.Now = time.Now
|
||||
}
|
||||
if config.StartupTimeout <= 0 {
|
||||
config.StartupTimeout = defaultStartupTimeout
|
||||
}
|
||||
if config.ForegroundTimeout <= 0 {
|
||||
config.ForegroundTimeout = defaultForegroundTimeout
|
||||
}
|
||||
if config.ForegroundInterval <= 0 {
|
||||
config.ForegroundInterval = defaultForegroundInterval
|
||||
}
|
||||
|
||||
feature := FeatureAvailabilitySnapshot{
|
||||
Keys: []string{},
|
||||
Source: "empty",
|
||||
}
|
||||
if config.FeatureCache != nil {
|
||||
cached, err := config.FeatureCache.Load(config.Identity)
|
||||
if err == nil {
|
||||
feature = cached
|
||||
log(config.Logger, slog.LevelInfo, "feature-cache-read", map[string]any{
|
||||
"count": len(cached.Keys),
|
||||
"result": "success",
|
||||
})
|
||||
} else if !errors.Is(err, os.ErrNotExist) {
|
||||
log(config.Logger, slog.LevelError, "feature-cache-read", map[string]any{
|
||||
"error": err.Error(),
|
||||
"result": "failure",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return &Service{
|
||||
config: config,
|
||||
initialDone: make(chan struct{}),
|
||||
snapshot: Snapshot{
|
||||
Identity: config.Identity,
|
||||
Policy: PolicySnapshot{Status: "checking"},
|
||||
FeatureAvailability: feature,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (service *Service) Start(parent context.Context) {
|
||||
service.mu.Lock()
|
||||
if service.started || service.closed {
|
||||
service.mu.Unlock()
|
||||
return
|
||||
}
|
||||
service.started = true
|
||||
ctx, cancel := context.WithCancel(parent)
|
||||
service.lifecycle = ctx
|
||||
service.cancel = cancel
|
||||
service.mu.Unlock()
|
||||
|
||||
if !service.config.ChecksEnabled {
|
||||
service.mu.Lock()
|
||||
service.snapshot.Policy = PolicySnapshot{
|
||||
Status: "skipped",
|
||||
Reason: "checksDisabled",
|
||||
}
|
||||
service.mu.Unlock()
|
||||
service.markInitialDone()
|
||||
return
|
||||
}
|
||||
go func() {
|
||||
_, _ = service.refresh(ctx, "startup")
|
||||
service.markInitialDone()
|
||||
}()
|
||||
}
|
||||
|
||||
func (service *Service) WaitInitial(ctx context.Context) (Snapshot, error) {
|
||||
service.mu.Lock()
|
||||
started := service.started
|
||||
initialDone := service.initialDone
|
||||
service.mu.Unlock()
|
||||
if !started {
|
||||
return Snapshot{}, errors.New("desktop update admission service has not started")
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return Snapshot{}, ctx.Err()
|
||||
case <-initialDone:
|
||||
return service.Snapshot(), nil
|
||||
}
|
||||
}
|
||||
|
||||
func (service *Service) Snapshot() Snapshot {
|
||||
service.mu.Lock()
|
||||
defer service.mu.Unlock()
|
||||
return cloneSnapshot(service.snapshot)
|
||||
}
|
||||
|
||||
func (service *Service) Refresh(ctx context.Context, trigger RefreshTrigger) (RefreshResult, error) {
|
||||
if trigger != RefreshTriggerForeground && trigger != RefreshTriggerRetry {
|
||||
return RefreshResult{}, errors.New("desktop update admission refresh trigger is invalid")
|
||||
}
|
||||
service.mu.Lock()
|
||||
if !service.started {
|
||||
service.mu.Unlock()
|
||||
return RefreshResult{}, errors.New("desktop update admission service has not started")
|
||||
}
|
||||
if service.closed {
|
||||
service.mu.Unlock()
|
||||
return RefreshResult{}, errors.New("desktop update admission service is closed")
|
||||
}
|
||||
if !service.config.ChecksEnabled {
|
||||
snapshot := cloneSnapshot(service.snapshot)
|
||||
service.mu.Unlock()
|
||||
return RefreshResult{SkipReason: "checksDisabled", Snapshot: snapshot}, nil
|
||||
}
|
||||
lifecycle := service.lifecycle
|
||||
service.mu.Unlock()
|
||||
|
||||
refreshCtx, cancel := context.WithCancel(ctx)
|
||||
stopLifecycleCancellation := context.AfterFunc(lifecycle, cancel)
|
||||
defer func() {
|
||||
stopLifecycleCancellation()
|
||||
cancel()
|
||||
}()
|
||||
return service.refresh(refreshCtx, string(trigger))
|
||||
}
|
||||
|
||||
func (service *Service) Close() {
|
||||
service.mu.Lock()
|
||||
if service.closed {
|
||||
service.mu.Unlock()
|
||||
return
|
||||
}
|
||||
service.closed = true
|
||||
cancel := service.cancel
|
||||
service.mu.Unlock()
|
||||
if cancel != nil {
|
||||
cancel()
|
||||
}
|
||||
}
|
||||
|
||||
func (service *Service) refresh(ctx context.Context, trigger string) (RefreshResult, error) {
|
||||
service.mu.Lock()
|
||||
if trigger == string(RefreshTriggerForeground) &&
|
||||
policyUsesForegroundThrottle(service.snapshot.Policy) &&
|
||||
service.snapshot.LastAttemptAt != nil {
|
||||
next := service.snapshot.LastAttemptAt.Add(service.config.ForegroundInterval)
|
||||
if service.config.Now().Before(next) {
|
||||
snapshot := cloneSnapshot(service.snapshot)
|
||||
service.mu.Unlock()
|
||||
return RefreshResult{
|
||||
SkipReason: "throttled",
|
||||
Snapshot: snapshot,
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
if active := service.active; active != nil {
|
||||
service.mu.Unlock()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return RefreshResult{}, ctx.Err()
|
||||
case <-active:
|
||||
return RefreshResult{
|
||||
SkipReason: "requestInFlight",
|
||||
Snapshot: service.Snapshot(),
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
active := make(chan struct{})
|
||||
service.active = active
|
||||
service.mu.Unlock()
|
||||
|
||||
defer func() {
|
||||
service.mu.Lock()
|
||||
if service.active == active {
|
||||
service.active = nil
|
||||
close(active)
|
||||
}
|
||||
service.mu.Unlock()
|
||||
}()
|
||||
|
||||
timeout := service.config.ForegroundTimeout
|
||||
if trigger == "startup" {
|
||||
timeout = service.config.StartupTimeout
|
||||
}
|
||||
checkCtx, cancel := context.WithTimeout(ctx, timeout)
|
||||
defer cancel()
|
||||
startedAt := service.config.Now().UTC()
|
||||
raw, err := service.config.Checker.Check(checkCtx, service.config.Identity)
|
||||
completedAt := service.config.Now().UTC()
|
||||
|
||||
service.mu.Lock()
|
||||
service.snapshot.LastAttemptAt = pointerTime(completedAt)
|
||||
if err != nil {
|
||||
service.snapshot.NextForegroundCheckAt = nil
|
||||
failureKind := "transport"
|
||||
if errors.Is(err, context.DeadlineExceeded) || errors.Is(checkCtx.Err(), context.DeadlineExceeded) {
|
||||
failureKind = "timeout"
|
||||
}
|
||||
service.snapshot.Policy = PolicySnapshot{
|
||||
Status: "failedOpen",
|
||||
Failure: &PolicyFailure{Kind: failureKind},
|
||||
}
|
||||
snapshot := cloneSnapshot(service.snapshot)
|
||||
service.mu.Unlock()
|
||||
log(service.config.Logger, slog.LevelError, "policy-check", map[string]any{
|
||||
"elapsedMs": completedAt.Sub(startedAt).Milliseconds(),
|
||||
"error": err.Error(),
|
||||
"result": "failure",
|
||||
"stage": trigger,
|
||||
})
|
||||
return RefreshResult{Performed: true, Snapshot: snapshot}, nil
|
||||
}
|
||||
|
||||
parsed, parseErr := ParseRemoteResponse(raw)
|
||||
if parseErr != nil {
|
||||
nextForeground := completedAt.Add(service.config.ForegroundInterval)
|
||||
service.snapshot.NextForegroundCheckAt = pointerTime(nextForeground)
|
||||
service.snapshot.Policy = PolicySnapshot{
|
||||
Status: "failedOpen",
|
||||
Failure: &PolicyFailure{Kind: "invalidResponse"},
|
||||
}
|
||||
snapshot := cloneSnapshot(service.snapshot)
|
||||
service.mu.Unlock()
|
||||
log(service.config.Logger, slog.LevelError, "policy-check", map[string]any{
|
||||
"elapsedMs": completedAt.Sub(startedAt).Milliseconds(),
|
||||
"error": parseErr.Error(),
|
||||
"result": "failure",
|
||||
"stage": trigger,
|
||||
})
|
||||
return RefreshResult{Performed: true, Snapshot: snapshot}, nil
|
||||
}
|
||||
|
||||
policy := parsed.Policy
|
||||
nextForeground := completedAt.Add(service.config.ForegroundInterval)
|
||||
service.snapshot.NextForegroundCheckAt = pointerTime(nextForeground)
|
||||
service.snapshot.Policy = PolicySnapshot{
|
||||
Status: "resolved",
|
||||
Response: &policy,
|
||||
}
|
||||
var cacheSnapshot *FeatureAvailabilitySnapshot
|
||||
if parsed.FeatureValid {
|
||||
revision := parsed.Policy.PolicyRevision
|
||||
fetchedAt := completedAt
|
||||
service.snapshot.FeatureAvailability = FeatureAvailabilitySnapshot{
|
||||
Keys: cloneFeatureKeys(parsed.Feature),
|
||||
Source: "remote",
|
||||
PolicyRevision: &revision,
|
||||
FetchedAt: &fetchedAt,
|
||||
}
|
||||
copied := cloneFeatureSnapshot(service.snapshot.FeatureAvailability)
|
||||
cacheSnapshot = &copied
|
||||
}
|
||||
snapshot := cloneSnapshot(service.snapshot)
|
||||
service.mu.Unlock()
|
||||
|
||||
if parsed.FeaturePresent && !parsed.FeatureValid {
|
||||
log(service.config.Logger, slog.LevelError, "feature-response", map[string]any{
|
||||
"error": parsed.FeatureParseError.Error(),
|
||||
"result": "retained",
|
||||
"stage": trigger,
|
||||
})
|
||||
}
|
||||
if cacheSnapshot != nil && service.config.FeatureCache != nil {
|
||||
if err := service.config.FeatureCache.Save(service.config.Identity, *cacheSnapshot); err != nil {
|
||||
log(service.config.Logger, slog.LevelError, "feature-cache-write", map[string]any{
|
||||
"error": err.Error(),
|
||||
"result": "failure",
|
||||
})
|
||||
}
|
||||
}
|
||||
log(service.config.Logger, slog.LevelInfo, "policy-check", map[string]any{
|
||||
"currentVersion": service.config.Identity.CurrentVersion,
|
||||
"decision": parsed.Policy.Decision,
|
||||
"elapsedMs": completedAt.Sub(startedAt).Milliseconds(),
|
||||
"minimumVersion": parsed.Policy.MinimumVersion,
|
||||
"policyRevision": parsed.Policy.PolicyRevision,
|
||||
"reason": parsed.Policy.Reason,
|
||||
"result": "success",
|
||||
"stage": trigger,
|
||||
})
|
||||
return RefreshResult{Performed: true, Snapshot: snapshot}, nil
|
||||
}
|
||||
|
||||
func policyUsesForegroundThrottle(policy PolicySnapshot) bool {
|
||||
return policy.Status == "resolved" ||
|
||||
(policy.Status == "failedOpen" &&
|
||||
policy.Failure != nil &&
|
||||
policy.Failure.Kind == "invalidResponse")
|
||||
}
|
||||
|
||||
func (service *Service) markInitialDone() {
|
||||
service.initialOnce.Do(func() {
|
||||
close(service.initialDone)
|
||||
})
|
||||
}
|
||||
|
||||
func cloneSnapshot(snapshot Snapshot) Snapshot {
|
||||
clone := snapshot
|
||||
if snapshot.Policy.Response != nil {
|
||||
response := *snapshot.Policy.Response
|
||||
clone.Policy.Response = &response
|
||||
}
|
||||
if snapshot.Policy.Failure != nil {
|
||||
failure := *snapshot.Policy.Failure
|
||||
clone.Policy.Failure = &failure
|
||||
}
|
||||
clone.FeatureAvailability = cloneFeatureSnapshot(snapshot.FeatureAvailability)
|
||||
if snapshot.LastAttemptAt != nil {
|
||||
clone.LastAttemptAt = pointerTime(*snapshot.LastAttemptAt)
|
||||
}
|
||||
if snapshot.NextForegroundCheckAt != nil {
|
||||
clone.NextForegroundCheckAt = pointerTime(*snapshot.NextForegroundCheckAt)
|
||||
}
|
||||
return clone
|
||||
}
|
||||
|
||||
func cloneFeatureSnapshot(snapshot FeatureAvailabilitySnapshot) FeatureAvailabilitySnapshot {
|
||||
clone := snapshot
|
||||
clone.Keys = cloneFeatureKeys(snapshot.Keys)
|
||||
if snapshot.PolicyRevision != nil {
|
||||
revision := *snapshot.PolicyRevision
|
||||
clone.PolicyRevision = &revision
|
||||
}
|
||||
if snapshot.FetchedAt != nil {
|
||||
clone.FetchedAt = pointerTime(*snapshot.FetchedAt)
|
||||
}
|
||||
return clone
|
||||
}
|
||||
|
||||
// cloneFeatureKeys preserves the wire contract that an empty key set is an
|
||||
// empty JSON array, never null. append([]string(nil), values...) would turn an
|
||||
// empty slice into nil and break strict feature-availability consumers.
|
||||
func cloneFeatureKeys(keys []string) []string {
|
||||
clone := make([]string, len(keys))
|
||||
copy(clone, keys)
|
||||
return clone
|
||||
}
|
||||
|
||||
func pointerTime(value time.Time) *time.Time {
|
||||
copied := value
|
||||
return &copied
|
||||
}
|
||||
|
||||
func log(logger *slog.Logger, level slog.Level, stage string, details map[string]any) {
|
||||
attributes := make([]any, 0, len(details)*2+4)
|
||||
attributes = append(attributes, "event", "desktop.update_admission."+stage, "stage", stage)
|
||||
for key, value := range details {
|
||||
attributes = append(attributes, key, value)
|
||||
}
|
||||
logger.Log(context.Background(), level, "[minimum-version-check]", attributes...)
|
||||
}
|
||||
@@ -0,0 +1,492 @@
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type checkerFunc func(context.Context, Identity) ([]byte, error)
|
||||
|
||||
func (fn checkerFunc) Check(ctx context.Context, identity Identity) ([]byte, error) {
|
||||
return fn(ctx, identity)
|
||||
}
|
||||
|
||||
func testIdentity() Identity {
|
||||
return Identity{
|
||||
Product: ProductTuttiDesktop,
|
||||
Platform: PlatformMacOS,
|
||||
Architecture: ArchitectureARM64,
|
||||
CurrentVersion: "1.0.0",
|
||||
}
|
||||
}
|
||||
|
||||
func TestServiceStartsCheckBeforeLocalRead(t *testing.T) {
|
||||
called := make(chan struct{}, 1)
|
||||
service, err := New(Config{
|
||||
Identity: testIdentity(),
|
||||
ChecksEnabled: true,
|
||||
Checker: checkerFunc(func(_ context.Context, got Identity) ([]byte, error) {
|
||||
if got != testIdentity() {
|
||||
t.Fatalf("identity = %#v", got)
|
||||
}
|
||||
called <- struct{}{}
|
||||
return []byte(`{"channel":"stable","decision":"allowed","reason":"minimumNotConfigured","policyRevision":"v1","featureAvailability":{"keys":[]}}`), nil
|
||||
}),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
service.Start(context.Background())
|
||||
select {
|
||||
case <-called:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("daemon did not start the policy request")
|
||||
}
|
||||
snapshot, err := service.WaitInitial(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if snapshot.Policy.Status != "resolved" || snapshot.Policy.Response.Decision != "allowed" {
|
||||
t.Fatalf("snapshot = %#v", snapshot)
|
||||
}
|
||||
assertEmptyFeatureKeysEncodeAsArray(t, snapshot)
|
||||
assertEmptyFeatureKeysEncodeAsArray(t, service.Snapshot())
|
||||
}
|
||||
|
||||
func TestServiceInitialSnapshotEncodesEmptyFeatureKeysAsArray(t *testing.T) {
|
||||
service, err := New(Config{
|
||||
Identity: testIdentity(),
|
||||
ChecksEnabled: false,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertEmptyFeatureKeysEncodeAsArray(t, service.Snapshot())
|
||||
}
|
||||
|
||||
func TestFeatureCacheEncodesEmptyFeatureKeysAsArray(t *testing.T) {
|
||||
cachePath := filepath.Join(t.TempDir(), "feature-cache.json")
|
||||
cache := FileFeatureCache{Path: cachePath}
|
||||
now := time.Date(2026, 8, 3, 1, 2, 3, 0, time.UTC)
|
||||
revision := "v1"
|
||||
if err := cache.Save(testIdentity(), FeatureAvailabilitySnapshot{
|
||||
Keys: nil,
|
||||
Source: "remote",
|
||||
PolicyRevision: &revision,
|
||||
FetchedAt: &now,
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
raw, err := os.ReadFile(cachePath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Contains(raw, []byte(`"keys":[]`)) {
|
||||
t.Fatalf("cache keys must encode as an array: %s", raw)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServicePersistsOnlyFeatureAvailabilityAndRestoresOnFailure(t *testing.T) {
|
||||
cachePath := filepath.Join(t.TempDir(), "feature-cache.json")
|
||||
cache := FileFeatureCache{Path: cachePath}
|
||||
service, err := New(Config{
|
||||
Identity: testIdentity(),
|
||||
ChecksEnabled: true,
|
||||
FeatureCache: cache,
|
||||
Checker: checkerFunc(func(context.Context, Identity) ([]byte, error) {
|
||||
return []byte(`{"channel":"stable","minimumVersion":"1.1.0","decision":"upgradeRequired","reason":"belowMinimum","policyRevision":"v2","featureAvailability":{"keys":["workspace.example"]}}`), nil
|
||||
}),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
service.Start(context.Background())
|
||||
if _, err := service.WaitInitial(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
raw, err := os.ReadFile(cachePath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, forbidden := range []string{"minimumVersion", "upgradeRequired", "belowMinimum"} {
|
||||
if stringContains(string(raw), forbidden) {
|
||||
t.Fatalf("cache contains policy field %q: %s", forbidden, raw)
|
||||
}
|
||||
}
|
||||
|
||||
restored, err := New(Config{
|
||||
Identity: testIdentity(),
|
||||
ChecksEnabled: true,
|
||||
FeatureCache: cache,
|
||||
Checker: checkerFunc(func(context.Context, Identity) ([]byte, error) {
|
||||
return nil, errors.New("offline")
|
||||
}),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
restored.Start(context.Background())
|
||||
snapshot, err := restored.WaitInitial(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if snapshot.Policy.Status != "failedOpen" {
|
||||
t.Fatalf("policy = %#v", snapshot.Policy)
|
||||
}
|
||||
if snapshot.FeatureAvailability.Source != "cache" ||
|
||||
len(snapshot.FeatureAvailability.Keys) != 1 ||
|
||||
snapshot.FeatureAvailability.Keys[0] != "workspace.example" {
|
||||
t.Fatalf("featureAvailability = %#v", snapshot.FeatureAvailability)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvalidFeatureRetainsCacheWithoutInvalidatingPolicy(t *testing.T) {
|
||||
cachePath := filepath.Join(t.TempDir(), "feature-cache.json")
|
||||
cache := FileFeatureCache{Path: cachePath}
|
||||
now := time.Date(2026, 8, 2, 1, 2, 3, 0, time.UTC)
|
||||
revision := "v1"
|
||||
if err := cache.Save(testIdentity(), FeatureAvailabilitySnapshot{
|
||||
Keys: []string{"cached.feature"},
|
||||
Source: "remote",
|
||||
PolicyRevision: &revision,
|
||||
FetchedAt: &now,
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
service, err := New(Config{
|
||||
Identity: testIdentity(),
|
||||
ChecksEnabled: true,
|
||||
FeatureCache: cache,
|
||||
Checker: checkerFunc(func(context.Context, Identity) ([]byte, error) {
|
||||
return []byte(`{"channel":"stable","decision":"allowed","reason":"minimumNotConfigured","policyRevision":"v2","featureAvailability":{"keys":[7]}}`), nil
|
||||
}),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
service.Start(context.Background())
|
||||
snapshot, err := service.WaitInitial(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if snapshot.Policy.Status != "resolved" {
|
||||
t.Fatalf("policy = %#v", snapshot.Policy)
|
||||
}
|
||||
if snapshot.FeatureAvailability.Source != "cache" ||
|
||||
snapshot.FeatureAvailability.Keys[0] != "cached.feature" {
|
||||
t.Fatalf("featureAvailability = %#v", snapshot.FeatureAvailability)
|
||||
}
|
||||
}
|
||||
|
||||
func TestForegroundRefreshIsThrottledAndRetryBypassesThrottle(t *testing.T) {
|
||||
var mu sync.Mutex
|
||||
calls := 0
|
||||
now := time.Date(2026, 8, 2, 1, 0, 0, 0, time.UTC)
|
||||
service, err := New(Config{
|
||||
Identity: testIdentity(),
|
||||
ChecksEnabled: true,
|
||||
ForegroundInterval: 30 * time.Minute,
|
||||
Now: func() time.Time { return now },
|
||||
Checker: checkerFunc(func(context.Context, Identity) ([]byte, error) {
|
||||
mu.Lock()
|
||||
calls++
|
||||
mu.Unlock()
|
||||
return []byte(`{"channel":"stable","decision":"allowed","reason":"minimumNotConfigured","policyRevision":"v1"}`), nil
|
||||
}),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
service.Start(context.Background())
|
||||
if _, err := service.WaitInitial(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
foreground, err := service.Refresh(context.Background(), RefreshTriggerForeground)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if foreground.Performed || foreground.SkipReason != "throttled" {
|
||||
t.Fatalf("foreground = %#v", foreground)
|
||||
}
|
||||
retry, err := service.Refresh(context.Background(), RefreshTriggerRetry)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !retry.Performed {
|
||||
t.Fatalf("retry = %#v", retry)
|
||||
}
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if calls != 2 {
|
||||
t.Fatalf("calls = %d, want 2", calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFailedOpenDoesNotThrottleForegroundRecovery(t *testing.T) {
|
||||
var mu sync.Mutex
|
||||
calls := 0
|
||||
now := time.Date(2026, 8, 13, 1, 0, 0, 0, time.UTC)
|
||||
service, err := New(Config{
|
||||
Identity: testIdentity(),
|
||||
ChecksEnabled: true,
|
||||
ForegroundInterval: 30 * time.Minute,
|
||||
Now: func() time.Time { return now },
|
||||
Checker: checkerFunc(func(context.Context, Identity) ([]byte, error) {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
calls++
|
||||
if calls == 1 {
|
||||
return nil, errors.New("network unavailable after system resume")
|
||||
}
|
||||
return []byte(`{"channel":"stable","minimumVersion":"1.1.0","decision":"upgradeRequired","reason":"belowMinimum","policyRevision":"v2"}`), nil
|
||||
}),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
service.Start(context.Background())
|
||||
initial, err := service.WaitInitial(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if initial.Policy.Status != "failedOpen" || initial.NextForegroundCheckAt != nil {
|
||||
t.Fatalf("initial snapshot = %#v", initial)
|
||||
}
|
||||
|
||||
foreground, err := service.Refresh(context.Background(), RefreshTriggerForeground)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !foreground.Performed || foreground.SkipReason != "" {
|
||||
t.Fatalf("foreground = %#v", foreground)
|
||||
}
|
||||
if foreground.Snapshot.Policy.Status != "resolved" ||
|
||||
foreground.Snapshot.Policy.Response == nil ||
|
||||
foreground.Snapshot.Policy.Response.Decision != "upgradeRequired" ||
|
||||
foreground.Snapshot.NextForegroundCheckAt == nil {
|
||||
t.Fatalf("recovered snapshot = %#v", foreground.Snapshot)
|
||||
}
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if calls != 2 {
|
||||
t.Fatalf("calls = %d, want startup failure plus foreground recovery", calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvalidResponseRetainsForegroundThrottle(t *testing.T) {
|
||||
calls := 0
|
||||
now := time.Date(2026, 8, 13, 1, 0, 0, 0, time.UTC)
|
||||
service, err := New(Config{
|
||||
Identity: testIdentity(),
|
||||
ChecksEnabled: true,
|
||||
ForegroundInterval: 30 * time.Minute,
|
||||
Now: func() time.Time { return now },
|
||||
Checker: checkerFunc(func(context.Context, Identity) ([]byte, error) {
|
||||
calls++
|
||||
return []byte(`{"decision":"unexpected"}`), nil
|
||||
}),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
service.Start(context.Background())
|
||||
initial, err := service.WaitInitial(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if initial.Policy.Status != "failedOpen" ||
|
||||
initial.Policy.Failure == nil ||
|
||||
initial.Policy.Failure.Kind != "invalidResponse" ||
|
||||
initial.NextForegroundCheckAt == nil {
|
||||
t.Fatalf("initial snapshot = %#v", initial)
|
||||
}
|
||||
|
||||
foreground, err := service.Refresh(context.Background(), RefreshTriggerForeground)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if foreground.Performed || foreground.SkipReason != "throttled" {
|
||||
t.Fatalf("foreground = %#v", foreground)
|
||||
}
|
||||
if calls != 1 {
|
||||
t.Fatalf("calls = %d, want one invalid request", calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStartupTimeoutFailsOpenWithoutCachingPolicy(t *testing.T) {
|
||||
service, err := New(Config{
|
||||
Identity: testIdentity(),
|
||||
ChecksEnabled: true,
|
||||
StartupTimeout: 10 * time.Millisecond,
|
||||
Checker: checkerFunc(func(ctx context.Context, _ Identity) ([]byte, error) {
|
||||
<-ctx.Done()
|
||||
return nil, ctx.Err()
|
||||
}),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
service.Start(context.Background())
|
||||
snapshot, err := service.WaitInitial(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if snapshot.Policy.Status != "failedOpen" ||
|
||||
snapshot.Policy.Failure == nil ||
|
||||
snapshot.Policy.Failure.Kind != "timeout" ||
|
||||
snapshot.Policy.Response != nil {
|
||||
t.Fatalf("policy = %#v", snapshot.Policy)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDisabledChecksCompleteStartupWithoutChecker(t *testing.T) {
|
||||
service, err := New(Config{
|
||||
Identity: testIdentity(),
|
||||
ChecksEnabled: false,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
service.Start(context.Background())
|
||||
snapshot, err := service.WaitInitial(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if snapshot.Policy.Status != "skipped" ||
|
||||
snapshot.Policy.Reason != "checksDisabled" {
|
||||
t.Fatalf("policy = %#v", snapshot.Policy)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConcurrentRefreshSharesOneActiveRequest(t *testing.T) {
|
||||
release := make(chan struct{})
|
||||
started := make(chan struct{}, 2)
|
||||
var mu sync.Mutex
|
||||
calls := 0
|
||||
service, err := New(Config{
|
||||
Identity: testIdentity(),
|
||||
ChecksEnabled: true,
|
||||
Checker: checkerFunc(func(context.Context, Identity) ([]byte, error) {
|
||||
mu.Lock()
|
||||
calls++
|
||||
call := calls
|
||||
mu.Unlock()
|
||||
if call > 1 {
|
||||
started <- struct{}{}
|
||||
<-release
|
||||
}
|
||||
return []byte(`{"channel":"stable","decision":"allowed","reason":"minimumNotConfigured","policyRevision":"v1"}`), nil
|
||||
}),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
service.Start(context.Background())
|
||||
if _, err := service.WaitInitial(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
firstDone := make(chan RefreshResult, 1)
|
||||
go func() {
|
||||
result, _ := service.Refresh(context.Background(), RefreshTriggerRetry)
|
||||
firstDone <- result
|
||||
}()
|
||||
<-started
|
||||
secondDone := make(chan RefreshResult, 1)
|
||||
go func() {
|
||||
result, _ := service.Refresh(context.Background(), RefreshTriggerRetry)
|
||||
secondDone <- result
|
||||
}()
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
close(release)
|
||||
first := <-firstDone
|
||||
second := <-secondDone
|
||||
if !first.Performed || second.Performed || second.SkipReason != "requestInFlight" {
|
||||
t.Fatalf("results = %#v and %#v", first, second)
|
||||
}
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if calls != 2 {
|
||||
t.Fatalf("calls = %d, want startup plus one refresh", calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCloseCancelsActiveRefresh(t *testing.T) {
|
||||
started := make(chan struct{}, 1)
|
||||
var mu sync.Mutex
|
||||
calls := 0
|
||||
service, err := New(Config{
|
||||
Identity: testIdentity(),
|
||||
ChecksEnabled: true,
|
||||
Checker: checkerFunc(func(ctx context.Context, _ Identity) ([]byte, error) {
|
||||
mu.Lock()
|
||||
calls++
|
||||
call := calls
|
||||
mu.Unlock()
|
||||
if call == 1 {
|
||||
return []byte(`{"channel":"stable","decision":"allowed","reason":"minimumNotConfigured","policyRevision":"v1"}`), nil
|
||||
}
|
||||
select {
|
||||
case started <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
<-ctx.Done()
|
||||
return nil, ctx.Err()
|
||||
}),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
service.Start(context.Background())
|
||||
if _, err := service.WaitInitial(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
refreshDone := make(chan RefreshResult, 1)
|
||||
go func() {
|
||||
result, _ := service.Refresh(context.Background(), RefreshTriggerRetry)
|
||||
refreshDone <- result
|
||||
}()
|
||||
<-started
|
||||
service.Close()
|
||||
|
||||
select {
|
||||
case result := <-refreshDone:
|
||||
if result.Snapshot.Policy.Status != "failedOpen" ||
|
||||
result.Snapshot.Policy.Failure == nil ||
|
||||
result.Snapshot.Policy.Failure.Kind != "transport" {
|
||||
t.Fatalf("policy = %#v", result.Snapshot.Policy)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("active refresh was not canceled when the service closed")
|
||||
}
|
||||
}
|
||||
|
||||
func assertEmptyFeatureKeysEncodeAsArray(t *testing.T, snapshot Snapshot) {
|
||||
t.Helper()
|
||||
if snapshot.FeatureAvailability.Keys == nil {
|
||||
t.Fatal("feature availability keys must be a non-nil empty slice")
|
||||
}
|
||||
raw, err := json.Marshal(snapshot)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Contains(raw, []byte(`"keys":[]`)) {
|
||||
t.Fatalf("snapshot keys must encode as an array: %s", raw)
|
||||
}
|
||||
}
|
||||
|
||||
func stringContains(value string, target string) bool {
|
||||
for index := 0; index+len(target) <= len(value); index++ {
|
||||
if value[index:index+len(target)] == target {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package daemon
|
||||
|
||||
import "time"
|
||||
|
||||
type Product string
|
||||
|
||||
const (
|
||||
ProductTSHDesktop Product = "tsh-desktop"
|
||||
ProductTuttiDesktop Product = "tutti-desktop"
|
||||
)
|
||||
|
||||
type Platform string
|
||||
|
||||
const (
|
||||
PlatformMacOS Platform = "macos"
|
||||
PlatformWindows Platform = "windows"
|
||||
PlatformLinux Platform = "linux"
|
||||
)
|
||||
|
||||
type Architecture string
|
||||
|
||||
const (
|
||||
ArchitectureARM64 Architecture = "arm64"
|
||||
ArchitectureX64 Architecture = "x64"
|
||||
)
|
||||
|
||||
type Identity struct {
|
||||
Product Product `json:"product"`
|
||||
Platform Platform `json:"platform"`
|
||||
Architecture Architecture `json:"architecture"`
|
||||
CurrentVersion string `json:"currentVersion"`
|
||||
}
|
||||
|
||||
type PolicyResponse struct {
|
||||
Channel string `json:"channel"`
|
||||
MinimumVersion string `json:"minimumVersion,omitempty"`
|
||||
Decision string `json:"decision"`
|
||||
Reason string `json:"reason"`
|
||||
PolicyRevision string `json:"policyRevision"`
|
||||
}
|
||||
|
||||
type PolicyFailure struct {
|
||||
Kind string `json:"kind"`
|
||||
}
|
||||
|
||||
type PolicySnapshot struct {
|
||||
Status string `json:"status"`
|
||||
Response *PolicyResponse `json:"response,omitempty"`
|
||||
Failure *PolicyFailure `json:"failure,omitempty"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
}
|
||||
|
||||
type FeatureAvailabilitySnapshot struct {
|
||||
Keys []string `json:"keys"`
|
||||
Source string `json:"source"`
|
||||
PolicyRevision *string `json:"policyRevision"`
|
||||
FetchedAt *time.Time `json:"fetchedAt"`
|
||||
}
|
||||
|
||||
type Snapshot struct {
|
||||
Identity Identity `json:"identity"`
|
||||
Policy PolicySnapshot `json:"policy"`
|
||||
FeatureAvailability FeatureAvailabilitySnapshot `json:"featureAvailability"`
|
||||
LastAttemptAt *time.Time `json:"lastAttemptAt"`
|
||||
NextForegroundCheckAt *time.Time `json:"nextForegroundCheckAt"`
|
||||
}
|
||||
|
||||
type RefreshTrigger string
|
||||
|
||||
const (
|
||||
RefreshTriggerForeground RefreshTrigger = "foreground"
|
||||
RefreshTriggerRetry RefreshTrigger = "retry"
|
||||
)
|
||||
|
||||
type RefreshResult struct {
|
||||
Performed bool `json:"performed"`
|
||||
SkipReason string `json:"skipReason,omitempty"`
|
||||
Snapshot Snapshot `json:"snapshot"`
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
module github.com/tutti-os/tutti/packages/desktop/update-admission
|
||||
|
||||
go 1.24.3
|
||||
|
||||
toolchain go1.24.5
|
||||
@@ -0,0 +1,125 @@
|
||||
{
|
||||
"name": "@tutti-os/desktop-update-admission",
|
||||
"version": "0.1.0",
|
||||
"private": false,
|
||||
"type": "module",
|
||||
"types": "./src/index.ts",
|
||||
"bin": {
|
||||
"desktop-update-admission-mock-server": "./dist/development/mock-server-cli.js"
|
||||
},
|
||||
"exports": {
|
||||
".": "./src/index.ts",
|
||||
"./contracts": "./src/contracts/index.ts",
|
||||
"./core": "./src/core/index.ts",
|
||||
"./development": "./src/development/index.ts",
|
||||
"./electron-main": "./src/electron-main/index.ts",
|
||||
"./feature-availability": "./src/feature-availability/index.ts",
|
||||
"./i18n": "./src/i18n/index.ts",
|
||||
"./mandatory-updater": "./src/mandatory-updater/index.ts",
|
||||
"./preload": "./src/preload/index.ts",
|
||||
"./preload/feature-availability": "./src/preload/featureAvailability.ts",
|
||||
"./preload/minimum-version": "./src/preload/minimumVersion.ts",
|
||||
"./react": "./src/react/index.ts"
|
||||
},
|
||||
"files": [
|
||||
"dist",
|
||||
"README.md"
|
||||
],
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/tutti-os/tutti.git",
|
||||
"directory": "packages/desktop/update-admission"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsup --config tsup.config.ts",
|
||||
"test": "node --test --experimental-strip-types \"./src/**/*.test.ts\"",
|
||||
"typecheck": "node ../../../tools/scripts/run-tsgo-typecheck.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@tutti-os/ui-i18n-runtime": "workspace:*",
|
||||
"@tutti-os/ui-system": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tutti-os/config-tsconfig": "workspace:*",
|
||||
"@types/node": "^24.0.1",
|
||||
"@types/react": "^19.1.6",
|
||||
"@types/react-dom": "^19.1.5",
|
||||
"electron": "^43.2.0",
|
||||
"react": "^19.1.0",
|
||||
"react-dom": "^19.1.0",
|
||||
"typescript": "^5.8.3"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"electron": ">=35.7.5 <44",
|
||||
"react": "^19.1.0",
|
||||
"react-dom": "^19.1.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"electron": {
|
||||
"optional": true
|
||||
},
|
||||
"react": {
|
||||
"optional": true
|
||||
},
|
||||
"react-dom": {
|
||||
"optional": true
|
||||
}
|
||||
},
|
||||
"tutti": {
|
||||
"tailwindSourceRoot": "src/react"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.js"
|
||||
},
|
||||
"./contracts": {
|
||||
"types": "./dist/contracts/index.d.ts",
|
||||
"import": "./dist/contracts/index.js"
|
||||
},
|
||||
"./core": {
|
||||
"types": "./dist/core/index.d.ts",
|
||||
"import": "./dist/core/index.js"
|
||||
},
|
||||
"./development": {
|
||||
"types": "./dist/development/index.d.ts",
|
||||
"import": "./dist/development/index.js"
|
||||
},
|
||||
"./electron-main": {
|
||||
"types": "./dist/electron-main/index.d.ts",
|
||||
"import": "./dist/electron-main/index.js"
|
||||
},
|
||||
"./feature-availability": {
|
||||
"types": "./dist/feature-availability/index.d.ts",
|
||||
"import": "./dist/feature-availability/index.js"
|
||||
},
|
||||
"./i18n": {
|
||||
"types": "./dist/i18n/index.d.ts",
|
||||
"import": "./dist/i18n/index.js"
|
||||
},
|
||||
"./mandatory-updater": {
|
||||
"types": "./dist/mandatory-updater/index.d.ts",
|
||||
"import": "./dist/mandatory-updater/index.js"
|
||||
},
|
||||
"./preload": {
|
||||
"types": "./dist/preload/index.d.ts",
|
||||
"import": "./dist/preload/index.js"
|
||||
},
|
||||
"./preload/feature-availability": {
|
||||
"types": "./dist/preload/feature-availability.d.ts",
|
||||
"import": "./dist/preload/feature-availability.js"
|
||||
},
|
||||
"./preload/minimum-version": {
|
||||
"types": "./dist/preload/minimum-version.d.ts",
|
||||
"import": "./dist/preload/minimum-version.js"
|
||||
},
|
||||
"./react": {
|
||||
"types": "./dist/react/index.d.ts",
|
||||
"import": "./dist/react/index.js"
|
||||
}
|
||||
},
|
||||
"types": "./dist/index.d.ts"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
export const desktopFeatureAvailabilityIpcChannels = {
|
||||
changed: "desktop-feature-availability:changed",
|
||||
getSnapshot: "desktop-feature-availability:get-snapshot",
|
||||
isSupported: "desktop-feature-availability:is-supported"
|
||||
} as const;
|
||||
@@ -0,0 +1,271 @@
|
||||
export const desktopUpdatePolicies = ["off", "prompt", "auto"] as const;
|
||||
export type DesktopUpdatePolicy = (typeof desktopUpdatePolicies)[number];
|
||||
|
||||
export const desktopUpdateChannels = ["stable", "rc"] as const;
|
||||
export type DesktopUpdateChannel = (typeof desktopUpdateChannels)[number];
|
||||
|
||||
export const desktopUpdateStatuses = [
|
||||
"disabled",
|
||||
"unsupported",
|
||||
"idle",
|
||||
"checking",
|
||||
"available",
|
||||
"downloading",
|
||||
"downloaded",
|
||||
"up_to_date",
|
||||
"error"
|
||||
] as const;
|
||||
export type DesktopUpdateStatus = (typeof desktopUpdateStatuses)[number];
|
||||
|
||||
export interface ConfigureDesktopUpdatesInput {
|
||||
channel: DesktopUpdateChannel;
|
||||
policy: DesktopUpdatePolicy;
|
||||
}
|
||||
|
||||
export interface DesktopUpdateState {
|
||||
channel: DesktopUpdateChannel;
|
||||
checkedAt: string | null;
|
||||
currentVersion: string;
|
||||
downloadedBytes: number | null;
|
||||
downloadPercent: number | null;
|
||||
latestVersion: string | null;
|
||||
message: string | null;
|
||||
policy: DesktopUpdatePolicy;
|
||||
releaseDate: string | null;
|
||||
releaseName: string | null;
|
||||
releaseNotesUrl: string | null;
|
||||
status: DesktopUpdateStatus;
|
||||
totalBytes: number | null;
|
||||
}
|
||||
|
||||
export const desktopProducts = ["tsh-desktop", "tutti-desktop"] as const;
|
||||
export type DesktopProduct = (typeof desktopProducts)[number];
|
||||
export type DesktopPlatform = "macos" | "windows" | "linux";
|
||||
export type DesktopArchitecture = "arm64" | "x64";
|
||||
|
||||
export interface MinimumVersionCheckRequest<
|
||||
TProduct extends DesktopProduct = DesktopProduct
|
||||
> {
|
||||
product: TProduct;
|
||||
platform: DesktopPlatform;
|
||||
architecture: DesktopArchitecture;
|
||||
currentVersion: string;
|
||||
}
|
||||
|
||||
export type MinimumVersionDecision =
|
||||
| "allowed"
|
||||
| "upgradeRequired"
|
||||
| "notApplicable";
|
||||
|
||||
interface MinimumVersionPolicyResponseBase {
|
||||
policyRevision: string;
|
||||
}
|
||||
|
||||
export type MinimumVersionPolicyResponse =
|
||||
| (MinimumVersionPolicyResponseBase & {
|
||||
channel: "unmanaged";
|
||||
decision: "notApplicable";
|
||||
reason: "unmanagedPrerelease";
|
||||
minimumVersion?: never;
|
||||
})
|
||||
| (MinimumVersionPolicyResponseBase & {
|
||||
channel: DesktopUpdateChannel;
|
||||
decision: "notApplicable";
|
||||
reason: "unsupportedRelease";
|
||||
minimumVersion?: never;
|
||||
})
|
||||
| (MinimumVersionPolicyResponseBase & {
|
||||
channel: DesktopUpdateChannel;
|
||||
decision: "allowed";
|
||||
reason: "minimumNotConfigured";
|
||||
minimumVersion?: never;
|
||||
})
|
||||
| (MinimumVersionPolicyResponseBase & {
|
||||
channel: DesktopUpdateChannel;
|
||||
decision: "allowed";
|
||||
reason: "meetsMinimum";
|
||||
minimumVersion: string;
|
||||
})
|
||||
| (MinimumVersionPolicyResponseBase & {
|
||||
channel: DesktopUpdateChannel;
|
||||
decision: "upgradeRequired";
|
||||
reason: "belowMinimum";
|
||||
minimumVersion: string;
|
||||
});
|
||||
|
||||
export type MinimumVersionCheckResponse = MinimumVersionPolicyResponse & {
|
||||
featureAvailability?: DesktopFeatureAvailability;
|
||||
};
|
||||
|
||||
export type MinimumVersionCheckResult<
|
||||
TProduct extends DesktopProduct = DesktopProduct
|
||||
> = MinimumVersionCheckRequest<TProduct> & MinimumVersionPolicyResponse;
|
||||
|
||||
export type UpgradeRequiredMinimumVersionCheckResult<
|
||||
TProduct extends DesktopProduct = DesktopProduct
|
||||
> = MinimumVersionCheckRequest<TProduct> &
|
||||
Extract<MinimumVersionPolicyResponse, { decision: "upgradeRequired" }>;
|
||||
|
||||
export interface DesktopFeatureAvailability {
|
||||
keys: readonly string[];
|
||||
}
|
||||
|
||||
export type DesktopFeatureAvailabilitySource = "remote" | "cache" | "empty";
|
||||
|
||||
export interface DesktopFeatureAvailabilitySnapshot<
|
||||
TProduct extends DesktopProduct = DesktopProduct
|
||||
> extends MinimumVersionCheckRequest<TProduct> {
|
||||
policyRevision: string | null;
|
||||
fetchedAt: string | null;
|
||||
source: DesktopFeatureAvailabilitySource;
|
||||
keys: readonly string[];
|
||||
}
|
||||
|
||||
export interface DesktopFeatureAvailabilityRuntime<
|
||||
TProduct extends DesktopProduct = DesktopProduct
|
||||
> {
|
||||
getSnapshot(): DesktopFeatureAvailabilitySnapshot<TProduct>;
|
||||
isSupported(key: string): boolean;
|
||||
subscribe(
|
||||
listener: (snapshot: DesktopFeatureAvailabilitySnapshot<TProduct>) => void
|
||||
): () => void;
|
||||
}
|
||||
|
||||
export type DesktopUpdateAdmissionPolicySnapshot =
|
||||
| {
|
||||
status: "checking";
|
||||
response?: never;
|
||||
failure?: never;
|
||||
reason?: never;
|
||||
}
|
||||
| {
|
||||
status: "resolved";
|
||||
response: MinimumVersionPolicyResponse;
|
||||
failure?: never;
|
||||
reason?: never;
|
||||
}
|
||||
| {
|
||||
status: "failedOpen";
|
||||
response?: never;
|
||||
failure: {
|
||||
kind: "timeout" | "transport" | "invalidResponse";
|
||||
};
|
||||
reason?: never;
|
||||
}
|
||||
| {
|
||||
status: "skipped";
|
||||
response?: never;
|
||||
failure?: never;
|
||||
reason: "checksDisabled";
|
||||
};
|
||||
|
||||
export interface DesktopUpdateAdmissionSnapshot<
|
||||
TProduct extends DesktopProduct = DesktopProduct
|
||||
> {
|
||||
identity: MinimumVersionCheckRequest<TProduct>;
|
||||
policy: DesktopUpdateAdmissionPolicySnapshot;
|
||||
featureAvailability: {
|
||||
keys: readonly string[];
|
||||
source: DesktopFeatureAvailabilitySource;
|
||||
policyRevision: string | null;
|
||||
fetchedAt: string | null;
|
||||
};
|
||||
lastAttemptAt: string | null;
|
||||
nextForegroundCheckAt: string | null;
|
||||
}
|
||||
|
||||
export interface DesktopUpdateAdmissionRefreshResult<
|
||||
TProduct extends DesktopProduct = DesktopProduct
|
||||
> {
|
||||
performed: boolean;
|
||||
skipReason?: "checksDisabled" | "throttled" | "requestInFlight";
|
||||
snapshot: DesktopUpdateAdmissionSnapshot<TProduct>;
|
||||
}
|
||||
|
||||
export interface DesktopUpdateAdmissionBackend<
|
||||
TProduct extends DesktopProduct = DesktopProduct
|
||||
> {
|
||||
getStartupSnapshot(
|
||||
signal: AbortSignal
|
||||
): Promise<DesktopUpdateAdmissionSnapshot<TProduct>>;
|
||||
refresh(
|
||||
trigger: "foreground" | "retry",
|
||||
signal: AbortSignal
|
||||
): Promise<DesktopUpdateAdmissionRefreshResult<TProduct>>;
|
||||
}
|
||||
|
||||
export interface DesktopFeatureAvailabilityApi {
|
||||
getSnapshot(): Promise<DesktopFeatureAvailabilitySnapshot>;
|
||||
isSupported(key: string): Promise<boolean>;
|
||||
onChanged(
|
||||
listener: (snapshot: DesktopFeatureAvailabilitySnapshot) => void
|
||||
): () => void;
|
||||
}
|
||||
|
||||
export type MinimumVersionUpgradePhase =
|
||||
| "blocked"
|
||||
| "checking"
|
||||
| "ready"
|
||||
| "downloading"
|
||||
| "downloaded"
|
||||
| "simulationComplete"
|
||||
| "error"
|
||||
| "released";
|
||||
|
||||
export type MinimumVersionUpgradeError =
|
||||
| "releaseBelowMinimum"
|
||||
| "updateUnavailable"
|
||||
| "policyCheckFailed"
|
||||
| "installFailed"
|
||||
| "updateFailed";
|
||||
|
||||
export interface MinimumVersionUpgradeState<
|
||||
TProduct extends DesktopProduct = DesktopProduct
|
||||
> {
|
||||
phase: MinimumVersionUpgradePhase;
|
||||
check: UpgradeRequiredMinimumVersionCheckResult<TProduct>;
|
||||
update: DesktopUpdateState;
|
||||
message: MinimumVersionUpgradeError | null;
|
||||
}
|
||||
|
||||
export interface MandatoryDesktopUpdateTarget {
|
||||
channel: DesktopUpdateChannel;
|
||||
minimumVersion: string;
|
||||
policyRevision: string;
|
||||
}
|
||||
|
||||
export interface MandatoryDesktopUpdateSession {
|
||||
retarget(input: MandatoryDesktopUpdateTarget): void;
|
||||
prepare(): Promise<DesktopUpdateState>;
|
||||
downloadUpdate(): Promise<DesktopUpdateState>;
|
||||
installUpdate(): Promise<void>;
|
||||
release(options?: { restoreNormal?: boolean }): Promise<void>;
|
||||
}
|
||||
|
||||
export interface MinimumVersionAppUpdateService {
|
||||
getState(): DesktopUpdateState;
|
||||
acquireMandatorySession(
|
||||
input: MandatoryDesktopUpdateTarget
|
||||
): Promise<MandatoryDesktopUpdateSession>;
|
||||
subscribe(listener: (state: DesktopUpdateState) => void): () => void;
|
||||
}
|
||||
|
||||
export interface DesktopUpdateAdmissionRuntime {
|
||||
checksEnabled: boolean;
|
||||
currentVersion: string;
|
||||
development: boolean;
|
||||
}
|
||||
|
||||
export { desktopFeatureAvailabilityIpcChannels } from "./featureAvailabilityIpc.ts";
|
||||
export { desktopUpdateAdmissionIpcChannels } from "./updateAdmissionIpc.ts";
|
||||
|
||||
export interface DesktopMinimumVersionApi {
|
||||
getState(): Promise<MinimumVersionUpgradeState | null>;
|
||||
start(): Promise<MinimumVersionUpgradeState | null>;
|
||||
retry(): Promise<MinimumVersionUpgradeState | null>;
|
||||
later(): Promise<void>;
|
||||
openManualDownload(): Promise<void>;
|
||||
exit(): Promise<void>;
|
||||
restart(): Promise<void>;
|
||||
onState(listener: (state: MinimumVersionUpgradeState) => void): () => void;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
export const desktopUpdateAdmissionIpcChannels = {
|
||||
exit: "desktop-update-admission:exit",
|
||||
getState: "desktop-update-admission:get-state",
|
||||
later: "desktop-update-admission:later",
|
||||
manualDownload: "desktop-update-admission:manual-download",
|
||||
restart: "desktop-update-admission:restart",
|
||||
retry: "desktop-update-admission:retry",
|
||||
start: "desktop-update-admission:start",
|
||||
state: "desktop-update-admission:state"
|
||||
} as const;
|
||||
@@ -0,0 +1,5 @@
|
||||
export {
|
||||
resolveMinimumVersionRuntimeTarget,
|
||||
updaterTargetMeetsMinimum,
|
||||
validateMinimumVersionResponse
|
||||
} from "./minimumVersion.ts";
|
||||
@@ -0,0 +1,70 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import {
|
||||
updaterTargetMeetsMinimum,
|
||||
validateMinimumVersionResponse
|
||||
} from "./minimumVersion.ts";
|
||||
|
||||
test("compares updater targets without numeric precision loss", () => {
|
||||
assert.equal(updaterTargetMeetsMinimum("1.6.0", "1.6.0"), true);
|
||||
assert.equal(updaterTargetMeetsMinimum("1.7.0", "1.7.0-rc.2"), true);
|
||||
assert.equal(updaterTargetMeetsMinimum("1.7.0-rc.1", "1.7.0-rc.2"), false);
|
||||
assert.equal(updaterTargetMeetsMinimum("1.7.0-beta.1", "1.7.0"), false);
|
||||
assert.deepEqual(
|
||||
updaterTargetMeetsMinimum(
|
||||
"900719925474099312345.0.0",
|
||||
"900719925474099312344.999.999"
|
||||
),
|
||||
true
|
||||
);
|
||||
});
|
||||
|
||||
test("combines a validated policy response with the local request identity", () => {
|
||||
const request = {
|
||||
architecture: "arm64",
|
||||
currentVersion: "1.6.0",
|
||||
platform: "macos",
|
||||
product: "tsh-desktop"
|
||||
} as const;
|
||||
assert.deepEqual(
|
||||
validateMinimumVersionResponse(
|
||||
{
|
||||
channel: "stable",
|
||||
decision: "upgradeRequired",
|
||||
minimumVersion: "1.6.1",
|
||||
policyRevision: "revision-1",
|
||||
reason: "belowMinimum"
|
||||
},
|
||||
request
|
||||
),
|
||||
{
|
||||
...request,
|
||||
channel: "stable",
|
||||
decision: "upgradeRequired",
|
||||
minimumVersion: "1.6.1",
|
||||
policyRevision: "revision-1",
|
||||
reason: "belowMinimum"
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
test("accepts an explicitly unconfigured minimum version", () => {
|
||||
const request = {
|
||||
architecture: "arm64",
|
||||
currentVersion: "1.6.0",
|
||||
platform: "macos",
|
||||
product: "tsh-desktop"
|
||||
} as const;
|
||||
const response = validateMinimumVersionResponse(
|
||||
{
|
||||
channel: "stable",
|
||||
decision: "allowed",
|
||||
policyRevision: "revision-1",
|
||||
reason: "minimumNotConfigured"
|
||||
},
|
||||
request
|
||||
);
|
||||
|
||||
assert.equal(response.reason, "minimumNotConfigured");
|
||||
assert.equal("minimumVersion" in response, false);
|
||||
});
|
||||
@@ -0,0 +1,194 @@
|
||||
import type {
|
||||
DesktopArchitecture,
|
||||
DesktopPlatform,
|
||||
DesktopProduct,
|
||||
MinimumVersionCheckRequest,
|
||||
MinimumVersionCheckResult
|
||||
} from "../contracts/index.ts";
|
||||
|
||||
type ManagedVersion = {
|
||||
major: string;
|
||||
minor: string;
|
||||
patch: string;
|
||||
rc: string | null;
|
||||
};
|
||||
|
||||
function parseManagedVersion(value: string): ManagedVersion | null {
|
||||
const match =
|
||||
/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-rc\.(0|[1-9]\d*))?$/u.exec(
|
||||
value.trim()
|
||||
);
|
||||
if (!match) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
major: match[1]!,
|
||||
minor: match[2]!,
|
||||
patch: match[3]!,
|
||||
rc: match[4] === undefined ? null : match[4]
|
||||
};
|
||||
}
|
||||
|
||||
function compareNumericIdentifier(left: string, right: string): number {
|
||||
if (left.length !== right.length) {
|
||||
return left.length < right.length ? -1 : 1;
|
||||
}
|
||||
return left === right ? 0 : left < right ? -1 : 1;
|
||||
}
|
||||
|
||||
function compareManagedVersions(
|
||||
left: ManagedVersion,
|
||||
right: ManagedVersion
|
||||
): number {
|
||||
for (const key of ["major", "minor", "patch"] as const) {
|
||||
if (left[key] !== right[key]) {
|
||||
return compareNumericIdentifier(left[key], right[key]);
|
||||
}
|
||||
}
|
||||
if (left.rc === right.rc) {
|
||||
return 0;
|
||||
}
|
||||
if (left.rc === null) {
|
||||
return 1;
|
||||
}
|
||||
if (right.rc === null) {
|
||||
return -1;
|
||||
}
|
||||
return compareNumericIdentifier(left.rc, right.rc);
|
||||
}
|
||||
|
||||
export function updaterTargetMeetsMinimum(
|
||||
releaseVersion: string | null,
|
||||
minimumVersion: string
|
||||
): boolean {
|
||||
if (!releaseVersion) {
|
||||
return false;
|
||||
}
|
||||
const release = parseManagedVersion(releaseVersion);
|
||||
const minimum = parseManagedVersion(minimumVersion);
|
||||
return Boolean(
|
||||
release && minimum && compareManagedVersions(release, minimum) >= 0
|
||||
);
|
||||
}
|
||||
|
||||
export function resolveMinimumVersionRuntimeTarget(
|
||||
platform: NodeJS.Platform,
|
||||
architecture: string
|
||||
): {
|
||||
platform: DesktopPlatform;
|
||||
architecture: DesktopArchitecture;
|
||||
} | null {
|
||||
const normalizedPlatform =
|
||||
platform === "darwin"
|
||||
? "macos"
|
||||
: platform === "win32"
|
||||
? "windows"
|
||||
: platform === "linux"
|
||||
? "linux"
|
||||
: null;
|
||||
const normalizedArchitecture =
|
||||
architecture === "arm64" ? "arm64" : architecture === "x64" ? "x64" : null;
|
||||
if (!normalizedPlatform || !normalizedArchitecture) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
architecture: normalizedArchitecture,
|
||||
platform: normalizedPlatform
|
||||
};
|
||||
}
|
||||
|
||||
export function validateMinimumVersionResponse<TProduct extends DesktopProduct>(
|
||||
value: unknown,
|
||||
request: MinimumVersionCheckRequest<TProduct>
|
||||
): MinimumVersionCheckResult<TProduct> {
|
||||
if (!value || typeof value !== "object") {
|
||||
throw new Error("minimum version response must be an object");
|
||||
}
|
||||
const response = value as Record<string, unknown>;
|
||||
if (
|
||||
typeof response.policyRevision !== "string" ||
|
||||
response.policyRevision.trim() === ""
|
||||
) {
|
||||
throw new Error("minimum version response has invalid policy revision");
|
||||
}
|
||||
if (response.channel === "unmanaged") {
|
||||
if (
|
||||
response.decision !== "notApplicable" ||
|
||||
response.reason !== "unmanagedPrerelease" ||
|
||||
"minimumVersion" in response
|
||||
) {
|
||||
throw new Error("minimum version response has invalid unmanaged policy");
|
||||
}
|
||||
return {
|
||||
...request,
|
||||
channel: response.channel,
|
||||
decision: response.decision,
|
||||
policyRevision: response.policyRevision,
|
||||
reason: response.reason
|
||||
};
|
||||
}
|
||||
if (response.channel !== "stable" && response.channel !== "rc") {
|
||||
throw new Error("minimum version response has invalid channel");
|
||||
}
|
||||
if (response.decision === "notApplicable") {
|
||||
if (
|
||||
response.reason !== "unsupportedRelease" ||
|
||||
"minimumVersion" in response
|
||||
) {
|
||||
throw new Error(
|
||||
"minimum version response has invalid non-applicable policy"
|
||||
);
|
||||
}
|
||||
return {
|
||||
...request,
|
||||
channel: response.channel,
|
||||
decision: response.decision,
|
||||
policyRevision: response.policyRevision,
|
||||
reason: response.reason
|
||||
};
|
||||
}
|
||||
if (
|
||||
response.decision === "allowed" &&
|
||||
response.reason === "minimumNotConfigured"
|
||||
) {
|
||||
if ("minimumVersion" in response) {
|
||||
throw new Error(
|
||||
"minimum version response has invalid unconfigured policy"
|
||||
);
|
||||
}
|
||||
return {
|
||||
...request,
|
||||
channel: response.channel,
|
||||
decision: response.decision,
|
||||
policyRevision: response.policyRevision,
|
||||
reason: response.reason
|
||||
};
|
||||
}
|
||||
if (
|
||||
response.decision !== "allowed" &&
|
||||
response.decision !== "upgradeRequired"
|
||||
) {
|
||||
throw new Error("minimum version response has invalid decision");
|
||||
}
|
||||
const pattern =
|
||||
response.channel === "rc"
|
||||
? /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)-rc\.(0|[1-9]\d*)$/u
|
||||
: /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/u;
|
||||
const expectedReason =
|
||||
response.decision === "allowed" ? "meetsMinimum" : "belowMinimum";
|
||||
if (
|
||||
typeof response.minimumVersion !== "string" ||
|
||||
!pattern.test(response.minimumVersion) ||
|
||||
response.reason !== expectedReason
|
||||
) {
|
||||
throw new Error("minimum version response has invalid managed policy");
|
||||
}
|
||||
return {
|
||||
...request,
|
||||
channel: response.channel,
|
||||
decision: response.decision,
|
||||
minimumVersion: response.minimumVersion,
|
||||
policyRevision: response.policyRevision,
|
||||
reason: response.reason
|
||||
} as MinimumVersionCheckResult<TProduct>;
|
||||
}
|
||||
@@ -0,0 +1,425 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { startDesktopUpdateDevelopmentMockServer } from "./mockServer.ts";
|
||||
import { createDevelopmentMinimumVersionChecker } from "./policyChecker.ts";
|
||||
import {
|
||||
resolveDesktopUpdateDevelopmentPolicyScenario,
|
||||
type DesktopUpdateDevelopmentPolicyScenario
|
||||
} from "./policyScenario.ts";
|
||||
import {
|
||||
resolveDesktopUpdateAdmissionDevelopment,
|
||||
resolveDesktopUpdateDevelopmentScenario,
|
||||
type DesktopUpdateDevelopmentScenario
|
||||
} from "./scenario.ts";
|
||||
import {
|
||||
completeDevelopmentUpdateInstallation,
|
||||
createDevelopmentAppUpdateDriver,
|
||||
DevelopmentInstallSuppressedError
|
||||
} from "./updaterDriver.ts";
|
||||
|
||||
const inProcessEnvironment = {
|
||||
DESKTOP_UPDATE_ADMISSION_CURRENT_VERSION: "1.0.0",
|
||||
DESKTOP_UPDATE_ADMISSION_DEV: "1",
|
||||
DESKTOP_UPDATE_ADMISSION_LATEST_VERSION: "1.2.0",
|
||||
DESKTOP_UPDATE_ADMISSION_MINIMUM_VERSION: "1.1.0",
|
||||
DESKTOP_UPDATE_ADMISSION_POLICY: "upgradeRequired",
|
||||
DESKTOP_UPDATE_ADMISSION_UPDATER: "available"
|
||||
} as const;
|
||||
|
||||
const loopbackClientEnvironment = {
|
||||
DESKTOP_UPDATE_ADMISSION_CURRENT_VERSION: "1.0.0",
|
||||
DESKTOP_UPDATE_ADMISSION_DEV: "1",
|
||||
DESKTOP_UPDATE_ADMISSION_MOCK_SERVER_URL: "http://127.0.0.1:43210",
|
||||
DESKTOP_UPDATE_ADMISSION_TRANSPORT: "loopback"
|
||||
} as const;
|
||||
|
||||
test("packaged resolution ignores invalid development variables", () => {
|
||||
const result = resolveDesktopUpdateAdmissionDevelopment({
|
||||
applicationVersion: "2.0.0",
|
||||
env: {
|
||||
DESKTOP_UPDATE_ADMISSION_CURRENT_VERSION: "invalid",
|
||||
DESKTOP_UPDATE_ADMISSION_DEV: "1",
|
||||
DESKTOP_UPDATE_ADMISSION_POLICY: "invalid"
|
||||
},
|
||||
isPackaged: true
|
||||
});
|
||||
|
||||
assert.equal(result.scenario, null);
|
||||
assert.deepEqual(result.runtime, {
|
||||
checksEnabled: true,
|
||||
currentVersion: "2.0.0",
|
||||
development: false
|
||||
});
|
||||
});
|
||||
|
||||
test("loopback client resolves without server policy variables", () => {
|
||||
const scenario = resolveDesktopUpdateDevelopmentScenario({
|
||||
env: loopbackClientEnvironment,
|
||||
isPackaged: false
|
||||
});
|
||||
|
||||
assert.deepEqual(scenario, {
|
||||
currentVersion: "1.0.0",
|
||||
mockServerUrl: "http://127.0.0.1:43210",
|
||||
transport: "loopback",
|
||||
updater: { check: "unavailable" }
|
||||
});
|
||||
});
|
||||
|
||||
test("loopback client rejects policy variables owned by the mock server", () => {
|
||||
for (const serverVariable of [
|
||||
"DESKTOP_UPDATE_ADMISSION_MINIMUM_VERSION",
|
||||
"DESKTOP_UPDATE_ADMISSION_FEATURE_KEYS",
|
||||
"DESKTOP_UPDATE_ADMISSION_POLICY",
|
||||
"DESKTOP_UPDATE_ADMISSION_POLICY_SEQUENCE",
|
||||
"DESKTOP_UPDATE_ADMISSION_SCENARIO"
|
||||
]) {
|
||||
assert.throws(
|
||||
() =>
|
||||
resolveDesktopUpdateDevelopmentScenario({
|
||||
env: {
|
||||
...loopbackClientEnvironment,
|
||||
[serverVariable]: "upgradeRequired"
|
||||
},
|
||||
isPackaged: false
|
||||
}),
|
||||
new RegExp(`${serverVariable} belongs to the loopback mock server`)
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test("loopback updater can be configured independently from server policy", () => {
|
||||
const scenario = resolveDesktopUpdateDevelopmentScenario({
|
||||
env: {
|
||||
...loopbackClientEnvironment,
|
||||
DESKTOP_UPDATE_ADMISSION_LATEST_VERSION: "1.2.0",
|
||||
DESKTOP_UPDATE_ADMISSION_UPDATER: "available"
|
||||
},
|
||||
isPackaged: false
|
||||
});
|
||||
|
||||
assert.deepEqual(scenario?.updater, {
|
||||
check: "available",
|
||||
download: "success",
|
||||
install: "simulated",
|
||||
latestVersion: "1.2.0"
|
||||
});
|
||||
});
|
||||
|
||||
test("development policy returns normalized feature keys", async () => {
|
||||
const policy = resolveDesktopUpdateDevelopmentPolicyScenario({
|
||||
env: {
|
||||
...inProcessEnvironment,
|
||||
DESKTOP_UPDATE_ADMISSION_FEATURE_KEYS: "workspace.example,agent.preview"
|
||||
}
|
||||
});
|
||||
assert.ok(policy);
|
||||
assert.deepEqual(policy.featureKeys, ["agent.preview", "workspace.example"]);
|
||||
|
||||
const response = await createDevelopmentMinimumVersionChecker(policy)(
|
||||
{
|
||||
architecture: "arm64",
|
||||
currentVersion: "1.0.0",
|
||||
platform: "macos",
|
||||
product: "tutti-desktop"
|
||||
},
|
||||
new AbortController().signal
|
||||
);
|
||||
assert.deepEqual(response.featureAvailability, {
|
||||
keys: ["agent.preview", "workspace.example"]
|
||||
});
|
||||
});
|
||||
|
||||
test("in-process client leaves policy validation to the daemon", () => {
|
||||
const scenario = resolveDesktopUpdateDevelopmentScenario({
|
||||
env: {
|
||||
DESKTOP_UPDATE_ADMISSION_CURRENT_VERSION: "1.0.0",
|
||||
DESKTOP_UPDATE_ADMISSION_DEV: "1",
|
||||
DESKTOP_UPDATE_ADMISSION_UPDATER: "unavailable"
|
||||
},
|
||||
isPackaged: false
|
||||
});
|
||||
assert.equal(scenario?.transport, "in-process");
|
||||
});
|
||||
|
||||
test("client resolution rejects invalid SemVer and non-loopback URL", () => {
|
||||
assert.throws(
|
||||
() =>
|
||||
resolveDesktopUpdateDevelopmentScenario({
|
||||
env: {
|
||||
...loopbackClientEnvironment,
|
||||
DESKTOP_UPDATE_ADMISSION_CURRENT_VERSION: "01.0.0"
|
||||
},
|
||||
isPackaged: false
|
||||
}),
|
||||
/must be valid SemVer/
|
||||
);
|
||||
assert.throws(
|
||||
() =>
|
||||
resolveDesktopUpdateDevelopmentScenario({
|
||||
env: {
|
||||
...loopbackClientEnvironment,
|
||||
DESKTOP_UPDATE_ADMISSION_MOCK_SERVER_URL: "http://localhost:43210"
|
||||
},
|
||||
isPackaged: false
|
||||
}),
|
||||
/must be an http:\/\/127\.0\.0\.1 origin/
|
||||
);
|
||||
});
|
||||
|
||||
test("target-below-minimum scenario keeps updater and policy versions coherent", () => {
|
||||
const scenario = resolveDesktopUpdateDevelopmentScenario({
|
||||
env: {
|
||||
...inProcessEnvironment,
|
||||
DESKTOP_UPDATE_ADMISSION_LATEST_VERSION: "1.1.0",
|
||||
DESKTOP_UPDATE_ADMISSION_MINIMUM_VERSION: "1.2.0",
|
||||
DESKTOP_UPDATE_ADMISSION_POLICY: undefined,
|
||||
DESKTOP_UPDATE_ADMISSION_SCENARIO: "startup-target-below-minimum",
|
||||
DESKTOP_UPDATE_ADMISSION_UPDATER: undefined
|
||||
},
|
||||
isPackaged: false
|
||||
});
|
||||
|
||||
assert.equal(scenario?.updater.check, "targetBelowMinimum");
|
||||
});
|
||||
|
||||
test("named scenarios only influence the client updater outcome", () => {
|
||||
const scenario = resolveDesktopUpdateDevelopmentScenario({
|
||||
env: {
|
||||
...inProcessEnvironment,
|
||||
DESKTOP_UPDATE_ADMISSION_POLICY: undefined,
|
||||
DESKTOP_UPDATE_ADMISSION_SCENARIO: "startup-force-success",
|
||||
DESKTOP_UPDATE_ADMISSION_UPDATER: undefined
|
||||
},
|
||||
isPackaged: false
|
||||
});
|
||||
assert.equal(scenario?.updater.check, "available");
|
||||
});
|
||||
|
||||
test("policy sequences advance and keep their final response", async () => {
|
||||
const policy = resolvePolicy({
|
||||
DESKTOP_UPDATE_ADMISSION_DEV: "1",
|
||||
DESKTOP_UPDATE_ADMISSION_POLICY_SEQUENCE:
|
||||
"upgradeRequired@1.1.0,minimumNotConfigured"
|
||||
});
|
||||
const checker = createDevelopmentMinimumVersionChecker(policy, {
|
||||
expectedCurrentVersion: "1.0.0"
|
||||
});
|
||||
const request = {
|
||||
architecture: "arm64",
|
||||
currentVersion: "1.0.0",
|
||||
platform: "macos",
|
||||
product: "tutti-desktop"
|
||||
} as const;
|
||||
|
||||
assert.equal(
|
||||
(await checker(request, new AbortController().signal)).decision,
|
||||
"upgradeRequired"
|
||||
);
|
||||
assert.equal(
|
||||
(await checker(request, new AbortController().signal)).reason,
|
||||
"minimumNotConfigured"
|
||||
);
|
||||
assert.equal(
|
||||
(await checker(request, new AbortController().signal)).reason,
|
||||
"minimumNotConfigured"
|
||||
);
|
||||
});
|
||||
|
||||
test("policy sequences advance independently for each desktop product", async () => {
|
||||
const policy = resolvePolicy({
|
||||
DESKTOP_UPDATE_ADMISSION_DEV: "1",
|
||||
DESKTOP_UPDATE_ADMISSION_POLICY_SEQUENCE:
|
||||
"upgradeRequired@1.1.0,minimumNotConfigured"
|
||||
});
|
||||
const checker = createDevelopmentMinimumVersionChecker(policy);
|
||||
const request = {
|
||||
architecture: "arm64",
|
||||
currentVersion: "1.0.0",
|
||||
platform: "macos"
|
||||
} as const;
|
||||
|
||||
assert.equal(
|
||||
(
|
||||
await checker(
|
||||
{ ...request, product: "tsh-desktop" },
|
||||
new AbortController().signal
|
||||
)
|
||||
).decision,
|
||||
"upgradeRequired"
|
||||
);
|
||||
assert.equal(
|
||||
(
|
||||
await checker(
|
||||
{ ...request, product: "tutti-desktop" },
|
||||
new AbortController().signal
|
||||
)
|
||||
).decision,
|
||||
"upgradeRequired"
|
||||
);
|
||||
});
|
||||
|
||||
test("timeout policy remains pending until the caller aborts", async () => {
|
||||
const checker = createDevelopmentMinimumVersionChecker(
|
||||
resolvePolicy({
|
||||
DESKTOP_UPDATE_ADMISSION_DEV: "1",
|
||||
DESKTOP_UPDATE_ADMISSION_POLICY: "timeout"
|
||||
})
|
||||
);
|
||||
const controller = new AbortController();
|
||||
const pending = checker(
|
||||
{
|
||||
architecture: "arm64",
|
||||
currentVersion: "1.0.0",
|
||||
platform: "macos",
|
||||
product: "tutti-desktop"
|
||||
},
|
||||
controller.signal
|
||||
);
|
||||
|
||||
controller.abort();
|
||||
|
||||
await assert.rejects(pending, { name: "AbortError" });
|
||||
});
|
||||
|
||||
test("retry-policy-released exposes retry after updater failure", async () => {
|
||||
const scenario = resolveDesktopUpdateDevelopmentScenario({
|
||||
env: {
|
||||
DESKTOP_UPDATE_ADMISSION_CURRENT_VERSION: "1.0.0",
|
||||
DESKTOP_UPDATE_ADMISSION_DEV: "1",
|
||||
DESKTOP_UPDATE_ADMISSION_LATEST_VERSION: "1.2.0",
|
||||
DESKTOP_UPDATE_ADMISSION_MINIMUM_VERSION: "1.1.0",
|
||||
DESKTOP_UPDATE_ADMISSION_SCENARIO: "retry-policy-released"
|
||||
},
|
||||
isPackaged: false
|
||||
});
|
||||
assert.ok(scenario?.transport === "in-process");
|
||||
const checker = createDevelopmentMinimumVersionChecker(
|
||||
resolvePolicy({
|
||||
DESKTOP_UPDATE_ADMISSION_DEV: "1",
|
||||
DESKTOP_UPDATE_ADMISSION_MINIMUM_VERSION: "1.1.0",
|
||||
DESKTOP_UPDATE_ADMISSION_SCENARIO: "retry-policy-released"
|
||||
}),
|
||||
{
|
||||
expectedCurrentVersion: scenario.currentVersion
|
||||
}
|
||||
);
|
||||
const request = {
|
||||
architecture: "arm64",
|
||||
currentVersion: scenario.currentVersion,
|
||||
platform: "macos",
|
||||
product: "tutti-desktop"
|
||||
} as const;
|
||||
|
||||
assert.equal(
|
||||
(await checker(request, new AbortController().signal)).decision,
|
||||
"upgradeRequired"
|
||||
);
|
||||
await assert.rejects(
|
||||
createDevelopmentAppUpdateDriver(scenario).checkForUpdates(),
|
||||
/Development update check failed/
|
||||
);
|
||||
assert.equal(
|
||||
(await checker(request, new AbortController().signal)).reason,
|
||||
"minimumNotConfigured"
|
||||
);
|
||||
});
|
||||
|
||||
test("development updater emits a deterministic successful download", async () => {
|
||||
const scenario = createScenario();
|
||||
const driver = createDevelopmentAppUpdateDriver(scenario);
|
||||
const events: string[] = [];
|
||||
driver.onCheckingForUpdate(() => events.push("checking"));
|
||||
driver.onUpdateAvailable((info) => events.push(`available:${info.version}`));
|
||||
driver.onDownloadProgress((progress) =>
|
||||
events.push(`progress:${progress.percent}`)
|
||||
);
|
||||
driver.onUpdateDownloaded((info) =>
|
||||
events.push(`downloaded:${info.version}`)
|
||||
);
|
||||
|
||||
await driver.checkForUpdates();
|
||||
await driver.downloadUpdate();
|
||||
|
||||
assert.deepEqual(events, [
|
||||
"checking",
|
||||
"available:1.2.0",
|
||||
"progress:100",
|
||||
"downloaded:1.2.0"
|
||||
]);
|
||||
assert.throws(
|
||||
() => completeDevelopmentUpdateInstallation(scenario),
|
||||
DevelopmentInstallSuppressedError
|
||||
);
|
||||
});
|
||||
|
||||
test("loopback mock server owns policy and returns its minimum version", async () => {
|
||||
const policy = resolvePolicy({
|
||||
DESKTOP_UPDATE_ADMISSION_DEV: "1",
|
||||
DESKTOP_UPDATE_ADMISSION_FEATURE_KEYS: "workspace.example,agent.preview",
|
||||
DESKTOP_UPDATE_ADMISSION_MINIMUM_VERSION: "1.4.0",
|
||||
DESKTOP_UPDATE_ADMISSION_POLICY: "upgradeRequired"
|
||||
});
|
||||
const server = await startDesktopUpdateDevelopmentMockServer({ policy });
|
||||
try {
|
||||
const response = await fetch(
|
||||
`${server.baseUrl}/api/desktop/v1/public/desktop-version/check`,
|
||||
{
|
||||
body: JSON.stringify({
|
||||
architecture: "arm64",
|
||||
currentVersion: "1.0.0",
|
||||
platform: "macos",
|
||||
product: "tsh-desktop"
|
||||
}),
|
||||
headers: { "content-type": "application/json" },
|
||||
method: "POST"
|
||||
}
|
||||
);
|
||||
assert.equal(response.status, 200);
|
||||
assert.deepEqual(await response.json(), {
|
||||
channel: "stable",
|
||||
decision: "upgradeRequired",
|
||||
featureAvailability: { keys: ["agent.preview", "workspace.example"] },
|
||||
minimumVersion: "1.4.0",
|
||||
policyRevision: "development-policy-1",
|
||||
reason: "belowMinimum"
|
||||
});
|
||||
const invalidResponse = await fetch(
|
||||
`${server.baseUrl}/api/desktop/v1/public/desktop-version/check`,
|
||||
{
|
||||
body: "{",
|
||||
headers: { "content-type": "application/json" },
|
||||
method: "POST"
|
||||
}
|
||||
);
|
||||
assert.equal(invalidResponse.status, 400);
|
||||
assert.equal(new URL(server.baseUrl).hostname, "127.0.0.1");
|
||||
} finally {
|
||||
await server.close();
|
||||
}
|
||||
});
|
||||
|
||||
function resolvePolicy(
|
||||
env: Readonly<Record<string, string | undefined>>
|
||||
): DesktopUpdateDevelopmentPolicyScenario {
|
||||
const policy = resolveDesktopUpdateDevelopmentPolicyScenario({ env });
|
||||
assert.ok(policy);
|
||||
return policy;
|
||||
}
|
||||
|
||||
function createScenario(): Extract<
|
||||
DesktopUpdateDevelopmentScenario,
|
||||
{ transport: "in-process" }
|
||||
> {
|
||||
return {
|
||||
currentVersion: "1.0.0",
|
||||
mockServerUrl: null,
|
||||
transport: "in-process",
|
||||
updater: {
|
||||
check: "available",
|
||||
download: "success",
|
||||
install: "simulated",
|
||||
latestVersion: "1.2.0"
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
export const desktopUpdateAdmissionDevelopmentEnvironment = {
|
||||
currentVersion: "DESKTOP_UPDATE_ADMISSION_CURRENT_VERSION",
|
||||
development: "DESKTOP_UPDATE_ADMISSION_DEV",
|
||||
download: "DESKTOP_UPDATE_ADMISSION_DOWNLOAD",
|
||||
foregroundIntervalMs: "DESKTOP_UPDATE_ADMISSION_FOREGROUND_INTERVAL_MS",
|
||||
featureKeys: "DESKTOP_UPDATE_ADMISSION_FEATURE_KEYS",
|
||||
install: "DESKTOP_UPDATE_ADMISSION_INSTALL",
|
||||
latestVersion: "DESKTOP_UPDATE_ADMISSION_LATEST_VERSION",
|
||||
minimumVersion: "DESKTOP_UPDATE_ADMISSION_MINIMUM_VERSION",
|
||||
mockServerUrl: "DESKTOP_UPDATE_ADMISSION_MOCK_SERVER_URL",
|
||||
policy: "DESKTOP_UPDATE_ADMISSION_POLICY",
|
||||
policySequence: "DESKTOP_UPDATE_ADMISSION_POLICY_SEQUENCE",
|
||||
scenario: "DESKTOP_UPDATE_ADMISSION_SCENARIO",
|
||||
transport: "DESKTOP_UPDATE_ADMISSION_TRANSPORT",
|
||||
updater: "DESKTOP_UPDATE_ADMISSION_UPDATER"
|
||||
} as const;
|
||||
|
||||
export function invalidDevelopmentScenario(message: string): never {
|
||||
throw new Error(`invalid desktop update development scenario: ${message}`);
|
||||
}
|
||||
|
||||
export function readRequiredDevelopmentEnvironment(
|
||||
env: Readonly<Record<string, string | undefined>>,
|
||||
name: string
|
||||
): string {
|
||||
const value = env[name]?.trim();
|
||||
if (!value) {
|
||||
return invalidDevelopmentScenario(`${name} is required`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
export function readDevelopmentEnabled(
|
||||
env: Readonly<Record<string, string | undefined>>
|
||||
): boolean {
|
||||
const name = desktopUpdateAdmissionDevelopmentEnvironment.development;
|
||||
const value = env[name]?.trim().toLowerCase();
|
||||
if (!value || ["0", "false", "no", "off"].includes(value)) {
|
||||
return false;
|
||||
}
|
||||
if (["1", "true", "yes", "on"].includes(value)) {
|
||||
return true;
|
||||
}
|
||||
return invalidDevelopmentScenario(`${name} must be a boolean flag`);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
export {
|
||||
completeDevelopmentUpdateInstallation,
|
||||
createDevelopmentAppUpdateDriver,
|
||||
DevelopmentInstallError,
|
||||
DevelopmentInstallSuppressedError,
|
||||
type DevelopmentAppUpdateDriver,
|
||||
type DevelopmentUpdateInfo,
|
||||
type DevelopmentUpdateProgress
|
||||
} from "./updaterDriver.ts";
|
||||
export { createDevelopmentMinimumVersionChecker } from "./policyChecker.ts";
|
||||
export {
|
||||
resolveDesktopUpdateDevelopmentPolicyScenario,
|
||||
type DesktopUpdateDevelopmentPolicyMinimum,
|
||||
type DesktopUpdateDevelopmentPolicyOutcome,
|
||||
type DesktopUpdateDevelopmentPolicyScenario,
|
||||
type DesktopUpdateDevelopmentPolicyStep
|
||||
} from "./policyScenario.ts";
|
||||
export {
|
||||
startDesktopUpdateDevelopmentMockServer,
|
||||
type DesktopUpdateDevelopmentMockServer
|
||||
} from "./mockServer.ts";
|
||||
export { desktopUpdateAdmissionDevelopmentEnvironment } from "./environment.ts";
|
||||
export {
|
||||
resolveDesktopUpdateAdmissionDevelopment,
|
||||
resolveDesktopUpdateDevelopmentScenario,
|
||||
type DesktopUpdateDevelopmentResolution,
|
||||
type DesktopUpdateDevelopmentScenario,
|
||||
type DesktopUpdateDevelopmentUpdaterScenario
|
||||
} from "./scenario.ts";
|
||||
@@ -0,0 +1,186 @@
|
||||
import {
|
||||
createServer,
|
||||
type IncomingMessage,
|
||||
type ServerResponse
|
||||
} from "node:http";
|
||||
import type {
|
||||
DesktopProduct,
|
||||
MinimumVersionCheckRequest
|
||||
} from "../contracts/index.ts";
|
||||
import { createDevelopmentMinimumVersionChecker } from "./policyChecker.ts";
|
||||
import type { DesktopUpdateDevelopmentPolicyScenario } from "./policyScenario.ts";
|
||||
|
||||
const maximumRequestBodyBytes = 64 * 1_024;
|
||||
const minimumVersionPath = "/api/desktop/v1/public/desktop-version/check";
|
||||
|
||||
export interface DesktopUpdateDevelopmentMockServer {
|
||||
readonly baseUrl: string;
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
class InvalidDevelopmentMockRequestError extends Error {
|
||||
public constructor(message: string) {
|
||||
super(message);
|
||||
this.name = "InvalidDevelopmentMockRequestError";
|
||||
}
|
||||
}
|
||||
|
||||
function invalidRequest(message: string): never {
|
||||
throw new InvalidDevelopmentMockRequestError(message);
|
||||
}
|
||||
|
||||
function writeJson(
|
||||
response: ServerResponse,
|
||||
statusCode: number,
|
||||
value: unknown
|
||||
): void {
|
||||
const body = JSON.stringify(value);
|
||||
response.writeHead(statusCode, {
|
||||
"content-length": Buffer.byteLength(body),
|
||||
"content-type": "application/json; charset=utf-8"
|
||||
});
|
||||
response.end(body);
|
||||
}
|
||||
|
||||
async function readJson(request: IncomingMessage): Promise<unknown> {
|
||||
let size = 0;
|
||||
const chunks: Buffer[] = [];
|
||||
for await (const value of request) {
|
||||
const chunk = Buffer.isBuffer(value) ? value : Buffer.from(value);
|
||||
size += chunk.byteLength;
|
||||
if (size > maximumRequestBodyBytes) {
|
||||
return invalidRequest("request body exceeds 64 KiB");
|
||||
}
|
||||
chunks.push(chunk);
|
||||
}
|
||||
try {
|
||||
return JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
||||
} catch {
|
||||
return invalidRequest("request body must contain valid JSON");
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeRequest(
|
||||
value: unknown
|
||||
): MinimumVersionCheckRequest<DesktopProduct> {
|
||||
if (!value || typeof value !== "object") {
|
||||
return invalidRequest("request must be an object");
|
||||
}
|
||||
const candidate = value as Record<string, unknown>;
|
||||
if (
|
||||
candidate.product !== "tsh-desktop" &&
|
||||
candidate.product !== "tutti-desktop"
|
||||
) {
|
||||
return invalidRequest("request has an invalid product");
|
||||
}
|
||||
if (
|
||||
candidate.platform !== "macos" &&
|
||||
candidate.platform !== "windows" &&
|
||||
candidate.platform !== "linux"
|
||||
) {
|
||||
return invalidRequest("request has an invalid platform");
|
||||
}
|
||||
if (candidate.architecture !== "arm64" && candidate.architecture !== "x64") {
|
||||
return invalidRequest("request has an invalid architecture");
|
||||
}
|
||||
if (
|
||||
typeof candidate.currentVersion !== "string" ||
|
||||
candidate.currentVersion.trim() === ""
|
||||
) {
|
||||
return invalidRequest("request has an invalid currentVersion");
|
||||
}
|
||||
return {
|
||||
architecture: candidate.architecture,
|
||||
currentVersion: candidate.currentVersion,
|
||||
platform: candidate.platform,
|
||||
product: candidate.product
|
||||
};
|
||||
}
|
||||
|
||||
export async function startDesktopUpdateDevelopmentMockServer(input: {
|
||||
port?: number;
|
||||
policy: DesktopUpdateDevelopmentPolicyScenario;
|
||||
}): Promise<DesktopUpdateDevelopmentMockServer> {
|
||||
const checker = createDevelopmentMinimumVersionChecker(input.policy);
|
||||
const server = createServer(async (request, response) => {
|
||||
if (request.url === "/healthz") {
|
||||
if (request.method !== "GET") {
|
||||
response.writeHead(405, { allow: "GET" });
|
||||
response.end();
|
||||
return;
|
||||
}
|
||||
writeJson(response, 200, { status: "ok" });
|
||||
return;
|
||||
}
|
||||
if (request.url !== minimumVersionPath) {
|
||||
writeJson(response, 404, { error: "not found" });
|
||||
return;
|
||||
}
|
||||
if (request.method !== "POST") {
|
||||
response.writeHead(405, { allow: "POST" });
|
||||
response.end();
|
||||
return;
|
||||
}
|
||||
if (
|
||||
!String(request.headers["content-type"] ?? "")
|
||||
.toLowerCase()
|
||||
.startsWith("application/json")
|
||||
) {
|
||||
writeJson(response, 415, {
|
||||
error: "content-type must be application/json"
|
||||
});
|
||||
return;
|
||||
}
|
||||
const abortController = new AbortController();
|
||||
request.once("aborted", () => abortController.abort());
|
||||
response.once("close", () => {
|
||||
if (!response.writableEnded) {
|
||||
abortController.abort();
|
||||
}
|
||||
});
|
||||
try {
|
||||
const policyRequest = normalizeRequest(await readJson(request));
|
||||
const result = await checker(policyRequest, abortController.signal);
|
||||
if (!response.destroyed) {
|
||||
writeJson(response, 200, result);
|
||||
}
|
||||
} catch (error) {
|
||||
if (abortController.signal.aborted || response.destroyed) {
|
||||
return;
|
||||
}
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
const statusCode =
|
||||
error instanceof InvalidDevelopmentMockRequestError ? 400 : 500;
|
||||
writeJson(response, statusCode, { error: message });
|
||||
}
|
||||
});
|
||||
const port = input.port ?? 0;
|
||||
if (!Number.isSafeInteger(port) || port < 0 || port > 65_535) {
|
||||
throw new Error("development mock server port must be between 0 and 65535");
|
||||
}
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.once("error", reject);
|
||||
server.listen(port, "127.0.0.1", () => {
|
||||
server.removeListener("error", reject);
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
const address = server.address();
|
||||
if (!address || typeof address === "string") {
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||
throw new Error("development mock server did not expose a TCP address");
|
||||
}
|
||||
return {
|
||||
baseUrl: `http://127.0.0.1:${address.port}`,
|
||||
close: () =>
|
||||
new Promise<void>((resolve, reject) => {
|
||||
server.close((error) => {
|
||||
if (error) {
|
||||
reject(error);
|
||||
} else {
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
})
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import { resolveDesktopUpdateDevelopmentPolicyScenario } from "./policyScenario.ts";
|
||||
import { startDesktopUpdateDevelopmentMockServer } from "./mockServer.ts";
|
||||
|
||||
function log(level: "info" | "error", details: Record<string, unknown>): void {
|
||||
const output = `[minimum-version-check] ${JSON.stringify(details)}`;
|
||||
if (level === "error") {
|
||||
process.stderr.write(`${output}\n`);
|
||||
} else {
|
||||
process.stdout.write(`${output}\n`);
|
||||
}
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const policy = resolveDesktopUpdateDevelopmentPolicyScenario({
|
||||
env: process.env
|
||||
});
|
||||
if (!policy) {
|
||||
throw new Error(
|
||||
"DESKTOP_UPDATE_ADMISSION_DEV=1 is required to start the mock server"
|
||||
);
|
||||
}
|
||||
const rawPort = process.env.DESKTOP_UPDATE_ADMISSION_MOCK_SERVER_PORT?.trim();
|
||||
const port = rawPort ? Number(rawPort) : undefined;
|
||||
const server = await startDesktopUpdateDevelopmentMockServer({
|
||||
port,
|
||||
policy
|
||||
});
|
||||
log("info", {
|
||||
baseUrl: server.baseUrl,
|
||||
result: "listening",
|
||||
stage: "development-mock-server"
|
||||
});
|
||||
let closing = false;
|
||||
const close = async (signal: string): Promise<void> => {
|
||||
if (closing) {
|
||||
return;
|
||||
}
|
||||
closing = true;
|
||||
await server.close();
|
||||
log("info", {
|
||||
result: "stopped",
|
||||
signal,
|
||||
stage: "development-mock-server"
|
||||
});
|
||||
};
|
||||
process.once("SIGINT", () => {
|
||||
void close("SIGINT");
|
||||
});
|
||||
process.once("SIGTERM", () => {
|
||||
void close("SIGTERM");
|
||||
});
|
||||
}
|
||||
|
||||
void main().catch((error) => {
|
||||
log("error", {
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
result: "failure",
|
||||
stage: "development-mock-server"
|
||||
});
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -0,0 +1,159 @@
|
||||
import type {
|
||||
DesktopProduct,
|
||||
MinimumVersionCheckRequest,
|
||||
MinimumVersionCheckResponse
|
||||
} from "../contracts/index.ts";
|
||||
import { validateMinimumVersionResponse } from "../core/index.ts";
|
||||
import type {
|
||||
DesktopUpdateDevelopmentPolicyMinimum,
|
||||
DesktopUpdateDevelopmentPolicyScenario,
|
||||
DesktopUpdateDevelopmentPolicyStep
|
||||
} from "./policyScenario.ts";
|
||||
import { validateDevelopmentPolicyScenarioForCurrentVersion } from "./policyScenario.ts";
|
||||
|
||||
function developmentChannel(
|
||||
currentVersion: string
|
||||
): "stable" | "rc" | "unmanaged" {
|
||||
if (
|
||||
/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)-rc\.(0|[1-9]\d*)$/u.test(
|
||||
currentVersion
|
||||
)
|
||||
) {
|
||||
return "rc";
|
||||
}
|
||||
if (
|
||||
/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u.test(
|
||||
currentVersion
|
||||
)
|
||||
) {
|
||||
return "stable";
|
||||
}
|
||||
return "unmanaged";
|
||||
}
|
||||
|
||||
function abortError(): Error {
|
||||
const error = new Error("development minimum-version policy check aborted");
|
||||
error.name = "AbortError";
|
||||
return error;
|
||||
}
|
||||
|
||||
function waitForAbort(signal: AbortSignal): Promise<never> {
|
||||
if (signal.aborted) {
|
||||
return Promise.reject(abortError());
|
||||
}
|
||||
return new Promise<never>((_resolve, reject) => {
|
||||
signal.addEventListener("abort", () => reject(abortError()), {
|
||||
once: true
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function responseForStep<TProduct extends DesktopProduct>(
|
||||
request: MinimumVersionCheckRequest<TProduct>,
|
||||
step: DesktopUpdateDevelopmentPolicyStep,
|
||||
revision: number,
|
||||
featureKeys: readonly string[]
|
||||
): MinimumVersionCheckResponse {
|
||||
const channel = developmentChannel(request.currentVersion);
|
||||
const base = {
|
||||
channel,
|
||||
featureAvailability: {
|
||||
keys: featureKeys
|
||||
},
|
||||
policyRevision: `development-policy-${revision}`
|
||||
} as const;
|
||||
const minimumVersion = (
|
||||
minimum: DesktopUpdateDevelopmentPolicyMinimum
|
||||
): string =>
|
||||
minimum.kind === "configured" ? minimum.version : request.currentVersion;
|
||||
const validatedResponse = (value: unknown): MinimumVersionCheckResponse => {
|
||||
validateMinimumVersionResponse(value, request);
|
||||
return value as MinimumVersionCheckResponse;
|
||||
};
|
||||
switch (step.outcome) {
|
||||
case "allowed":
|
||||
return validatedResponse({
|
||||
...base,
|
||||
channel,
|
||||
decision: "allowed",
|
||||
minimumVersion: minimumVersion(step.minimum),
|
||||
reason: "meetsMinimum"
|
||||
});
|
||||
case "upgradeRequired":
|
||||
return validatedResponse({
|
||||
...base,
|
||||
channel,
|
||||
decision: "upgradeRequired",
|
||||
minimumVersion: minimumVersion(step.minimum),
|
||||
reason: "belowMinimum"
|
||||
});
|
||||
case "minimumNotConfigured":
|
||||
return validatedResponse({
|
||||
...base,
|
||||
decision: "allowed",
|
||||
reason: "minimumNotConfigured"
|
||||
});
|
||||
case "unsupported":
|
||||
return validatedResponse({
|
||||
...base,
|
||||
decision: "notApplicable",
|
||||
reason: "unsupportedRelease"
|
||||
});
|
||||
case "unmanagedPrerelease":
|
||||
return validatedResponse({
|
||||
...base,
|
||||
channel: "unmanaged",
|
||||
decision: "notApplicable",
|
||||
reason: "unmanagedPrerelease"
|
||||
});
|
||||
case "error":
|
||||
case "timeout":
|
||||
throw new Error(`cannot synthesize ${step.outcome} as a policy response`);
|
||||
}
|
||||
}
|
||||
|
||||
export function createDevelopmentMinimumVersionChecker(
|
||||
policy: DesktopUpdateDevelopmentPolicyScenario,
|
||||
options: {
|
||||
expectedCurrentVersion?: string;
|
||||
} = {}
|
||||
): <TProduct extends DesktopProduct>(
|
||||
request: MinimumVersionCheckRequest<TProduct>,
|
||||
signal: AbortSignal
|
||||
) => Promise<MinimumVersionCheckResponse> {
|
||||
const checkIndexes = new Map<string, number>();
|
||||
const policyFeatureKeys = policy.featureKeys;
|
||||
return async <TProduct extends DesktopProduct>(
|
||||
request: MinimumVersionCheckRequest<TProduct>,
|
||||
signal: AbortSignal
|
||||
): Promise<MinimumVersionCheckResponse> => {
|
||||
if (
|
||||
options.expectedCurrentVersion &&
|
||||
request.currentVersion !== options.expectedCurrentVersion
|
||||
) {
|
||||
throw new Error(
|
||||
`development policy expected currentVersion ${options.expectedCurrentVersion}, received ${request.currentVersion}`
|
||||
);
|
||||
}
|
||||
const requestIdentity = [
|
||||
request.product,
|
||||
request.platform,
|
||||
request.architecture
|
||||
].join(":");
|
||||
const checkIndex = checkIndexes.get(requestIdentity) ?? 0;
|
||||
const stepIndex = Math.min(checkIndex, policy.policySteps.length - 1);
|
||||
const step = policy.policySteps[stepIndex]!;
|
||||
checkIndexes.set(requestIdentity, checkIndex + 1);
|
||||
if (step.outcome === "timeout") {
|
||||
return await waitForAbort(signal);
|
||||
}
|
||||
if (step.outcome === "error") {
|
||||
throw new Error(step.message);
|
||||
}
|
||||
validateDevelopmentPolicyScenarioForCurrentVersion(
|
||||
{ featureKeys: policyFeatureKeys, policySteps: [step] },
|
||||
request.currentVersion
|
||||
);
|
||||
return responseForStep(request, step, stepIndex + 1, policyFeatureKeys);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,305 @@
|
||||
import {
|
||||
desktopUpdateAdmissionDevelopmentEnvironment,
|
||||
invalidDevelopmentScenario,
|
||||
readDevelopmentEnabled
|
||||
} from "./environment.ts";
|
||||
import {
|
||||
compareDevelopmentManagedVersions,
|
||||
parseDevelopmentManagedVersion,
|
||||
validateStrictDevelopmentSemVer
|
||||
} from "./version.ts";
|
||||
import { normalizeDesktopFeatureKeys } from "../feature-availability/core.ts";
|
||||
|
||||
export type DesktopUpdateDevelopmentPolicyOutcome =
|
||||
| "allowed"
|
||||
| "upgradeRequired"
|
||||
| "minimumNotConfigured"
|
||||
| "unsupported"
|
||||
| "unmanagedPrerelease"
|
||||
| "error"
|
||||
| "timeout";
|
||||
|
||||
export type DesktopUpdateDevelopmentPolicyMinimum =
|
||||
| {
|
||||
kind: "configured";
|
||||
version: string;
|
||||
}
|
||||
| {
|
||||
kind: "requestCurrentVersion";
|
||||
};
|
||||
|
||||
export type DesktopUpdateDevelopmentPolicyStep =
|
||||
| {
|
||||
outcome: "allowed" | "upgradeRequired";
|
||||
minimum: DesktopUpdateDevelopmentPolicyMinimum;
|
||||
}
|
||||
| {
|
||||
outcome: "minimumNotConfigured" | "unsupported" | "unmanagedPrerelease";
|
||||
}
|
||||
| {
|
||||
outcome: "error";
|
||||
message: string;
|
||||
}
|
||||
| {
|
||||
outcome: "timeout";
|
||||
};
|
||||
|
||||
export interface DesktopUpdateDevelopmentPolicyScenario {
|
||||
featureKeys: readonly string[];
|
||||
policySteps: readonly DesktopUpdateDevelopmentPolicyStep[];
|
||||
}
|
||||
|
||||
function resolveFeatureKeys(
|
||||
env: Readonly<Record<string, string | undefined>>
|
||||
): readonly string[] {
|
||||
const raw =
|
||||
env[desktopUpdateAdmissionDevelopmentEnvironment.featureKeys]?.trim();
|
||||
if (!raw) {
|
||||
return Object.freeze([]);
|
||||
}
|
||||
return normalizeDesktopFeatureKeys(
|
||||
raw.split(",").map((value) => value.trim())
|
||||
);
|
||||
}
|
||||
|
||||
function parseOutcome(value: string): DesktopUpdateDevelopmentPolicyOutcome {
|
||||
switch (value) {
|
||||
case "allowed":
|
||||
case "upgradeRequired":
|
||||
case "minimumNotConfigured":
|
||||
case "unsupported":
|
||||
case "unmanagedPrerelease":
|
||||
case "error":
|
||||
case "timeout":
|
||||
return value;
|
||||
default:
|
||||
return invalidDevelopmentScenario(
|
||||
`unknown policy outcome ${JSON.stringify(value)}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function configuredMinimum(
|
||||
value: string,
|
||||
name: string
|
||||
): DesktopUpdateDevelopmentPolicyMinimum {
|
||||
const version = validateStrictDevelopmentSemVer(value, name);
|
||||
if (!parseDevelopmentManagedVersion(version)) {
|
||||
return invalidDevelopmentScenario(
|
||||
`${name} must be a managed stable or RC version`
|
||||
);
|
||||
}
|
||||
return { kind: "configured", version };
|
||||
}
|
||||
|
||||
function createPolicyStep(
|
||||
token: string,
|
||||
fallbackMinimumVersion: string | undefined
|
||||
): DesktopUpdateDevelopmentPolicyStep {
|
||||
const [rawOutcome, rawMinimumVersion, ...extra] = token.split("@");
|
||||
if (!rawOutcome || extra.length > 0) {
|
||||
return invalidDevelopmentScenario(
|
||||
`invalid policy step ${JSON.stringify(token)}`
|
||||
);
|
||||
}
|
||||
const outcome = parseOutcome(rawOutcome.trim());
|
||||
if (outcome === "allowed" || outcome === "upgradeRequired") {
|
||||
return {
|
||||
minimum: configuredMinimum(
|
||||
rawMinimumVersion?.trim() || fallbackMinimumVersion || "",
|
||||
desktopUpdateAdmissionDevelopmentEnvironment.minimumVersion
|
||||
),
|
||||
outcome
|
||||
};
|
||||
}
|
||||
if (rawMinimumVersion !== undefined) {
|
||||
return invalidDevelopmentScenario(
|
||||
`policy outcome ${outcome} must not include a minimum version`
|
||||
);
|
||||
}
|
||||
if (outcome === "error") {
|
||||
return {
|
||||
message: "Development minimum-version policy check failed",
|
||||
outcome
|
||||
};
|
||||
}
|
||||
return { outcome };
|
||||
}
|
||||
|
||||
function createPresetPolicySteps(
|
||||
name: string,
|
||||
minimumVersion: string | undefined
|
||||
): readonly DesktopUpdateDevelopmentPolicyStep[] {
|
||||
const requiredMinimum = (): DesktopUpdateDevelopmentPolicyMinimum =>
|
||||
configuredMinimum(
|
||||
minimumVersion || "",
|
||||
desktopUpdateAdmissionDevelopmentEnvironment.minimumVersion
|
||||
);
|
||||
switch (name) {
|
||||
case "startup-force-success":
|
||||
case "startup-updater-unavailable":
|
||||
case "startup-target-below-minimum":
|
||||
case "startup-download-error":
|
||||
return [
|
||||
{
|
||||
minimum: requiredMinimum(),
|
||||
outcome: "upgradeRequired"
|
||||
}
|
||||
];
|
||||
case "startup-policy-timeout":
|
||||
return [{ outcome: "timeout" }];
|
||||
case "retry-policy-released":
|
||||
return [
|
||||
{
|
||||
minimum: requiredMinimum(),
|
||||
outcome: "upgradeRequired"
|
||||
},
|
||||
{ outcome: "minimumNotConfigured" }
|
||||
];
|
||||
case "foreground-upgrade-required":
|
||||
return [
|
||||
{
|
||||
minimum: { kind: "requestCurrentVersion" },
|
||||
outcome: "allowed"
|
||||
},
|
||||
{
|
||||
minimum: requiredMinimum(),
|
||||
outcome: "upgradeRequired"
|
||||
}
|
||||
];
|
||||
default:
|
||||
return invalidDevelopmentScenario(
|
||||
`unknown named scenario ${JSON.stringify(name)}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function resolvePolicySteps(
|
||||
env: Readonly<Record<string, string | undefined>>
|
||||
): readonly DesktopUpdateDevelopmentPolicyStep[] {
|
||||
const names = desktopUpdateAdmissionDevelopmentEnvironment;
|
||||
const fallbackMinimumVersion = env[names.minimumVersion]?.trim();
|
||||
const preset = env[names.scenario]?.trim();
|
||||
if (preset) {
|
||||
for (const conflictingName of [names.policy, names.policySequence]) {
|
||||
if (env[conflictingName]?.trim()) {
|
||||
return invalidDevelopmentScenario(
|
||||
`${names.scenario} and ${conflictingName} are mutually exclusive`
|
||||
);
|
||||
}
|
||||
}
|
||||
return createPresetPolicySteps(preset, fallbackMinimumVersion);
|
||||
}
|
||||
const sequence = env[names.policySequence]?.trim();
|
||||
const single = env[names.policy]?.trim();
|
||||
if (sequence && single) {
|
||||
return invalidDevelopmentScenario(
|
||||
`${names.policy} and ${names.policySequence} are mutually exclusive`
|
||||
);
|
||||
}
|
||||
const rawSteps = sequence
|
||||
? sequence.split(",").map((value) => value.trim())
|
||||
: single
|
||||
? [single]
|
||||
: invalidDevelopmentScenario(
|
||||
`${names.policy} or ${names.policySequence} is required`
|
||||
);
|
||||
if (rawSteps.some((value) => value.length === 0)) {
|
||||
return invalidDevelopmentScenario(
|
||||
`${names.policySequence} contains an empty step`
|
||||
);
|
||||
}
|
||||
return rawSteps.map((token) =>
|
||||
createPolicyStep(token, fallbackMinimumVersion)
|
||||
);
|
||||
}
|
||||
|
||||
function configuredVersion(
|
||||
minimum: DesktopUpdateDevelopmentPolicyMinimum,
|
||||
currentVersion: string
|
||||
): string {
|
||||
return minimum.kind === "configured" ? minimum.version : currentVersion;
|
||||
}
|
||||
|
||||
export function validateDevelopmentPolicyScenarioForCurrentVersion(
|
||||
scenario: DesktopUpdateDevelopmentPolicyScenario,
|
||||
currentVersion: string
|
||||
): void {
|
||||
const normalizedCurrent = validateStrictDevelopmentSemVer(
|
||||
currentVersion,
|
||||
desktopUpdateAdmissionDevelopmentEnvironment.currentVersion
|
||||
);
|
||||
const current = parseDevelopmentManagedVersion(normalizedCurrent);
|
||||
for (const step of scenario.policySteps) {
|
||||
if (step.outcome === "unmanagedPrerelease") {
|
||||
if (current) {
|
||||
invalidDevelopmentScenario(
|
||||
"unmanagedPrerelease requires an unmanaged currentVersion"
|
||||
);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (step.outcome !== "allowed" && step.outcome !== "upgradeRequired") {
|
||||
if (
|
||||
(step.outcome === "minimumNotConfigured" ||
|
||||
step.outcome === "unsupported") &&
|
||||
!current
|
||||
) {
|
||||
invalidDevelopmentScenario(
|
||||
`${step.outcome} requires a managed currentVersion`
|
||||
);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (!current) {
|
||||
invalidDevelopmentScenario(
|
||||
`${step.outcome} requires a managed currentVersion`
|
||||
);
|
||||
}
|
||||
const minimumVersion = configuredVersion(step.minimum, normalizedCurrent);
|
||||
const minimum = parseDevelopmentManagedVersion(minimumVersion);
|
||||
if (!minimum || minimum.channel !== current.channel) {
|
||||
invalidDevelopmentScenario(
|
||||
`minimumVersion must use the ${current.channel} channel`
|
||||
);
|
||||
}
|
||||
const compared = compareDevelopmentManagedVersions(current, minimum);
|
||||
if (step.outcome === "allowed" && compared < 0) {
|
||||
invalidDevelopmentScenario(
|
||||
"allowed requires currentVersion to meet minimumVersion"
|
||||
);
|
||||
}
|
||||
if (step.outcome === "upgradeRequired" && compared >= 0) {
|
||||
invalidDevelopmentScenario(
|
||||
"upgradeRequired requires currentVersion below minimumVersion"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function resolveDesktopUpdateDevelopmentPolicyScenario(input: {
|
||||
env: Readonly<Record<string, string | undefined>>;
|
||||
}): DesktopUpdateDevelopmentPolicyScenario | null {
|
||||
if (!readDevelopmentEnabled(input.env)) {
|
||||
return null;
|
||||
}
|
||||
const scenario: DesktopUpdateDevelopmentPolicyScenario = {
|
||||
featureKeys: resolveFeatureKeys(input.env),
|
||||
policySteps: resolvePolicySteps(input.env)
|
||||
};
|
||||
return Object.freeze({
|
||||
featureKeys: scenario.featureKeys,
|
||||
policySteps: Object.freeze(
|
||||
scenario.policySteps.map((step) =>
|
||||
Object.freeze(
|
||||
"minimum" in step
|
||||
? {
|
||||
...step,
|
||||
minimum: Object.freeze({ ...step.minimum })
|
||||
}
|
||||
: { ...step }
|
||||
)
|
||||
)
|
||||
)
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
import type { DesktopUpdateAdmissionRuntime } from "../contracts/index.ts";
|
||||
import {
|
||||
desktopUpdateAdmissionDevelopmentEnvironment,
|
||||
invalidDevelopmentScenario,
|
||||
readDevelopmentEnabled,
|
||||
readRequiredDevelopmentEnvironment
|
||||
} from "./environment.ts";
|
||||
import {
|
||||
compareDevelopmentManagedVersions,
|
||||
parseDevelopmentManagedVersion,
|
||||
validateStrictDevelopmentSemVer
|
||||
} from "./version.ts";
|
||||
|
||||
export type DesktopUpdateDevelopmentUpdaterScenario =
|
||||
| {
|
||||
check: "available" | "downloaded" | "targetBelowMinimum";
|
||||
latestVersion: string;
|
||||
download: "success" | "error";
|
||||
install: "simulated" | "error";
|
||||
}
|
||||
| {
|
||||
check: "unavailable" | "error";
|
||||
};
|
||||
|
||||
interface DesktopUpdateDevelopmentScenarioBase {
|
||||
currentVersion: string;
|
||||
updater: DesktopUpdateDevelopmentUpdaterScenario;
|
||||
}
|
||||
|
||||
export type DesktopUpdateDevelopmentScenario =
|
||||
| (DesktopUpdateDevelopmentScenarioBase & {
|
||||
mockServerUrl: null;
|
||||
transport: "in-process";
|
||||
})
|
||||
| (DesktopUpdateDevelopmentScenarioBase & {
|
||||
mockServerUrl: string;
|
||||
transport: "loopback";
|
||||
});
|
||||
|
||||
export interface DesktopUpdateDevelopmentResolution {
|
||||
runtime: DesktopUpdateAdmissionRuntime;
|
||||
scenario: DesktopUpdateDevelopmentScenario | null;
|
||||
}
|
||||
|
||||
function resolveUpdater(
|
||||
env: Readonly<Record<string, string | undefined>>,
|
||||
options: {
|
||||
defaultCheck: "available" | "unavailable";
|
||||
preset: string | undefined;
|
||||
}
|
||||
): DesktopUpdateDevelopmentUpdaterScenario {
|
||||
const names = desktopUpdateAdmissionDevelopmentEnvironment;
|
||||
if (options.preset) {
|
||||
for (const conflictingName of [
|
||||
names.updater,
|
||||
names.download,
|
||||
names.install
|
||||
]) {
|
||||
if (env[conflictingName]?.trim()) {
|
||||
return invalidDevelopmentScenario(
|
||||
`${names.scenario} and ${conflictingName} are mutually exclusive`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
const configured = env[names.updater]?.trim();
|
||||
const check =
|
||||
options.preset === "startup-updater-unavailable"
|
||||
? "unavailable"
|
||||
: options.preset === "startup-target-below-minimum"
|
||||
? "targetBelowMinimum"
|
||||
: options.preset === "retry-policy-released"
|
||||
? "error"
|
||||
: configured || options.defaultCheck;
|
||||
if (check === "unavailable" || check === "error") {
|
||||
return { check };
|
||||
}
|
||||
if (
|
||||
check !== "available" &&
|
||||
check !== "downloaded" &&
|
||||
check !== "targetBelowMinimum"
|
||||
) {
|
||||
return invalidDevelopmentScenario(
|
||||
`unknown updater outcome ${JSON.stringify(check)}`
|
||||
);
|
||||
}
|
||||
const download =
|
||||
options.preset === "startup-download-error"
|
||||
? "error"
|
||||
: env[names.download]?.trim() || "success";
|
||||
if (download !== "success" && download !== "error") {
|
||||
return invalidDevelopmentScenario(
|
||||
`${names.download} must be success or error`
|
||||
);
|
||||
}
|
||||
const install = env[names.install]?.trim() || "simulated";
|
||||
if (install !== "simulated" && install !== "error") {
|
||||
return invalidDevelopmentScenario(
|
||||
`${names.install} must be simulated or error`
|
||||
);
|
||||
}
|
||||
return {
|
||||
check,
|
||||
download,
|
||||
install,
|
||||
latestVersion: validateStrictDevelopmentSemVer(
|
||||
readRequiredDevelopmentEnvironment(env, names.latestVersion),
|
||||
names.latestVersion
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
function validateLoopbackUrl(raw: string): string {
|
||||
let parsed: URL;
|
||||
try {
|
||||
parsed = new URL(raw);
|
||||
} catch {
|
||||
return invalidDevelopmentScenario("mock server URL must be a valid URL");
|
||||
}
|
||||
if (
|
||||
parsed.protocol !== "http:" ||
|
||||
parsed.hostname !== "127.0.0.1" ||
|
||||
parsed.username ||
|
||||
parsed.password ||
|
||||
parsed.search ||
|
||||
parsed.hash ||
|
||||
(parsed.pathname !== "" && parsed.pathname !== "/")
|
||||
) {
|
||||
return invalidDevelopmentScenario(
|
||||
"mock server URL must be an http://127.0.0.1 origin"
|
||||
);
|
||||
}
|
||||
return parsed.origin;
|
||||
}
|
||||
|
||||
function rejectLoopbackPolicyEnvironment(
|
||||
env: Readonly<Record<string, string | undefined>>
|
||||
): void {
|
||||
const names = desktopUpdateAdmissionDevelopmentEnvironment;
|
||||
for (const name of [
|
||||
names.featureKeys,
|
||||
names.minimumVersion,
|
||||
names.policy,
|
||||
names.policySequence,
|
||||
names.scenario
|
||||
]) {
|
||||
if (env[name]?.trim()) {
|
||||
invalidDevelopmentScenario(
|
||||
`${name} belongs to the loopback mock server, not the client`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function validateUpdater(
|
||||
updater: DesktopUpdateDevelopmentUpdaterScenario,
|
||||
currentVersion: string
|
||||
): void {
|
||||
if (!("latestVersion" in updater)) {
|
||||
return;
|
||||
}
|
||||
const current = parseDevelopmentManagedVersion(currentVersion);
|
||||
if (!current) {
|
||||
invalidDevelopmentScenario(
|
||||
"an available updater requires a managed currentVersion"
|
||||
);
|
||||
}
|
||||
const latest = parseDevelopmentManagedVersion(updater.latestVersion);
|
||||
if (!latest || latest.channel !== current.channel) {
|
||||
invalidDevelopmentScenario(
|
||||
`latestVersion must use the ${current.channel} channel`
|
||||
);
|
||||
}
|
||||
if (compareDevelopmentManagedVersions(latest, current) <= 0) {
|
||||
invalidDevelopmentScenario(
|
||||
"an available updater requires latestVersion above currentVersion"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export function resolveDesktopUpdateDevelopmentScenario(input: {
|
||||
env: Readonly<Record<string, string | undefined>>;
|
||||
isPackaged: boolean;
|
||||
}): DesktopUpdateDevelopmentScenario | null {
|
||||
if (input.isPackaged || !readDevelopmentEnabled(input.env)) {
|
||||
return null;
|
||||
}
|
||||
const names = desktopUpdateAdmissionDevelopmentEnvironment;
|
||||
const currentVersion = validateStrictDevelopmentSemVer(
|
||||
readRequiredDevelopmentEnvironment(input.env, names.currentVersion),
|
||||
names.currentVersion
|
||||
);
|
||||
const transport = input.env[names.transport]?.trim() || "in-process";
|
||||
if (transport !== "in-process" && transport !== "loopback") {
|
||||
return invalidDevelopmentScenario(
|
||||
`${names.transport} must be in-process or loopback`
|
||||
);
|
||||
}
|
||||
if (transport === "loopback") {
|
||||
rejectLoopbackPolicyEnvironment(input.env);
|
||||
}
|
||||
const preset =
|
||||
transport === "in-process" ? input.env[names.scenario]?.trim() : undefined;
|
||||
const updater = resolveUpdater(input.env, {
|
||||
defaultCheck: transport === "in-process" ? "available" : "unavailable",
|
||||
preset
|
||||
});
|
||||
const scenario: DesktopUpdateDevelopmentScenario =
|
||||
transport === "in-process"
|
||||
? {
|
||||
currentVersion,
|
||||
mockServerUrl: null,
|
||||
transport,
|
||||
updater
|
||||
}
|
||||
: {
|
||||
currentVersion,
|
||||
mockServerUrl: validateLoopbackUrl(
|
||||
readRequiredDevelopmentEnvironment(input.env, names.mockServerUrl)
|
||||
),
|
||||
transport,
|
||||
updater
|
||||
};
|
||||
validateUpdater(scenario.updater, currentVersion);
|
||||
if (scenario.transport === "in-process") {
|
||||
return Object.freeze({
|
||||
...scenario,
|
||||
updater: Object.freeze({ ...scenario.updater })
|
||||
});
|
||||
}
|
||||
return Object.freeze({
|
||||
...scenario,
|
||||
updater: Object.freeze({ ...scenario.updater })
|
||||
});
|
||||
}
|
||||
|
||||
export function resolveDesktopUpdateAdmissionDevelopment(input: {
|
||||
applicationVersion: string;
|
||||
env: Readonly<Record<string, string | undefined>>;
|
||||
isPackaged: boolean;
|
||||
}): DesktopUpdateDevelopmentResolution {
|
||||
const applicationVersion = input.applicationVersion.trim();
|
||||
if (!applicationVersion) {
|
||||
throw new Error("desktop application version is required");
|
||||
}
|
||||
const scenario = resolveDesktopUpdateDevelopmentScenario(input);
|
||||
if (input.isPackaged) {
|
||||
return {
|
||||
runtime: {
|
||||
checksEnabled: true,
|
||||
currentVersion: applicationVersion,
|
||||
development: false
|
||||
},
|
||||
scenario: null
|
||||
};
|
||||
}
|
||||
if (!scenario) {
|
||||
return {
|
||||
runtime: {
|
||||
checksEnabled: false,
|
||||
currentVersion: applicationVersion,
|
||||
development: false
|
||||
},
|
||||
scenario: null
|
||||
};
|
||||
}
|
||||
return {
|
||||
runtime: {
|
||||
checksEnabled: true,
|
||||
currentVersion: scenario.currentVersion,
|
||||
development: true
|
||||
},
|
||||
scenario
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
import type { DesktopUpdateDevelopmentScenario } from "./scenario.ts";
|
||||
|
||||
type DriverDisposer = () => void;
|
||||
|
||||
export interface DevelopmentUpdateInfo {
|
||||
downloadedFile: string;
|
||||
files: never[];
|
||||
path: string;
|
||||
releaseDate: string;
|
||||
releaseName: string;
|
||||
sha512: string;
|
||||
version: string;
|
||||
}
|
||||
|
||||
export interface DevelopmentUpdateProgress {
|
||||
bytesPerSecond: number;
|
||||
delta: number;
|
||||
percent: number;
|
||||
total: number;
|
||||
transferred: number;
|
||||
}
|
||||
|
||||
export interface DevelopmentAppUpdateDriver {
|
||||
checkForUpdates(): Promise<void>;
|
||||
configure(...args: unknown[]): void;
|
||||
downloadUpdate(): Promise<void>;
|
||||
onCheckingForUpdate(listener: () => void): DriverDisposer;
|
||||
onDownloadProgress(
|
||||
listener: (progress: DevelopmentUpdateProgress) => void
|
||||
): DriverDisposer;
|
||||
onError(listener: (error: Error) => void): DriverDisposer;
|
||||
onUpdateAvailable(
|
||||
listener: (info: DevelopmentUpdateInfo) => void
|
||||
): DriverDisposer;
|
||||
onUpdateDownloaded(
|
||||
listener: (info: DevelopmentUpdateInfo) => void
|
||||
): DriverDisposer;
|
||||
onUpdateNotAvailable(
|
||||
listener: (info: DevelopmentUpdateInfo) => void
|
||||
): DriverDisposer;
|
||||
quitAndInstall(): void;
|
||||
setFeedUrl(_url: string): void;
|
||||
}
|
||||
|
||||
export class DevelopmentInstallSuppressedError extends Error {
|
||||
public constructor() {
|
||||
super(
|
||||
"development update simulation does not install or restart the application"
|
||||
);
|
||||
this.name = "DevelopmentInstallSuppressedError";
|
||||
}
|
||||
}
|
||||
|
||||
export class DevelopmentInstallError extends Error {
|
||||
public constructor() {
|
||||
super("development update installation failed");
|
||||
this.name = "DevelopmentInstallError";
|
||||
}
|
||||
}
|
||||
|
||||
export function completeDevelopmentUpdateInstallation(
|
||||
scenario: DesktopUpdateDevelopmentScenario
|
||||
): never {
|
||||
if (
|
||||
scenario.updater.check === "available" ||
|
||||
scenario.updater.check === "downloaded" ||
|
||||
scenario.updater.check === "targetBelowMinimum"
|
||||
) {
|
||||
if (scenario.updater.install === "error") {
|
||||
throw new DevelopmentInstallError();
|
||||
}
|
||||
}
|
||||
throw new DevelopmentInstallSuppressedError();
|
||||
}
|
||||
|
||||
export function createDevelopmentAppUpdateDriver(
|
||||
scenario: DesktopUpdateDevelopmentScenario
|
||||
): DevelopmentAppUpdateDriver {
|
||||
const updater = scenario.updater;
|
||||
const checkingListeners = new Set<() => void>();
|
||||
const progressListeners = new Set<
|
||||
(progress: DevelopmentUpdateProgress) => void
|
||||
>();
|
||||
const errorListeners = new Set<(error: Error) => void>();
|
||||
const availableListeners = new Set<(info: DevelopmentUpdateInfo) => void>();
|
||||
const downloadedListeners = new Set<(info: DevelopmentUpdateInfo) => void>();
|
||||
const notAvailableListeners = new Set<
|
||||
(info: DevelopmentUpdateInfo) => void
|
||||
>();
|
||||
const latestVersion =
|
||||
updater.check === "available" ||
|
||||
updater.check === "downloaded" ||
|
||||
updater.check === "targetBelowMinimum"
|
||||
? updater.latestVersion
|
||||
: scenario.currentVersion;
|
||||
const updateInfo = (): DevelopmentUpdateInfo => ({
|
||||
downloadedFile: "development-update-simulation",
|
||||
files: [],
|
||||
path: "",
|
||||
releaseDate: new Date().toISOString(),
|
||||
releaseName: latestVersion,
|
||||
sha512: "",
|
||||
version: latestVersion
|
||||
});
|
||||
const emitError = (message: string): Error => {
|
||||
const error = new Error(message);
|
||||
for (const listener of errorListeners) {
|
||||
listener(error);
|
||||
}
|
||||
return error;
|
||||
};
|
||||
|
||||
return {
|
||||
async checkForUpdates() {
|
||||
for (const listener of checkingListeners) {
|
||||
listener();
|
||||
}
|
||||
if (updater.check === "error") {
|
||||
throw emitError("Development update check failed");
|
||||
}
|
||||
const info = updateInfo();
|
||||
if (updater.check === "unavailable") {
|
||||
for (const listener of notAvailableListeners) {
|
||||
listener(info);
|
||||
}
|
||||
return;
|
||||
}
|
||||
for (const listener of availableListeners) {
|
||||
listener(info);
|
||||
}
|
||||
if (updater.check === "downloaded") {
|
||||
for (const listener of downloadedListeners) {
|
||||
listener(info);
|
||||
}
|
||||
}
|
||||
},
|
||||
configure() {},
|
||||
async downloadUpdate() {
|
||||
if (!("download" in updater)) {
|
||||
throw emitError("Development update is unavailable");
|
||||
}
|
||||
if (updater.download === "error") {
|
||||
throw emitError("Development update download failed");
|
||||
}
|
||||
const info = updateInfo();
|
||||
for (const listener of progressListeners) {
|
||||
listener({
|
||||
bytesPerSecond: 100,
|
||||
delta: 100,
|
||||
percent: 100,
|
||||
total: 100,
|
||||
transferred: 100
|
||||
});
|
||||
}
|
||||
for (const listener of downloadedListeners) {
|
||||
listener(info);
|
||||
}
|
||||
},
|
||||
onCheckingForUpdate(listener) {
|
||||
checkingListeners.add(listener);
|
||||
return () => checkingListeners.delete(listener);
|
||||
},
|
||||
onDownloadProgress(listener) {
|
||||
progressListeners.add(listener);
|
||||
return () => progressListeners.delete(listener);
|
||||
},
|
||||
onError(listener) {
|
||||
errorListeners.add(listener);
|
||||
return () => errorListeners.delete(listener);
|
||||
},
|
||||
onUpdateAvailable(listener) {
|
||||
availableListeners.add(listener);
|
||||
return () => availableListeners.delete(listener);
|
||||
},
|
||||
onUpdateDownloaded(listener) {
|
||||
downloadedListeners.add(listener);
|
||||
return () => downloadedListeners.delete(listener);
|
||||
},
|
||||
onUpdateNotAvailable(listener) {
|
||||
notAvailableListeners.add(listener);
|
||||
return () => notAvailableListeners.delete(listener);
|
||||
},
|
||||
quitAndInstall() {
|
||||
completeDevelopmentUpdateInstallation(scenario);
|
||||
},
|
||||
setFeedUrl() {}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import type { DesktopUpdateChannel } from "../contracts/index.ts";
|
||||
import { invalidDevelopmentScenario } from "./environment.ts";
|
||||
|
||||
const strictSemVerPattern =
|
||||
/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/u;
|
||||
const managedStablePattern =
|
||||
/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u;
|
||||
const managedRcPattern =
|
||||
/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)-rc\.(0|[1-9]\d*)$/u;
|
||||
|
||||
export type DevelopmentManagedVersion = {
|
||||
channel: DesktopUpdateChannel;
|
||||
core: [string, string, string];
|
||||
rc: string | null;
|
||||
};
|
||||
|
||||
export function validateStrictDevelopmentSemVer(
|
||||
value: string,
|
||||
name: string
|
||||
): string {
|
||||
const normalized = value.trim();
|
||||
const match = strictSemVerPattern.exec(normalized);
|
||||
if (!match) {
|
||||
return invalidDevelopmentScenario(`${name} must be valid SemVer`);
|
||||
}
|
||||
const prerelease = match[4];
|
||||
if (prerelease) {
|
||||
for (const identifier of prerelease.split(".")) {
|
||||
if (
|
||||
/^\d+$/u.test(identifier) &&
|
||||
identifier.length > 1 &&
|
||||
identifier[0] === "0"
|
||||
) {
|
||||
return invalidDevelopmentScenario(`${name} must be valid SemVer`);
|
||||
}
|
||||
}
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
export function parseDevelopmentManagedVersion(
|
||||
value: string
|
||||
): DevelopmentManagedVersion | null {
|
||||
const stable = managedStablePattern.exec(value);
|
||||
if (stable) {
|
||||
return {
|
||||
channel: "stable",
|
||||
core: [stable[1]!, stable[2]!, stable[3]!],
|
||||
rc: null
|
||||
};
|
||||
}
|
||||
const rc = managedRcPattern.exec(value);
|
||||
if (!rc) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
channel: "rc",
|
||||
core: [rc[1]!, rc[2]!, rc[3]!],
|
||||
rc: rc[4]!
|
||||
};
|
||||
}
|
||||
|
||||
function compareNumericIdentifier(left: string, right: string): number {
|
||||
if (left.length !== right.length) {
|
||||
return left.length < right.length ? -1 : 1;
|
||||
}
|
||||
return left === right ? 0 : left < right ? -1 : 1;
|
||||
}
|
||||
|
||||
export function compareDevelopmentManagedVersions(
|
||||
left: DevelopmentManagedVersion,
|
||||
right: DevelopmentManagedVersion
|
||||
): number {
|
||||
for (const index of [0, 1, 2] as const) {
|
||||
const compared = compareNumericIdentifier(
|
||||
left.core[index],
|
||||
right.core[index]
|
||||
);
|
||||
if (compared !== 0) {
|
||||
return compared;
|
||||
}
|
||||
}
|
||||
if (left.rc === right.rc) {
|
||||
return 0;
|
||||
}
|
||||
if (left.rc === null) {
|
||||
return 1;
|
||||
}
|
||||
if (right.rc === null) {
|
||||
return -1;
|
||||
}
|
||||
return compareNumericIdentifier(left.rc, right.rc);
|
||||
}
|
||||
+362
@@ -0,0 +1,362 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { EventEmitter } from "node:events";
|
||||
import test from "node:test";
|
||||
import type {
|
||||
DesktopUpdateAdmissionBackend,
|
||||
DesktopUpdateAdmissionSnapshot,
|
||||
MinimumVersionAppUpdateService
|
||||
} from "../contracts/index.ts";
|
||||
import { createDesktopUpdateAdmissionController } from "./createDesktopUpdateAdmissionController.ts";
|
||||
|
||||
function allowedSnapshot(): DesktopUpdateAdmissionSnapshot<"tutti-desktop"> {
|
||||
const platform =
|
||||
process.platform === "darwin"
|
||||
? "macos"
|
||||
: process.platform === "win32"
|
||||
? "windows"
|
||||
: "linux";
|
||||
const architecture = process.arch === "arm64" ? "arm64" : "x64";
|
||||
return {
|
||||
featureAvailability: {
|
||||
fetchedAt: "2026-08-02T09:00:00Z",
|
||||
keys: ["workspace.example"],
|
||||
policyRevision: "v1",
|
||||
source: "cache"
|
||||
},
|
||||
identity: {
|
||||
architecture,
|
||||
currentVersion: "1.0.0",
|
||||
platform,
|
||||
product: "tutti-desktop"
|
||||
},
|
||||
lastAttemptAt: "2026-08-02T09:00:00Z",
|
||||
nextForegroundCheckAt: "2026-08-02T09:30:00Z",
|
||||
policy: {
|
||||
response: {
|
||||
channel: "stable",
|
||||
decision: "allowed",
|
||||
minimumVersion: "1.0.0",
|
||||
policyRevision: "v1",
|
||||
reason: "meetsMinimum"
|
||||
},
|
||||
status: "resolved"
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function upgradeRequiredSnapshot(): DesktopUpdateAdmissionSnapshot<"tutti-desktop"> {
|
||||
const snapshot = allowedSnapshot();
|
||||
return {
|
||||
...snapshot,
|
||||
identity: {
|
||||
...snapshot.identity,
|
||||
currentVersion: "0.9.0"
|
||||
},
|
||||
policy: {
|
||||
response: {
|
||||
channel: "stable",
|
||||
decision: "upgradeRequired",
|
||||
minimumVersion: "1.0.0",
|
||||
policyRevision: "v1",
|
||||
reason: "belowMinimum"
|
||||
},
|
||||
status: "resolved"
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function failedOpenSnapshot(): DesktopUpdateAdmissionSnapshot<"tutti-desktop"> {
|
||||
const snapshot = upgradeRequiredSnapshot();
|
||||
return {
|
||||
...snapshot,
|
||||
nextForegroundCheckAt: null,
|
||||
policy: {
|
||||
failure: { kind: "timeout" },
|
||||
status: "failedOpen"
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function updateService(): MinimumVersionAppUpdateService {
|
||||
return {
|
||||
async acquireMandatorySession() {
|
||||
throw new Error("not used");
|
||||
},
|
||||
getState() {
|
||||
return {
|
||||
channel: "stable",
|
||||
checkedAt: null,
|
||||
currentVersion: "1.0.0",
|
||||
downloadedBytes: null,
|
||||
downloadPercent: null,
|
||||
latestVersion: null,
|
||||
message: null,
|
||||
policy: "prompt",
|
||||
releaseDate: null,
|
||||
releaseName: null,
|
||||
releaseNotesUrl: null,
|
||||
status: "idle",
|
||||
totalBytes: null
|
||||
};
|
||||
},
|
||||
subscribe() {
|
||||
return () => undefined;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
test("controller consumes daemon startup and foreground snapshots without owning timing", async () => {
|
||||
const app = new EventEmitter();
|
||||
const snapshot = allowedSnapshot();
|
||||
const calls: string[] = [];
|
||||
const backend: DesktopUpdateAdmissionBackend<"tutti-desktop"> = {
|
||||
async getStartupSnapshot() {
|
||||
calls.push("startup");
|
||||
return snapshot;
|
||||
},
|
||||
async refresh(trigger) {
|
||||
calls.push(trigger);
|
||||
return {
|
||||
performed: false,
|
||||
skipReason: "throttled",
|
||||
snapshot
|
||||
};
|
||||
}
|
||||
};
|
||||
const featureSnapshots: DesktopUpdateAdmissionSnapshot<"tutti-desktop">[] =
|
||||
[];
|
||||
const registeredHandlers = new Map<string, (...args: unknown[]) => unknown>();
|
||||
const controller = createDesktopUpdateAdmissionController({
|
||||
backend,
|
||||
electron: {
|
||||
app: app as never,
|
||||
BrowserWindow: class {
|
||||
constructor() {
|
||||
throw new Error("allowed policy must not open an upgrade window");
|
||||
}
|
||||
} as never,
|
||||
ipcMain: {
|
||||
handle(channel: string, handler: (...args: unknown[]) => unknown) {
|
||||
registeredHandlers.set(channel, handler);
|
||||
},
|
||||
removeHandler(channel: string) {
|
||||
registeredHandlers.delete(channel);
|
||||
}
|
||||
} as never,
|
||||
shell: { openExternal: async () => undefined } as never
|
||||
},
|
||||
featureAvailability: {
|
||||
acceptDaemonSnapshot(value) {
|
||||
featureSnapshots.push(value);
|
||||
}
|
||||
},
|
||||
listBusinessWindows: () => [],
|
||||
logger: { error() {}, info() {} },
|
||||
manualDownloadUrl: () => "https://tutti.sh/desktop/download",
|
||||
onPolicyReleased() {},
|
||||
preloadPath: "/preload.cjs",
|
||||
product: "tutti-desktop",
|
||||
rendererFilePath: "/minimum-version.html",
|
||||
runtime: {
|
||||
checksEnabled: true,
|
||||
currentVersion: "1.0.0",
|
||||
development: true
|
||||
},
|
||||
updateService: updateService()
|
||||
});
|
||||
|
||||
assert.equal(await controller.runStartupCheck(), false);
|
||||
await controller.checkAfterForegroundRestore();
|
||||
assert.deepEqual(calls, ["startup", "foreground"]);
|
||||
assert.equal(featureSnapshots.length, 2);
|
||||
controller.dispose();
|
||||
assert.equal(registeredHandlers.size, 0);
|
||||
});
|
||||
|
||||
test("startup admission opens a modal upgrade window over the visible business window", async () => {
|
||||
const app = new EventEmitter();
|
||||
const snapshot = upgradeRequiredSnapshot();
|
||||
let businessWindowHidden = false;
|
||||
let upgradeWindowCreated = false;
|
||||
const upgradeWindowOptions: Array<Record<string, unknown>> = [];
|
||||
const businessWindow = {
|
||||
focus() {},
|
||||
hide() {
|
||||
businessWindowHidden = true;
|
||||
},
|
||||
isDestroyed: () => false,
|
||||
isFocused: () => true,
|
||||
isMinimized: () => false,
|
||||
isVisible: () => true,
|
||||
minimize() {},
|
||||
show() {}
|
||||
};
|
||||
class UpgradeWindow {
|
||||
public readonly webContents = {
|
||||
id: 1,
|
||||
send() {},
|
||||
setWindowOpenHandler() {},
|
||||
on() {}
|
||||
};
|
||||
|
||||
public constructor(options: Record<string, unknown>) {
|
||||
upgradeWindowCreated = true;
|
||||
upgradeWindowOptions.push(options);
|
||||
}
|
||||
|
||||
public destroy() {}
|
||||
public focus() {}
|
||||
public isDestroyed() {
|
||||
return false;
|
||||
}
|
||||
public isFocused() {
|
||||
return false;
|
||||
}
|
||||
public isMinimized() {
|
||||
return false;
|
||||
}
|
||||
public isVisible() {
|
||||
return false;
|
||||
}
|
||||
public loadFile() {
|
||||
return Promise.resolve();
|
||||
}
|
||||
public loadURL() {
|
||||
return Promise.resolve();
|
||||
}
|
||||
public minimize() {}
|
||||
public on() {}
|
||||
public once() {}
|
||||
public show() {}
|
||||
}
|
||||
const controller = createDesktopUpdateAdmissionController({
|
||||
backend: {
|
||||
async getStartupSnapshot() {
|
||||
return snapshot;
|
||||
},
|
||||
async refresh() {
|
||||
return { performed: false, skipReason: "throttled", snapshot };
|
||||
}
|
||||
},
|
||||
electron: {
|
||||
app: app as never,
|
||||
BrowserWindow: UpgradeWindow as never,
|
||||
ipcMain: {
|
||||
handle() {},
|
||||
removeHandler() {}
|
||||
} as never,
|
||||
shell: { openExternal: async () => undefined } as never
|
||||
},
|
||||
listBusinessWindows: () => [businessWindow as never],
|
||||
logger: { error() {}, info() {} },
|
||||
manualDownloadUrl: () => "https://tutti.sh/desktop/download",
|
||||
onPolicyReleased() {},
|
||||
preloadPath: "/preload.cjs",
|
||||
product: "tutti-desktop",
|
||||
rendererFilePath: "/minimum-version.html",
|
||||
runtime: {
|
||||
checksEnabled: true,
|
||||
currentVersion: "0.9.0",
|
||||
development: true
|
||||
},
|
||||
updateService: updateService()
|
||||
});
|
||||
|
||||
assert.equal(await controller.runStartupCheck(), true);
|
||||
assert.equal(businessWindowHidden, false);
|
||||
assert.equal(upgradeWindowCreated, true);
|
||||
assert.equal(upgradeWindowOptions[0]?.modal, true);
|
||||
assert.equal(upgradeWindowOptions[0]?.parent, businessWindow);
|
||||
controller.dispose();
|
||||
});
|
||||
|
||||
test("foreground admission retries a failed-open check after network recovery", async () => {
|
||||
const app = new EventEmitter();
|
||||
const failedSnapshot = failedOpenSnapshot();
|
||||
const recoveredSnapshot = upgradeRequiredSnapshot();
|
||||
const calls: string[] = [];
|
||||
let resolveUpgradeWindowCreated: (() => void) | undefined;
|
||||
const upgradeWindowCreated = new Promise<void>((resolve) => {
|
||||
resolveUpgradeWindowCreated = resolve;
|
||||
});
|
||||
const businessWindow = {
|
||||
isDestroyed: () => false,
|
||||
isFocused: () => true,
|
||||
isVisible: () => true
|
||||
};
|
||||
class UpgradeWindow {
|
||||
public readonly webContents = {
|
||||
id: 1,
|
||||
send() {},
|
||||
setWindowOpenHandler() {},
|
||||
on() {}
|
||||
};
|
||||
|
||||
public constructor() {
|
||||
resolveUpgradeWindowCreated?.();
|
||||
}
|
||||
|
||||
public destroy() {}
|
||||
public focus() {}
|
||||
public isDestroyed() {
|
||||
return false;
|
||||
}
|
||||
public loadFile() {
|
||||
return Promise.resolve();
|
||||
}
|
||||
public loadURL() {
|
||||
return Promise.resolve();
|
||||
}
|
||||
public on() {}
|
||||
public once() {}
|
||||
public show() {}
|
||||
}
|
||||
const controller = createDesktopUpdateAdmissionController({
|
||||
backend: {
|
||||
async getStartupSnapshot() {
|
||||
return failedSnapshot;
|
||||
},
|
||||
async refresh(trigger) {
|
||||
calls.push(trigger);
|
||||
return {
|
||||
performed: true,
|
||||
snapshot: calls.length === 1 ? failedSnapshot : recoveredSnapshot
|
||||
};
|
||||
}
|
||||
},
|
||||
electron: {
|
||||
app: app as never,
|
||||
BrowserWindow: UpgradeWindow as never,
|
||||
ipcMain: {
|
||||
handle() {},
|
||||
removeHandler() {}
|
||||
} as never,
|
||||
shell: { openExternal: async () => undefined } as never
|
||||
},
|
||||
foregroundFailureRetryDelayMs: 1,
|
||||
listBusinessWindows: () => [businessWindow as never],
|
||||
logger: { error() {}, info() {} },
|
||||
manualDownloadUrl: () => "https://tutti.sh/desktop/download",
|
||||
onPolicyReleased() {},
|
||||
preloadPath: "/preload.cjs",
|
||||
product: "tutti-desktop",
|
||||
rendererFilePath: "/minimum-version.html",
|
||||
runtime: {
|
||||
checksEnabled: true,
|
||||
currentVersion: "0.9.0",
|
||||
development: true
|
||||
},
|
||||
updateService: updateService()
|
||||
});
|
||||
|
||||
await controller.checkAfterForegroundRestore();
|
||||
await Promise.race([
|
||||
upgradeWindowCreated,
|
||||
new Promise<never>((_, reject) =>
|
||||
setTimeout(() => reject(new Error("upgrade window was not created")), 500)
|
||||
)
|
||||
]);
|
||||
|
||||
assert.deepEqual(calls, ["foreground", "retry"]);
|
||||
controller.dispose();
|
||||
});
|
||||
+634
@@ -0,0 +1,634 @@
|
||||
import type {
|
||||
BrowserWindow as ElectronBrowserWindow,
|
||||
BrowserWindowConstructorOptions
|
||||
} from "electron";
|
||||
import {
|
||||
desktopUpdateAdmissionIpcChannels,
|
||||
type DesktopUpdateAdmissionBackend,
|
||||
type DesktopUpdateAdmissionRuntime,
|
||||
type DesktopUpdateAdmissionSnapshot,
|
||||
type DesktopProduct,
|
||||
type MinimumVersionAppUpdateService,
|
||||
type MinimumVersionCheckRequest,
|
||||
type MinimumVersionCheckResult,
|
||||
type MinimumVersionUpgradeError,
|
||||
type MinimumVersionUpgradeState,
|
||||
type UpgradeRequiredMinimumVersionCheckResult,
|
||||
type MandatoryDesktopUpdateSession,
|
||||
type MandatoryDesktopUpdateTarget
|
||||
} from "../contracts/index.ts";
|
||||
import {
|
||||
resolveMinimumVersionRuntimeTarget,
|
||||
validateMinimumVersionResponse
|
||||
} from "../core/index.ts";
|
||||
import { DevelopmentInstallSuppressedError } from "../development/updaterDriver.ts";
|
||||
import { MandatoryUpdateTargetError } from "../mandatory-updater/index.ts";
|
||||
|
||||
export interface DesktopUpdateAdmissionElectronRuntime {
|
||||
app: typeof import("electron").app;
|
||||
BrowserWindow: typeof import("electron").BrowserWindow;
|
||||
ipcMain: typeof import("electron").ipcMain;
|
||||
shell: typeof import("electron").shell;
|
||||
}
|
||||
|
||||
export interface DesktopUpdateAdmissionLogger {
|
||||
info(message: string): void;
|
||||
error(message: string): void;
|
||||
}
|
||||
|
||||
export interface DesktopUpdateAdmissionController {
|
||||
runStartupCheck(): Promise<boolean>;
|
||||
checkAfterForegroundRestore(): Promise<void>;
|
||||
dispose(): void;
|
||||
}
|
||||
|
||||
export interface DesktopUpdateAdmissionControllerOptions<
|
||||
TProduct extends DesktopProduct
|
||||
> {
|
||||
product: TProduct;
|
||||
runtime: DesktopUpdateAdmissionRuntime;
|
||||
electron: DesktopUpdateAdmissionElectronRuntime;
|
||||
backend: DesktopUpdateAdmissionBackend<TProduct>;
|
||||
featureAvailability?: {
|
||||
acceptDaemonSnapshot(
|
||||
snapshot: DesktopUpdateAdmissionSnapshot<TProduct>
|
||||
): void;
|
||||
};
|
||||
updateService: MinimumVersionAppUpdateService;
|
||||
logger: DesktopUpdateAdmissionLogger;
|
||||
onPolicyReleased(): void | Promise<void>;
|
||||
preloadPath: string;
|
||||
rendererFilePath: string;
|
||||
rendererUrl?: string;
|
||||
manualDownloadUrl(
|
||||
response: UpgradeRequiredMinimumVersionCheckResult<TProduct>
|
||||
): string;
|
||||
listBusinessWindows(): ElectronBrowserWindow[];
|
||||
icon?: BrowserWindowConstructorOptions["icon"];
|
||||
foregroundFailureRetryDelayMs?: number;
|
||||
}
|
||||
|
||||
interface PolicyCheckOutcome<TProduct extends DesktopProduct> {
|
||||
response: MinimumVersionCheckResult<TProduct> | null;
|
||||
retryable: boolean;
|
||||
}
|
||||
|
||||
function logMinimumVersionCheck(
|
||||
logger: DesktopUpdateAdmissionLogger,
|
||||
level: "info" | "error",
|
||||
details: Record<string, unknown>
|
||||
): void {
|
||||
logger[level](`[minimum-version-check] ${JSON.stringify(details)}`);
|
||||
}
|
||||
|
||||
export function createDesktopUpdateAdmissionController<
|
||||
TProduct extends DesktopProduct
|
||||
>(
|
||||
options: DesktopUpdateAdmissionControllerOptions<TProduct>
|
||||
): DesktopUpdateAdmissionController {
|
||||
const { app, BrowserWindow, ipcMain, shell } = options.electron;
|
||||
let foregroundPrompted = false;
|
||||
let state: MinimumVersionUpgradeState<TProduct> | null = null;
|
||||
let upgradeWindow: ElectronBrowserWindow | null = null;
|
||||
let mode: "startup" | "foreground" = "startup";
|
||||
let forcedFlowStarted = false;
|
||||
let installRequested = false;
|
||||
let disposed = false;
|
||||
let activeCheck: Promise<PolicyCheckOutcome<TProduct>> | null = null;
|
||||
let activeForcedFlow: Promise<void> | null = null;
|
||||
let foregroundRetryTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let appQuitStarted = false;
|
||||
let mandatoryUpdateSession: MandatoryDesktopUpdateSession | null = null;
|
||||
const lifecycleAbort = new AbortController();
|
||||
const foregroundFailureRetryDelayMs =
|
||||
options.foregroundFailureRetryDelayMs ?? 5_000;
|
||||
|
||||
const handleBeforeQuit = (): void => {
|
||||
appQuitStarted = true;
|
||||
};
|
||||
app.on("before-quit", handleBeforeQuit);
|
||||
|
||||
const emitState = (): void => {
|
||||
if (state && upgradeWindow && !upgradeWindow.isDestroyed()) {
|
||||
upgradeWindow.webContents.send(
|
||||
desktopUpdateAdmissionIpcChannels.state,
|
||||
state
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const applyState = (
|
||||
phase: MinimumVersionUpgradeState["phase"],
|
||||
update = options.updateService.getState(),
|
||||
message: MinimumVersionUpgradeError | null = null
|
||||
): void => {
|
||||
if (!state) {
|
||||
return;
|
||||
}
|
||||
state = { ...state, message, phase, update };
|
||||
emitState();
|
||||
};
|
||||
|
||||
const closeUpgradeWindow = (): void => {
|
||||
const currentWindow = upgradeWindow;
|
||||
upgradeWindow = null;
|
||||
if (currentWindow && !currentWindow.isDestroyed()) {
|
||||
currentWindow.destroy();
|
||||
}
|
||||
};
|
||||
|
||||
const openUpgradeWindow = (nextMode: "startup" | "foreground"): void => {
|
||||
if (upgradeWindow && !upgradeWindow.isDestroyed()) {
|
||||
upgradeWindow.show();
|
||||
upgradeWindow.focus();
|
||||
return;
|
||||
}
|
||||
mode = nextMode;
|
||||
const businessWindows = options
|
||||
.listBusinessWindows()
|
||||
.filter(
|
||||
(candidate) => candidate !== upgradeWindow && !candidate.isDestroyed()
|
||||
);
|
||||
const parent =
|
||||
businessWindows.find((candidate) => candidate.isFocused()) ??
|
||||
businessWindows.find((candidate) => candidate.isVisible()) ??
|
||||
businessWindows[0];
|
||||
const window = new BrowserWindow({
|
||||
autoHideMenuBar: true,
|
||||
fullscreenable: false,
|
||||
height: 420,
|
||||
icon: options.icon,
|
||||
maximizable: false,
|
||||
minHeight: 380,
|
||||
minWidth: 480,
|
||||
modal: parent !== undefined,
|
||||
parent,
|
||||
resizable: false,
|
||||
show: false,
|
||||
webPreferences: {
|
||||
contextIsolation: true,
|
||||
nodeIntegration: false,
|
||||
preload: options.preloadPath,
|
||||
sandbox: true
|
||||
},
|
||||
width: 520
|
||||
});
|
||||
upgradeWindow = window;
|
||||
window.webContents.setWindowOpenHandler(() => ({ action: "deny" }));
|
||||
window.webContents.on("will-navigate", (event) => event.preventDefault());
|
||||
window.on("close", (event) => {
|
||||
if (!appQuitStarted && (mode === "startup" || forcedFlowStarted)) {
|
||||
event.preventDefault();
|
||||
app.quit();
|
||||
}
|
||||
});
|
||||
window.on("closed", () => {
|
||||
if (upgradeWindow === window) {
|
||||
upgradeWindow = null;
|
||||
}
|
||||
});
|
||||
window.once("ready-to-show", () => {
|
||||
if (!window.isDestroyed()) {
|
||||
window.show();
|
||||
}
|
||||
});
|
||||
const search = `mode=${nextMode}`;
|
||||
if (options.rendererUrl) {
|
||||
void window.loadURL(`${options.rendererUrl}?${search}`);
|
||||
} else {
|
||||
void window.loadFile(options.rendererFilePath, { search });
|
||||
}
|
||||
};
|
||||
|
||||
const requestPayload = (): MinimumVersionCheckRequest<TProduct> | null => {
|
||||
const target = resolveMinimumVersionRuntimeTarget(
|
||||
process.platform,
|
||||
process.arch
|
||||
);
|
||||
if (!target) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
...target,
|
||||
currentVersion: options.runtime.currentVersion,
|
||||
product: options.product
|
||||
};
|
||||
};
|
||||
|
||||
const runPolicyCheck = async (
|
||||
stage: "startup" | "foreground" | "retry"
|
||||
): Promise<PolicyCheckOutcome<TProduct>> => {
|
||||
const request = requestPayload();
|
||||
if (!request) {
|
||||
logMinimumVersionCheck(options.logger, "info", {
|
||||
architecture: process.arch,
|
||||
decision: "notApplicable",
|
||||
platform: process.platform,
|
||||
reason: "unsupportedRuntime",
|
||||
result: "success",
|
||||
stage
|
||||
});
|
||||
return { response: null, retryable: false };
|
||||
}
|
||||
const controller = new AbortController();
|
||||
const abortForLifecycle = (): void => controller.abort();
|
||||
lifecycleAbort.signal.addEventListener("abort", abortForLifecycle, {
|
||||
once: true
|
||||
});
|
||||
try {
|
||||
const snapshot =
|
||||
stage === "startup"
|
||||
? await options.backend.getStartupSnapshot(controller.signal)
|
||||
: (
|
||||
await options.backend.refresh(
|
||||
stage === "retry" ? "retry" : "foreground",
|
||||
controller.signal
|
||||
)
|
||||
).snapshot;
|
||||
if (
|
||||
snapshot.identity.product !== request.product ||
|
||||
snapshot.identity.platform !== request.platform ||
|
||||
snapshot.identity.architecture !== request.architecture ||
|
||||
snapshot.identity.currentVersion !== request.currentVersion
|
||||
) {
|
||||
throw new Error("desktop update admission daemon identity mismatch");
|
||||
}
|
||||
if (options.featureAvailability) {
|
||||
try {
|
||||
options.featureAvailability.acceptDaemonSnapshot(snapshot);
|
||||
} catch (error) {
|
||||
logMinimumVersionCheck(options.logger, "error", {
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
result: "failure",
|
||||
stage: "feature-availability"
|
||||
});
|
||||
}
|
||||
}
|
||||
if (snapshot.policy.status !== "resolved") {
|
||||
logMinimumVersionCheck(
|
||||
options.logger,
|
||||
snapshot.policy.status === "failedOpen" ? "error" : "info",
|
||||
{
|
||||
failure:
|
||||
snapshot.policy.status === "failedOpen"
|
||||
? snapshot.policy.failure.kind
|
||||
: null,
|
||||
result:
|
||||
snapshot.policy.status === "failedOpen" ? "failure" : "skipped",
|
||||
stage,
|
||||
status: snapshot.policy.status
|
||||
}
|
||||
);
|
||||
return {
|
||||
response: null,
|
||||
retryable:
|
||||
snapshot.policy.status === "failedOpen" &&
|
||||
snapshot.policy.failure.kind !== "invalidResponse"
|
||||
};
|
||||
}
|
||||
const validated = validateMinimumVersionResponse(
|
||||
snapshot.policy.response,
|
||||
request
|
||||
);
|
||||
logMinimumVersionCheck(options.logger, "info", {
|
||||
currentVersion: validated.currentVersion,
|
||||
decision: validated.decision,
|
||||
minimumVersion: validated.minimumVersion,
|
||||
policyRevision: validated.policyRevision,
|
||||
reason: validated.reason,
|
||||
result: "success",
|
||||
stage
|
||||
});
|
||||
return { response: validated, retryable: false };
|
||||
} catch (error) {
|
||||
logMinimumVersionCheck(options.logger, "error", {
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
result: "failure",
|
||||
stage
|
||||
});
|
||||
return { response: null, retryable: true };
|
||||
} finally {
|
||||
lifecycleAbort.signal.removeEventListener("abort", abortForLifecycle);
|
||||
}
|
||||
};
|
||||
|
||||
const checkPolicy = async (
|
||||
stage: "startup" | "foreground" | "retry"
|
||||
): Promise<PolicyCheckOutcome<TProduct>> => {
|
||||
if (activeCheck) {
|
||||
return activeCheck;
|
||||
}
|
||||
const pendingCheck = runPolicyCheck(stage);
|
||||
activeCheck = pendingCheck;
|
||||
try {
|
||||
return await pendingCheck;
|
||||
} finally {
|
||||
if (activeCheck === pendingCheck) {
|
||||
activeCheck = null;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const releaseMandatoryUpdater = async (
|
||||
restoreNormal = true
|
||||
): Promise<void> => {
|
||||
const session = mandatoryUpdateSession;
|
||||
mandatoryUpdateSession = null;
|
||||
try {
|
||||
await session?.release({ restoreNormal });
|
||||
} catch (error) {
|
||||
logMinimumVersionCheck(options.logger, "error", {
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
result: "failure",
|
||||
stage: "normal-update-restore"
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const releasePolicyBlock = async (): Promise<void> => {
|
||||
applyState("released");
|
||||
forcedFlowStarted = false;
|
||||
installRequested = false;
|
||||
await releaseMandatoryUpdater();
|
||||
closeUpgradeWindow();
|
||||
await options.onPolicyReleased();
|
||||
};
|
||||
|
||||
const installForcedUpdate = async (): Promise<void> => {
|
||||
if (installRequested) {
|
||||
return;
|
||||
}
|
||||
installRequested = true;
|
||||
try {
|
||||
if (!mandatoryUpdateSession) {
|
||||
throw new Error("mandatory update session is unavailable");
|
||||
}
|
||||
await mandatoryUpdateSession.installUpdate();
|
||||
} catch (error) {
|
||||
installRequested = false;
|
||||
if (error instanceof DevelopmentInstallSuppressedError) {
|
||||
logMinimumVersionCheck(options.logger, "info", {
|
||||
result: "simulated",
|
||||
stage: "install"
|
||||
});
|
||||
applyState("simulationComplete", options.updateService.getState());
|
||||
return;
|
||||
}
|
||||
logMinimumVersionCheck(options.logger, "error", {
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
result: "failure",
|
||||
stage: "install"
|
||||
});
|
||||
applyState("error", options.updateService.getState(), "installFailed");
|
||||
}
|
||||
};
|
||||
|
||||
const prepareAndDownloadForcedUpdate = async (): Promise<void> => {
|
||||
if (!state) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
forcedFlowStarted = true;
|
||||
applyState("checking");
|
||||
const target: MandatoryDesktopUpdateTarget = {
|
||||
channel: state.check.channel === "rc" ? "rc" : "stable",
|
||||
minimumVersion: state.check.minimumVersion,
|
||||
policyRevision: state.check.policyRevision
|
||||
};
|
||||
if (mandatoryUpdateSession) {
|
||||
mandatoryUpdateSession.retarget(target);
|
||||
} else {
|
||||
const acquiredSession =
|
||||
await options.updateService.acquireMandatorySession(target);
|
||||
if (disposed) {
|
||||
await acquiredSession.release({ restoreNormal: false });
|
||||
return;
|
||||
}
|
||||
mandatoryUpdateSession = acquiredSession;
|
||||
}
|
||||
const prepared = await mandatoryUpdateSession.prepare();
|
||||
if (prepared.status === "downloaded") {
|
||||
applyState("downloaded", prepared);
|
||||
await installForcedUpdate();
|
||||
return;
|
||||
}
|
||||
if (prepared.status !== "available") {
|
||||
applyState("error", prepared, "updateUnavailable");
|
||||
return;
|
||||
}
|
||||
applyState("ready", prepared);
|
||||
const downloaded = await mandatoryUpdateSession.downloadUpdate();
|
||||
if (downloaded.status !== "downloaded") {
|
||||
applyState("error", downloaded, "updateFailed");
|
||||
return;
|
||||
}
|
||||
applyState("downloaded", downloaded);
|
||||
await installForcedUpdate();
|
||||
} catch (error) {
|
||||
logMinimumVersionCheck(options.logger, "error", {
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
result: "failure",
|
||||
stage: "forced-update"
|
||||
});
|
||||
applyState(
|
||||
"error",
|
||||
options.updateService.getState(),
|
||||
error instanceof MandatoryUpdateTargetError
|
||||
? "releaseBelowMinimum"
|
||||
: "updateFailed"
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const runForcedUpdateFlow = (): Promise<void> => {
|
||||
if (activeForcedFlow) {
|
||||
return activeForcedFlow;
|
||||
}
|
||||
const pending = prepareAndDownloadForcedUpdate();
|
||||
activeForcedFlow = pending;
|
||||
void pending.then(
|
||||
() => {
|
||||
if (activeForcedFlow === pending) {
|
||||
activeForcedFlow = null;
|
||||
}
|
||||
},
|
||||
() => {
|
||||
if (activeForcedFlow === pending) {
|
||||
activeForcedFlow = null;
|
||||
}
|
||||
}
|
||||
);
|
||||
return pending;
|
||||
};
|
||||
|
||||
const unsubscribeUpdate = options.updateService.subscribe((update) => {
|
||||
if (!state || !forcedFlowStarted) {
|
||||
return;
|
||||
}
|
||||
if (update.status === "downloading") {
|
||||
applyState("downloading", update);
|
||||
} else if (update.status === "error") {
|
||||
installRequested = false;
|
||||
applyState("error", update, "updateFailed");
|
||||
}
|
||||
});
|
||||
|
||||
const assertUpgradeWindowSender = (senderId: number): void => {
|
||||
if (
|
||||
!upgradeWindow ||
|
||||
upgradeWindow.isDestroyed() ||
|
||||
upgradeWindow.webContents.id !== senderId
|
||||
) {
|
||||
throw new Error(
|
||||
"desktop update admission IPC is restricted to the upgrade window"
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
ipcMain.handle(desktopUpdateAdmissionIpcChannels.getState, (event) => {
|
||||
assertUpgradeWindowSender(event.sender.id);
|
||||
return state;
|
||||
});
|
||||
ipcMain.handle(desktopUpdateAdmissionIpcChannels.start, async (event) => {
|
||||
assertUpgradeWindowSender(event.sender.id);
|
||||
await runForcedUpdateFlow();
|
||||
return state;
|
||||
});
|
||||
ipcMain.handle(desktopUpdateAdmissionIpcChannels.retry, async (event) => {
|
||||
assertUpgradeWindowSender(event.sender.id);
|
||||
await activeForcedFlow;
|
||||
const { response } = await checkPolicy("retry");
|
||||
if (!response) {
|
||||
applyState(
|
||||
"error",
|
||||
options.updateService.getState(),
|
||||
"policyCheckFailed"
|
||||
);
|
||||
} else if (response.decision !== "upgradeRequired") {
|
||||
await releasePolicyBlock();
|
||||
} else if (state) {
|
||||
state = { ...state, check: response };
|
||||
await runForcedUpdateFlow();
|
||||
}
|
||||
return state;
|
||||
});
|
||||
ipcMain.handle(desktopUpdateAdmissionIpcChannels.later, (event) => {
|
||||
assertUpgradeWindowSender(event.sender.id);
|
||||
if (mode === "foreground" && !forcedFlowStarted) {
|
||||
closeUpgradeWindow();
|
||||
}
|
||||
});
|
||||
ipcMain.handle(
|
||||
desktopUpdateAdmissionIpcChannels.manualDownload,
|
||||
async (event) => {
|
||||
assertUpgradeWindowSender(event.sender.id);
|
||||
if (!state) {
|
||||
return;
|
||||
}
|
||||
await shell.openExternal(options.manualDownloadUrl(state.check));
|
||||
}
|
||||
);
|
||||
ipcMain.handle(desktopUpdateAdmissionIpcChannels.exit, (event) => {
|
||||
assertUpgradeWindowSender(event.sender.id);
|
||||
app.quit();
|
||||
});
|
||||
ipcMain.handle(desktopUpdateAdmissionIpcChannels.restart, (event) => {
|
||||
assertUpgradeWindowSender(event.sender.id);
|
||||
if (state?.phase !== "simulationComplete") {
|
||||
throw new Error(
|
||||
"desktop update admission restart requires a completed update"
|
||||
);
|
||||
}
|
||||
app.relaunch();
|
||||
app.quit();
|
||||
});
|
||||
|
||||
const checkAfterForegroundRestore = async (
|
||||
stage: "foreground" | "retry"
|
||||
): Promise<void> => {
|
||||
if (
|
||||
!options.runtime.checksEnabled ||
|
||||
disposed ||
|
||||
foregroundPrompted ||
|
||||
(mode === "startup" &&
|
||||
upgradeWindow !== null &&
|
||||
!upgradeWindow.isDestroyed())
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const outcome = await checkPolicy(stage);
|
||||
const response = outcome.response;
|
||||
if (outcome.retryable && !foregroundRetryTimer) {
|
||||
foregroundRetryTimer = setTimeout(() => {
|
||||
foregroundRetryTimer = null;
|
||||
if (
|
||||
disposed ||
|
||||
foregroundPrompted ||
|
||||
!options
|
||||
.listBusinessWindows()
|
||||
.some(
|
||||
(candidate) => !candidate.isDestroyed() && candidate.isFocused()
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
void checkAfterForegroundRestore("retry");
|
||||
}, foregroundFailureRetryDelayMs);
|
||||
}
|
||||
if (disposed || !response || response.decision !== "upgradeRequired") {
|
||||
return;
|
||||
}
|
||||
if (foregroundRetryTimer) {
|
||||
clearTimeout(foregroundRetryTimer);
|
||||
foregroundRetryTimer = null;
|
||||
}
|
||||
foregroundPrompted = true;
|
||||
state = {
|
||||
check: response,
|
||||
message: null,
|
||||
phase: "blocked",
|
||||
update: options.updateService.getState()
|
||||
};
|
||||
openUpgradeWindow("foreground");
|
||||
};
|
||||
|
||||
return {
|
||||
async runStartupCheck() {
|
||||
if (!options.runtime.checksEnabled) {
|
||||
return false;
|
||||
}
|
||||
const { response } = await checkPolicy("startup");
|
||||
if (!response || response.decision !== "upgradeRequired") {
|
||||
return false;
|
||||
}
|
||||
state = {
|
||||
check: response,
|
||||
message: null,
|
||||
phase: "blocked",
|
||||
update: options.updateService.getState()
|
||||
};
|
||||
openUpgradeWindow("startup");
|
||||
return true;
|
||||
},
|
||||
async checkAfterForegroundRestore() {
|
||||
await checkAfterForegroundRestore("foreground");
|
||||
},
|
||||
dispose() {
|
||||
disposed = true;
|
||||
if (foregroundRetryTimer) {
|
||||
clearTimeout(foregroundRetryTimer);
|
||||
foregroundRetryTimer = null;
|
||||
}
|
||||
lifecycleAbort.abort();
|
||||
void releaseMandatoryUpdater(false);
|
||||
app.removeListener("before-quit", handleBeforeQuit);
|
||||
unsubscribeUpdate();
|
||||
closeUpgradeWindow();
|
||||
for (const channel of Object.values(desktopUpdateAdmissionIpcChannels)) {
|
||||
if (channel !== desktopUpdateAdmissionIpcChannels.state) {
|
||||
ipcMain.removeHandler(channel);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
export {
|
||||
createDesktopUpdateAdmissionController,
|
||||
type DesktopUpdateAdmissionController,
|
||||
type DesktopUpdateAdmissionControllerOptions,
|
||||
type DesktopUpdateAdmissionLogger
|
||||
} from "./createDesktopUpdateAdmissionController.ts";
|
||||
export {
|
||||
registerDesktopFeatureAvailabilityIpc,
|
||||
type DesktopFeatureAvailabilityIpcRuntime
|
||||
} from "./registerDesktopFeatureAvailabilityIpc.ts";
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import type { WebContents } from "electron";
|
||||
import { desktopFeatureAvailabilityIpcChannels } from "../contracts/index.ts";
|
||||
import { registerDesktopFeatureAvailabilityIpc } from "./registerDesktopFeatureAvailabilityIpc.ts";
|
||||
|
||||
test("feature availability IPC rejects untrusted senders and invalid keys", async () => {
|
||||
type FeatureHandler = (
|
||||
event: { sender: WebContents },
|
||||
key?: unknown
|
||||
) => unknown;
|
||||
const handlers = new Map<string, FeatureHandler>();
|
||||
const trustedSender = { id: 1 } as WebContents;
|
||||
const untrustedSender = { id: 2 } as WebContents;
|
||||
const registration = registerDesktopFeatureAvailabilityIpc({
|
||||
electron: {
|
||||
broadcast() {},
|
||||
ipcMain: {
|
||||
handle(channel: string, handler: FeatureHandler) {
|
||||
handlers.set(channel, handler);
|
||||
},
|
||||
removeHandler(channel: string) {
|
||||
handlers.delete(channel);
|
||||
}
|
||||
} as never,
|
||||
isTrustedSender: (sender) => sender === trustedSender
|
||||
},
|
||||
runtime: {
|
||||
getSnapshot: () => ({
|
||||
architecture: "arm64",
|
||||
currentVersion: "1.0.0",
|
||||
fetchedAt: null,
|
||||
keys: [],
|
||||
platform: "macos",
|
||||
policyRevision: null,
|
||||
product: "tutti-desktop",
|
||||
source: "empty"
|
||||
}),
|
||||
isSupported: (key) => key === "workspace.example",
|
||||
subscribe: () => () => undefined
|
||||
}
|
||||
});
|
||||
|
||||
const getSnapshot = handlers.get(
|
||||
desktopFeatureAvailabilityIpcChannels.getSnapshot
|
||||
);
|
||||
const isSupported = handlers.get(
|
||||
desktopFeatureAvailabilityIpcChannels.isSupported
|
||||
);
|
||||
assert.ok(getSnapshot);
|
||||
assert.ok(isSupported);
|
||||
assert.throws(() => getSnapshot({ sender: untrustedSender }), /not trusted/);
|
||||
assert.throws(
|
||||
() => isSupported({ sender: trustedSender }, "../invalid"),
|
||||
/invalid/
|
||||
);
|
||||
assert.equal(
|
||||
isSupported({ sender: trustedSender }, "workspace.example"),
|
||||
true
|
||||
);
|
||||
|
||||
registration.dispose();
|
||||
assert.equal(handlers.size, 0);
|
||||
});
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
import type { WebContents } from "electron";
|
||||
import {
|
||||
desktopFeatureAvailabilityIpcChannels,
|
||||
type DesktopFeatureAvailabilityRuntime,
|
||||
type DesktopFeatureAvailabilitySnapshot
|
||||
} from "../contracts/index.ts";
|
||||
import { isValidDesktopFeatureKey } from "../feature-availability/core.ts";
|
||||
|
||||
export interface DesktopFeatureAvailabilityIpcRuntime {
|
||||
ipcMain: typeof import("electron").ipcMain;
|
||||
broadcast(
|
||||
channel: string,
|
||||
snapshot: DesktopFeatureAvailabilitySnapshot
|
||||
): void;
|
||||
isTrustedSender(sender: WebContents): boolean;
|
||||
}
|
||||
|
||||
export function registerDesktopFeatureAvailabilityIpc(input: {
|
||||
electron: DesktopFeatureAvailabilityIpcRuntime;
|
||||
runtime: DesktopFeatureAvailabilityRuntime;
|
||||
}): { dispose(): void } {
|
||||
const assertTrustedSender = (sender: WebContents): void => {
|
||||
if (!input.electron.isTrustedSender(sender)) {
|
||||
throw new Error("desktop feature availability IPC sender is not trusted");
|
||||
}
|
||||
};
|
||||
input.electron.ipcMain.handle(
|
||||
desktopFeatureAvailabilityIpcChannels.getSnapshot,
|
||||
(event) => {
|
||||
assertTrustedSender(event.sender);
|
||||
return input.runtime.getSnapshot();
|
||||
}
|
||||
);
|
||||
input.electron.ipcMain.handle(
|
||||
desktopFeatureAvailabilityIpcChannels.isSupported,
|
||||
(event, key: unknown) => {
|
||||
assertTrustedSender(event.sender);
|
||||
if (typeof key !== "string" || !isValidDesktopFeatureKey(key)) {
|
||||
throw new Error("desktop feature key is invalid");
|
||||
}
|
||||
return input.runtime.isSupported(key);
|
||||
}
|
||||
);
|
||||
const unsubscribe = input.runtime.subscribe((snapshot) => {
|
||||
input.electron.broadcast(
|
||||
desktopFeatureAvailabilityIpcChannels.changed,
|
||||
snapshot
|
||||
);
|
||||
});
|
||||
return {
|
||||
dispose() {
|
||||
unsubscribe();
|
||||
input.electron.ipcMain.removeHandler(
|
||||
desktopFeatureAvailabilityIpcChannels.getSnapshot
|
||||
);
|
||||
input.electron.ipcMain.removeHandler(
|
||||
desktopFeatureAvailabilityIpcChannels.isSupported
|
||||
);
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import {
|
||||
isDesktopFeatureSupported,
|
||||
normalizeDesktopFeatureKeys,
|
||||
parseDesktopFeatureAvailability
|
||||
} from "./core.ts";
|
||||
|
||||
test("normalizes a unique deterministic feature key list", () => {
|
||||
assert.deepEqual(
|
||||
normalizeDesktopFeatureKeys(["workspace.z", "agent.preview"]),
|
||||
["agent.preview", "workspace.z"]
|
||||
);
|
||||
assert.throws(() =>
|
||||
normalizeDesktopFeatureKeys(["workspace.z", "workspace.z"])
|
||||
);
|
||||
assert.throws(() => normalizeDesktopFeatureKeys([" invalid"]));
|
||||
});
|
||||
|
||||
test("distinguishes a missing envelope from an authoritative empty list", () => {
|
||||
assert.equal(parseDesktopFeatureAvailability({}), null);
|
||||
assert.deepEqual(
|
||||
parseDesktopFeatureAvailability({ featureAvailability: { keys: [] } }),
|
||||
{ keys: [] }
|
||||
);
|
||||
assert.throws(() =>
|
||||
parseDesktopFeatureAvailability({
|
||||
featureAvailability: { keys: [], unexpected: true }
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
test("queries feature support by exact case-sensitive key membership", () => {
|
||||
const snapshot = { keys: ["workspace.example"] };
|
||||
assert.equal(isDesktopFeatureSupported(snapshot, "workspace.example"), true);
|
||||
assert.equal(isDesktopFeatureSupported(snapshot, "Workspace.example"), false);
|
||||
assert.equal(isDesktopFeatureSupported(snapshot, "invalid key"), false);
|
||||
});
|
||||
@@ -0,0 +1,81 @@
|
||||
import type {
|
||||
DesktopFeatureAvailability,
|
||||
DesktopFeatureAvailabilitySnapshot,
|
||||
DesktopProduct,
|
||||
MinimumVersionCheckRequest
|
||||
} from "../contracts/index.ts";
|
||||
|
||||
const featureKeyPattern = /^[A-Za-z][A-Za-z0-9]*(?:[._-][A-Za-z0-9]+)*$/u;
|
||||
const maximumFeatureKeyLength = 128;
|
||||
const maximumFeatureKeys = 256;
|
||||
|
||||
export function isValidDesktopFeatureKey(value: string): boolean {
|
||||
return (
|
||||
value.length <= maximumFeatureKeyLength && featureKeyPattern.test(value)
|
||||
);
|
||||
}
|
||||
|
||||
export function normalizeDesktopFeatureKeys(value: unknown): readonly string[] {
|
||||
if (!Array.isArray(value) || value.length > maximumFeatureKeys) {
|
||||
throw new Error(
|
||||
"feature availability keys must be an array of at most 256 keys"
|
||||
);
|
||||
}
|
||||
const keys = value.map((entry) => {
|
||||
if (typeof entry !== "string" || !isValidDesktopFeatureKey(entry)) {
|
||||
throw new Error("feature availability contains an invalid key");
|
||||
}
|
||||
return entry;
|
||||
});
|
||||
const sorted = [...new Set(keys)].sort();
|
||||
if (sorted.length !== keys.length) {
|
||||
throw new Error("feature availability contains duplicate keys");
|
||||
}
|
||||
return Object.freeze(sorted);
|
||||
}
|
||||
|
||||
export function parseDesktopFeatureAvailability(
|
||||
response: unknown
|
||||
): DesktopFeatureAvailability | null {
|
||||
if (!response || typeof response !== "object") {
|
||||
throw new Error("desktop version response must be an object");
|
||||
}
|
||||
const value = (response as Record<string, unknown>).featureAvailability;
|
||||
if (value === undefined) {
|
||||
return null;
|
||||
}
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
||||
throw new Error("feature availability must be an object");
|
||||
}
|
||||
const record = value as Record<string, unknown>;
|
||||
if (
|
||||
Object.keys(record).some((key) => key !== "keys") ||
|
||||
!Object.prototype.hasOwnProperty.call(record, "keys")
|
||||
) {
|
||||
throw new Error("feature availability has invalid fields");
|
||||
}
|
||||
return Object.freeze({
|
||||
keys: normalizeDesktopFeatureKeys(record.keys)
|
||||
});
|
||||
}
|
||||
|
||||
export function desktopFeatureAvailabilityIdentityMatches<
|
||||
TProduct extends DesktopProduct
|
||||
>(
|
||||
snapshot: DesktopFeatureAvailabilitySnapshot,
|
||||
identity: MinimumVersionCheckRequest<TProduct>
|
||||
): snapshot is DesktopFeatureAvailabilitySnapshot<TProduct> {
|
||||
return (
|
||||
snapshot.product === identity.product &&
|
||||
snapshot.platform === identity.platform &&
|
||||
snapshot.architecture === identity.architecture &&
|
||||
snapshot.currentVersion === identity.currentVersion
|
||||
);
|
||||
}
|
||||
|
||||
export function isDesktopFeatureSupported(
|
||||
snapshot: Pick<DesktopFeatureAvailabilitySnapshot, "keys">,
|
||||
key: string
|
||||
): boolean {
|
||||
return isValidDesktopFeatureKey(key) && snapshot.keys.includes(key);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
export {
|
||||
desktopFeatureAvailabilityIdentityMatches,
|
||||
isDesktopFeatureSupported,
|
||||
isValidDesktopFeatureKey,
|
||||
normalizeDesktopFeatureKeys,
|
||||
parseDesktopFeatureAvailability
|
||||
} from "./core.ts";
|
||||
export {
|
||||
createDesktopFeatureAvailabilityRuntime,
|
||||
type DesktopFeatureAvailabilityLogger,
|
||||
type MutableDesktopFeatureAvailabilityRuntime
|
||||
} from "./runtime.ts";
|
||||
@@ -0,0 +1,104 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import type { DesktopUpdateAdmissionSnapshot } from "../contracts/index.ts";
|
||||
import { createDesktopFeatureAvailabilityRuntime } from "./runtime.ts";
|
||||
|
||||
const identity = {
|
||||
architecture: "arm64",
|
||||
currentVersion: "1.0.0",
|
||||
platform: "macos",
|
||||
product: "tutti-desktop"
|
||||
} as const;
|
||||
|
||||
function daemonSnapshot(
|
||||
featureAvailability: DesktopUpdateAdmissionSnapshot<"tutti-desktop">["featureAvailability"]
|
||||
): DesktopUpdateAdmissionSnapshot<"tutti-desktop"> {
|
||||
return {
|
||||
featureAvailability,
|
||||
identity,
|
||||
lastAttemptAt: "2026-08-02T09:00:00Z",
|
||||
nextForegroundCheckAt: "2026-08-02T09:30:00Z",
|
||||
policy: {
|
||||
response: {
|
||||
channel: "stable",
|
||||
decision: "allowed",
|
||||
minimumVersion: "1.0.0",
|
||||
policyRevision: "v1",
|
||||
reason: "meetsMinimum"
|
||||
},
|
||||
status: "resolved"
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
test("feature runtime projects daemon-owned cache snapshot without disk access", () => {
|
||||
const runtime = createDesktopFeatureAvailabilityRuntime({
|
||||
identity,
|
||||
logger: { error() {}, info() {} }
|
||||
});
|
||||
const observed: Array<readonly string[]> = [];
|
||||
runtime.subscribe((snapshot) => observed.push(snapshot.keys));
|
||||
|
||||
runtime.acceptDaemonSnapshot(
|
||||
daemonSnapshot({
|
||||
fetchedAt: "2026-08-02T08:30:00Z",
|
||||
keys: ["workspace.example"],
|
||||
policyRevision: "v1",
|
||||
source: "cache"
|
||||
})
|
||||
);
|
||||
|
||||
assert.deepEqual(runtime.getSnapshot(), {
|
||||
...identity,
|
||||
fetchedAt: "2026-08-02T08:30:00Z",
|
||||
keys: ["workspace.example"],
|
||||
policyRevision: "v1",
|
||||
source: "cache"
|
||||
});
|
||||
assert.equal(runtime.isSupported("workspace.example"), true);
|
||||
assert.deepEqual(observed, [["workspace.example"]]);
|
||||
});
|
||||
|
||||
test("feature runtime rejects daemon snapshots for another identity", () => {
|
||||
const runtime = createDesktopFeatureAvailabilityRuntime({
|
||||
identity,
|
||||
logger: { error() {}, info() {} }
|
||||
});
|
||||
const snapshot = daemonSnapshot({
|
||||
fetchedAt: null,
|
||||
keys: [],
|
||||
policyRevision: null,
|
||||
source: "empty"
|
||||
});
|
||||
|
||||
assert.throws(
|
||||
() =>
|
||||
runtime.acceptDaemonSnapshot({
|
||||
...snapshot,
|
||||
identity: { ...identity, currentVersion: "2.0.0" }
|
||||
}),
|
||||
/daemon identity mismatch/
|
||||
);
|
||||
});
|
||||
|
||||
test("feature runtime stops notifying after disposal", () => {
|
||||
const runtime = createDesktopFeatureAvailabilityRuntime({
|
||||
identity,
|
||||
logger: { error() {}, info() {} }
|
||||
});
|
||||
let notifications = 0;
|
||||
runtime.subscribe(() => {
|
||||
notifications += 1;
|
||||
});
|
||||
runtime.dispose();
|
||||
runtime.acceptDaemonSnapshot(
|
||||
daemonSnapshot({
|
||||
fetchedAt: null,
|
||||
keys: ["workspace.example"],
|
||||
policyRevision: null,
|
||||
source: "empty"
|
||||
})
|
||||
);
|
||||
assert.equal(notifications, 0);
|
||||
assert.deepEqual(runtime.getSnapshot().keys, []);
|
||||
});
|
||||
@@ -0,0 +1,117 @@
|
||||
import type {
|
||||
DesktopFeatureAvailabilityRuntime,
|
||||
DesktopFeatureAvailabilitySnapshot,
|
||||
DesktopProduct,
|
||||
DesktopUpdateAdmissionSnapshot,
|
||||
MinimumVersionCheckRequest
|
||||
} from "../contracts/index.ts";
|
||||
import {
|
||||
isDesktopFeatureSupported,
|
||||
normalizeDesktopFeatureKeys
|
||||
} from "./core.ts";
|
||||
|
||||
export interface DesktopFeatureAvailabilityLogger {
|
||||
info(message: string): void;
|
||||
error(message: string): void;
|
||||
}
|
||||
|
||||
export interface MutableDesktopFeatureAvailabilityRuntime<
|
||||
TProduct extends DesktopProduct = DesktopProduct
|
||||
> extends DesktopFeatureAvailabilityRuntime<TProduct> {
|
||||
acceptDaemonSnapshot(
|
||||
snapshot: DesktopUpdateAdmissionSnapshot<TProduct>
|
||||
): void;
|
||||
dispose(): void;
|
||||
}
|
||||
|
||||
function emptySnapshot<TProduct extends DesktopProduct>(
|
||||
identity: MinimumVersionCheckRequest<TProduct>
|
||||
): DesktopFeatureAvailabilitySnapshot<TProduct> {
|
||||
return Object.freeze({
|
||||
...identity,
|
||||
fetchedAt: null,
|
||||
keys: Object.freeze([]),
|
||||
policyRevision: null,
|
||||
source: "empty"
|
||||
});
|
||||
}
|
||||
|
||||
function log(
|
||||
logger: DesktopFeatureAvailabilityLogger,
|
||||
level: "info" | "error",
|
||||
details: Record<string, unknown>
|
||||
): void {
|
||||
logger[level](`[desktop-feature-availability] ${JSON.stringify(details)}`);
|
||||
}
|
||||
|
||||
export function createDesktopFeatureAvailabilityRuntime<
|
||||
TProduct extends DesktopProduct
|
||||
>(input: {
|
||||
identity: MinimumVersionCheckRequest<TProduct>;
|
||||
logger: DesktopFeatureAvailabilityLogger;
|
||||
}): MutableDesktopFeatureAvailabilityRuntime<TProduct> {
|
||||
let snapshot = emptySnapshot(input.identity);
|
||||
const listeners = new Set<
|
||||
(value: DesktopFeatureAvailabilitySnapshot<TProduct>) => void
|
||||
>();
|
||||
let disposed = false;
|
||||
|
||||
return {
|
||||
acceptDaemonSnapshot(value) {
|
||||
if (disposed) {
|
||||
return;
|
||||
}
|
||||
if (
|
||||
value.identity.product !== input.identity.product ||
|
||||
value.identity.platform !== input.identity.platform ||
|
||||
value.identity.architecture !== input.identity.architecture ||
|
||||
value.identity.currentVersion !== input.identity.currentVersion
|
||||
) {
|
||||
throw new Error("feature availability daemon identity mismatch");
|
||||
}
|
||||
const next: DesktopFeatureAvailabilitySnapshot<TProduct> = Object.freeze({
|
||||
...input.identity,
|
||||
fetchedAt: value.featureAvailability.fetchedAt,
|
||||
keys: normalizeDesktopFeatureKeys(value.featureAvailability.keys),
|
||||
policyRevision: value.featureAvailability.policyRevision,
|
||||
source: value.featureAvailability.source
|
||||
});
|
||||
snapshot = next;
|
||||
log(input.logger, "info", {
|
||||
count: next.keys.length,
|
||||
policyRevision: next.policyRevision,
|
||||
result: "accepted",
|
||||
source: next.source,
|
||||
stage: "daemon-snapshot"
|
||||
});
|
||||
for (const listener of listeners) {
|
||||
try {
|
||||
listener(next);
|
||||
} catch (error) {
|
||||
log(input.logger, "error", {
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
result: "failure",
|
||||
stage: "subscriber-notify"
|
||||
});
|
||||
}
|
||||
}
|
||||
},
|
||||
dispose() {
|
||||
disposed = true;
|
||||
listeners.clear();
|
||||
},
|
||||
getSnapshot() {
|
||||
return snapshot;
|
||||
},
|
||||
isSupported(key) {
|
||||
return isDesktopFeatureSupported(snapshot, key);
|
||||
},
|
||||
subscribe(listener) {
|
||||
if (disposed) {
|
||||
return () => undefined;
|
||||
}
|
||||
listeners.add(listener);
|
||||
return () => listeners.delete(listener);
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
export {
|
||||
createMinimumVersionAdmissionI18nRuntime,
|
||||
minimumVersionAdmissionEn,
|
||||
minimumVersionAdmissionZhCN,
|
||||
type MinimumVersionAdmissionI18nKey,
|
||||
type MinimumVersionAdmissionI18nRuntime,
|
||||
type MinimumVersionAdmissionLocale
|
||||
} from "./minimumVersionAdmissionI18n.ts";
|
||||
@@ -0,0 +1,119 @@
|
||||
import {
|
||||
createI18nRuntime,
|
||||
type I18nDictionary,
|
||||
type I18nRuntime
|
||||
} from "@tutti-os/ui-i18n-runtime";
|
||||
|
||||
export type MinimumVersionAdmissionLocale = "en" | "zh-CN";
|
||||
export type MinimumVersionAdmissionI18nKey =
|
||||
| "startupTitle"
|
||||
| "startupDetail"
|
||||
| "foregroundTitle"
|
||||
| "foregroundDetail"
|
||||
| "checkingTitle"
|
||||
| "downloadingTitle"
|
||||
| "failedTitle"
|
||||
| "simulationCompleteTitle"
|
||||
| "simulationCompleteDetail"
|
||||
| "currentVersion"
|
||||
| "minimumVersion"
|
||||
| "downloadProgress"
|
||||
| "autoRestartNotice"
|
||||
| "upgrade"
|
||||
| "upgradeNow"
|
||||
| "later"
|
||||
| "retry"
|
||||
| "manualDownload"
|
||||
| "exit"
|
||||
| "restart"
|
||||
| "errors.releaseBelowMinimum"
|
||||
| "errors.updateUnavailable"
|
||||
| "errors.policyCheckFailed"
|
||||
| "errors.installFailed"
|
||||
| "errors.updateFailed";
|
||||
|
||||
export type MinimumVersionAdmissionI18nRuntime =
|
||||
I18nRuntime<MinimumVersionAdmissionI18nKey>;
|
||||
|
||||
export const minimumVersionAdmissionEn = {
|
||||
startupTitle: "Update {{productName}} to continue",
|
||||
startupDetail:
|
||||
"Your {{productName}} version is out of date. Update to the latest version. Your automatic update settings won't be changed.",
|
||||
foregroundTitle: "Update {{productName}} to continue",
|
||||
foregroundDetail:
|
||||
"Your {{productName}} version is out of date. Update to the latest version. Your automatic update settings won't be changed.",
|
||||
checkingTitle: "Checking the required update",
|
||||
downloadingTitle: "Downloading the required update",
|
||||
failedTitle: "Unable to complete the required update",
|
||||
simulationCompleteTitle: "Development update simulation completed",
|
||||
simulationCompleteDetail:
|
||||
"The update reached the installation step. Development mode simulated installation; restart {{productName}} to continue.",
|
||||
currentVersion: "Current version:",
|
||||
minimumVersion: "Required version:",
|
||||
downloadProgress: "Download progress",
|
||||
autoRestartNotice:
|
||||
"{{productName}} will install the update and restart automatically when the download completes.",
|
||||
upgrade: "Update now",
|
||||
upgradeNow: "Update now",
|
||||
later: "Later",
|
||||
retry: "Retry",
|
||||
manualDownload: "Manual download",
|
||||
exit: "Exit",
|
||||
restart: "Quit and restart",
|
||||
errors: {
|
||||
releaseBelowMinimum:
|
||||
"The latest published update is below the required minimum version.",
|
||||
updateUnavailable:
|
||||
"No suitable update is available from the release source.",
|
||||
policyCheckFailed: "The minimum-version policy could not be checked.",
|
||||
installFailed: "The update was downloaded but could not be installed.",
|
||||
updateFailed: "The update could not be downloaded or verified."
|
||||
}
|
||||
} as const satisfies I18nDictionary;
|
||||
|
||||
export const minimumVersionAdmissionZhCN = {
|
||||
startupTitle: "需要更新 {{productName}} 后才能继续使用",
|
||||
startupDetail:
|
||||
"你的 {{productName}} 版本过低,请更新到最新版本。你的自动更新设置不会被修改。",
|
||||
foregroundTitle: "需要更新 {{productName}} 后才能继续使用",
|
||||
foregroundDetail:
|
||||
"你的 {{productName}} 版本过低,请更新到最新版本。你的自动更新设置不会被修改。",
|
||||
checkingTitle: "正在检查必须安装的更新",
|
||||
downloadingTitle: "正在下载必须安装的更新",
|
||||
failedTitle: "无法完成必须安装的更新",
|
||||
simulationCompleteTitle: "开发更新模拟已完成",
|
||||
simulationCompleteDetail:
|
||||
"更新流程已到达安装阶段,开发模式已模拟安装,请重启 {{productName}} 后继续",
|
||||
currentVersion: "当前版本:",
|
||||
minimumVersion: "需要版本:",
|
||||
downloadProgress: "下载进度",
|
||||
autoRestartNotice: "下载完成后,{{productName}} 将自动安装更新并重启",
|
||||
upgrade: "立即更新",
|
||||
upgradeNow: "立即更新",
|
||||
later: "稍后",
|
||||
retry: "重试",
|
||||
manualDownload: "手动下载",
|
||||
exit: "退出",
|
||||
restart: "退出并重启",
|
||||
errors: {
|
||||
releaseBelowMinimum: "当前发布的最新版本仍低于要求的最低版本",
|
||||
updateUnavailable: "发布源中没有可用的更新",
|
||||
policyCheckFailed: "无法检查最低版本策略,请检查网络后重试",
|
||||
installFailed: "更新已下载,但无法安装",
|
||||
updateFailed: "更新下载或校验失败"
|
||||
}
|
||||
} as const satisfies I18nDictionary;
|
||||
|
||||
export function createMinimumVersionAdmissionI18nRuntime(
|
||||
locale: MinimumVersionAdmissionLocale,
|
||||
overrides?: I18nDictionary
|
||||
): MinimumVersionAdmissionI18nRuntime {
|
||||
return createI18nRuntime<MinimumVersionAdmissionI18nKey>({
|
||||
dictionaries: [
|
||||
overrides ?? {},
|
||||
locale === "zh-CN"
|
||||
? minimumVersionAdmissionZhCN
|
||||
: minimumVersionAdmissionEn
|
||||
]
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export * from "./contracts/index.ts";
|
||||
export * from "./core/index.ts";
|
||||
export * from "./feature-availability/index.ts";
|
||||
@@ -0,0 +1,9 @@
|
||||
export {
|
||||
createMandatoryUpdaterLeaseManager,
|
||||
MandatoryUpdateTargetError,
|
||||
type MandatoryUpdaterLeaseManager
|
||||
} from "./mandatoryUpdaterSession.ts";
|
||||
export type {
|
||||
MandatoryDesktopUpdateSession,
|
||||
MandatoryDesktopUpdateTarget
|
||||
} from "../contracts/index.ts";
|
||||
+181
@@ -0,0 +1,181 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import type { DesktopUpdateState } from "../contracts/index.ts";
|
||||
import {
|
||||
createMandatoryUpdaterLeaseManager,
|
||||
MandatoryUpdateTargetError
|
||||
} from "./mandatoryUpdaterSession.ts";
|
||||
|
||||
function updateState(
|
||||
status: DesktopUpdateState["status"],
|
||||
latestVersion: string | null
|
||||
): DesktopUpdateState {
|
||||
return {
|
||||
channel: "stable",
|
||||
checkedAt: null,
|
||||
currentVersion: "1.0.0",
|
||||
downloadedBytes: null,
|
||||
downloadPercent: null,
|
||||
latestVersion,
|
||||
message: null,
|
||||
policy: "prompt",
|
||||
releaseDate: null,
|
||||
releaseName: null,
|
||||
releaseNotesUrl: null,
|
||||
status,
|
||||
totalBytes: null
|
||||
};
|
||||
}
|
||||
|
||||
test("owns updater access and restores the captured configuration", async () => {
|
||||
let state = updateState("available", "2.0.0");
|
||||
let restored: string | null = null;
|
||||
const manager = createMandatoryUpdaterLeaseManager({
|
||||
captureNormalConfiguration: () => "normal",
|
||||
downloadUpdate: async () => {
|
||||
state = updateState("downloaded", "2.0.0");
|
||||
return state;
|
||||
},
|
||||
getState: () => state,
|
||||
installUpdate: async () => undefined,
|
||||
prepareMandatoryUpdate: async () => state,
|
||||
restoreNormalConfiguration: async (configuration) => {
|
||||
restored = configuration;
|
||||
},
|
||||
suspendNormalUpdates: async () => undefined
|
||||
});
|
||||
|
||||
const session = await manager.acquire({
|
||||
channel: "stable",
|
||||
minimumVersion: "2.0.0",
|
||||
policyRevision: "revision-1"
|
||||
});
|
||||
assert.throws(() => manager.assertAccess());
|
||||
assert.equal((await session.prepare()).status, "available");
|
||||
assert.equal((await session.downloadUpdate()).status, "downloaded");
|
||||
await session.installUpdate();
|
||||
await session.release();
|
||||
assert.equal(restored, "normal");
|
||||
manager.assertAccess();
|
||||
});
|
||||
|
||||
test("retargets an active lease without losing its captured normal configuration", async () => {
|
||||
let state = updateState("available", "2.1.0");
|
||||
const preparedChannels: string[] = [];
|
||||
let restored: string | null = null;
|
||||
const manager = createMandatoryUpdaterLeaseManager({
|
||||
captureNormalConfiguration: () => "normal",
|
||||
downloadUpdate: async () => state,
|
||||
getState: () => state,
|
||||
installUpdate: async () => undefined,
|
||||
prepareMandatoryUpdate: async (configuration) => {
|
||||
preparedChannels.push(configuration.channel);
|
||||
return state;
|
||||
},
|
||||
restoreNormalConfiguration: async (configuration) => {
|
||||
restored = configuration;
|
||||
},
|
||||
suspendNormalUpdates: async () => undefined
|
||||
});
|
||||
const session = await manager.acquire({
|
||||
channel: "stable",
|
||||
minimumVersion: "2.0.0",
|
||||
policyRevision: "revision-1"
|
||||
});
|
||||
|
||||
session.retarget({
|
||||
channel: "rc",
|
||||
minimumVersion: "2.1.0-rc.1",
|
||||
policyRevision: "revision-2"
|
||||
});
|
||||
await session.prepare();
|
||||
await session.release();
|
||||
|
||||
assert.deepEqual(preparedChannels, ["rc"]);
|
||||
assert.equal(restored, "normal");
|
||||
});
|
||||
|
||||
test("retains updater ownership until normal configuration restoration finishes", async () => {
|
||||
const state = updateState("available", "2.0.0");
|
||||
let finishRestore!: () => void;
|
||||
const restoreStarted = new Promise<void>((resolve) => {
|
||||
finishRestore = resolve;
|
||||
});
|
||||
const manager = createMandatoryUpdaterLeaseManager({
|
||||
captureNormalConfiguration: () => "normal",
|
||||
downloadUpdate: async () => state,
|
||||
getState: () => state,
|
||||
installUpdate: async () => undefined,
|
||||
prepareMandatoryUpdate: async () => state,
|
||||
restoreNormalConfiguration: async () => restoreStarted,
|
||||
suspendNormalUpdates: async () => undefined
|
||||
});
|
||||
const session = await manager.acquire({
|
||||
channel: "stable",
|
||||
minimumVersion: "2.0.0",
|
||||
policyRevision: "revision-1"
|
||||
});
|
||||
|
||||
const release = session.release();
|
||||
assert.throws(() => manager.assertAccess());
|
||||
await assert.rejects(
|
||||
manager.acquire({
|
||||
channel: "stable",
|
||||
minimumVersion: "2.0.0",
|
||||
policyRevision: "revision-2"
|
||||
})
|
||||
);
|
||||
finishRestore();
|
||||
await release;
|
||||
manager.assertAccess();
|
||||
});
|
||||
|
||||
test("rejects an updater target before installation", async () => {
|
||||
const state = updateState("available", "1.9.9");
|
||||
const manager = createMandatoryUpdaterLeaseManager({
|
||||
captureNormalConfiguration: () => null,
|
||||
downloadUpdate: async () => state,
|
||||
getState: () => state,
|
||||
installUpdate: async () => assert.fail("install must not run"),
|
||||
prepareMandatoryUpdate: async () => state,
|
||||
restoreNormalConfiguration: async () => undefined,
|
||||
suspendNormalUpdates: async () => undefined
|
||||
});
|
||||
const session = await manager.acquire({
|
||||
channel: "stable",
|
||||
minimumVersion: "2.0.0",
|
||||
policyRevision: "revision-1"
|
||||
});
|
||||
await assert.rejects(session.prepare(), MandatoryUpdateTargetError);
|
||||
});
|
||||
|
||||
test("releases ownership when suspension fails", async () => {
|
||||
const state = updateState("idle", null);
|
||||
let fail = true;
|
||||
const manager = createMandatoryUpdaterLeaseManager({
|
||||
captureNormalConfiguration: () => null,
|
||||
downloadUpdate: async () => state,
|
||||
getState: () => state,
|
||||
installUpdate: async () => undefined,
|
||||
prepareMandatoryUpdate: async () => state,
|
||||
restoreNormalConfiguration: async () => undefined,
|
||||
suspendNormalUpdates: async () => {
|
||||
if (fail) {
|
||||
fail = false;
|
||||
throw new Error("suspend failed");
|
||||
}
|
||||
}
|
||||
});
|
||||
await assert.rejects(
|
||||
manager.acquire({
|
||||
channel: "stable",
|
||||
minimumVersion: "2.0.0",
|
||||
policyRevision: "revision-1"
|
||||
})
|
||||
);
|
||||
await manager.acquire({
|
||||
channel: "stable",
|
||||
minimumVersion: "2.0.0",
|
||||
policyRevision: "revision-2"
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,173 @@
|
||||
import { AsyncLocalStorage } from "node:async_hooks";
|
||||
import type {
|
||||
ConfigureDesktopUpdatesInput,
|
||||
DesktopUpdateState,
|
||||
MandatoryDesktopUpdateSession,
|
||||
MandatoryDesktopUpdateTarget
|
||||
} from "../contracts/index.ts";
|
||||
import { updaterTargetMeetsMinimum } from "../core/index.ts";
|
||||
|
||||
export class MandatoryUpdateTargetError extends Error {
|
||||
public readonly latestVersion: string | null;
|
||||
public readonly minimumVersion: string;
|
||||
|
||||
public constructor(latestVersion: string | null, minimumVersion: string) {
|
||||
super(
|
||||
`mandatory update target ${latestVersion ?? "unknown"} is below ${minimumVersion}`
|
||||
);
|
||||
this.name = "MandatoryUpdateTargetError";
|
||||
this.latestVersion = latestVersion;
|
||||
this.minimumVersion = minimumVersion;
|
||||
}
|
||||
}
|
||||
|
||||
export interface MandatoryUpdaterLeaseManager {
|
||||
assertAccess(): void;
|
||||
isMandatoryAccess(): boolean;
|
||||
acquire(
|
||||
input: MandatoryDesktopUpdateTarget
|
||||
): Promise<MandatoryDesktopUpdateSession>;
|
||||
}
|
||||
|
||||
export function createMandatoryUpdaterLeaseManager<
|
||||
TNormalConfiguration
|
||||
>(options: {
|
||||
captureNormalConfiguration(): TNormalConfiguration | null;
|
||||
suspendNormalUpdates(): Promise<void>;
|
||||
prepareMandatoryUpdate(
|
||||
input: ConfigureDesktopUpdatesInput
|
||||
): Promise<DesktopUpdateState>;
|
||||
downloadUpdate(): Promise<DesktopUpdateState>;
|
||||
installUpdate(): Promise<void>;
|
||||
getState(): DesktopUpdateState;
|
||||
restoreNormalConfiguration(
|
||||
configuration: TNormalConfiguration
|
||||
): Promise<void>;
|
||||
}): MandatoryUpdaterLeaseManager {
|
||||
const mandatoryContext = new AsyncLocalStorage<symbol>();
|
||||
const normalRestoreContext = new AsyncLocalStorage<symbol>();
|
||||
let mandatoryOwner: symbol | null = null;
|
||||
|
||||
const assertAccess = (): void => {
|
||||
if (mandatoryOwner && mandatoryContext.getStore() !== mandatoryOwner) {
|
||||
throw new Error(
|
||||
"application updater is owned by the mandatory update session"
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
assertAccess,
|
||||
isMandatoryAccess: () =>
|
||||
mandatoryOwner !== null &&
|
||||
mandatoryContext.getStore() === mandatoryOwner &&
|
||||
normalRestoreContext.getStore() !== mandatoryOwner,
|
||||
async acquire(input) {
|
||||
if (mandatoryOwner) {
|
||||
throw new Error("a mandatory update session is already active");
|
||||
}
|
||||
const owner = Symbol(
|
||||
`mandatory-update:${input.policyRevision}:${input.minimumVersion}`
|
||||
);
|
||||
mandatoryOwner = owner;
|
||||
const configurationToRestore = options.captureNormalConfiguration();
|
||||
try {
|
||||
await options.suspendNormalUpdates();
|
||||
} catch (error) {
|
||||
if (mandatoryOwner === owner) {
|
||||
mandatoryOwner = null;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
let target = input;
|
||||
let released = false;
|
||||
let releasePromise: Promise<void> | null = null;
|
||||
const run = <T>(operation: () => Promise<T>): Promise<T> => {
|
||||
if (released || mandatoryOwner !== owner) {
|
||||
return Promise.reject(
|
||||
new Error("mandatory update session is no longer active")
|
||||
);
|
||||
}
|
||||
return mandatoryContext.run(owner, operation);
|
||||
};
|
||||
const assertTargetVersion = (update: DesktopUpdateState): void => {
|
||||
if (
|
||||
!updaterTargetMeetsMinimum(
|
||||
update.latestVersion,
|
||||
target.minimumVersion
|
||||
)
|
||||
) {
|
||||
throw new MandatoryUpdateTargetError(
|
||||
update.latestVersion,
|
||||
target.minimumVersion
|
||||
);
|
||||
}
|
||||
};
|
||||
const assertTargetWhenPresent = (update: DesktopUpdateState): void => {
|
||||
if (update.status === "available" || update.status === "downloaded") {
|
||||
assertTargetVersion(update);
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
retarget: (nextTarget) => {
|
||||
if (released || mandatoryOwner !== owner) {
|
||||
throw new Error("mandatory update session is no longer active");
|
||||
}
|
||||
target = nextTarget;
|
||||
},
|
||||
prepare: () =>
|
||||
run(async () => {
|
||||
const update = await options.prepareMandatoryUpdate({
|
||||
channel: target.channel,
|
||||
policy: "prompt"
|
||||
});
|
||||
assertTargetWhenPresent(update);
|
||||
return update;
|
||||
}),
|
||||
downloadUpdate: () =>
|
||||
run(async () => {
|
||||
const update = await options.downloadUpdate();
|
||||
if (update.status === "downloaded") {
|
||||
assertTargetVersion(update);
|
||||
}
|
||||
return update;
|
||||
}),
|
||||
installUpdate: () =>
|
||||
run(async () => {
|
||||
assertTargetVersion(options.getState());
|
||||
await options.installUpdate();
|
||||
}),
|
||||
release: (releaseOptions) => {
|
||||
if (releasePromise) {
|
||||
return releasePromise;
|
||||
}
|
||||
releasePromise = (async () => {
|
||||
released = true;
|
||||
if (mandatoryOwner !== owner) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
if (
|
||||
releaseOptions?.restoreNormal !== false &&
|
||||
configurationToRestore
|
||||
) {
|
||||
await mandatoryContext.run(owner, () =>
|
||||
normalRestoreContext.run(owner, () =>
|
||||
options.restoreNormalConfiguration(configurationToRestore)
|
||||
)
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
if (mandatoryOwner === owner) {
|
||||
mandatoryOwner = null;
|
||||
}
|
||||
}
|
||||
})();
|
||||
return releasePromise;
|
||||
}
|
||||
};
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import type {
|
||||
DesktopFeatureAvailabilityApi,
|
||||
DesktopFeatureAvailabilitySnapshot
|
||||
} from "../contracts/index.ts";
|
||||
import { desktopFeatureAvailabilityIpcChannels } from "../contracts/featureAvailabilityIpc.ts";
|
||||
|
||||
export function createDesktopFeatureAvailabilityApi(input: {
|
||||
invoke<T>(channel: string, ...args: unknown[]): Promise<T>;
|
||||
on(
|
||||
channel: string,
|
||||
listener: (
|
||||
event: unknown,
|
||||
snapshot: DesktopFeatureAvailabilitySnapshot
|
||||
) => void
|
||||
): void;
|
||||
removeListener(
|
||||
channel: string,
|
||||
listener: (
|
||||
event: unknown,
|
||||
snapshot: DesktopFeatureAvailabilitySnapshot
|
||||
) => void
|
||||
): void;
|
||||
}): DesktopFeatureAvailabilityApi {
|
||||
return {
|
||||
getSnapshot: () =>
|
||||
input.invoke<DesktopFeatureAvailabilitySnapshot>(
|
||||
desktopFeatureAvailabilityIpcChannels.getSnapshot
|
||||
),
|
||||
isSupported: (key) =>
|
||||
input.invoke<boolean>(
|
||||
desktopFeatureAvailabilityIpcChannels.isSupported,
|
||||
key
|
||||
),
|
||||
onChanged(listener) {
|
||||
const handler = (
|
||||
_event: unknown,
|
||||
snapshot: DesktopFeatureAvailabilitySnapshot
|
||||
): void => listener(snapshot);
|
||||
input.on(desktopFeatureAvailabilityIpcChannels.changed, handler);
|
||||
return () =>
|
||||
input.removeListener(
|
||||
desktopFeatureAvailabilityIpcChannels.changed,
|
||||
handler
|
||||
);
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export { createDesktopFeatureAvailabilityApi } from "./featureAvailability.ts";
|
||||
export { createDesktopMinimumVersionApi } from "./minimumVersion.ts";
|
||||
@@ -0,0 +1,47 @@
|
||||
import type {
|
||||
DesktopMinimumVersionApi,
|
||||
MinimumVersionUpgradeState
|
||||
} from "../contracts/index.ts";
|
||||
import { desktopUpdateAdmissionIpcChannels } from "../contracts/updateAdmissionIpc.ts";
|
||||
|
||||
export function createDesktopMinimumVersionApi(input: {
|
||||
invoke<T>(channel: string): Promise<T>;
|
||||
on(
|
||||
channel: string,
|
||||
listener: (event: unknown, state: MinimumVersionUpgradeState) => void
|
||||
): void;
|
||||
removeListener(
|
||||
channel: string,
|
||||
listener: (event: unknown, state: MinimumVersionUpgradeState) => void
|
||||
): void;
|
||||
}): DesktopMinimumVersionApi {
|
||||
return {
|
||||
getState: () =>
|
||||
input.invoke<MinimumVersionUpgradeState | null>(
|
||||
desktopUpdateAdmissionIpcChannels.getState
|
||||
),
|
||||
start: () =>
|
||||
input.invoke<MinimumVersionUpgradeState | null>(
|
||||
desktopUpdateAdmissionIpcChannels.start
|
||||
),
|
||||
retry: () =>
|
||||
input.invoke<MinimumVersionUpgradeState | null>(
|
||||
desktopUpdateAdmissionIpcChannels.retry
|
||||
),
|
||||
later: () => input.invoke<void>(desktopUpdateAdmissionIpcChannels.later),
|
||||
openManualDownload: () =>
|
||||
input.invoke<void>(desktopUpdateAdmissionIpcChannels.manualDownload),
|
||||
exit: () => input.invoke<void>(desktopUpdateAdmissionIpcChannels.exit),
|
||||
restart: () =>
|
||||
input.invoke<void>(desktopUpdateAdmissionIpcChannels.restart),
|
||||
onState(listener) {
|
||||
const handler = (
|
||||
_event: unknown,
|
||||
state: MinimumVersionUpgradeState
|
||||
): void => listener(state);
|
||||
input.on(desktopUpdateAdmissionIpcChannels.state, handler);
|
||||
return () =>
|
||||
input.removeListener(desktopUpdateAdmissionIpcChannels.state, handler);
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Button, CloseIcon, LoadingIcon } from "@tutti-os/ui-system";
|
||||
import type {
|
||||
DesktopMinimumVersionApi,
|
||||
MinimumVersionUpgradeError,
|
||||
MinimumVersionUpgradeState
|
||||
} from "../contracts/index.ts";
|
||||
import type { MinimumVersionAdmissionI18nRuntime } from "../i18n/index.ts";
|
||||
|
||||
function percent(value: number | null): string {
|
||||
return `${Math.max(0, Math.min(100, Math.round(value ?? 0)))}%`;
|
||||
}
|
||||
|
||||
export function MinimumVersionUpgradeApp(props: {
|
||||
i18n: MinimumVersionAdmissionI18nRuntime;
|
||||
mode: "startup" | "foreground";
|
||||
port: DesktopMinimumVersionApi;
|
||||
productName: string;
|
||||
}) {
|
||||
const { i18n, mode, port, productName } = props;
|
||||
const [state, setState] = useState<MinimumVersionUpgradeState | null>(null);
|
||||
const [pending, setPending] = useState(false);
|
||||
const t = (
|
||||
key: Parameters<MinimumVersionAdmissionI18nRuntime["t"]>[0]
|
||||
): string => i18n.t(key, { productName });
|
||||
|
||||
useEffect(() => {
|
||||
let disposed = false;
|
||||
void port.getState().then((value) => {
|
||||
if (!disposed) {
|
||||
setState(value);
|
||||
}
|
||||
});
|
||||
const unsubscribe = port.onState(setState);
|
||||
return () => {
|
||||
disposed = true;
|
||||
unsubscribe();
|
||||
};
|
||||
}, [port]);
|
||||
|
||||
const run = (operation: () => Promise<unknown>): void => {
|
||||
setPending(true);
|
||||
void operation()
|
||||
.catch(() => undefined)
|
||||
.finally(() => setPending(false));
|
||||
};
|
||||
|
||||
if (!state) {
|
||||
return (
|
||||
<main className="flex min-h-screen items-center justify-center bg-[var(--background)] text-[var(--foreground)]">
|
||||
<LoadingIcon className="size-6 animate-spin" />
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
const prompt = mode === "foreground" && state.phase === "blocked";
|
||||
const checking = state.phase === "checking";
|
||||
const downloading = state.phase === "downloading";
|
||||
const failed = state.phase === "error";
|
||||
const simulationComplete = state.phase === "simulationComplete";
|
||||
const title = simulationComplete
|
||||
? t("simulationCompleteTitle")
|
||||
: prompt
|
||||
? t("foregroundTitle")
|
||||
: failed
|
||||
? t("failedTitle")
|
||||
: downloading
|
||||
? t("downloadingTitle")
|
||||
: checking
|
||||
? t("checkingTitle")
|
||||
: t("startupTitle");
|
||||
const errorKey =
|
||||
`errors.${state.message ?? "updateFailed"}` as `errors.${MinimumVersionUpgradeError}`;
|
||||
|
||||
return (
|
||||
<main className="relative flex min-h-screen items-center justify-center bg-[var(--card)] p-8 text-[var(--foreground)]">
|
||||
<Button
|
||||
aria-label={t("exit")}
|
||||
className="absolute top-3 left-3"
|
||||
disabled={pending}
|
||||
size="icon-sm"
|
||||
title={t("exit")}
|
||||
variant="ghost"
|
||||
onClick={() => run(() => port.exit())}
|
||||
>
|
||||
<CloseIcon />
|
||||
</Button>
|
||||
<section className="w-full max-w-[440px]">
|
||||
<h1 className="text-lg font-semibold">{title}</h1>
|
||||
<p className="mt-2 text-sm leading-5 text-[var(--muted-foreground)]">
|
||||
{simulationComplete
|
||||
? t("simulationCompleteDetail")
|
||||
: prompt
|
||||
? t("foregroundDetail")
|
||||
: failed
|
||||
? t(errorKey)
|
||||
: t("startupDetail")}
|
||||
</p>
|
||||
{failed && state.update.message ? (
|
||||
<p className="mt-2 break-words text-xs leading-5 text-[var(--destructive)]">
|
||||
{state.update.message}
|
||||
</p>
|
||||
) : null}
|
||||
<dl className="mt-6 grid grid-cols-[auto_1fr] items-center gap-x-2 gap-y-1 text-sm">
|
||||
<dt className="text-[var(--muted-foreground)]">
|
||||
{t("currentVersion")}
|
||||
</dt>
|
||||
<dd className="tabular-nums">{state.check.currentVersion}</dd>
|
||||
<dt className="text-[var(--muted-foreground)]">
|
||||
{t("minimumVersion")}
|
||||
</dt>
|
||||
<dd className="tabular-nums">{state.check.minimumVersion}</dd>
|
||||
</dl>
|
||||
{downloading ? (
|
||||
<div className="mt-5">
|
||||
<div className="mb-2 flex justify-between text-xs text-[var(--muted-foreground)]">
|
||||
<span>{t("downloadProgress")}</span>
|
||||
<span className="tabular-nums">
|
||||
{percent(state.update.downloadPercent)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="h-2 overflow-hidden rounded-full bg-[var(--muted)]">
|
||||
<div
|
||||
className="h-full bg-[var(--primary)] transition-[width]"
|
||||
style={{ width: percent(state.update.downloadPercent) }}
|
||||
/>
|
||||
</div>
|
||||
<p className="mt-3 text-xs text-[var(--muted-foreground)]">
|
||||
{t("autoRestartNotice")}
|
||||
</p>
|
||||
</div>
|
||||
) : null}
|
||||
<div className="mt-6 flex flex-wrap justify-end gap-2">
|
||||
{simulationComplete ? (
|
||||
<Button
|
||||
variant="secondary"
|
||||
disabled={pending}
|
||||
onClick={() => run(() => port.restart())}
|
||||
>
|
||||
{t("restart")}
|
||||
</Button>
|
||||
) : null}
|
||||
{failed ? (
|
||||
<>
|
||||
<Button
|
||||
variant="secondary"
|
||||
disabled={pending}
|
||||
onClick={() => run(() => port.exit())}
|
||||
>
|
||||
{t("exit")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="secondary"
|
||||
disabled={pending}
|
||||
onClick={() => run(() => port.openManualDownload())}
|
||||
>
|
||||
{t("manualDownload")}
|
||||
</Button>
|
||||
<Button
|
||||
disabled={pending}
|
||||
onClick={() => run(() => port.retry())}
|
||||
>
|
||||
{t("retry")}
|
||||
</Button>
|
||||
</>
|
||||
) : state.phase === "blocked" ? (
|
||||
<Button disabled={pending} onClick={() => run(() => port.start())}>
|
||||
{t("upgradeNow")}
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export { MinimumVersionUpgradeApp } from "./MinimumVersionUpgradeApp.tsx";
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"extends": "../../../packages/configs/tsconfig/base.json",
|
||||
"compilerOptions": {
|
||||
"allowImportingTsExtensions": true,
|
||||
"jsx": "react-jsx",
|
||||
"types": ["node", "react", "react-dom"]
|
||||
},
|
||||
"include": ["src/**/*", "tsup.config.ts"]
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { defineConfig } from "tsup";
|
||||
|
||||
export default defineConfig({
|
||||
clean: true,
|
||||
dts: true,
|
||||
entry: {
|
||||
index: "src/index.ts",
|
||||
"contracts/index": "src/contracts/index.ts",
|
||||
"core/index": "src/core/index.ts",
|
||||
"development/index": "src/development/index.ts",
|
||||
"development/mock-server-cli": "src/development/mockServerCli.ts",
|
||||
"electron-main/index": "src/electron-main/index.ts",
|
||||
"feature-availability/index": "src/feature-availability/index.ts",
|
||||
"i18n/index": "src/i18n/index.ts",
|
||||
"mandatory-updater/index": "src/mandatory-updater/index.ts",
|
||||
"preload/feature-availability": "src/preload/featureAvailability.ts",
|
||||
"preload/index": "src/preload/index.ts",
|
||||
"preload/minimum-version": "src/preload/minimumVersion.ts",
|
||||
"react/index": "src/react/index.ts"
|
||||
},
|
||||
external: ["electron", "react", "react-dom"],
|
||||
format: ["esm"],
|
||||
removeNodeProtocol: false,
|
||||
sourcemap: true
|
||||
});
|
||||
Reference in new issue
Block a user