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 DigestNoSubscriberWarning(cfg *config.Config) string
- func MatchWebhooks(cfg *config.NotificationConfig, eventType, projectKey string) []config.WebhookConfig
- func NormalizeKind(k string) string
- func PostWebhook(ctx context.Context, target, eventType string, body []byte, secretValue string, ...) error
- func RenderMessage(kind string, m Message) ([]byte, error)
- func RenderMessageWithLimit(kind string, m Message, 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 EventPayload
- type JobSummary
- type 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, agent, project, idleAt, link string, ...) Message
- func TransferMessage(eventType, detailJSON string, at int64) (Message, bool)
- type Payload
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
Variables ¶
var DefaultTriggerEvents = []string{"job.terminal", "interaction.created", "job.needs_review", "plan.blocked", "job.retry_exhausted", "job.budget_exceeded", "plan.leader_exhausted", "session.awaiting_reply", EventWorkRemind, EventWorkDigest, EventWorkNeedsMe}
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.
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 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 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, 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.
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.
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 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 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, idleAt, link string, at int64) Message
SessionAwaitingReplyMessage renders the delayed continuous-session reminder.
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"`
}
Payload is the full webhook body `{event, job}`.