notify

package
v0.1.9 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: Apache-2.0 Imports: 43 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package notify is the library part of the notify module: delivery rules as pure functions (severity filter, quiet hours, grouping), the notice model, the send record and the email approval tokens. The channel adapters live in the channel subpackage. Nothing here touches a database or core; The module wiring connects these functions to them.

Index

Constants

View Source
const (
	EventFindingCreated       = "findings.finding.created"
	EventFindingStatusChanged = "findings.finding.status_changed"
	// EventUrgencyRaised: an open finding rose into a more urgent layer of 1–4 {finding_id, cve, severity, from, to, at}: one notice per
	// escalation (a finding is told again only at a more urgent layer than any it was told at).
	EventUrgencyRaised = "findings.finding.urgency_raised"
	// EventFirstRun: the rises of a first-run window in one pass {key, at, findings, devices, layer, finding_ids, cve_list}: one summary
	// notice each, the later ones of a window saying "N more".
	EventFirstRun        = "findings.urgency.first_run"
	EventAssetDiscovered = "inventory.asset.discovered"
	EventAssetApproved   = "inventory.asset.approved" // B9: {asset_id, actor}
	EventAssetIgnored    = "inventory.asset.ignored"  // {asset_id, actor}: a person said the device needs no watching
	EventAssetUpdated    = "inventory.asset.updated"  // {asset_id}: also what a person's Approve publishes today
	EventHoneypotHit     = "honeypot.hit.created"
	EventLogAnomaly      = "logs.anomaly.detected"
	EventLogBadAddress   = "logs.bad_address.detected"
	EventIntrusion       = "ids.alert.detected" // {alert_id, source, target, title, what, action, severity, link, at, devices}
)

Names of the events notify listens to. core/events wants <module>.<object>.<verb>, so the two-part names of the CONTRACT (honeypot.hit, logs.anomaly, logs.bad_address) are spelled with a verb here; the producers must publish these names (see CONTRACT "Events").

View Source
const (
	SummarySent    = "sent"     // a channel delivered it
	SummaryWaiting = "waiting"  // queued: it waits for the rest of its load (settle), quiet hours, or the next deliver run
	SummaryNotSent = "not_sent" // no channel took it, or every channel that tried failed: Home shows it all the same
)

Summary states for Home.

View Source
const (
	ReasonModuleOff       = "module_off"
	ReasonChannelNotReady = "channel_not_ready"
)

Reasons EmailReady gives (POST-5).

View Source
const (
	KindVuln     = "vuln"
	KindIncident = "incident"
)

Notice kinds that travel through Publish.

View Source
const (

	// ApprovalTTL is the lifetime of an email or Zalo OA approval link.
	ApprovalTTL = 30 * time.Minute
	// MinApprovalKeyLen is the shortest accepted K_approval (256 bits).
	MinApprovalKeyLen = 32
)
View Source
const DefaultTimeZone = "Asia/Ho_Chi_Minh"

DefaultTimeZone is the box time zone when core does not say otherwise (the same default as the ai module).

View Source
const (

	// EventApprovalDecided is published when a decision made in chat was recorded by the response module (POST-8).
	EventApprovalDecided = "notify.approval.decided"
)
View Source
const EventDecisionMade = "response.decision.made"

EventDecisionMade is the decision event of the response module (CONTRACT "Events": received).

View Source
const MaxBulkIncidents = 500

MaxBulkIncidents is how many incidents one bulk change may name (INV-25): the 500 the Incidents page shows, in one short write.

View Source
const ModuleID = "notify"

ModuleID is the id of this module in the registry.

View Source
const TriggerVuln = "vulnerability"

TriggerVuln is the trigger of the vulnerability notices (an exploited or urgent vulnerability on a device).

Variables

View Source
var (
	ErrTokenInvalid     = errors.New("notify: approval token is not valid")
	ErrTokenExpired     = errors.New("notify: approval token has expired")
	ErrTokenUsed        = errors.New("notify: approval token was already used")
	ErrBadBinding       = errors.New("notify: invalid approval token binding")
	ErrKeyTooShort      = errors.New("notify: approval key must be at least 32 bytes")
	ErrHighRiskViaEmail = errors.New("notify: high-risk actions cannot be approved by email; use the app with two-step sign-in")
)

Errors of the token functions. ErrTokenInvalid covers a malformed token, a wrong MAC and any binding mismatch alike: the HTTP layer answers all of them with the same 404 "unknown" (spec §10) so nothing can be probed.

View Source
var (
	// ErrInvalidNotice means a Notice or IncidentInput broke its precondition (PRE-1, PRE-2).
	ErrInvalidNotice = errors.New("notify: invalid notice")
	// ErrApprovalUnavailable means approval requests cannot be sent: approval links are credentials and need the real box address.
	ErrApprovalUnavailable = errors.New("notify: approval requests are not available: the box address (BaseURL) is not set")
	// ErrApprovalKeyUnavailable means the approval key (K_approval) does not exist or cannot be opened, so no link can be
	// checked. VerifyApprovalLink never makes a key.
	ErrApprovalKeyUnavailable = errors.New("notify: the approval key is not available")
	// ErrModuleOff means the module is off: Publish, OpenIncident and SendApprovalRequest do nothing and queue nothing.
	ErrModuleOff = errors.New("notify: the module is off")
)

Errors of the service that are not API errors.

View Source
var ErrBadGrouping = errors.New("notify: invalid grouping window")

ErrBadGrouping means the batching rule is malformed.

View Source
var ErrBadQuiet = errors.New("notify: invalid quiet hours")

ErrBadQuiet means the quiet-hours rule is malformed.

View Source
var ErrEmailNotReady = errors.New("notify: the email channel is not ready")

ErrEmailNotReady is returned by SendCode when the email channel is off, missing or the module is off.

View Source
var ErrUnsendable = errors.New("notify: batch holds a notice that must not be sent")

ErrUnsendable means a batch holds a notice that must not go to its channel (FORBID-1, INV-4).

IncidentKinds lists every kind, in the order the API documents them.

View Source
var Migrations = mustSub(migrationFiles, "migrations/sqlite")

Migrations holds the SQLite migrations of the module, rooted at the directory that contains the NNNN_*.sql files. Pass it to store.Migrate(ctx, db, "notify", notify.Migrations).

NoticeEvents lists every event notify writes.

Functions

func ApprovalExpiry

func ApprovalExpiry(now, requestExpires time.Time) time.Time

ApprovalExpiry returns the expiry for a token minted now for a request that expires at requestExpires: 30 minutes, never beyond the request (spec §3.2).

func ApprovalViaChannelAllowed

func ApprovalViaChannelAllowed(channel string, risk Risk) error

ApprovalViaChannelAllowed reports whether a request of the given risk may be approved from channel: high risk never over a link channel (email, zalo), because a link is a bearer credential. An unknown risk is treated as high. Core calls it again when the decision arrives (spec §3.5).

func IsBaseline

func IsBaseline(ctx context.Context) bool

IsBaseline reports whether ctx carries the mark of WithBaseline.

func MeetsMin

func MeetsMin(sev, floor Severity) bool

MeetsMin implements INV-4: a channel receives a notice only when its severity is at least the channel's min_severity (critical|high|medium|low). An invalid severity or minimum never passes (fail closed), and "info" is below every possible minimum, so it is never sent to a channel.

func WithBaseline

func WithBaseline(ctx context.Context) context.Context

WithBaseline marks ctx as the work that follows the first CISA pull: the pull publishes one feeds.sync.baseline instead of one event per CVE, and inventory re-matches every device, which makes findings in bulk. cmd/vedette marks the context of that re-match; the mark travels with the context through inventory, findings and the event bus, down to the findings.finding.created handler here, which sends nothing for it.

Types

type ApprovalChannel

type ApprovalChannel struct {
	Type      channel.Type
	Approvers []Approver
}

ApprovalChannel is a channel that takes approvals and the people who may approve on it.

type ApprovalLast4

type ApprovalLast4 struct {
	AppToken *string `json:"app_token"`
	BotToken *string `json:"bot_token"`
}

ApprovalLast4 holds the last 4 characters of the Slack Socket Mode tokens (never the tokens).

type ApprovalRequest

type ApprovalRequest struct {
	ID       string // 1 to 128 characters of A-Z a-z 0-9 _ . : @ + - (it goes into the signed token)
	Title    string
	What     string
	Action   string
	Severity Severity
	Risk     Risk
	Expires  time.Time
	// Channels are the channels the response module allows for this request; empty sends nothing (PRE-4). Only
	// a channel that is in the list and has approvals on receives a message.
	Channels []channel.Type
	// InAppOnly is a high-risk request from the AI (INV-16 of response): every channel only gets a message that says
	// to open Vedette. No approval link, no button, no reply code, and no token is made or recorded.
	InAppOnly bool
	// NoChatButtons: no chat channel gets Approve/Reject buttons, only a message that says to open Vedette (response decides, from
	// the risk and from whether the whole change fits one message; notify only obeys).
	NoChatButtons bool
}

ApprovalRequest is one action waiting for approval (module response). Expires is when the request itself ends; a link never outlives it.

type Approver

type Approver struct {
	UserID  string `json:"user_id"`
	Address string `json:"address"`
	// Name is the display name of the approver's account on the channel, as the picker showed it (Zalo personal); "" elsewhere.
	Name string `json:"name,omitempty"`
}

Approver is a Vedette user who may approve actions from a channel, with the address on that channel.

type ApproverLinks interface {
	Linked(ctx context.Context, userID string, ch channel.Type, address string) (bool, error)
}

ApproverLinks is implemented by the code that owns users (core/auth, wired in cmd/vedette). It says whether the user has linked this address on this channel in My account. An error is not an answer: the approver is skipped. Rules for the adapter: an error must not carry the address (it is logged); email addresses are compared case-insensitively; chat ids (Telegram, Slack, Zalo) are exact decimal or opaque strings and are compared exactly.

type Batch

type Batch struct {
	Notices []Notice
	// contains filtered or unexported fields
}

Batch is a set of notices that go out as one message on one channel. Build it with Group or GroupHeld: they filter by the channel's min_severity and by sendability, and Message refuses a batch that was not built that way.

func Group

func Group(ns []Notice, g Grouping, floor Severity) []Batch

Group implements INV-3 for one channel (floor is its min_severity). Notices that are not sendable (FORBID-1) or below floor (INV-4) are dropped first, so a low notice can never ride in a batch to a high-only channel. Then, with grouping enabled, vulnerability notices for the same product whose time is within WindowMin of the first notice of the batch become one batch; everything else is a batch of its own. A critical notice is never grouped: it is always its own batch, due at its own time (INV-6). Batches come out in the order of their first notice. An invalid window groups nothing.

func GroupHeld

func GroupHeld(ns []Notice, floor Severity) []Batch

GroupHeld groups the notices kept during quiet hours: one batch per product, whatever the window setting, so people get one message when the window ends rather than one per notice. Same filtering as Group; a critical notice still stays a batch of its own.

func (Batch) DueAt

func (b Batch) DueAt(g Grouping) time.Time

DueAt is when a batch opened by its first notice must be sent at the latest under the grouping rule: the first notice time plus the window. A critical or non-vulnerability notice is due at its own time. Callers compare it with the 60-minute bound of INV-6.

func (Batch) Listed

func (b Batch) Listed() []Notice

Listed is the notices the message of the batch names one by one, in its order: at most channel.MaxItems (the message counts the rest in "and N more"). A chat channel may send fewer lines whole (channel.Listed); only the lines sent count as told.

func (Batch) Message

func (b Batch) Message() (channel.Message, error)

Message renders the batch as one channel.Message (what, urgency, what to do first, link; S-ALERT-1). A single notice is passed through; several notices of one product become "N vulnerabilities in <product> ...", with one detail line per notice. Strings stay unescaped: each adapter escapes for its own target. It returns ErrUnsendable for an empty batch, a notice that is not sendable or below the channel's min_severity, or a batch not built by Group.

func (Batch) Severity

func (b Batch) Severity() Severity

Severity is the highest severity in the batch.

func (Batch) Told

func (b Batch) Told(t channel.Type, msg channel.Message) []Notice

Told is the notices a message of the batch on channel t actually names: one notice is the message itself; of several, the ones whose line t sends whole (channel.Listed of msg, the message of the batch).

type Binding

type Binding struct {
	RequestID string    // the action request
	UserID    string    // the Vedette user who may approve (one token per approver)
	Channel   string    // "email" or "zalo": the channels that carry a link
	ExpiresAt time.Time // min(mint time + 30 min, request expiry)
}

Binding is what a token is bound to.

type BulkResult

type BulkResult struct {
	Updated             int `json:"updated"`
	AlreadyResolved     int `json:"already_resolved"`
	AlreadyAcknowledged int `json:"already_acknowledged"`
}

BulkResult is the answer of POST /notify/incidents/status.

type Bus

type Bus interface {
	Publish(ctx context.Context, e events.Event) error
	Subscribe(name string, fn events.Handler) (unsubscribe func())
	Flush(ctx context.Context, o *events.Outbox)
}

Bus is the part of core/events.Bus notify uses. A nil Bus drops events.

type Channel

type Channel struct {
	Type          channel.Type      `json:"type"`
	Configured    bool              `json:"configured"`
	Enabled       bool              `json:"enabled"`
	Fields        map[string]string `json:"fields"`
	SecretLast4   *string           `json:"secret_last4"`
	MinSeverity   Severity          `json:"min_severity"`
	LastTest      *TestResult       `json:"last_test"`
	Approvals     bool              `json:"approvals"`
	Approvers     []Approver        `json:"approvers"`
	ApprovalLast4 ApprovalLast4     `json:"approval_last4"`
}

Channel is one channel as the API shows it (INV-1: only secret_last4 and approval_last4).

type ChannelInput

type ChannelInput struct {
	Enabled     bool
	Fields      map[string]string
	Secret      string
	MinSeverity Severity
	Approvals   bool
	Approvers   []Approver
	AppToken    string
	BotToken    string
	Signin      string // email: a finished user sign-in whose refresh token becomes the secret
	// SecretKey and RefreshToken (Zalo OA): the app's secret key and the OA refresh token; Secret is then the current access
	// token, optional. Empty keeps the saved one.
	SecretKey    string
	RefreshToken string
	// ZaloLogin (Zalo personal): the session of the saving administrator's finished QR sign-in becomes the channel's secret.
	ZaloLogin bool
}

ChannelInput is the body of PUT /notify/channels/{type}. An empty secret, AppToken or BotToken keeps the saved one.

type ChannelsView

type ChannelsView struct {
	Channels       []Channel     `json:"channels"`
	Quiet          Quiet         `json:"quiet"`
	Grouping       Grouping      `json:"grouping"`
	Triggers       []TriggerView `json:"triggers"`
	EmailCodeUsers int           `json:"email_code_users"`
}

ChannelsView is the answer of GET /notify/channels.

type CodeMailer

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

CodeMailer is what core/auth wants (auth.CodeMailer): two-step sign-in codes over the email channel (INV-9).

func (CodeMailer) Available

func (m CodeMailer) Available(ctx context.Context) bool

Available reports whether SendCode can work now.

func (CodeMailer) Proven

func (m CodeMailer) Proven(ctx context.Context) bool

Proven reports whether the email channel has shown that it sends: it is ready (Available) and its last test, since the settings were last saved, succeeded. core asks it before a person may choose two-step sign-in by email (auth.ProvenMailer), so nobody waits for a code from a channel that was never seen working. Sign-in and step-up codes keep using Available: a failed test must not lock out an account that already uses email codes.

func (CodeMailer) SendCode

func (m CodeMailer) SendCode(ctx context.Context, to, code string) error

SendCode mails the 6-digit code to one address through the saved SMTP settings. The code is not logged, not stored and not put into any error or history row. A failure is a fixed error that may carry the numeric SMTP status and nothing else: no server reply text (a banner can name internals) and no address (the caller may log the error, and an address is personal data).

func (CodeMailer) SendStepUpCode

func (m CodeMailer) SendStepUpCode(ctx context.Context, to, code, summary string) error

SendStepUpCode mails a step-up code (core/auth.StepUpMailer): the same SMTP path, the same availability and the same fixed errors as SendCode, but the message says what is being approved so it cannot be taken for a sign-in code. summary is one line built by the server; it still goes through the line cleaner of the channel package (control and bidi characters, line breaks). There is no link in the message and nothing in it but the code. The code is not logged or stored.

type Config

type Config struct {
	DB      *store.DB
	Secrets *secrets.Store
	Audit   *audit.Log
	Users   Users
	Log     *slog.Logger

	Modules  ModuleGate       // nil = notify counts as on (tests); main passes modreg.Registry
	Bus      Bus              // nil = events are dropped
	Findings FindingDirectory // nil = finding events are logged and skipped
	Signals  SignalDirectory  // nil = the History page counts no exploited vulnerability that matched nothing
	Devices  DeviceDirectory  // nil = device events show the asset id
	Tokens   TokenRecorder    // nil = email approvers get a message that says to open Vedette instead of a link
	// ApproverLinks, when set, makes an approver whose address the user has not linked in My account a skipped approver;
	// an error from it skips the approver too (fail closed). nil = no link check, as before.
	ApproverLinks ApproverLinks
	Hits          HitConnections // trap incidents show the connections the trap saw; nil = notify's own count
	// Sessions reads the hits of one source so a trap incident that groups a session says everything the source did (title and
	// timeline); nil or an error = the incident keeps the words of the hit that opened it.
	Sessions  HitSessions
	Decisions Decisions // module response: takes decisions made in chat (13b-8); nil = chat decisions are not taken
	// LinkCodes makes the code a Zalo personal approver replies with to prove their Zalo account; nil = no code is sent and the
	// approver stays not linked.
	LinkCodes LinkCodes

	Clock func() time.Time // nil = time.Now
	// Zone returns the IANA name of the box time zone (core_org.timezone), asked at every use so a change applies at
	// once; nil or an empty or unknown name = DefaultTimeZone. The process time zone is never used (quiet hours
	// and the day of the history follow the wall clock of the people, not of the server).
	Zone func(context.Context) string
	// Location, when set, is the box time zone and Zone is not asked (tests).
	Location *time.Location
	// BaseURL is the address people open Vedette at, e.g. https://192.168.10.2:8443 (links in messages), asked at every use so a change
	// of the box address applies at once (cmd/vedette gives the Box address of Settings → Box network). nil or "": messages
	// carry no link and say to open Vedette, and approval requests are refused (ErrApprovalUnavailable): a link that
	// approves an action is a credential and must point at the real box.
	BaseURL func() string
	// BoxAddrs is the machine's addresses (vedette-host, the container's gateway): no webhook or SMTP server on Vedette's own ports
	// there (the container's own interfaces are read by the channel package, never a target). known=false means the box does not know its own addresses yet (vedette-host has not answered since the start): saving a
	// webhook is then 503 host_unreachable and no webhook connection is made (fail closed, #157). nil = only the interfaces,
	// known (tests, a box without vedette-host).
	BoxAddrs func() (addrs []netip.Addr, known bool)
	// SelfAddrs lists more addresses that are Vedette itself (the honeypot's decoys): no webhook or SMTP server there on any port.
	// Nil: none.
	SelfAddrs func() []netip.Addr
	// HTTPClient is given to the Slack, Telegram and Zalo adapters (not to webhooks: their client always checks the
	// address at connect time). nil = their own clients (no redirects, timeouts). Tests pass a fake. Its Timeout should be 0: the
	// Telegram listener long-polls longer than any usual total timeout, so it clears Timeout on its own copy and gives every call a
	// deadline of its own; the senders keep the client's Timeout.
	HTTPClient *http.Client
	// SMTPLoopback is for tests only (the fake SMTP servers of the notify and cmd/vedette tests, and the e2e box, listen on
	// 127.0.0.1): the email channel may then use a loopback server, and the box's own addresses are not checked. main never sets
	// it: core never runs on the host network, so loopback is core itself.
	SMTPLoopback bool
}

Config wires a Service. DB, Secrets, Audit, Users and Log are required.

type Decision

type Decision struct {
	Channel    channel.Type
	ExternalID string
	RequestID  string
	Approve    bool
	Code       string
}

Decision is what a chat listener passes to Decisions after it has checked the platform (Slack team and channel, Telegram chat, Zalo session): ExternalID is the sender on the platform, RequestID comes from the button (empty for a Zalo personal reply code), Code is the text the approver typed (reply codes only).

type DecisionResult

type DecisionResult struct {
	Status    string
	Message   string
	RequestID string
}

DecisionResult is the answer of the response module: Status says what was recorded (the module response owns the values), Message is the short private reply for the person who pressed the button, RequestID the request that was decided (a Zalo reply code names its request only through response's record; empty on a refusal).

type Decisions

type Decisions interface {
	Decide(ctx context.Context, d Decision) (DecisionResult, error)
}

Decisions is the port of the response module that takes decisions made in chat (PRE-8). notify decides nothing itself. Nothing a chat account sends links it to a Vedette user: a Zalo personal approver is linked only by confirming a link while signed in.

type Device

type Device struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

Device names a device of an incident. ID is the inventory asset id.

type DeviceDirectory

type DeviceDirectory interface {
	DeviceName(ctx context.Context, assetID string) (string, bool, error)
	// DeviceStates is the devices as the Devices page shows them now, for their unknown_device incidents; a device the
	// inventory does not have is absent from the map.
	DeviceStates(ctx context.Context, assetIDs []string) (map[string]DeviceState, error)
}

DeviceDirectory names a device by inventory id. Without one, device events show the id.

type DeviceState

type DeviceState struct {
	Name       string    // inventory's one naming rule, else the MAC, else the kind; plain text, at most 160 characters
	Address    string    // the IP, else the MAC; "" when neither is known
	Approved   bool      // a person (or an osquery enrolment) approved it
	ApprovedAt time.Time // when; zero when unknown (approved before inventory kept it)
}

DeviceState is a device as the Devices page shows it now.

type EmailSignin

type EmailSignin struct {
	ID              string    `json:"id"`
	Provider        string    `json:"provider"`
	Flow            string    `json:"flow"`
	Status          string    `json:"status"`
	UserCode        string    `json:"user_code,omitempty"`
	VerificationURI string    `json:"verification_uri,omitempty"`
	Interval        int       `json:"interval,omitempty"`
	ConsentURL      string    `json:"consent_url,omitempty"`
	ExpiresAt       time.Time `json:"expires_at"`
	Mailbox         string    `json:"mailbox,omitempty"`
}

EmailSignin is what the API shows of a sign-in.

type EmailSigninStart

type EmailSigninStart struct {
	Provider     string `json:"provider"`
	TenantID     string `json:"tenant_id"`
	ClientID     string `json:"client_id"`
	ClientSecret string `json:"client_secret"`
}

EmailSigninStart is the body of POST /notify/email-signin.

type FindingDirectory

type FindingDirectory interface {
	Finding(ctx context.Context, id string) (FindingInfo, bool, error)
}

FindingDirectory looks a finding up by id. Without one, finding events cannot become notices.

type FindingInfo

type FindingInfo struct {
	CVE      string
	Product  string
	Severity Severity
	// Open: the finding is open now. A finding that was handled since its event is never announced.
	Open bool
	// Layer is the stored urgency layer of the finding (1 under attack here .. 5 update recommended). Layer 5 never alerts.
	Layer int
	// Status is the name of the status the finding page shows ("Public exploit available"), Meaning the sentence that says what it asks
	// of a person, Reasons the line of the reasons ("Exploited in the wild: CISA KEV (19 Nov 2026)"; "" when none), all from findings.
	Status, Meaning, Reasons string
	// Verification is the second line under the status on every screen: how Vedette knows the device is affected ("Confirmed by a safe
	// check", "Not confirmed yet: based on a scan banner"; View.VerificationLine of findings); "" when not known.
	Verification string
	// Note is said after the meaning when the device needs it ("The device is not added yet: open the finding to add it or ignore it.").
	Note    string
	Action  string   // what to do first
	Devices []string // names of the devices the finding matched; empty = it matched none
}

FindingInfo describes a finding for a notice, as findings.View shows it now: the status and its words come from findings (one wording source), notify only frames them for the event that is told.

type FirstRunSummary

type FirstRunSummary struct {
	ID    string // the load's first summary's notice id: it stays the same while later passes add summaries
	Load  string // install, catalogue or source
	Title string
	At    time.Time // when the first summary was made (its load's first event)
	State string    // SummarySent, SummaryWaiting or SummaryNotSent: of the first look's delivered summary, else of its newest
	// sent: the first delivery of a summary of the load and the channels that delivered it.
	SentAt   time.Time
	Channels []channel.Type
	// waiting: when it goes out (the earliest queue row), and whether only quiet hours hold it.
	DueAt time.Time
	Quiet bool
	// not_sent: why, as the History page says it (INV-24).
	NotSent *NotSent
	// Link is the findings list of every summary of the load: /findings?tab=device&status=<the statuses they named>.
	Link string
	// Later counts the summaries of the same load made after one was delivered ("N more urgent findings…"); LaterTitle is the newest one's title.
	Later      int
	LaterTitle string
}

FirstRunSummary is the summary of one load as Home shows it. Its headline is the load's first look: every summary of the load made before one was delivered (all of them while none was), as one title that counts each finding they told once ("Patch first: …"). A first look told in several summaries (no channel to wait in, a pass that came while the first one was being sent) is still one look. Only the summaries made after one was delivered are "N more" on Home.

type Grouping

type Grouping struct {
	Enabled   bool `json:"enabled"`
	WindowMin int  `json:"window_min"` // 15, 60 or 240
}

Grouping is the batching rule (contract.ts Grouping).

func (Grouping) Validate

func (g Grouping) Validate() error

Validate checks that the window is one of the allowed values.

type HistoryItem

type HistoryItem struct {
	SendView
	Kind string `json:"kind"` // incident | vuln | approval
	What string `json:"what"`
	Link string `json:"link"`
	// Resent: a person sent this message again from the History (Send again); its words are those of the message it copies.
	Resent bool `json:"resent"`
}

HistoryItem is a SendView with what it was about.

type HistoryView

type HistoryView struct {
	Items      []HistoryItem  `json:"items"`
	NotSent    []UnsentNotice `json:"not_sent"`
	Suppressed struct {
		Count int `json:"count"`
		Days  int `json:"days"`
	} `json:"suppressed"`
}

HistoryView is the answer of GET /notify/history. Suppressed counts the new vulnerabilities that matched no device in the last Days days (INV-2): they were not sent. NotSent lists the vulnerability notices of the same days that no channel delivered, each with why (waiting for its grouping window or quiet hours, below the channels' minimum, no channel, failed).

type HitConnections

type HitConnections interface {
	HitConnections(ctx context.Context, hits []HitRef) (map[string]int, error)
}

HitConnections is what notify reads from the honeypot at render time: how many connections each hit saw (hp_hits.conn_count; later connections of the same source, service and trap IP fold into the hit and raise no event, honeypot INV-17). Hits it does not know are left out. ponytail: read at render, not kept; switch to the honeypot.hit.updated event {id, conn_count} when honeypot sends it.

type HitRef

type HitRef struct {
	ID string
	At time.Time
}

HitRef names a trap hit an incident links to: its id and the time it was seen (the incident's first_seen).

type HitSessions

type HitSessions interface {
	SourceHits(ctx context.Context, src string, from, to time.Time) ([]SessionHit, error)
}

HitSessions reads the honeypot hits of one source address between two times, oldest first, without test hits.

type Incident

type Incident struct {
	ID   string       `json:"id"`
	Kind IncidentKind `json:"kind"`
	// Attempt (bad_address only): the device that logged the connection blocked it, so it was an attempt, not a connection.
	Attempt   bool           `json:"attempt"`
	Title     string         `json:"title"`
	Link      string         `json:"link"`
	Devices   []Device       `json:"devices"`
	Severity  Severity       `json:"severity"`
	What      string         `json:"what"`
	Action    string         `json:"action"`
	FirstSeen string         `json:"first_seen"`
	LastSeen  string         `json:"last_seen"`
	Count     int            `json:"count"`
	Status    IncidentStatus `json:"status"`
	HandledBy *string        `json:"handled_by"`
	HandledAt *string        `json:"handled_at"`
	Note      *string        `json:"note"`
	// ResolvedReason is why Vedette closed the incident by itself (INV-22), a plain-English sentence such as "Closed by
	// Vedette: no new activity for 7 days."; nil when a person handled it last or it is open.
	ResolvedReason *string `json:"resolved_reason"`
	// FirstRunSummary: opened in the box's first 36 hours as a low or medium bad-connection or log incident, so it was told in the
	// hourly first-run summary message, not one by one (INV-23).
	FirstRunSummary bool       `json:"first_run_summary"`
	Sends           []SendView `json:"sends"`
	// NotSent says why no channel has the incident (INV-24); nil when any attempt delivered it.
	NotSent *NotSent `json:"not_sent"`
}

Incident is one incident as the API shows it.

type IncidentDetail

type IncidentDetail struct {
	Incident Incident  `json:"incident"`
	Previews []Preview `json:"previews"`
}

IncidentDetail is the answer of GET and PATCH /notify/incidents/{id}.

type IncidentInput

type IncidentInput struct {
	Kind     IncidentKind
	Source   string // who did it, e.g. the source IP
	Target   string // what it touched, e.g. the trap or the destination
	Title    string // one plain sentence: who did what
	Severity Severity
	What     string
	Action   string
	Link     string // where to see the source, a path inside Vedette: /honeypot/hits/<id>, /logs, /devices/<id>
	Devices  []Device
	At       time.Time // zero = now
	// Attempt (bad_address only) says the connection was blocked (logs.bad_address.detected "blocked"). An attempt is a
	// repeat of an open incident of the same source and target, attempt or not; a connection is never a repeat of an attempt, so
	// a blocked attempt never hides the connection that follows it.
	Attempt bool
	// Session (trap only) is the quiet that ends a session: a repeat joins the open incident only when it comes within Session
	// of its last hit and raises it when it is more serious; after a longer quiet the open incident keeps what it had and the
	// repeat opens a new one. Zero = every repeat joins the open incident, as before.
	Session time.Duration
}

IncidentInput is what a producer (honeypot, logs, inventory) gives OpenIncident (PRE-2). Source and Target make the dedupe key with Kind (INV-10): the same thing happening again is one incident.

type IncidentKind

type IncidentKind string

IncidentKind is what an incident is about (INV-10). There is no vulnerability kind: those are findings.

const (
	IncidentTrap          IncidentKind = "trap"
	IncidentBadAddress    IncidentKind = "bad_address"
	IncidentLogAnomaly    IncidentKind = "log_anomaly"
	IncidentUnknownDevice IncidentKind = "unknown_device"
	// IncidentIntrusion is an IPS or IDS event (ids.alert.detected): one incident per CVE ids or rule and source address while it repeats.
	IncidentIntrusion IncidentKind = "intrusion"
)

The incident kinds. The column is an open vocabulary (a shape check only): a new kind is a value here, never a table change.

func (IncidentKind) Valid

func (k IncidentKind) Valid() bool

Valid reports whether k has the shape of a kind (lower case words and digits, at most 40 characters): the vocabulary is open, so a producer's new kind needs no change here. "vuln" is taken: a vulnerability is a finding and its notice, never an incident.

type IncidentPeriod

type IncidentPeriod struct {
	Kinds []KindCount
	Top   []IncidentTop
}

IncidentPeriod is the incidents with activity in a period: how many of each kind (all of them, however many there are, with the newest activity) and the first few that matter most, by severity then recency.

type IncidentRef

type IncidentRef struct {
	ID     string
	Status IncidentStatus
}

IncidentRef is the id and handling state of one incident.

type IncidentStatus

type IncidentStatus string

IncidentStatus is the handling state of an incident.

const (
	StatusNew          IncidentStatus = "new"
	StatusAcknowledged IncidentStatus = "acknowledged"
	StatusResolved     IncidentStatus = "resolved"
)

The three incident states; a person can move an incident to any of them (reopening is "new").

type IncidentTop

type IncidentTop struct {
	Kind       IncidentKind
	Severity   Severity
	Title      string
	LastSeen   time.Time
	DeviceID   string
	DeviceName string
	Devices    int // how many devices the incident names (DeviceID is the first by name)
}

IncidentTop is one incident of an IncidentPeriod: its kind, severity, title, the newest activity and its first device ("" = none).

type KindCount

type KindCount struct {
	Kind       IncidentKind
	Incidents  int
	New        int
	LastSeenAt time.Time // the newest activity of the kind in the window; zero when none
}

KindCount is how many incidents of a kind had activity in a window, and how many of them nobody acknowledged or resolved yet.

type LinkApprover

type LinkApprover struct {
	UserID     string  `json:"user_id"`
	Address    string  `json:"address"`
	Name       string  `json:"name"`
	State      string  `json:"state"`
	SentAt     *string `json:"sent_at"`
	Error      string  `json:"error"`
	Self       bool    `json:"self"`
	BoxAccount bool    `json:"box_account"`
	Link       string  `json:"link,omitempty"`
}

LinkApprover is the link state of one approver of the Zalo personal channel (GET /notify/zalo/approvers): linked, sending (the confirm link is on its way), waiting (sent, not confirmed yet), not_sent (never sent, failed, or expired; Error says which). Self marks the administrator asking; BoxAccount, that the address is the box's own signed-in Zalo account (the QR sign-in proved it is theirs, as far as the box last signed in). Only when both hold is no message sent: the answer of POST …/code carries the confirm page (Link) and they confirm it in their session. Any other address of their own gets the message like everyone's.

type LinkCodes

type LinkCodes interface {
	ChatLinkToken(ctx context.Context, userID string, ch channel.Type, address string) (token, name string, err error)
	DropChatLink(ctx context.Context, actor, userID string, ch channel.Type, address string) error
	DropLinkToken(ctx context.Context, userID string, ch channel.Type, address, token string) error
}

LinkCodes makes the token of the confirm link the box sends to an approver's chat ID (Zalo personal; module response keeps the token and the proof): only the person, signed in to Vedette as themself, confirms it, so no administrator links anyone. name is the Vedette user's name for the message. A refusal is an *apierr.Error (not listed, already linked, a new link too soon, Response off): it goes to the administrator as it is. DropChatLink ends the proof of one address when an administrator removes that approver or gives them another address, so the old address never counts again without a new proof. DropLinkToken removes one token that could not be delivered, and only that token: a newer one, or a proof, stays.

type ModuleGate

type ModuleGate interface{ Enabled(id string) bool }

ModuleGate says whether a module is on (modreg.Registry satisfies it).

type NonceStore

type NonceStore interface {
	Consume(ctx context.Context, id TokenID) (first bool, err error)
}

NonceStore records consumed tokens. Consume must be atomic and report true only for the first call with an id: the database version is the conditional "UPDATE … SET used_at = … WHERE token_id = ? AND used_at IS NULL" inside the same transaction as the decision (spec §4.3), so two concurrent POSTs have exactly one winner.

type NotSent

type NotSent struct {
	Reason NotSentReason `json:"reason"`
	Text   string        `json:"text"`
	// Channel is the channel to fix: the one that failed, the one that was turned off or removed, or the one with the lowest minimum severity.
	Channel channel.Type `json:"channel,omitempty"`
	// Until (quiet_hours) is when the held message goes out.
	Until string `json:"until,omitempty"`
}

NotSent is the reason an incident has no message on any channel, in the customer's words (INV-24).

type NotSentReason

type NotSentReason string

NotSentReason is why an incident or a vulnerability notice reached no channel (INV-24).

const (
	UnsentQueued       NotSentReason = "queued"             // a channel took it; the deliver job sends it within a minute
	UnsentQuietHours   NotSentReason = "quiet_hours"        // held until quiet hours end (INV-5), then sent
	UnsentGrouped      NotSentReason = "grouped"            // a vulnerability notice waiting for its grouping window (INV-3), then sent
	UnsentNoChannel    NotSentReason = "no_channel"         // no channel was set up
	UnsentChannelsOff  NotSentReason = "channels_off"       // channels were set up, none was on
	UnsentChannelOff   NotSentReason = "channel_off"        // the one channel it waited for (quiet hours, rate limit) was turned off before it went
	UnsentChannelGone  NotSentReason = "channel_removed"    // the one channel it waited for was removed before it went
	UnsentBelowMin     NotSentReason = "below_min_severity" // every channel that was on sends only higher severities (INV-4)
	UnsentFailed       NotSentReason = "failed"             // a channel tried and failed (INV-6)
	UnsentDroppedStale NotSentReason = "dropped_stale"      // it waited while the module was off and was too old when it came back on
	UnsentFirstRun     NotSentReason = "first_run_summary"  // held by the first-run window (INV-23), told in the hourly summary
	UnsentLineLeftOut  NotSentReason = "line_left_out"      // a vulnerability notice queued and sent, but its line was past what the message could hold
	UnsentUnknown      NotSentReason = "unknown"            // opened before the reason was kept, and today's channels would take it
	UnsentTriggerOff   NotSentReason = "trigger_off"        // its alert trigger is off, or it is below the trigger's minimum (INV-31)
)

The reasons. queued and quiet_hours are not final: the message still goes out by itself.

type Notice

type Notice struct {
	ID       string
	Kind     string // KindVuln or KindIncident
	Severity Severity
	Product  string   // vulnerability: grouping key, e.g. "QNAP Photo Station"
	CVEs     []string // vulnerability
	// FindingIDs are the findings this notice is about (vulnerability); they let the finding page list who was told.
	FindingIDs []string
	// Event is the finding event the notice tells (NoticeCreated, NoticeUrgencyChanged, NoticeReopened, NoticeAcceptanceExpired,
	// NoticeFirstRun); "" for a notice that tells none. A notice of the kinds that tell an urgency (created, urgency_changed, first_run)
	// is recorded at its layer (FindingLayers, else Layer) and is not sent for a finding already told at that layer or a more urgent one.
	Event NoticeEvent
	// FindingLayers is the layer each of FindingIDs is told at, parallel to it; empty = Layer for all.
	FindingLayers []int
	Devices       []string // names of the matched devices (vulnerability: at least one)
	Title         string   // one plain sentence
	What          string   // what happened and how urgent
	Action        string   // what to do first
	Change        string   // vulnerability changed since it was first told ("now critical (was medium)"): added to its line of a digest
	// Reasons is the finding page's reasons line (the status and its sources with their dates: "Exploited in the wild: CISA KEV (4 Mar);
	// fix by 25 Mar 2025"), from findings; a digest puts it on the finding's line, so a grouped alert says why as the page does.
	Reasons string
	// Status (the badge, "Exploited in the wild") and Verification (how Vedette knows the device is affected) are the finding page's
	// first and second lines; a digest line carries them with the reasons line.
	Status, Verification string
	// Layer is the urgency layer of the vulnerability (FindingInfo.Layer); a digest says "exploited" only when every notice is.
	Layer int
	// Lines are the detail lines of a notice about several findings (a first-run summary): one per finding, worded as a digest line
	// ("<product>: <CVE> on <device> — <reasons> · <verification>"), in the order of FindingIDs. Empty: the message lists the CVEs.
	Lines []string `json:",omitempty"`
	// More counts the findings the notice tells but does not list (a first-run summary of more findings than an event lists).
	More int `json:",omitempty"`
	// Forced: a person asked to send it now (History, Send now). The channels' minimum severity does not hold it back; everything else does.
	Forced bool   `json:",omitempty"`
	Link   string // absolute URL of the finding or incident in Vedette
	At     time.Time

	// IncidentKind (incidents) and DeviceIDs (parallel to Devices, when the ids are known) only feed the structured
	// fields of the webhook payload (kind, devices[]); the text channels do not use them.
	IncidentKind string
	DeviceIDs    []string
}

Notice is one thing to tell people about. A vulnerability notice (S-ALERT-1) carries the devices the finding matched; an incident does not.

func SplitSendable

func SplitSendable(ns []Notice) (send []Notice, suppressed int)

SplitSendable separates the notices that may be sent from the count of vulnerability notices dropped for matching no device (HistoryResponse.suppressed).

func (Notice) Sendable

func (n Notice) Sendable() bool

Sendable implements INV-2: a vulnerability notice needs at least one matched device with a name (FORBID-1); blank names do not count. Other kinds are always sendable. Group, GroupHeld and Batch.Message enforce it themselves.

type NoticeEvent

type NoticeEvent string

NoticeEvent is the finding event a vulnerability notice tells. The column is an open vocabulary (a shape check); these are the ones notify writes, and "" is a notice that tells none.

const (
	NoticeCreated           NoticeEvent = "created"
	NoticeUrgencyChanged    NoticeEvent = "urgency_changed"
	NoticeReopened          NoticeEvent = "reopened"
	NoticeAcceptanceExpired NoticeEvent = "acceptance_expired"
	NoticeFirstRun          NoticeEvent = "first_run"
)

The finding events a vulnerability notice tells (Notice.Event, notify_notice.event): the kinds of the findings module's own history that a person has to know, and the summary of a first load. An open vocabulary.

func (NoticeEvent) Valid

func (e NoticeEvent) Valid() bool

Valid reports whether e is "" or one of NoticeEvents.

type NotifyHandlers

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

NotifyHandlers implements the 20 operations of the notify module. Embed it in the composite handler of cmd/vedette. The role of each route comes from the route table, so nothing here checks roles.

ogen generates a separate struct per operation for the same schema, so answers are built from the domain types (their JSON names are the wire names) and decoded into the generated ones; request bodies go the other way.

func NewNotifyHandlers

func NewNotifyHandlers(svc *Service) *NotifyHandlers

NewNotifyHandlers returns the handlers of the module.

func (*NotifyHandlers) NotifyDeleteNotifyChannelsType

func (h *NotifyHandlers) NotifyDeleteNotifyChannelsType(ctx context.Context, params oas.NotifyDeleteNotifyChannelsTypeParams) error

NotifyDeleteNotifyChannelsType implements DELETE /notify/channels/{type} (admin).

func (*NotifyHandlers) NotifyDeleteNotifyZaloLogin

func (h *NotifyHandlers) NotifyDeleteNotifyZaloLogin(ctx context.Context) error

NotifyDeleteNotifyZaloLogin implements DELETE /notify/zalo/login (admin).

func (*NotifyHandlers) NotifyGetNotifyAlertsIDTarget

NotifyGetNotifyAlertsIDTarget implements GET /notify/alerts/{id}/target (viewer).

func (*NotifyHandlers) NotifyGetNotifyChannels

func (h *NotifyHandlers) NotifyGetNotifyChannels(ctx context.Context) (*oas.NotifyGetNotifyChannelsOK, error)

NotifyGetNotifyChannels implements GET /notify/channels (admin).

func (*NotifyHandlers) NotifyGetNotifyFindingsIDNotices

NotifyGetNotifyFindingsIDNotices implements GET /notify/findings/{id}/notices (viewer).

func (*NotifyHandlers) NotifyGetNotifyHistory

func (h *NotifyHandlers) NotifyGetNotifyHistory(ctx context.Context) (*oas.NotifyGetNotifyHistoryOK, error)

NotifyGetNotifyHistory implements GET /notify/history (admin).

func (*NotifyHandlers) NotifyGetNotifyIncidents

func (h *NotifyHandlers) NotifyGetNotifyIncidents(ctx context.Context) (*oas.NotifyGetNotifyIncidentsOK, error)

NotifyGetNotifyIncidents implements GET /notify/incidents (viewer).

func (*NotifyHandlers) NotifyGetNotifyIncidentsID

NotifyGetNotifyIncidentsID implements GET /notify/incidents/{id} (viewer).

func (*NotifyHandlers) NotifyGetNotifyTelegramApprovers

func (h *NotifyHandlers) NotifyGetNotifyTelegramApprovers(ctx context.Context) (*oas.NotifyGetNotifyTelegramApproversOK, error)

NotifyGetNotifyTelegramApprovers implements GET /notify/telegram/approvers (admin).

func (*NotifyHandlers) NotifyGetNotifyZaloApprovers

func (h *NotifyHandlers) NotifyGetNotifyZaloApprovers(ctx context.Context) (*oas.NotifyGetNotifyZaloApproversOK, error)

NotifyGetNotifyZaloApprovers implements GET /notify/zalo/approvers (admin).

func (*NotifyHandlers) NotifyGetNotifyZaloContacts

func (h *NotifyHandlers) NotifyGetNotifyZaloContacts(ctx context.Context) (*oas.NotifyGetNotifyZaloContactsOK, error)

NotifyGetNotifyZaloContacts implements GET /notify/zalo/contacts (admin).

func (*NotifyHandlers) NotifyGetNotifyZaloLogin

func (h *NotifyHandlers) NotifyGetNotifyZaloLogin(ctx context.Context) (*oas.NotifyGetNotifyZaloLoginOK, error)

NotifyGetNotifyZaloLogin implements GET /notify/zalo/login (admin).

func (*NotifyHandlers) NotifyPatchNotifyIncidentsID

NotifyPatchNotifyIncidentsID implements PATCH /notify/incidents/{id} (operator).

func (*NotifyHandlers) NotifyPostNotifyChannelsTypeTest

NotifyPostNotifyChannelsTypeTest implements POST /notify/channels/{type}/test (admin).

func (*NotifyHandlers) NotifyPostNotifyEmailSignin

NotifyPostNotifyEmailSignin implements POST /notify/email-signin (admin).

func (*NotifyHandlers) NotifyPostNotifyEmailSigninID

NotifyPostNotifyEmailSigninID implements POST /notify/email-signin/{id} (admin).

func (*NotifyHandlers) NotifyPostNotifyHistoryIDResend

NotifyPostNotifyHistoryIDResend implements POST /notify/history/{id}/resend (operator).

func (*NotifyHandlers) NotifyPostNotifyIncidentsStatus

NotifyPostNotifyIncidentsStatus implements POST /notify/incidents/status (operator, INV-25).

func (*NotifyHandlers) NotifyPostNotifyNoticesIDSend

NotifyPostNotifyNoticesIDSend implements POST /notify/notices/{id}/send (operator).

func (*NotifyHandlers) NotifyPostNotifyTelegramApproversUserIDCode

NotifyPostNotifyTelegramApproversUserIDCode implements POST /notify/telegram/approvers/{user_id}/code (admin).

func (*NotifyHandlers) NotifyPostNotifyTelegramChats

NotifyPostNotifyTelegramChats implements POST /notify/telegram/chats (admin).

func (*NotifyHandlers) NotifyPostNotifyZaloApproversUserIDCode

NotifyPostNotifyZaloApproversUserIDCode implements POST /notify/zalo/approvers/{user_id}/code (admin).

func (*NotifyHandlers) NotifyPostNotifyZaloLogin

func (h *NotifyHandlers) NotifyPostNotifyZaloLogin(ctx context.Context) (*oas.NotifyPostNotifyZaloLoginOK, error)

NotifyPostNotifyZaloLogin implements POST /notify/zalo/login (admin).

func (*NotifyHandlers) NotifyPostNotifyZaloResolve

NotifyPostNotifyZaloResolve implements POST /notify/zalo/resolve (admin).

func (*NotifyHandlers) NotifyPutNotifyChannelsType

NotifyPutNotifyChannelsType implements PUT /notify/channels/{type} (admin).

func (*NotifyHandlers) NotifyPutNotifyRules

NotifyPutNotifyRules implements PUT /notify/rules (admin).

func (*NotifyHandlers) NotifyPutNotifyTriggers

NotifyPutNotifyTriggers implements PUT /notify/triggers (admin).

type Preview

type Preview struct {
	Channel channel.Type `json:"channel"`
	Subject string       `json:"subject,omitempty"`
	Text    string       `json:"text"`
}

Preview is what one channel received (or would receive) for an incident.

type Quiet

type Quiet struct {
	Enabled       bool   `json:"enabled"`
	From          string `json:"from"`
	To            string `json:"to"`
	AllowCritical bool   `json:"allow_critical"`
}

Quiet is the quiet-hours rule (contract.ts Quiet). From and To are "HH:MM" in the box's local time.

func (Quiet) Active

func (q Quiet) Active(now time.Time) bool

Active reports whether now falls inside the quiet window. now carries the box's time zone; the window is [From, To) and may cross midnight. A rule that is disabled or invalid is never active.

func (Quiet) EndsAt

func (q Quiet) EndsAt(now time.Time) time.Time

EndsAt returns the next instant the quiet window ends, in now's location, or the zero time when the window is not active at now.

func (Quiet) Validate

func (q Quiet) Validate() error

Validate checks the rule (INV-5): both times are HH:MM, and when enabled they differ. The window may cross midnight.

type ReplyCode

type ReplyCode struct {
	RequestID string
	UserID    string
	Address   string
	Approve   bool
	CodeHash  string
	ExpiresAt time.Time
}

ReplyCode is one reply code of one approver for one request: CodeHash is the lowercase hex SHA-256 of spec 7.1, Address the approver's Zalo user id, Approve false for the "R-" (reject) code. ExpiresAt is never after the request ends and at most 30 minutes after the code is made.

type ReportMail

type ReportMail struct {
	Title, What, Action string
	Items               []string
	Path                string // a path on this box, for example "/reports"
	// Doc, when set, is the report itself: the mail is HTML with a plain-text alternative carrying the document's sections, cut to a
	// size the mail servers take with the link to the whole report (channel.Doc). Without it the mail is the plain-text digest.
	Doc *channel.Doc
}

ReportMail is the weekly report as an email: a digest with the things left to do, and the page of Vedette that holds the full report. The reports module builds it from the figures; every text field goes through the line cleaner of the channel package.

type Risk

type Risk string

Risk is the risk level of an action request.

const (
	RiskLow    Risk = "low"
	RiskMedium Risk = "medium"
	RiskHigh   Risk = "high"
)

Risk levels.

type Rules

type Rules struct {
	Quiet    Quiet    `json:"quiet"`
	Grouping Grouping `json:"grouping"`
}

Rules is the quiet-hours and grouping rule pair.

type SendRecord

type SendRecord struct {
	ID      string
	Channel channel.Type
	To      string
	At      time.Time
	OK      bool
	Error   string // for people: short, friendly, secret-free (see friendlyError); empty when OK
	// MessageID is the provider's id of the sent message (Telegram), 0 when unknown; kept only to remove approval buttons later.
	MessageID int64
	ChatID    string // the provider's chat of the sent message (Telegram, a checked number), "" when unknown
	TS        string // Slack: the ts of the posted approval message, "" when unknown
	// Limited is set when the provider asked to slow down (channel.RateLimitError), RetryAfter is the wait it named (0 = none).
	Limited    bool
	RetryAfter time.Duration
	Delayed    bool // the history row of a message held back by a rate limit; it is sent again by itself
}

SendRecord is one delivery attempt (contract.ts SendRecord, table notify_send).

func Deliver

func Deliver(ctx context.Context, id string, s channel.Sender, m channel.Message, now func() time.Time) (rec SendRecord)

Deliver makes one attempt through s and always returns its record (INV-6: there is no attempt without a record), even when the sender panics: that is recorded as a failure with the error "internal error". Now is the injected clock. Whether to try at all (min_severity, quiet hours, grouping) is decided before, by Decide and Group. The record's Error is friendlyError of what the adapter returned: the raw text of a provider or a server never reaches the GUI.

type SendView

type SendView struct {
	ID      string       `json:"id"`
	Channel channel.Type `json:"channel"`
	To      string       `json:"to"`
	At      string       `json:"at"`
	OK      bool         `json:"ok"`
	Error   string       `json:"error,omitempty"`
	// Delayed: the provider asked to slow down and the message waits in the queue; it is sent again by itself.
	Delayed bool `json:"delayed"`
}

SendView is one delivery attempt as the API shows it.

type Service

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

Service is the notify module: channel settings, delivery, incidents and history. Create it once with New and share it between the handlers, the jobs, the event subscriptions and the code mailer.

func New

func New(c Config) (*Service, error)

New builds a Service.

func (*Service) AlertTarget

func (s *Service) AlertTarget(ctx context.Context, id string) (string, error)

AlertTarget says where an old alert id leads now: the finding or the incident it became.

func (*Service) ApprovalChannels

func (s *Service) ApprovalChannels(ctx context.Context) ([]ApprovalChannel, error)

ApprovalChannels lists the enabled channels with approvals on (IMPACT: other modules read the approval setup through this, never from the notify_ tables). Whether an approver is still an active operator or admin is for the caller to check again when a decision arrives (spec 3.5).

func (*Service) CancelZaloLogin

func (s *Service) CancelZaloLogin(who string)

CancelZaloLogin is DELETE /notify/zalo/login: the sign-in of who ends (a finished one is dropped unsaved).

func (*Service) Channels

func (s *Service) Channels(ctx context.Context) (ChannelsView, error)

Channels returns the six channels, the rules and the number of two-step email users (GET /notify/channels).

func (*Service) CheckEmailSignin

func (s *Service) CheckEmailSignin(ctx context.Context, actor, id, pasted string) (EmailSignin, error)

CheckEmailSignin asks Microsoft once whether the person finished (never before the interval Microsoft gave), or finishes a Google sign-in with the pasted address (POST /notify/email-signin/{id}).

func (*Service) CodeMailer

func (s *Service) CodeMailer() CodeMailer

CodeMailer returns the mailer of this service. Pass it as auth.Config.Mailer.

func (*Service) DeleteChannel

func (s *Service) DeleteChannel(ctx context.Context, actor string, t channel.Type) error

DeleteChannel removes the saved configuration and every secret of a channel, and with them a Zalo personal session (INV-12). The row stays, blank, so the API still lists six channels. The approvers' proofs of their addresses on it end too (Config.LinkCodes.DropChatLink).

func (*Service) DeviceDeleted

func (s *Service) DeviceDeleted(ctx context.Context, tx *sql.Tx, d lifecycle.Delete) error

DeviceDeleted is notify's part of deleting a device (core/lifecycle, inside the inventory's write): the device leaves the open new-device incidents (INV-20, see leaveDevice), with who deleted it in the reason. Resolved incidents and the other kinds keep it with the name they stored: they are history. Nothing is sent.

func (*Service) DeviceMerged

func (s *Service) DeviceMerged(ctx context.Context, tx *sql.Tx, m lifecycle.Merge) error

DeviceMerged is notify's part of a merge (core/lifecycle, inside the inventory's write): the row inventory joined into another device leaves the open new-device incidents like a delete (INV-20), with the reason that says where it went: "Closed by Vedette: merged into <name>.". The device it joined keeps its own incident: it is still to approve. Every other incident that lists the row (a trap hit, a bad connection, a resolved one) lists the device it joined instead, with the name it stored; one that already lists that device keeps its row.

func (*Service) EmailReady

func (s *Service) EmailReady(ctx context.Context) (ok bool, reason string)

EmailReady reports whether email can be sent now: the module is on and the email channel is configured and enabled (POST-5). The reason is one of ReasonModuleOff, ReasonChannelNotReady.

func (*Service) ExportAlerts

func (s *Service) ExportAlerts(ctx context.Context, from, to time.Time, w io.Writer) error

ExportAlerts is the "alerts" source of GET /core/logs/export: the delivery log (notify_send) from through to, both ends inclusive, oldest first, one JSON object per line; a zero time is open. Not a hash chain. A link is cut to its path without query or fragment, and the path of an approval link (/approve/<token>) to "/approve/…": nothing that works as a credential is written (the stored link is the in-app page, never a token, but the file does not rely on that). A destination that is a URL is cut to scheme://host.

func (*Service) FindingFolded

func (s *Service) FindingFolded(ctx context.Context, tx *sql.Tx, f lifecycle.FindingFold) error

FindingFolded is notify's part of a merge that folds finding f.From into f.Into (core/lifecycle, inside the inventory's write): the notices sent for the folded finding are listed on the one that stays, so "who was told" keeps them and an old alert's link to the finding still opens. A notice that already lists the kept finding keeps its row.

func (*Service) FindingNotices

func (s *Service) FindingNotices(ctx context.Context, findingID string) ([]SendView, error)

FindingNotices lists who was told about a finding, oldest first (GET /notify/findings/{id}/notices).

func (*Service) FirstRunAt

func (s *Service) FirstRunAt(ctx context.Context) (time.Time, error)

FirstRunAt is when the box first ran (notify_box.first_run_at: its install); zero when not known. Findings folds the urgency rises its first look brings into one summary.

func (*Service) FirstRunSummary

func (s *Service) FirstRunSummary(ctx context.Context, since time.Time) (*FirstRunSummary, error)

FirstRunSummary is the summary of the newest load whose summary was made at or after since; nil when there is none. A few small reads: the newest summary, its load's summaries and their first deliveries, the state of the one Home speaks of, the statuses the load named; and, when the first look is told in several summaries, the findings they told.

func (*Service) Flush

func (s *Service) Flush(ctx context.Context) error

Flush delivers what is due: held notices when quiet hours have ended, grouped batches at their DueAt, everything else at once. It is the body of the "deliver" job. Rows are claimed in one transaction before anything is sent, so a notice is never sent twice by two runs. Each channel is served by its own goroutine that Flush waits for, so a slow or dead channel does not hold up the others; within a channel critical notices go first and at most maxBatchesPerRun messages are sent per run.

func (*Service) HandleIncident

func (s *Service) HandleIncident(ctx context.Context, actor, id string, status IncidentStatus, note string) (IncidentDetail, error)

HandleIncident acknowledges, resolves or reopens an incident (PATCH /notify/incidents/{id}, INV-10). Reopening (status new) clears who handled it and the note; acknowledging or resolving without a note keeps the note already there.

func (*Service) HandleIncidents

func (s *Service) HandleIncidents(ctx context.Context, actor string, ids []string, status IncidentStatus, note string) (BulkResult, error)

HandleIncidents acknowledges or resolves several incidents with one note (POST /notify/incidents/status, INV-25), like the findings bulk change. Every incident that changes gets what PATCH gives it: who, when, the note and its own core_audit row (INV-10), except that with no note the note already there stays. A resolved incident keeps its state and its note (already_resolved), and acknowledging an acknowledged one changes nothing (already_acknowledged): a bulk change never overwrites what someone wrote. Reopening is not a bulk action. All or nothing: an unknown id writes nothing. A duplicate id counts once.

func (*Service) History

func (s *Service) History(ctx context.Context) (HistoryView, error)

History lists every message sent, newest first, the vulnerability notices of the last historyDays days that no channel delivered with why, and how many new vulnerabilities matched no device recently (GET /notify/history). Each list has at most historyLimit rows.

func (*Service) IncidentDetail

func (s *Service) IncidentDetail(ctx context.Context, id string) (IncidentDetail, error)

IncidentDetail returns one incident with what each channel received (GET /notify/incidents/{id}).

func (*Service) IncidentOf

func (s *Service) IncidentOf(ctx context.Context, kind IncidentKind, source, target string, at time.Time) (IncidentRef, bool, error)

IncidentOf finds the incident a producer's event counted on: the newest incident of the kind, source and target (OpenIncident's dedupe key) opened at or before at, whatever its status now. The ids module links an alert to its intrusion incident with it. ok is false when there is none.

func (*Service) Incidents

func (s *Service) Incidents(ctx context.Context) ([]Incident, error)

Incidents lists the incidents for GET /notify/incidents: every open one (new or acknowledged) first, then the resolved ones, each most recently seen first, at most incidentsLimit. An open incident is never cut by the limit (the page once counted its "open" from the 500 seen last, while Home and the nav badge count every open one with OpenIncidents).

func (*Service) IncidentsIn

func (s *Service) IncidentsIn(ctx context.Context, from, to time.Time, top int) (IncidentPeriod, error)

IncidentsIn reads the incidents with activity in the period (from, to]: first seen before its end and last seen after its start, for the periodic report; top is how many incidents to name.

func (*Service) Jobs

func (s *Service) Jobs() []jobs.Job

Jobs returns the scheduler jobs of the module: "deliver" sends what is due (held notices when quiet hours end, grouped batches at their DueAt, the rest at once); "autoclose" sends the first-run summary and closes quiet incidents (autoclose.go); "telegram-listen" and "slack-listen" take approval button presses while the Telegram / Slack channel takes approvals (tglisten.go, slacklisten.go). The five above run only while the module is on: `deliver` sends and its deletes are queue upkeep, not a customer retention, so it is not housekeeping. "retention" is Housekeeping (retention.go).

func (*Service) KindCounts

func (s *Service) KindCounts(ctx context.Context, since time.Time) ([]KindCount, error)

KindCounts counts the incidents of every kind with activity (last_seen) at or after since: the kinds of IncidentKinds in their order, then any other kind that has incidents. The kind is an open vocabulary.

func (*Service) ListZaloContacts

func (s *Service) ListZaloContacts(ctx context.Context, who string) (ZaloContacts, error)

ListZaloContacts is GET /notify/zalo/contacts.

func (*Service) OpenIncident

func (s *Service) OpenIncident(ctx context.Context, in IncidentInput) (id string, created bool, err error)

OpenIncident records an incident (PRE-2, POST-2, INV-10). The same kind, source and target while the incident is not resolved only raises its count and last_seen; a new incident is queued for the channels and announced as notify.incident.created. Repeats are not sent again. In the first-run window a low or medium bad-connection or log incident is not queued: the hourly first-run summary tells it (INV-23). It returns the incident id and whether it was created.

func (*Service) OpenIncidents

func (s *Service) OpenIncidents(ctx context.Context) (open, urgent int, err error)

OpenIncidents counts the open incidents (new or acknowledged, the Incidents page's Open tab) and, of them, the urgent ones (high or critical, its "?severity=urgent" filter): the shell's nav badge and Home (#825). One read on notify_incident_status_ix.

func (*Service) Publish

func (s *Service) Publish(ctx context.Context, n Notice) error

Publish queues a notice for every enabled channel that should receive it (PRE-1, POST-1). A vulnerability notice that matched no device is never sent: its CVEs only add to the suppressed count (INV-2, FORBID-1). Delivery happens in Flush; each attempt there writes a SendRecord (INV-6). While the module is off nothing is queued and ErrModuleOff is returned.

func (*Service) Resend

func (s *Service) Resend(ctx context.Context, actor, id string) (HistoryItem, error)

Resend sends a message of the history again through the same channel (POST /notify/history/{id}/resend, INV-11). A failed attempt is still a 200 with ok=false: it is a new row in the history.

func (*Service) ResolveZalo

func (s *Service) ResolveZalo(ctx context.Context, who, query string) (ZaloFound, error)

ResolveZalo is POST /notify/zalo/resolve: a group invite link, a phone number, or a numeric Zalo ID (taken as a person, no look-up).

func (*Service) ResolvedSince

func (s *Service) ResolvedSince(ctx context.Context, event string, data any, since time.Time) (bool, error)

ResolvedSince says whether a producer must let a repeat through although it already announced the event's key at since: no incident the event would count on is open (OpenIncident would open a new one) and one of them was resolved, by a person or by Vedette, at or after since. A producer that holds back repeats of a key (the ids hourly announcement dedupe, the logs dedupe time of a bad connection or of failed logins, the honeypot hit window) asks it before holding one back: a repeat after the incident was resolved is a new incident and must reach notify (the producer's hourly budget still applies). False while an incident of the key is open (notify only counts the repeat), when none was resolved since the producer's announcement (the producer's budget held it, or notify was off), for an event that opens no incident, and while the module is off.

func (*Service) RunRetention

func (s *Service) RunRetention(ctx context.Context) error

RunRetention deletes, in one transaction, what is older than the retention:

  • notify_send rows whose attempt (at) is older than a year;
  • notify_incident rows with status resolved whose handled_at (last_seen when it is missing) is older than a year, unless a send newer than the cut still points to it (a resend of an old incident); an incident that is new or acknowledged is open work and is never deleted, however old (its devices go with it, ON DELETE CASCADE);
  • notify_notice rows created over a year ago, except one a queued message still names (notify_pending) or a send newer than the cut still covers (a resend of an old notice): the notice rows of a grouped message are only removed with the last send that covers them.

notify_pending (the queue of what is not sent yet) is never touched: it is not history, and the stale rule owns it.

func (*Service) SaveChannel

func (s *Service) SaveChannel(ctx context.Context, actor string, t channel.Type, in ChannelInput) (Channel, error)

SaveChannel stores the configuration of one channel (PUT /notify/channels/{type}, PRE-3, INV-1, INV-7, INV-8). An empty Secret, AppToken or BotToken keeps the saved one. Errors are *apierr.Error.

func (*Service) SaveRules

func (s *Service) SaveRules(ctx context.Context, actor string, r Rules) (Rules, error)

SaveRules stores quiet hours and grouping (PUT /notify/rules, INV-3, INV-5).

func (*Service) SaveTriggers

func (s *Service) SaveTriggers(ctx context.Context, actor string, in []Trigger) ([]TriggerView, error)

SaveTriggers stores the alert triggers (PUT /notify/triggers, INV-31). Every trigger in the request must be known and have a minimum of critical, high, medium or low; a trigger left out keeps its rule. The audit entry names each change, old and new.

func (*Service) SendApprovalRequest

func (s *Service) SendApprovalRequest(ctx context.Context, req ApprovalRequest) ([]SendView, error)

SendApprovalRequest tells the approvers (PRE-4, S-RESP-2 transport for email). Every email approver gets their own message at their own address, never the alert list: with a signed one-time link when the risk allows a link and a token recorder is wired (spec approval-tokens.md 4; the record of the token, with the address, is stored by the TokenRecorder before the mail goes out), otherwise (high risk, or no recorder) a message that says to open Vedette. Other channels with approvals on get one message without a link that approves; on Telegram and Slack it carries Approve/Reject buttons (tglisten.go, slacklisten.go) unless the request is in-app only. On Zalo personal, when reply codes are allowed (replyCodesAllowed), every approver instead gets their own direct message with their own two codes, recorded before it goes out (replycode.go, spec 7.1); otherwise the configured recipient gets one message that says to open Vedette.

A message with a link is sent at most once: nothing here is retried, and the request ending (ctx) stops the messages not yet started. Each attempt that was made is recorded, also after ctx ended. It returns one SendView per message, each also written to the history. Without BaseURL the links would point nowhere, and a link that approves is a credential, so ErrApprovalUnavailable is returned and nothing is sent.

func (s *Service) SendApproverLink(ctx context.Context, actor string, t channel.Type, userID string) (link string, err error)

SendApproverLink sends the approver userID of a confirm-link channel a new confirm link: response's Send again in My account (response Config.LinkSender), where actor is that person. link is set when nothing was sent because the person confirms in their session (Zalo: their own row with the box's own account).

func (*Service) SendNow

func (s *Service) SendNow(ctx context.Context, actor, id string) (UnsentNotice, error)

SendNow sends a vulnerability notice that no channel delivered (History, Not sent) to every channel that is on, now: a person decided it matters, so the channels' minimum severity, quiet hours and grouping do not hold it back. It is written again from its findings as findings shows them now (the status, the reasons and the verification line of today), keeps its id, so the message that delivers it takes it off the Not sent list, and goes out with the next run of the deliver job. Refused (409) when a message already delivered it or has told all its findings since at their status or a more urgent one (one alert per finding), when its findings are no longer open at an urgent status (1-4), or when no channel is on.

func (*Service) SendReport

func (s *Service) SendReport(ctx context.Context, to []string, r ReportMail) error

SendReport mails a report digest to the given addresses (at most 20) through the saved SMTP settings (reports INV-4: the email channel of notify, no mail path of its own). The message is not logged or put into the history of alerts. A failure is a fixed error that may carry the numeric SMTP status and nothing else.

func (s *Service) SendTelegramLink(ctx context.Context, actor, userID string) (LinkApprover, error)

SendTelegramLink is POST /notify/telegram/approvers/{user_id}/code: a new confirm link for that approver (the old one stops working), sent privately by the bot. An administrator's own row gets the message like everyone's; they confirm it in their session.

func (*Service) SendTrapTest

func (s *Service) SendTrapTest(ctx context.Context, hit TrapHit) ([]TestDelivery, error)

SendTrapTest sends the alert a real hit on a trap would send, marked Test, to every channel that is on, now, and says what each did (honeypot "Test trap", "Test scan", "Test token"): the person sees the whole path from the trap to their phone work. It follows the channels' choice of what to send (a channel that would not take the real alert is skipped and says why; every channel is, when the trap's alert trigger holds the real one back) and says when quiet hours would hold the real one; it opens no incident, writes no history row and counts nowhere. The source address is the box's own. No channel on: an empty list.

func (*Service) SendZaloCode

func (s *Service) SendZaloCode(ctx context.Context, actor, userID string) (LinkApprover, error)

SendZaloCode is POST /notify/zalo/approvers/{user_id}/code: a new confirm link for that approver (the old one stops working), sent to their Zalo. Only for the administrator's own row whose address is the box's own signed-in Zalo account is nothing sent: the answer carries the link (Link) and they confirm it in this session, through the same page and check as anyone. Their own row with any other Zalo gets the message, so a wrongly picked friend never becomes their identity without that account's link being opened.

func (*Service) SentSince

func (s *Service) SentSince(ctx context.Context, since time.Time) (sent, failed int, err error)

SentSince counts the alert messages (kinds incident and vuln: an approval request is not an alert) sent since a time (Home's "alerts sent", #825): sent = attempts that arrived; failed = attempts that did not arrive, are not waiting to be sent again (a "Delayed" row resends by itself), and were not resent with success later to the same channel for the same item (kind, ref_id). One range on notify_send_at_ix; the resend check is a lookup on notify_send_ref_ix.

func (*Service) StartEmailSignin

func (s *Service) StartEmailSignin(ctx context.Context, actor string, in EmailSigninStart) (EmailSignin, error)

StartEmailSignin begins a user sign-in (POST /notify/email-signin).

func (*Service) StartZaloLogin

func (s *Service) StartZaloLogin(ctx context.Context, who string) (ZaloLogin, error)

StartZaloLogin starts a QR sign-in for the administrator who (POST /notify/zalo/login). Another administrator's sign-in in progress is 409 login_busy; more than one start in 30 s or 5 in an hour is 429 (repeated sign-ins can get the account locked).

func (*Service) Subscribe

func (s *Service) Subscribe(bus Bus) (unsubscribe func())

Subscribe registers the event handlers on bus and returns a function that removes them all. Handlers only record and queue (a database write); sending is the job's work, so a handler never holds the publisher on the network. Events are not persisted: a missed one is not replayed.

func (*Service) TelegramApprovers

func (s *Service) TelegramApprovers(ctx context.Context, who string) ([]LinkApprover, error)

TelegramApprovers is GET /notify/telegram/approvers: each saved approver of the Telegram channel and whether their Telegram is linked; who is the administrator asking (their own row is Self).

func (*Service) TelegramChats

func (s *Service) TelegramChats(ctx context.Context, token string) (chats []channel.TelegramChat, fresh bool, err error)

TelegramChats is POST /notify/telegram/chats (admin): the chats the bot has seen, for the Chat ID picker. The token is the one in the form, or, when the form has none (an edit), the saved one, which never goes back to the browser. Telegram is asked once, without an offset, so no update is confirmed and the approval buttons lose nothing. No chat yet is an empty list, not an error.

func (*Service) TestChannel

func (s *Service) TestChannel(ctx context.Context, actor string, t channel.Type) (TestResult, error)

TestChannel sends a test message through the saved channel and records the result as last_test (INV-11). The result is not a history row: History lists incidents, vulnerabilities and approvals only.

func (s *Service) VerifyApprovalLink(ctx context.Context, token string, b Binding, keyID string) (TokenID, error)

VerifyApprovalLink checks the format and the MAC of an approval link token against the binding stored with it and the key named by keyID (PRE-7, spec approval-tokens.md 4). It writes nothing and burns nothing: reading the confirmation page calls it, and the module response burns the token in the transaction of the decision. It never creates the key: a missing key is ErrApprovalKeyUnavailable, never a new key (a new key could not have signed any link). A token that is malformed (any length), a binding that differs in any field and an unknown keyID are ErrTokenInvalid, refused before the key store is read. Expiry is not checked here: the record knows it, and response answers expired, not unknown.

func (*Service) WebhookTarget

func (s *Service) WebhookTarget(ctx context.Context) (url, signingKey string, ok bool, err error)

WebhookTarget returns where the webhook channel posts and the key that signs its body, for the response module's webhook_call action (a neutral read for wiring; the caller applies its own address guard, and the values must never be logged or shown). ok is false when the webhook channel is not configured and enabled.

func (*Service) ZaloApprovers

func (s *Service) ZaloApprovers(ctx context.Context, who string) ([]LinkApprover, error)

ZaloApprovers is GET /notify/zalo/approvers: each saved approver of the Zalo personal channel and whether their Zalo is linked; who is the administrator asking (their own row is Self).

func (*Service) ZaloLoginState

func (s *Service) ZaloLoginState(who string) ZaloLogin

ZaloLoginState is GET /notify/zalo/login: the sign-in of who, or state none.

type SessionHit

type SessionHit struct {
	ID      string
	At      time.Time
	Kind    string // service | token | scan
	Service string
	Label   string // the trap or token as the honeypot names it: "SSH", "File token Payroll", ...
}

SessionHit is one hit of a source as a trap session tells it.

type Severity

type Severity string

Severity is a notice severity (contract.ts Severity).

const (
	Critical Severity = "critical"
	High     Severity = "high"
	Medium   Severity = "medium"
	Low      Severity = "low"
	Info     Severity = "info"
)

Severities, highest first.

func AlertSeverity

func AlertSeverity(cvss Severity, layer int) Severity

AlertSeverity is the severity a channel judges a finding's notice at (its min_severity, quiet hours, grouping): the finding's CVSS band raised to the floor of its urgency layer. Layers 1–4 are the ones Vedette alerts for, so none of them is below High; a flaw attackers use (under attack here, exploited in the wild) is Critical whatever its CVSS score, as the exploit-aware ratings of the large scanners rate a flaw on CISA's list. So a channel on the default "Medium and above", or on "High and above", gets every finding that enters layers 1–4; "Critical only" gets the exploited ones and the critical scores. An unknown band takes the floor.

func (Severity) Valid

func (s Severity) Valid() bool

Valid reports whether s is one of the five severities.

type SignalDirectory

type SignalDirectory interface {
	// UnmatchedExploited counts the CVEs a source reported as exploited (a qualifying signal the box stored at or after since, not one
	// that came with a source's first load) that no device has a finding for.
	UnmatchedExploited(ctx context.Context, since time.Time) (int, error)
}

SignalDirectory reads the exploitation news the box holds (feeds_signal) for the History page.

type TestDelivery

type TestDelivery struct {
	Channel channel.Type `json:"channel"`
	OK      bool         `json:"ok"`
	Skipped bool         `json:"skipped"`
	Detail  string       `json:"detail"`
}

TestDelivery is what one channel did with a test alert: delivered (OK, Detail the provider's receipt), failed (Detail why), or skipped because the real alert would not go through it (Skipped, Detail why).

type TestResult

type TestResult struct {
	At     string `json:"at"`
	OK     bool   `json:"ok"`
	Detail string `json:"detail"`
}

TestResult is the outcome of the last test message of a channel.

type TokenID

type TokenID [tokenIDLen]byte

TokenID identifies a token record (the database stores its hash).

func ConsumeApprovalToken

func ConsumeApprovalToken(ctx context.Context, store NonceStore, key []byte, token string, b Binding, now time.Time) (TokenID, error)

ConsumeApprovalToken is the POST path: verify, then burn the token. A token that was already used returns ErrTokenUsed (409 "used").

func MintApprovalToken

func MintApprovalToken(key []byte, b Binding, risk Risk, now time.Time) (string, TokenID, error)

MintApprovalToken creates a token for b. The caller stores the TokenID with the binding and the key id. It refuses a key shorter than 32 bytes, a binding outside the alphabet, an expiry that is not in the future or is more than 30 minutes away, and a high-risk request for the email channel.

func ParseApprovalToken

func ParseApprovalToken(token string) (TokenID, error)

ParseApprovalToken returns the token id (to look the record up) after a structural check only; it proves nothing about authenticity.

func VerifyApprovalToken

func VerifyApprovalToken(key []byte, token string, b Binding, now time.Time) (TokenID, error)

VerifyApprovalToken checks token against the binding read from its record: structure, MAC (constant time) and expiry. It changes nothing, so the GET that shows the confirmation page (and any link scanner) can call it freely. key is the K_approval named by the record's key id.

func (TokenID) String

func (id TokenID) String() string

String is the lowercase hex form, for in-memory keys and database lookups. Never log it: it identifies a live token record.

type TokenRecorder

type TokenRecorder interface {
	// address is where the link was sent (the approver's email): the record carries it (spec 4.1, 4.2).
	RecordToken(ctx context.Context, id TokenID, b Binding, keyID, address string) error
	// RecordReplyCode stores the hash of one Zalo personal reply code (spec approval-tokens.md 7.1) before the message
	// that carries the code is sent; without a recorder no code is sent. The plain code is never stored or logged.
	RecordReplyCode(ctx context.Context, c ReplyCode) error
}

TokenRecorder stores an approval token record (spec approval-tokens.md 4.1: the record in the database is the source of truth). The response module implements it; notify mints the token but never keeps the record, so without a recorder email approvers get a message that says to open Vedette, not a link.

type TrapHit

type TrapHit struct {
	ID         string `json:"id"`
	TS         string `json:"ts"`
	Kind       string `json:"kind"`
	Service    string `json:"service"`
	SrcIP      string `json:"src_ip"`
	Label      string `json:"label"`
	Decoy      string `json:"decoy"`
	SrcAssetID string `json:"src_asset_id"`
	SrcName    string `json:"src_name"`
}

TrapHit is a honeypot hit as notify reads it (the data of honeypot.hit.created). Every text is data from the network: it is cut to size and rendered as plain text by the adapters.

type Trigger

type Trigger struct {
	ID  string   `json:"id"`
	On  bool     `json:"on"`
	Min Severity `json:"min"` // the lowest severity that sends: critical, high, medium or low
}

Trigger is the rule of one trigger (contract.ts AlertTrigger).

type TriggerView

type TriggerView struct {
	Trigger
	DefaultOn  bool     `json:"default_on"`
	DefaultMin Severity `json:"default_min"`
}

TriggerView is a trigger as GET /notify/channels shows it: the rule and its default.

type Triggers

type Triggers []Trigger

Triggers is the stored rule of every trigger: the defaults with the administrator's changes over them.

type UnsentNotice

type UnsentNotice struct {
	ID      string  `json:"id"`
	At      string  `json:"at"`
	What    string  `json:"what"`
	Link    string  `json:"link"`
	NotSent NotSent `json:"not_sent"`
}

UnsentNotice is a vulnerability notice no channel has delivered: what it says, when it was made, the finding (or the findings list) it links to, and why it was not sent.

type User

type User struct {
	ID     string
	Email  string
	Role   string // viewer | operator | admin
	Active bool
}

User is a Vedette user as notify needs to see one (INV-7).

type Users

type Users interface {
	// Lookup returns the user, or found=false when there is none.
	Lookup(ctx context.Context, id string) (u User, found bool, err error)
	// EmailCodeUsers counts the active users who sign in with a two-step code sent by email (INV-9).
	EmailCodeUsers(ctx context.Context) (int, error)
}

Users is implemented by the code that owns users (core/auth). notify never reads core tables.

type Verdict

type Verdict int

Verdict is what to do with a notice on one channel right now.

const (
	Send Verdict = iota // send immediately
	Hold                // keep it and send it grouped when quiet hours end
	Skip                // below the channel's min_severity: never sent here
)

Verdicts.

func Decide

func Decide(now time.Time, minSev Severity, q Quiet, sev Severity) (Verdict, time.Time)

Decide combines INV-4 and INV-5 (and the quiet-hours hold) for one channel: below min_severity is skipped; during quiet hours it is held until the window ends, except a critical notice when allow_critical is set, which goes at once. The returned time is the release time of a held notice (zero otherwise).

func (Verdict) String

func (v Verdict) String() string

type ZaloContacts

type ZaloContacts struct {
	Friends []channel.ZaloContact `json:"friends"`
	Groups  []channel.ZaloContact `json:"groups"`
}

ZaloContacts is the account's friends and groups (GET /notify/zalo/contacts).

type ZaloFound

type ZaloFound struct {
	channel.ZaloContact
	Member bool `json:"member"`
}

ZaloFound is the person or group behind a look-up (POST /notify/zalo/resolve). Member is false for a group the account is not in.

type ZaloLogin

type ZaloLogin struct {
	State     string               `json:"state"`
	QR        *channel.ZaloQRImage `json:"qr"`
	Name      string               `json:"name"`
	Error     string               `json:"error"`
	ExpiresAt *string              `json:"expires_at"`
}

ZaloLogin is the state of the signed-in administrator's QR sign-in (GET /notify/zalo/login). State: none, waiting (show QR), scanned (Name is who scanned it), signed_in (Name is the account), expired, declined, failed (Error says why).

Directories

Path Synopsis
Package channel holds the notification channel adapters of the notify module (Slack, Telegram, email over SMTP, Zalo OA, generic webhook, Zalo personal).
Package channel holds the notification channel adapters of the notify module (Slack, Telegram, email over SMTP, Zalo OA, generic webhook, Zalo personal).

Jump to

Keyboard shortcuts

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