permission

package
v0.1.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 27, 2026 License: MIT Imports: 7 Imported by: 0

Documentation

Overview

Package permission implements the Permission Hook Bridge for handling permission requests from external Claude Code instances via Claude's hook system.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ExtractPreview

func ExtractPreview(toolName string, toolInput map[string]interface{}) string

ExtractPreview extracts a preview (content snippet) from tool input.

func ExtractTarget

func ExtractTarget(toolName string, toolInput map[string]interface{}) string

ExtractTarget extracts the target (file path or command) from tool input.

func GeneratePattern

func GeneratePattern(toolName string, toolInput map[string]interface{}) string

GeneratePattern generates a pattern from a tool name and input. Patterns are used to match future similar permission requests.

Examples:

  • Bash(rm:*) for any rm command
  • Write(*.py) for writing Python files
  • Edit(/path/to/*.json) for editing JSON files in a directory

func GeneratePermissionType

func GeneratePermissionType(toolName string) string

GeneratePermissionType maps tool names to permission event types.

func GenerateReadableDescription

func GenerateReadableDescription(toolName string, toolInput map[string]interface{}) string

GenerateReadableDescription generates a human-readable description of a permission request.

func MatchPattern

func MatchPattern(pattern, toolName string, toolInput map[string]interface{}) bool

MatchPattern checks if a permission request matches a stored pattern.

func SanitizeCommand

func SanitizeCommand(cmd string) string

SanitizeCommand sanitizes a command for display, removing sensitive info.

Types

type Config

type Config struct {
	SessionMemory SessionMemoryConfig `mapstructure:"session_memory"`
}

Config holds configuration for the permission system.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns the default permission configuration.

type Decision

type Decision string

Decision represents the user's decision for a permission request.

const (
	DecisionAllow Decision = "allow"
	DecisionDeny  Decision = "deny"
)

type HookInput

type HookInput struct {
	SessionID      string                 `json:"session_id"`
	TranscriptPath string                 `json:"transcript_path"`
	Cwd            string                 `json:"cwd"`
	PermissionMode string                 `json:"permission_mode"`
	HookEventName  string                 `json:"hook_event_name"`
	ToolName       string                 `json:"tool_name"`
	ToolInput      map[string]interface{} `json:"tool_input"`
	ToolUseID      string                 `json:"tool_use_id"`
}

HookInput represents the JSON input from Claude Code's hook system. This is what Claude sends to the hook command via stdin.

type HookOutput

type HookOutput struct {
	HookSpecificOutput HookSpecificOutput `json:"hookSpecificOutput"`
}

HookOutput represents the JSON output to Claude Code's hook system. This is what the hook command returns to Claude via stdout.

type HookSpecificOutput

type HookSpecificOutput struct {
	HookEventName            string                 `json:"hookEventName"`
	PermissionDecision       string                 `json:"permissionDecision"`                 // "allow", "deny", or "ask"
	PermissionDecisionReason string                 `json:"permissionDecisionReason,omitempty"` // Explanation shown to user
	UpdatedInput             map[string]interface{} `json:"updatedInput,omitempty"`             // Optional modified input
}

HookSpecificOutput contains the permission-specific response. Uses the new permissionDecision format expected by Claude Code.

type MemoryManager

type MemoryManager struct {
	// contains filtered or unexported fields
}

MemoryManager manages permission decisions across Claude sessions. It provides "Allow for Session" functionality by remembering decisions and auto-responding to matching permission requests.

func NewMemoryManager

func NewMemoryManager(config SessionMemoryConfig, logger zerolog.Logger) *MemoryManager

NewMemoryManager creates a new permission memory manager.

func (*MemoryManager) AddPendingRequest

func (m *MemoryManager) AddPendingRequest(req *Request)

AddPendingRequest adds a request waiting for mobile response.

func (*MemoryManager) CheckMemory

func (m *MemoryManager) CheckMemory(sessionID, toolName string, toolInput map[string]interface{}) *StoredDecision

CheckMemory checks if there's a stored decision for a permission request. Returns the decision if found, or nil if no matching pattern exists. This method is thread-safe and holds the lock for the entire operation to prevent TOCTOU race conditions.

func (*MemoryManager) ClearSession

func (m *MemoryManager) ClearSession(sessionID string)

ClearSession clears all memory for a specific session.

func (*MemoryManager) ClearWorkspace

func (m *MemoryManager) ClearWorkspace(workspaceID string)

ClearWorkspace clears all memory for sessions in a workspace.

func (*MemoryManager) GetAndRemovePendingRequest

func (m *MemoryManager) GetAndRemovePendingRequest(toolUseID string) *Request

GetAndRemovePendingRequest atomically retrieves and removes a pending request. Returns nil if the request doesn't exist. This prevents race conditions where the request is accessed after removal.

func (*MemoryManager) GetOrCreateSession

func (m *MemoryManager) GetOrCreateSession(sessionID, workspaceID string) *SessionMemory

GetOrCreateSession gets or creates session memory for a Claude session.

func (*MemoryManager) GetPendingRequest

func (m *MemoryManager) GetPendingRequest(toolUseID string) *Request

GetPendingRequest retrieves a pending request by tool use ID. Returns nil if the request doesn't exist.

func (*MemoryManager) GetSessionStats

func (m *MemoryManager) GetSessionStats() map[string]interface{}

GetSessionStats returns statistics about session memory. This method acquires locks in a consistent order to prevent deadlocks.

func (*MemoryManager) ListPendingRequests

func (m *MemoryManager) ListPendingRequests() []*Request

ListPendingRequests returns all pending permission requests. This is used when cdev-ios reconnects to get any permissions that were missed.

func (*MemoryManager) RemovePendingRequest

func (m *MemoryManager) RemovePendingRequest(toolUseID string)

RemovePendingRequest removes a pending request and closes its response channel.

func (*MemoryManager) RespondToRequest

func (m *MemoryManager) RespondToRequest(toolUseID string, response *Response) bool

RespondToRequest sends a response to a pending request. Returns true if the request was found and responded to. This method atomically removes the request and sends the response.

func (*MemoryManager) StartCleanup

func (m *MemoryManager) StartCleanup(ctx context.Context)

StartCleanup starts a goroutine that periodically cleans up expired sessions.

func (*MemoryManager) StoreDecision

func (m *MemoryManager) StoreDecision(sessionID, workspaceID, pattern string, decision Decision)

StoreDecision stores a permission decision in session memory. This method is thread-safe and atomic.

type PermissionEvent

type PermissionEvent struct {
	ToolUseID   string             `json:"tool_use_id"`
	Type        string             `json:"type"`        // "bash_command", "write_file", "edit_file"
	Target      string             `json:"target"`      // filename or command
	Description string             `json:"description"` // human-readable description
	Preview     string             `json:"preview"`     // content preview
	Options     []PermissionOption `json:"options"`     // available choices
	SessionID   string             `json:"session_id"`
	WorkspaceID string             `json:"workspace_id"`
}

PermissionEvent represents the event sent to mobile app for permission prompts.

type PermissionOption

type PermissionOption struct {
	Key         string `json:"key"`                   // "allow_once", "allow_session", "deny"
	Label       string `json:"label"`                 // "Allow Once", "Allow for Session"
	Description string `json:"description,omitempty"` // optional extra info
}

PermissionOption represents a choice in a permission prompt.

type Request

type Request struct {
	ID           string                 `json:"id"`           // Unique request ID (typically tool_use_id)
	SessionID    string                 `json:"session_id"`   // Claude session ID
	WorkspaceID  string                 `json:"workspace_id"` // cdev workspace ID (derived from cwd)
	ToolName     string                 `json:"tool_name"`    // e.g., "Bash", "Write", "Edit"
	ToolInput    map[string]interface{} `json:"tool_input"`   // The tool's input parameters
	ToolUseID    string                 `json:"tool_use_id"`  // Claude's tool use ID
	CreatedAt    time.Time              `json:"created_at"`   // When the request was received
	ResponseChan chan *Response         `json:"-"`            // Channel to receive response (not serialized)
}

Request represents a permission request being tracked by cdev.

type Response

type Response struct {
	Decision     Decision               `json:"decision"`                // allow or deny
	Scope        Scope                  `json:"scope"`                   // once, session, or path
	Pattern      string                 `json:"pattern,omitempty"`       // Pattern for session/path scope
	UpdatedInput map[string]interface{} `json:"updated_input,omitempty"` // Optional modified input
	Message      string                 `json:"message,omitempty"`       // Optional message
	Interrupt    bool                   `json:"interrupt,omitempty"`     // If true, interrupt Claude
}

Response represents a response to a permission request.

type Scope

type Scope string

Scope represents the scope of a permission decision.

const (
	ScopeOnce    Scope = "once"    // Allow/deny just this one request
	ScopeSession Scope = "session" // Allow/deny for the rest of the session
	ScopePath    Scope = "path"    // Allow for this path pattern (persisted to settings)
)

type SessionMemory

type SessionMemory struct {
	SessionID   string                    `json:"session_id"`
	WorkspaceID string                    `json:"workspace_id"`
	Decisions   map[string]StoredDecision `json:"decisions"` // pattern -> decision
	CreatedAt   time.Time                 `json:"created_at"`
	LastAccess  time.Time                 `json:"last_access"`
}

SessionMemory holds permission decisions for a single Claude session.

type SessionMemoryConfig

type SessionMemoryConfig struct {
	Enabled     bool          `mapstructure:"enabled"`
	TTL         time.Duration `mapstructure:"ttl"`          // Idle timeout for session memory
	MaxPatterns int           `mapstructure:"max_patterns"` // Max patterns per session
}

SessionMemoryConfig holds configuration for session memory.

type StoredDecision

type StoredDecision struct {
	Pattern    string    `json:"pattern"`
	Decision   Decision  `json:"decision"`
	CreatedAt  time.Time `json:"created_at"`
	UsageCount int       `json:"usage_count"` // How many times this pattern was matched
}

StoredDecision represents a decision stored in session memory.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL