Documentation
¶
Overview ¶
Package notify implements the E14 webhook outbound side (design §5.5–5.7): it validates a webhook URL against the outbound allowlist + SSRF rules, signs and POSTs the delivery body, and matches an event to its subscribed webhooks. It depends only on internal/config (a leaf) so internal/job can enqueue/POST deliveries without an import cycle.
Index ¶
- Constants
- Variables
- func ApplyProviderAuth(kind, rawURL string, body []byte, secret string, now time.Time) (string, []byte, error)
- func BuildBody(seq int64, jobID, eventType, detailJSON string, at int64, job JobSummary) ([]byte, error)
- func BuildBodyWithLink(seq int64, jobID, eventType, detailJSON string, at int64, job JobSummary, ...) ([]byte, error)
- func CheckProviderResponse(kind string, body []byte) error
- func DigestNoSubscriberWarning(cfg *config.Config) string
- func MatchDesktop(cfg *config.NotificationConfig, eventType, projectKey string) bool
- func MatchEventHooks(hooks []config.EventHookConfig, eventType, projectKey string) []config.EventHookConfig
- func MatchWebhooks(cfg *config.NotificationConfig, eventType, projectKey string) []config.WebhookConfig
- func NormalizeKind(k string) string
- func PostWebhook(ctx context.Context, kind, target, eventType string, body []byte, ...) error
- func RenderMessage(kind string, m Message, keyword string) ([]byte, error)
- func RenderMessageWithLimit(kind string, m Message, keyword string, maxRunes int) ([]byte, error)
- func Sign(body []byte, secret string) string
- func ValidKind(k string) bool
- func ValidateWebhookURL(raw string, cfg config.NotificationConfig) error
- type EventGroup
- type EventInfo
- type EventPayload
- type JobSummary
- type Message
- func ApprovalMessage(eventType, title, reason, what, expires, link string, at int64) Message
- func BudgetMessage(eventType, detailJSON string, job JobSummary, at int64) (Message, bool)
- func InteractionMessage(eventType, summary string, options []string, link string, at int64) Message
- func PlanMessage(eventType, detailJSON string, at int64) (Message, bool)
- func RetryMessage(eventType, detailJSON string, job JobSummary, at int64) (Message, bool)
- func SessionAwaitingReplyMessage(eventType, title, body string, turn int, ...) Message
- func TransferMessage(eventType, detailJSON string, at int64) (Message, bool)
- type Payload
- type ProviderError
Constants ¶
const ( // EventWorkRemind fires once when a work item's remind_at (or the park_until of a // parked item) passes. EventWorkRemind = "work.remind" // EventWorkDigest is the deterministic daily summary (work.digest_time, default 09:00). EventWorkDigest = "work.digest" // EventWorkNeedsMe fires when a work item enters "needs me" (X2). It is a default // trigger only in the sense that a webhook without an events filter matches it; the // work.needs_me_notify switch (default OFF) is what keeps it quiet until opted in. EventWorkNeedsMe = "work.needs_me" )
Work-item notification events (W1).
const ( KindGeneric = config.WebhookKindGeneric KindDingTalk = config.WebhookKindDingTalk KindFeishu = config.WebhookKindFeishu )
Webhook kinds (OBS-07a). `generic` is the original gofer contract: the `{event, job}` JSON body signed with an X-Gofer-Signature header. The other kinds are IM bot adapters — they speak the provider's own message JSON, so a group bot renders a readable card instead of rejecting an unknown payload. The canonical list lives in internal/config (next to the yaml field it validates); these are aliases so the renderers read naturally.
const ( EventHeader = "X-Gofer-Event" SignatureHeader = "X-Gofer-Signature" )
EventHeader / SignatureHeader are the headers a webhook POST carries. The signature is `sha256=<hex hmac>` over the exact request body (design §5.6); X-Gofer-Event echoes the triggering event type.
const DefaultPostTimeoutSeconds = 5
DefaultPostTimeoutSeconds bounds one webhook POST (SR603/§5.6). It is a hard upper bound on a single attempt; the sweeper retries on the backoff table.
const DingTalkFeishuMaxBytes = 18000
const EventUpdateAvailable = "update.available"
EventUpdateAvailable fires once per newly found gofer release (server.update).
Variables ¶
var DefaultDesktopEvents = []string{"job.awaiting_approval", "interaction.created", "session.awaiting_reply", "job.needs_review"}
DefaultDesktopEvents is the trigger set the DESKTOP channel subscribes to when its `events` list is omitted (gofer-3wce). It is deliberately narrower than the webhook default: a desktop notification is an interruption on the machine's own screen, so only "this waits for a person right now" belongs in it — a job held for approval, an interaction (a question / permission) the agent raised, a continuous session waiting for a reply, and a job parked for human review.
var DefaultTriggerEvents = []string{"job.terminal", "interaction.created", "job.needs_review", "job.awaiting_approval", "plan.blocked", "job.retry_exhausted", "job.budget_exceeded", "plan.leader_exhausted", "session.awaiting_reply", EventWorkRemind, EventWorkDigest, EventWorkNeedsMe, "job.delivery_failed", EventUpdateAvailable}
DefaultTriggerEvents is the trigger set a webhook subscribes to when its `events` list is omitted (design §5.5/D5): the terminal event, a new interaction, and — since GATE-01 S3 — a job parking for人工验收. All of them are "a human/system must step in" signals; job.needs_review can only happen for a job that explicitly asked for review (--review / require_review), so a project that never uses the gate never sees it. The follow-up decision (job.reviewed) is NOT a default trigger — it closes a loop the subscriber already opened — but a webhook can subscribe to it explicitly.
plan.blocked (PLAN-03, design §六 decision 1) joins them: a chain job failing parks the whole plan, and nobody else will move it — exactly the "a human must act" shape. It can only happen on a plan that USES dependencies, so a project with flat checklists never sees it.
job.retry_exhausted (R2/AUTO-03, design §二.3) joins them for the same reason: the retry budget is spent, so nobody will run this work again — and it can only happen on a job whose retry policy was turned ON deliberately. Its two siblings (job.retry_scheduled / job.retry_started) are NOT defaults: a retry that is still coming is not a call to action, and a subscriber can list them explicitly. plan.leader_exhausted (MCP-05 阶段 B, design §二.B.3) joins them for the same reason: a plan has spent its leader-round budget, gofer has stopped waking leaders for it and nothing moves the chain until a person does — the sibling events (leader_woken / leader_skipped / leader_cancelled) stay out, because a round that ran (or was taken over by a human) is not a call to action.
job.budget_exceeded (N2 §B GATE-02) joins them too: the budget meter killed a job at its spend ceiling, and only a person can decide whether the limit was wrong or the job ran away (the job.terminal that follows it says "failed", this one says why).
work.remind and work.digest (W1, work items) join them: a reminder is the person's own deadline arriving, and the daily digest is the one summary nobody has to ask for — both only exist when work items are used, so a deployment that never creates one sees nothing.
job.awaiting_approval (gofer-9b1b) joins them: a job held for approval does nothing until a person approves it, and it only happens to a job submitted with --hold. The decisions that follow (job.hold_approved / job.hold_rejected / job.hold_expired) are NOT defaults — they close the loop the approver already acted on (an expired hold ends in job.terminal{cancelled}, which is one).
job.delivery_failed (GIT-02) joins them: a finished job's branch could not be merged / pushed / turned into a pull request, and only a person can fix the cause (a conflict, a missing token, a branch that moved). job.delivered is not a default — it closes the loop the project config already decided.
update.available (gofer-29gi) joins them: a newer gofer release was found, and only an administrator decides when to upgrade. It fires once per version, and never when the update check is off.
var EventGroups = []EventGroup{
{Key: "job", Zh: "任务", En: "Jobs"},
{Key: "interaction", Zh: "交互与审批", En: "Interactions and approvals"},
{Key: "session", Zh: "持续会话", En: "Sessions"},
{Key: "plan", Zh: "计划与工作流", En: "Plans"},
{Key: "work", Zh: "工作项", En: "Work items"},
{Key: "system", Zh: "系统", En: "System"},
}
EventGroups is the ordered group list the console shows. A catalog entry whose group is missing here is a bug the coverage test catches.
Functions ¶
func ApplyProviderAuth ¶
func ApplyProviderAuth(kind, rawURL string, body []byte, secret string, now time.Time) (string, []byte, error)
ApplyProviderAuth applies the provider's own signature to a rendered delivery just before it is posted (both schemes bind a fresh timestamp, so this cannot happen at enqueue time). secret == "" means the bot uses keyword or IP-allowlist security instead — nothing to do.
- DingTalk: sign = base64(HMAC-SHA256(key=secret, data="<ms-timestamp>\n<secret>")), carried as the `timestamp` + `sign` query parameters.
- Feishu: sign = base64(HMAC-SHA256(key="<sec-timestamp>\n<secret>", data="")), carried as the `timestamp` + `sign` fields of the JSON body.
It returns the URL and body to actually post; for the generic kind both are returned unchanged (its HMAC lives in the X-Gofer-Signature header instead).
func BuildBody ¶
func BuildBody(seq int64, jobID, eventType, detailJSON string, at int64, job JobSummary) ([]byte, error)
BuildBody marshals the webhook body. detailJSON is the event's detail_json original (may be ""); it is embedded as a raw JSON value when it is valid JSON, otherwise dropped (the event still carries seq/type/at). It never errors on a bad detail — the body is an audit/notify payload, not a strict contract.
func BuildBodyWithLink ¶ added in v0.137.0
func BuildBodyWithLink(seq int64, jobID, eventType, detailJSON string, at int64, job JobSummary, link string) ([]byte, error)
BuildBodyWithLink is BuildBody plus the optional top-level link.
func CheckProviderResponse ¶ added in v0.186.0
CheckProviderResponse inspects a webhook response body for kind and returns a *ProviderError when the provider accepted the HTTP call but refused the message. It returns nil for the generic kind (which has no such envelope), for a body that is not a JSON object, and for one that carries no code field.
func DigestNoSubscriberWarning ¶
DigestNoSubscriberWarning is the OBS-13 check shared by `gofer steward status`, GET /v1/steward and `gofer config validate`: the daily digest (or the steward, whose review shares the digest's clock) is ON, yet no webhook would match work.digest, so the summary is built and silently goes nowhere. It returns "" when nothing is wrong.
func MatchDesktop ¶ added in v0.186.0
func MatchDesktop(cfg *config.NotificationConfig, eventType, projectKey string) bool
MatchDesktop reports whether an event should pop a desktop notification on the server's own machine (gofer-3wce): the notification block is not paused, the desktop channel exists and is not paused, the project filter admits projectKey and the event filter admits eventType (empty = DefaultDesktopEvents).
Like MatchWebhooks it applies the pause switches at ENQUEUE time and does not consult the per-project notify_enabled gate, which the caller applies (it has the ProjectConfig).
func MatchEventHooks ¶ added in v0.140.0
func MatchEventHooks(hooks []config.EventHookConfig, eventType, projectKey string) []config.EventHookConfig
MatchEventHooks returns the event hooks that subscribe to eventType for projectKey (AUTO-04). It shares the webhook filter rules (events / projects, an empty event filter = DefaultTriggerEvents) plus the hook-only wildcard `*` = every event, and skips a paused hook or one without a command.
Unlike MatchWebhooks it has NO notification gate: notification.enabled and the per-project notify_enabled are switches for notifying people, while a hook is an automation side channel with its own enabled / projects.
func MatchWebhooks ¶
func MatchWebhooks(cfg *config.NotificationConfig, eventType, projectKey string) []config.WebhookConfig
MatchWebhooks returns the webhooks in cfg that subscribe to eventType for projectKey (design §5.6 enqueue match): a webhook matches when
- the notification block itself is not paused (Enabled, S4), AND
- the webhook itself is not paused (Enabled, S4), AND
- its project filter is empty OR contains projectKey, AND
- its event filter contains eventType (or, when its event filter is empty, eventType is in DefaultTriggerEvents).
It does NOT consult per-project notify_enabled — that gate is applied by the caller (the job service has the ProjectConfig) so this stays a pure function of the notification config. The returned slice is the subset to enqueue one delivery each for.
The two pause switches are applied HERE, at ENQUEUE time, and deliberately not in the delivery sweeper: pausing stops NEW notifications, while a delivery already queued still drains (a pause must not strand a pending row, and nobody paused it asking for a half-sent webhook).
func NormalizeKind ¶
NormalizeKind maps "" to KindGeneric and lowercases the rest.
func PostWebhook ¶
func PostWebhook(ctx context.Context, kind, target, eventType string, body []byte, secretValue string, cfg config.NotificationConfig) error
PostWebhook validates target and POSTs body as application/json with the E14 headers (design §5.6). It re-validates the URL on every send (config can have reloaded) and resolves the HMAC secret from secretEnv via os.Getenv (SR403 — secret is never logged or stored). The request runs under ctx (the sweeper gives it a per-attempt timeout) and does NOT follow redirects (anti-SSRF: a 3xx could bounce to an internal host). A 2xx is success (nil); any other status or a transport error is returned.
For the IM kinds a 2xx is not the last word: dingtalk / feishu answer 200 with a business code in the body when they refuse the message, so the body is parsed too and a non-zero code becomes a *ProviderError (gofer-map1).
eventType is stamped into X-Gofer-Event. secretValue is the already-resolved secret (the caller reads the env so this stays test-friendly / pure).
func RenderMessage ¶
RenderMessage builds the POST body for kind. The provider signature is NOT applied here (it is time-sensitive): call ApplyProviderAuth at post time. keyword is the target webhook's `keyword` (see withKeyword); "" injects nothing.
func RenderMessageWithLimit ¶
RenderMessageWithLimit renders an IM payload using the target webhook's rune budget. Generic webhooks retain their original JSON contract and are not truncated; IM adapters apply the rune budget and provider byte ceiling.
func Sign ¶
Sign returns the hex HMAC-SHA256 of body under secret, formatted as the X-Gofer-Signature value `sha256=<hex>`. An empty secret yields "".
func ValidateWebhookURL ¶
func ValidateWebhookURL(raw string, cfg config.NotificationConfig) error
ValidateWebhookURL enforces the E14 outbound safety rules (design §5.7, SR904):
- the URL parses and has a host;
- the scheme is https (http only when cfg.AllowHTTP, for local testing);
- the host is in cfg.AllowHosts (when AllowHosts is non-empty; an empty allowlist means "no host is permitted" — fail closed);
- every resolved IP is public: loopback / private / link-local / unique-local / unspecified / multicast addresses are rejected (anti-SSRF).
It performs DNS resolution, so a host that resolves only to internal addresses is rejected even if it is allowlisted by name (defence in depth). A host that does not resolve is rejected (cannot prove it is public).
Types ¶
type EventGroup ¶ added in v0.201.0
EventGroup is one group of the catalog (the picker's section heading).
type EventInfo ¶ added in v0.201.0
type EventInfo struct {
Key string `json:"key"`
Group string `json:"group"`
Zh string `json:"zh"`
En string `json:"en"`
// Default reports membership of DefaultTriggerEvents: a webhook (or event hook,
// which shares the set) with no events filter receives this event.
Default bool `json:"default"`
// DesktopDefault reports membership of DefaultDesktopEvents: the desktop channel
// with no events filter pops this event.
DesktopDefault bool `json:"desktop_default"`
}
EventInfo is one catalog entry: the trigger key, the group it belongs to, the description in both console languages, and whether each channel subscribes to it when its own `events` list is empty.
func EventCatalog ¶ added in v0.201.0
func EventCatalog() []EventInfo
EventCatalog returns the catalog with each entry's Default / DesktopDefault flags filled from the two default sets, i.e. from the same values the matchers use. The slice is a copy: a caller cannot mutate the package's catalog.
type EventPayload ¶
type EventPayload struct {
Seq int64 `json:"seq"`
JobID string `json:"job_id"`
Type string `json:"type"`
Detail json.RawMessage `json:"detail,omitempty"`
At int64 `json:"at"`
}
EventPayload / JobSummary / Payload are the webhook POST body shape (design §5.6). detail is the event's raw detail_json passed through as a JSON value (RawMessage) so the consumer sees the same structure recorded in the stream.
type JobSummary ¶
type JobSummary struct {
ID string `json:"id"`
Status string `json:"status"`
Project string `json:"project"`
Agent string `json:"agent,omitempty"`
Runner string `json:"runner,omitempty"`
ExitCode int `json:"exit_code"`
Title string `json:"title,omitempty"`
SessionEndReason string `json:"session_end_reason,omitempty"`
SessionID string `json:"session_id,omitempty"`
}
JobSummary is the small job snapshot attached to a webhook body (no secrets): just identity/routing/status so the consumer can act without a follow-up fetch.
type Message ¶
type Message struct {
EventType string
Title string
Text string
Link string
LinkLabel string
// At is the event time (unix seconds); 0 = omit from the generic body.
At int64
}
Message is the provider-neutral notification an IM adapter renders. Title is one line; Text may be multi-line; Link, when set, is appended as a tappable link (that is why DingTalk uses markdown rather than text). EventType is echoed in the X-Gofer-Event header and in the generic body.
func ApprovalMessage ¶ added in v0.137.0
ApprovalMessage renders job.awaiting_approval (gofer-9b1b) for an IM bot: a job held for a person's approval. what is the head of what it would run (an exec job's command line, or the first lines of an agent job's prompt), expires the local time the hold lapses (the job is then cancelled). The link opens the job page, where the approval panel is.
func BudgetMessage ¶
func BudgetMessage(eventType, detailJSON string, job JobSummary, at int64) (Message, bool)
BudgetMessage renders job.budget_exceeded (N2 §B GATE-02) for an IM bot: WHICH job the budget meter killed and which limit it crossed (ceiling and used value), the two facts the person deciding "raise the limit or stop the job" needs. ok=false for every other event type.
func InteractionMessage ¶
InteractionMessage is the compact IM-only rendering for an approval or question event. The generic webhook keeps its durable {event, job} contract.
func PlanMessage ¶
PlanMessage renders a plan-scope event (scope `plan:<id>`) as the short message an IM bot shows (PLAN-03). plan.blocked is the one in the default trigger set: a chain job failed and the plan parked on its item, so the message names the ITEM, the JOB and the reason — the three things the person who has to unblock it needs. Every other plan event (a queued item, a completed chain) renders as its own type with whatever ids its detail carries; ok=false for a non-plan event, so a caller falls back to the job shape.
func RetryMessage ¶
func RetryMessage(eventType, detailJSON string, job JobSummary, at int64) (Message, bool)
RetryMessage renders job.retry_exhausted (R2/AUTO-03, design §二.3) as the short message an IM bot shows: WHICH job gave up, how many attempts were made and the last exit code — the three facts the person who now has to take the work over needs. It is a default trigger, so this is the one shape that reaches a channel nobody configured.
ok=false for every other event type, so the caller falls back to the generic job line (job.retry_scheduled / job.retry_started are readable as-is: what matters about them is the job, not a number).
func SessionAwaitingReplyMessage ¶
func SessionAwaitingReplyMessage(eventType, title, body string, turn int, agent, project, runner, idleAt, link string, at int64) Message
SessionAwaitingReplyMessage renders the delayed continuous-session reminder. runner is the machine the session runs on (already a display name, see config.RunnerDisplayName); "" drops the segment.
func TransferMessage ¶
TransferMessage renders a file-transfer event (xfer.put|xfer.get) as the short message an IM bot shows: WHO moved WHAT, from/to which machine and project, how big. ok=false for any other event type, so a caller falls back to the job shape (a transfer has no job, no status and no console page to link to).
detailJSON is the transfer's audit detail as recorded (the xfer event's own fields); an unparseable one still yields a message naming the event type, never an error — this is a notification, not a contract.
type Payload ¶
type Payload struct {
Event EventPayload `json:"event"`
Job JobSummary `json:"job"`
Link string `json:"link,omitempty"`
}
Payload is the full webhook body `{event, job}`. Link is the console page the event asks a person to act on (set for job.awaiting_approval, gofer-9b1b, when server.web_base_url is configured); absent otherwise.
type ProviderError ¶ added in v0.186.0
type ProviderError struct {
// Endpoint is the adapter that was refused: KindDingTalk / KindFeishu.
Endpoint string
// Code is the provider's business code (non-zero).
Code int64
// Message is the provider's error description verbatim.
Message string
// Permanent reports that retrying the same message cannot change the outcome
// (see the classification above), so the delivery fails at once.
Permanent bool
}
ProviderError is a business rejection from an IM bot webhook: the HTTP POST succeeded (2xx) but the provider's own code says the message was not accepted. Message is the provider's original error text — it is what the delivery record, the log line and the console show, so the operator reads the real cause ("keywords not in content") instead of "status 200".
func (*ProviderError) Error ¶ added in v0.186.0
func (e *ProviderError) Error() string