Files
skillshare/internal/server/handler_hooks.go
T
ed3c825c49 feat(hooks): record Codex hook trust on sync with --trust (#829)
* feat(hooks): record Codex hook trust on sync with --trust

Codex runs a user-level hook only after its trusted_hash is stored in that
home's config.toml, keyed by the hook's position in hooks.json. Only the
TUI's /hooks review writes it, so every hook Skillshare adds or moves starts
untrusted and codex exec skips it without a word.

`hooks sync --trust` (global mode, opt-in) asks each Codex home's
`codex app-server` for the current hash of the hooks Skillshare owns and
writes trusted_hash through config/batchWrite, the same calls /hooks makes,
so the hash is always the one Codex computes. It changes nothing else in
config.toml: disabled hooks stay disabled and are reported. Trust it wrote
is remembered in the hooks state directory, so when a hook moves or is
removed the next --trust sync clears the old position, unless that trust
has changed since. Without codex on PATH the hook files are still written
and the command fails saying trust was not recorded.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(hooks): scope Codex trust to config owner

Scope trust selection and saved hashes to the active config owner so a global config cannot trust or reconcile another config’s hooks.

Recheck hooks.json after hooks/list to avoid trusting a handler from a stale position, and only report trusted or cleared actions after config/batchWrite succeeds. Keep v1 ownerless hashes cleanup-only so upgraded installs clear stale trust after hook removal without trusting foreign hooks.

* fix(hooks): retain parked Codex trust receipts

Locate hooks using all records for their canonical file before selecting the active config owner, so identical hooks remain identifiable across shared and symlinked homes. Keep cleanup receipts for parked registrations whose native group still matches, including when duplicate counts make locate ambiguous, while clearing receipts for removed hooks.

Add regressions for identical hooks across config owners, symlink aliases, parked-home restoration, ambiguous duplicates, and stale receipt cleanup.

* fix(hooks): coalesce symlinked Codex trust homes

Canonicalize current-owner and legacy trust receipts so symlink spellings of one hooks.json are processed once. Remove the redundant parked-position branch because the hash-matching fallback below covers it. Add regression coverage for current and legacy receipts.

* fix(hooks): coalesce removed Codex hook homes

Resolve existing home directories when hook files have been removed so trust receipts for symlink aliases reconcile once. Correct canonical key expectations and exercise coalescing without unsupported ledger migration.

* fix(hooks): read reconciled trust fixture into fresh state

JSON decoding retains existing map entries, so reusing the seeded receipt map makes the alias appear to survive reconciliation. Decode the persisted state into a new value to verify its actual contents.

* feat(hooks): confirm Codex trust before recording it and drop the receipts file

`hooks sync --trust` recorded trust for every owned hook without showing
what it was trusting, and tracked its own writes in codex-trust.json so
it could clear them later. Codex's review exists so that a person sees a
command before it runs, and the receipts file was the source of most of
the edge cases found in review.

Trust is now two steps. A preview asks Codex which owned hooks are new
or changed and returns them with their commands and a revision; the
write takes that revision and is refused when the hooks changed since.
The CLI lists the hooks and asks once, `--yes` skips the question, and
without a terminal nothing is trusted unless `--yes` is given. The
dashboard gets the same two steps as API routes.

Nothing is cleared any more: a leftover entry only matches a hook with
the same event, matcher and handler at that position, which is the hook
the user already approved. That removes codex-trust.json.

The app-server is started without CODEX_HOME for the default home.
Codex resolves the symlinks of CODEX_HOME but not of ~/.codex, so a
symlinked default home got a trust key the user's own Codex never looks
up.

A home whose write fails no longer stops the other homes, and the error
names which were recorded. A preview releases the hooks operation lock
before it waits on Codex, so a slow Codex does not fail other hooks
operations.

Refs #828

* feat(ui): trust Codex hooks from the Hooks page

The dashboard could sync Codex hooks but left them untrusted, so Codex
skipped them until the user ran the CLI or approved each one in Codex.

The Sync box now offers "Trust Codex hooks" in the global scope when a
hook is bound to a Codex target. The dialog shows each hook that needs
trust with its full command and records trust for exactly that list; a
change since the list was shown is refused. The button is hidden while
changes are pending, because trust covers the hooks on disk and the next
sync would invalidate it.

Refs #828

* test(ui): cover the Codex trust dialog's refused, empty and disabled states

Only the happy path was tested, so a regression in the states where the
dialog must not offer a write would have passed. The docs sentence on
several Codex homes now says what is isolated: a failed write, not a
home that cannot be listed.

Refs #828

* refactor(hooks): split the trust prompt and output rendering out of the handlers

hooks_handlers.go had grown past 500 lines and mixed orchestration with
the confirmation prompt and every print function, which the CLI layering
rule asks to keep apart. The code is moved unchanged: the prompt goes to
hooks_prompt.go and the printing to hooks_render.go.

* fix(hooks): leave out a Codex home that cannot be listed instead of stopping

With several Codex homes, one home Codex could not list aborted the whole
trust run, so a broken account home kept every other home untrusted.

A home that fails to list is now reported and left out, and the other
homes are previewed and trusted as usual. The CLI warns before the
question and exits with an error that names the home; the dashboard
dialog shows the same note. When no home can be listed the preview still
fails.

Codex answers a home it cannot load, such as one with an invalid
config.toml, with a successful reply that has no hooks and the reason in
`errors`. That was read as a home without hooks and passed silently. It
is now a failed listing that carries Codex's own message.

Refs #828

* fix(hooks): check the reviewed Codex hooks per home when recording trust

The revision was one digest over every home's hooks. When a home was
listed in the preview but failed to list again at the write, its hooks
dropped out of the digest, so the write was refused as stale: the homes
the user had just reviewed stayed untrusted and the real listing error
was hidden behind "changed since they were listed".

The revision now has one part per home. A home is refused only when its
own hooks changed; a home that cannot be listed any more is reported and
the reviewed homes are still trusted.

Refs #828

* chore: release as 0.30.10

Keep the next release on the patch version the maintainer asked for,
instead of the 0.31.0 that Release Please derives from the feat commit.

Release-As: 0.30.10

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Willie <egg358358@gmail.com>
2026-11-17 15:54:20 +08:00

372 lines
11 KiB
Go

package server
import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"reflect"
"slices"
"strings"
"time"
"skillshare/internal/config"
"skillshare/internal/hooks"
)
func (s *Server) hooksService() *hooks.Service {
service := &hooks.Service{ConfigPath: s.configPath(), ProjectRoot: s.projectRoot, StateDir: config.StateDir(), ConfigDirs: hooks.ConfigDirsFromEnv(), GitGlobalConfig: os.Getenv("GIT_CONFIG_GLOBAL")}
if !s.IsProjectMode() {
service.Accounts = hooksAccounts(s.cfg)
}
return service
}
// requireLocalHooks applies the MCP DNS-rebinding guard: hooks write commands that Agents run.
func (s *Server) requireLocalHooks(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if !s.mcpRequestAllowed(r) {
writeError(w, http.StatusForbidden, "Hooks settings are available only from the dashboard itself, opened by localhost, an IP address or a trusted origin")
return
}
next(w, r)
}
}
type hooksRequest struct {
Mutation hooks.Mutation `json:"mutation"`
Revision string `json:"revision"`
Sync bool `json:"sync"`
// Root, with sync and no mutation, applies only that hooks.projects root's changes.
Root string `json:"root"`
}
type hooksRestoreRequest struct {
BackupID string `json:"backupId"`
Preview bool `json:"preview"`
Revision string `json:"revision"`
}
func decodeHooksRequest(w http.ResponseWriter, r *http.Request, value any) bool {
var extra bool
err := decodeJSONWith(w, r, defaultJSONBodyLimit, func(d *json.Decoder) error {
d.DisallowUnknownFields()
if err := d.Decode(value); err != nil {
return err
}
extra = d.Decode(new(any)) != io.EOF
return nil
})
switch {
case errors.Is(err, errBodyTooLarge):
return false
case err != nil:
writeError(w, http.StatusBadRequest, "invalid hooks request")
return false
case extra:
writeError(w, http.StatusBadRequest, "expected one hooks request")
return false
}
return true
}
func (s *Server) handleHooksList(w http.ResponseWriter, r *http.Request) {
s.mu.RLock()
defer s.mu.RUnlock()
inventory, err := s.hooksService().List()
if err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
writeJSON(w, inventory)
}
// handleHooksCatalog lists each command Agent's documented events and timeout unit.
func (s *Server) handleHooksCatalog(w http.ResponseWriter, r *http.Request) {
writeJSON(w, hooks.Catalog)
}
func (s *Server) handleHooksPreview(w http.ResponseWriter, r *http.Request) {
var body hooksRequest
if !decodeHooksRequest(w, r, &body) {
return
}
s.mu.RLock()
defer s.mu.RUnlock()
p, err := s.hooksService().PreviewMutation(body.Mutation)
if err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
// Only the preview carries full file texts, for the dashboard's diff.
writeJSON(w, struct {
*hooks.Plan
Files []hooks.FileDiff `json:"files"`
}{p, p.Files()})
}
// handleHooksRender shows one hook's native files without planning, saving or writing.
func (s *Server) handleHooksRender(w http.ResponseWriter, r *http.Request) {
var body struct {
Mutation hooks.Mutation `json:"mutation"`
}
if !decodeHooksRequest(w, r, &body) {
return
}
s.mu.RLock()
defer s.mu.RUnlock()
files, err := s.hooksService().RenderNative(body.Mutation)
if err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
writeJSON(w, map[string]any{"rendered": files})
}
func (s *Server) handleHooksConfigure(w http.ResponseWriter, r *http.Request) {
var body hooksRequest
if !decodeHooksRequest(w, r, &body) {
return
}
if body.Revision == "" {
writeError(w, http.StatusBadRequest, "preview the hooks changes before saving")
return
}
if body.Root != "" && (!body.Sync || !reflect.DeepEqual(body.Mutation, hooks.Mutation{})) {
writeError(w, http.StatusBadRequest, "a project sync takes no changes")
return
}
if body.Root != "" && s.IsProjectMode() {
writeError(w, http.StatusBadRequest, "hooks.projects roots are available only in global mode; omit root")
return
}
s.mu.Lock()
defer s.mu.Unlock()
start := time.Now()
var result *hooks.Result
var err error
args := map[string]any{"scope": "ui", "sync": body.Sync}
if body.Root != "" {
args["project"] = body.Root
result, err = s.hooksService().ApplyProject(body.Revision, body.Root)
} else {
result, err = s.hooksService().Mutate(body.Mutation, body.Revision, body.Sync)
}
if body.Mutation.Name != "" {
args["name"] = body.Mutation.Name
}
s.writeOpsLog("hooks configure", opStatus(err), start, args, "")
if errors.Is(err, hooks.ErrUnknownProject) {
writeError(w, http.StatusBadRequest, err.Error())
return
}
if err != nil {
writeHooksFailure(w, result, err)
return
}
if err := s.reloadConfig(); err != nil {
writeError(w, http.StatusInternalServerError, "hooks saved, but config reload failed")
return
}
writeJSON(w, result)
}
type hooksNativeRequest struct {
Edits []hooks.NativeEdit `json:"edits"`
Revision string `json:"revision"`
}
// handleHooksNativePreview plans changes to hooks Skillshare does not manage.
func (s *Server) handleHooksNativePreview(w http.ResponseWriter, r *http.Request) {
var body hooksNativeRequest
if !decodeHooksRequest(w, r, &body) {
return
}
s.mu.RLock()
defer s.mu.RUnlock()
p, err := s.hooksService().PreviewNativeEdits(body.Edits)
if err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
writeJSON(w, struct {
*hooks.Plan
Files []hooks.FileDiff `json:"files"`
}{p, p.Files()})
}
// handleHooksNativeApply writes previewed changes to hooks Skillshare does not manage.
func (s *Server) handleHooksNativeApply(w http.ResponseWriter, r *http.Request) {
var body hooksNativeRequest
if !decodeHooksRequest(w, r, &body) {
return
}
if body.Revision == "" {
writeError(w, http.StatusBadRequest, "preview the hooks changes before saving")
return
}
s.mu.Lock()
defer s.mu.Unlock()
start := time.Now()
result, err := s.hooksService().ApplyNativeEdits(body.Edits, body.Revision)
targets := []string{}
for _, e := range body.Edits {
if at := e.Target + "@" + e.Root; !slices.Contains(targets, strings.TrimSuffix(at, "@")) {
targets = append(targets, strings.TrimSuffix(at, "@"))
}
}
s.writeOpsLog("hooks edit-native", opStatus(err), start, map[string]any{"scope": "ui", "edits": len(body.Edits), "targets": strings.Join(targets, ", ")}, "")
if err != nil {
writeHooksFailure(w, result, err)
return
}
writeJSON(w, result)
}
type hooksTrustRequest struct {
Revision string `json:"revision"`
}
// handleHooksCodexTrustPreview lists the Codex hooks Skillshare owns and which need trust.
func (s *Server) handleHooksCodexTrustPreview(w http.ResponseWriter, r *http.Request) {
if s.IsProjectMode() {
writeError(w, http.StatusBadRequest, "Codex trust is recorded in global Codex homes only")
return
}
// Codex can be slow to answer, so the server lock is held only to read the config.
s.mu.RLock()
service := s.hooksService()
s.mu.RUnlock()
plan, err := service.PreviewCodexTrust()
if err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
writeJSON(w, plan)
}
// handleHooksCodexTrust records trust for the hooks a preview listed, after the
// dashboard's confirmation; the revision ties the write to what was shown.
func (s *Server) handleHooksCodexTrust(w http.ResponseWriter, r *http.Request) {
var body hooksTrustRequest
if !decodeHooksRequest(w, r, &body) {
return
}
if s.IsProjectMode() {
writeError(w, http.StatusBadRequest, "Codex trust is recorded in global Codex homes only")
return
}
if body.Revision == "" {
writeError(w, http.StatusBadRequest, "review the Codex hooks before trusting them")
return
}
s.mu.Lock()
defer s.mu.Unlock()
start := time.Now()
plan, err := s.hooksService().TrustCodex(body.Revision)
s.writeOpsLog("hooks trust", opStatus(err), start, map[string]any{"scope": "ui"}, "")
if err != nil {
status := http.StatusBadRequest
if errors.Is(err, hooks.ErrStaleRevision) {
status = http.StatusConflict
}
writeError(w, status, err.Error())
return
}
writeJSON(w, plan)
}
func (s *Server) handleHooksImport(w http.ResponseWriter, r *http.Request) {
var body hooks.ImportRequest
if !decodeHooksRequest(w, r, &body) {
return
}
s.mu.RLock()
defer s.mu.RUnlock()
candidates, err := s.hooksService().Import(body)
if err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
if candidates == nil {
candidates = []hooks.Candidate{}
}
writeJSON(w, map[string]any{"candidates": candidates})
}
func (s *Server) handleHooksRestore(w http.ResponseWriter, r *http.Request) {
var body hooksRestoreRequest
if !decodeHooksRequest(w, r, &body) {
return
}
if body.BackupID == "" {
writeError(w, http.StatusBadRequest, "backupId is required")
return
}
s.mu.Lock()
defer s.mu.Unlock()
service := s.hooksService()
if body.Preview {
p, err := service.PreviewRestore(body.BackupID)
if err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
writeJSON(w, p)
return
}
if body.Revision == "" {
writeError(w, http.StatusBadRequest, "preview before restoring")
return
}
start := time.Now()
result, err := service.Restore(body.BackupID, body.Revision)
s.writeOpsLog("hooks restore", opStatus(err), start, map[string]any{"scope": "ui", "backup": body.BackupID}, "")
if err != nil {
writeHooksFailure(w, result, err)
return
}
writeJSON(w, result)
}
func opStatus(err error) string {
if err != nil {
return "error"
}
return "ok"
}
// writeHooksFailure reports stale previews, conflicts and partial writes as 409 with the
// result, so the dashboard can show what was already applied; other errors are 400.
func writeHooksFailure(w http.ResponseWriter, result *hooks.Result, err error) {
partial := result != nil && len(result.Applied) > 0
if !partial && !errors.Is(err, hooks.ErrStaleRevision) && !errors.Is(err, hooks.ErrConflict) {
writeError(w, http.StatusBadRequest, err.Error())
return
}
message := err.Error()
if partial {
message += fmt.Sprintf("; already applied: %s; backup IDs: %s", strings.Join(result.Applied, ", "), strings.Join(result.BackupIDs, ", "))
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusConflict)
body := map[string]any{"error": message, "result": result}
if partial {
body["error_params"] = map[string]any{"applied": result.Applied}
}
_ = json.NewEncoder(w).Encode(body)
}
// hooksAccounts are the global targets with their own native config homes.
func hooksAccounts(cfg *config.Config) map[string]hooks.Account {
accounts := map[string]hooks.Account{}
for name, target := range cfg.Targets {
if target.Agent != "" && target.ConfigDir != "" {
accounts[name] = hooks.Account{Agent: target.Agent, Dir: target.ConfigDir, CLI: target.CLI}
}
}
return accounts
}