internal/frontend/hub_saved.go

package frontend

import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"io"
	"sort"
	"strconv"

	"git.cafe/ezterry/ez-agent/internal/agenthub/store"
)

type savedHubRow struct {
	target              store.HubTarget
	pin                 store.ID
	alias               string
	successOrder        uint64
	last                bool
	needsAdmission      bool
	completedAdmission  bool
	unansweredAdmission bool
	revoked             bool
}

func savedAddressSuccessOrder(entry store.Entry, address store.Address) uint64 {
	if entry.AddressHistory == nil {
		return 0
	}
	for _, use := range entry.AddressHistory.Successes {
		if use.Address == address {
			return use.SuccessOrder
		}
	}
	return 0
}

// savedHubRows gives each exact local address its own deterministic chooser
// row. Successful addresses sort newest first; never-used addresses follow in
// identity and address order.
func savedHubRows(entries []store.Entry) []savedHubRow {
	rows := make([]savedHubRow, 0)
	for _, entry := range entries {
		if entry.Trust.GenesisID == nil {
			continue
		}
		for _, address := range entry.Addresses {
			rows = append(rows, savedHubRow{
				target:         store.HubTarget{Genesis: *entry.Trust.GenesisID, Address: address},
				pin:            entry.Trust.PinnedID,
				alias:          entry.Alias,
				successOrder:   savedAddressSuccessOrder(entry, address),
				last:           entry.LastAddress != nil && *entry.LastAddress == address,
				needsAdmission: entry.AuthorizationRevision == nil && entry.Receipt == nil,
				revoked:        entry.RecognizedRevocation != nil,
			})
		}
	}
	sort.Slice(rows, func(i, j int) bool {
		a, b := rows[i], rows[j]
		if a.successOrder != b.successOrder {
			return a.successOrder > b.successOrder
		}
		if compared := bytes.Compare(a.target.Genesis[:], b.target.Genesis[:]); compared != 0 {
			return compared < 0
		}
		if a.target.Address.Host != b.target.Address.Host {
			return a.target.Address.Host < b.target.Address.Host
		}
		return a.target.Address.Port < b.target.Address.Port
	})
	return rows
}

func clearSavedHubEntries(entries []store.Entry) {
	for i := range entries {
		entries[i].Close()
	}
	clear(entries)
}

func writeSavedHubChooser(out io.Writer, rows []savedHubRow) error {
	if out == nil {
		return ErrHubAdmissionDisplayFailed
	}
	if _, err := io.WriteString(out, "Saved AgentHubs:\n"); err != nil {
		return ErrHubAdmissionDisplayFailed
	}
	if len(rows) == 0 {
		if _, err := io.WriteString(out, "  No saved AgentHubs. Enter a deliberate new address below.\n"); err != nil {
			return ErrHubAdmissionDisplayFailed
		}
	}
	for i, row := range rows {
		alias := terminalSafeField(row.alias)
		if alias == "" {
			alias = "(no alias)"
		}
		use := "never connected"
		if row.successOrder != 0 {
			use = "previously connected"
		}
		if row.last {
			use = "last successful address"
		}
		if row.needsAdmission {
			use += "; admission recovery pending, not access"
		}
		if row.completedAdmission {
			use += "; completed admission did not grant access"
		}
		if row.unansweredAdmission {
			use += "; unanswered admission request saved, retry the same JOIN details"
		}
		if row.revoked {
			use += "; confirmed revoked, ordinary connection blocked"
		}
		if _, err := fmt.Fprintf(out, "  %d) %s\n     Alias: %s; Hub fingerprint: %s; Hub genesis: %s; %s\n", i+1, terminalSafeField(row.target.Address.String()), alias, row.pin.String(), row.target.Genesis.String(), use); err != nil {
			return ErrHubAdmissionDisplayFailed
		}
	}
	if _, err := io.WriteString(out, "  Enter a new host:port only for an independently verified admission. Unrelated new Hubs cannot be added to a populated store.\n"); err != nil {
		return ErrHubAdmissionDisplayFailed
	}
	if len(rows) != 0 {
		if _, err := io.WriteString(out, "  Type 'name' to set, rename, or remove a local Hub alias.\n  Type 'readmit' to select an exact saved address for admission recovery or a fresh claimant-locked invitation. This never erases trust or grants access without owner approval.\n"); err != nil {
			return ErrHubAdmissionDisplayFailed
		}
	}
	return nil
}

type hubChoice struct {
	target           store.HubTarget
	admissionAddress string
	admit            bool
	exactTarget      bool
}

func savedTargetNeedsAdmission(entries []store.Entry, target store.HubTarget) bool {
	for _, entry := range entries {
		if entry.Trust.GenesisID == nil || *entry.Trust.GenesisID != target.Genesis || entry.RecognizedRevocation != nil {
			continue
		}
		for _, address := range entry.Addresses {
			if address == target.Address {
				return entry.AuthorizationRevision == nil && entry.Receipt == nil
			}
		}
	}
	return false
}

func admissionRecoveryChoice(entries []store.Entry, choice hubChoice) hubChoice {
	if !choice.admit && savedTargetNeedsAdmission(entries, choice.target) {
		choice.admit = true
		choice.admissionAddress = choice.target.Address.String()
	}
	return choice
}

type hubSavedDependencies struct {
	saved    func(context.Context, *store.ClientStore) ([]store.Entry, error)
	pending  func(context.Context, *store.ClientStore) (store.AdmissionPreflightView, error)
	resolve  func(context.Context, *store.ClientStore, string) (store.HubTarget, error)
	revision func(context.Context, *store.ClientStore) (uint64, error)
	setAlias func(context.Context, *store.ClientStore, uint64, store.ID, string) error
}

func savedTargetRevoked(entries []store.Entry, target store.HubTarget) bool {
	for _, entry := range entries {
		if entry.Trust.GenesisID != nil && *entry.Trust.GenesisID == target.Genesis && entry.RecognizedRevocation != nil {
			for _, address := range entry.Addresses {
				if address == target.Address {
					return true
				}
			}
		}
	}
	return false
}

func savedReadmissionChoice(ctx context.Context, in *confirmationInput, out io.Writer, entries []store.Entry, target store.HubTarget) (hubChoice, error) {
	if out == nil {
		return hubChoice{}, ErrHubAdmissionDisplayFailed
	}
	var pin store.ID
	for _, entry := range entries {
		if entry.Trust.GenesisID != nil && *entry.Trust.GenesisID == target.Genesis {
			pin = entry.Trust.PinnedID
		}
	}
	status := "Fresh admission or recovery is explicit; ordinary transport failure does not confirm revocation."
	if savedTargetRevoked(entries, target) {
		status = "Confirmed revoked; ordinary connection is blocked."
	}
	if _, err := fmt.Fprintf(out, "Saved Hub genesis %s at %s, accepted pin %s. %s\nRecover its exact interrupted admission, or use a fresh invitation locked to this client. The saved pin and address will not change.\n", target.Genesis.String(), terminalSafeField(target.Address.String()), pin.String(), status); err != nil {
		return hubChoice{}, ErrHubAdmissionDisplayFailed
	}
	action, err := promptLine(ctx, in, out, "Type 'readmit' to continue, or 'cancel': ")
	if err != nil {
		return hubChoice{}, err
	}
	if action != "readmit" {
		return hubChoice{}, ErrHubReadmissionCancelled
	}
	return hubChoice{target: target, exactTarget: true, admit: true, admissionAddress: target.Address.String()}, nil
}

var defaultHubSavedDependencies = hubSavedDependencies{
	pending: func(ctx context.Context, client *store.ClientStore) (store.AdmissionPreflightView, error) {
		return client.AdmissionPreflight(ctx)
	},
	saved: func(ctx context.Context, client *store.ClientStore) ([]store.Entry, error) {
		return client.SavedHubs(ctx)
	},
	resolve: func(ctx context.Context, client *store.ClientStore, selection string) (store.HubTarget, error) {
		return client.ResolveSavedHub(ctx, selection)
	},
	revision: func(ctx context.Context, client *store.ClientStore) (uint64, error) {
		view, err := client.RevisionContext(ctx)
		return view.Revision, err
	},
	setAlias: func(ctx context.Context, client *store.ClientStore, revision uint64, genesis store.ID, alias string) error {
		return client.SetHubAlias(ctx, revision, genesis, alias)
	},
}

func renameSavedHub(ctx context.Context, in *confirmationInput, out io.Writer, client *store.ClientStore, rows []savedHubRow, deps hubSavedDependencies) error {
	if len(rows) == 0 || deps.revision == nil || deps.setAlias == nil {
		return ErrHubSelectionRequired
	}
	selection, err := promptLine(ctx, in, out, "Saved Hub row to name or rename: ")
	if err != nil {
		return err
	}
	number, err := strconv.Atoi(selection)
	if err != nil || number < 1 || number > len(rows) {
		return ErrHubSelectionRequired
	}
	alias, err := promptLine(ctx, in, out, "Local Hub alias (blank removes it): ")
	if err != nil {
		return err
	}
	revision, err := deps.revision(ctx, client)
	if err != nil {
		return err
	}
	if err := deps.setAlias(ctx, client, revision, rows[number-1].target.Genesis, alias); err != nil {
		return err
	}
	shown := terminalSafeField(alias)
	if shown == "" {
		shown = "(no alias)"
	}
	if _, err := fmt.Fprintf(out, "Local alias for Hub %s is now %s. Aliases are labels, never trust input.\n", rows[number-1].target.Genesis.String(), shown); err != nil {
		return ErrHubAdmissionDisplayFailed
	}
	return nil
}

func resolveHubChoice(ctx context.Context, client *store.ClientStore, selection string, rows []savedHubRow, deps hubSavedDependencies) (hubChoice, error) {
	if deps.resolve != nil {
		target, err := deps.resolve(ctx, client, selection)
		if err == nil {
			return hubChoice{target: target, exactTarget: true}, nil
		}
		if contextErr := ctx.Err(); contextErr != nil {
			return hubChoice{}, contextErr
		}
		if errors.Is(err, store.ErrAmbiguous) {
			return hubChoice{}, store.ErrAmbiguous
		}
		if !errors.Is(err, store.ErrMissing) {
			return hubChoice{}, ErrHubSelectionRequired
		}
	}
	// Local aliases take precedence above, so aliases with numeric text remain
	// usable without hiding exact numbered rows.
	if number, err := strconv.Atoi(selection); err == nil {
		if number < 1 || number > len(rows) {
			return hubChoice{}, ErrHubSelectionRequired
		}
		return hubChoice{target: rows[number-1].target, exactTarget: true}, nil
	}
	if _, parseErr := store.ParseAddress(selection); parseErr == nil {
		return hubChoice{admit: true, admissionAddress: selection}, nil
	}
	return hubChoice{}, ErrHubSelectionRequired
}

func chooseSavedHub(ctx context.Context, requested string, in *confirmationInput, out io.Writer, owner *HubClient, deps hubSavedDependencies) (hubChoice, error) {
	client, err := owner.clientStore()
	if err != nil {
		return hubChoice{}, err
	}
	if deps.saved == nil {
		return hubChoice{}, ErrHubSelectionRequired
	}
	entries, err := deps.saved(ctx, client)
	defer clearSavedHubEntries(entries)
	if err != nil {
		if contextErr := ctx.Err(); contextErr != nil {
			return hubChoice{}, contextErr
		}
		return hubChoice{}, ErrHubSelectionRequired
	}
	rows := savedHubRows(entries)
	if deps.pending != nil {
		view, err := deps.pending(ctx, client)
		defer view.Close()
		if err != nil {
			return hubChoice{}, ErrHubSelectionRequired
		}
		for i := range rows {
			recovery, found, recoveryErr := selectAdmissionRecovery(view, rows[i].target)
			rows[i].needsAdmission = rows[i].needsAdmission || found || errors.Is(recoveryErr, ErrHubAdmissionRecoveryRequired)
			completed := found && !recovery.pendingApproval
			if errors.Is(recoveryErr, ErrHubAdmissionRecoveryRequired) {
				choices, err := admissionRecoveryChoices(view, rows[i].target)
				completed = err == nil && len(choices) != 0
				for _, choice := range choices {
					completed = completed && !choice.pendingApproval
				}
			}
			if completed {
				rows[i].needsAdmission = false
				rows[i].completedAdmission = true
			}
			for _, pending := range view.Pending {
				if pending.Phase == store.PendingUnanswered && pending.Subject == rows[i].pin && pending.AdmissionAddress != nil && *pending.AdmissionAddress == rows[i].target.Address {
					rows[i].unansweredAdmission = true
				}
			}
		}
	}

	if requested != "" {
		choice, resolveErr := resolveHubChoice(ctx, client, requested, rows, deps)
		if resolveErr == nil {
			if savedTargetRevoked(entries, choice.target) {
				return savedReadmissionChoice(ctx, in, out, entries, choice.target)
			}
			return admissionRecoveryChoice(entries, choice), nil
		}
		if !errors.Is(resolveErr, store.ErrAmbiguous) {
			return hubChoice{}, resolveErr
		}
	}

	if err := writeSavedHubChooser(out, rows); err != nil {
		return hubChoice{}, err
	}
	for {
		selection, promptErr := promptLine(ctx, in, out, "Select a number, alias, exact address, or 'last'; type 'name' to rename or 'readmit' for admission: ")
		if promptErr != nil {
			if contextErr := ctx.Err(); contextErr != nil {
				return hubChoice{}, contextErr
			}
			return hubChoice{}, ErrHubSelectionRequired
		}
		if selection == "readmit" {
			row, err := promptLine(ctx, in, out, "Exact saved address row to re-admit: ")
			if err != nil {
				return hubChoice{}, err
			}
			number, err := strconv.Atoi(row)
			if err != nil || number < 1 || number > len(rows) {
				return hubChoice{}, ErrHubSelectionRequired
			}
			return savedReadmissionChoice(ctx, in, out, entries, rows[number-1].target)
		}
		if selection == "name" {
			if renameErr := renameSavedHub(ctx, in, out, client, rows, deps); renameErr == nil {
				continue
			} else if contextErr := ctx.Err(); contextErr != nil {
				return hubChoice{}, contextErr
			}
			if _, writeErr := io.WriteString(out, "The local alias was not changed. Choose a saved row and a unique non-address alias.\n"); writeErr != nil {
				return hubChoice{}, ErrHubAdmissionDisplayFailed
			}
			continue
		}
		choice, resolveErr := resolveHubChoice(ctx, client, selection, rows, deps)
		if resolveErr == nil {
			if savedTargetRevoked(entries, choice.target) {
				return savedReadmissionChoice(ctx, in, out, entries, choice.target)
			}
			return admissionRecoveryChoice(entries, choice), nil
		}
		if !errors.Is(resolveErr, store.ErrAmbiguous) && !errors.Is(resolveErr, ErrHubSelectionRequired) {
			return hubChoice{}, resolveErr
		}
		if _, writeErr := io.WriteString(out, "That selection is not exact. Choose one address row or enter a deliberate new address.\n"); writeErr != nil {
			return hubChoice{}, ErrHubAdmissionDisplayFailed
		}
	}
}