hostrepute

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Oct 24, 2026 License: AGPL-3.0 Imports: 37 Imported by: 0

Documentation

Overview

Package hostrepute connects a workspace to HostRepute (hostrepute.com), the sibling email-reputation service: OAuth 2 (PKCE) or API-key connection, encrypted tokens, a River job that syncs blocklist, Postmaster, SNDS, DMARC and alert data, "Add to monitoring" and disconnect.

The API is reached only through the Client interface; HTTPClient implements it against docs/integrations/hostrepute.md. Only sending domains, organization domains, dedicated IPs and server hostnames cross the boundary: never contacts, email content or reports.

Index

Constants

View Source
const (
	RoleSendingDomain      = "sending_domain"
	RoleOrganizationDomain = "organization_domain"
	RoleDedicatedIP        = "dedicated_ip"
	RoleServerHostname     = "server_hostname"
	RoleOther              = "other"
)

Asset roles: why an asset belongs to the workspace.

View Source
const (
	ScopeMonitorRead = "monitor:read"
	ScopeAlertsRead  = "alerts:read"
	ScopeAssetsWrite = "assets:write"
)

Scopes ReputeCast asks for, with what each one is used for.

View Source
const (
	AssetDomain   = "domain"
	AssetIP       = "ip"
	AssetHostname = "hostname"
)

Asset types HostRepute monitors.

View Source
const (
	PostmasterDays = 30
	SNDSDays       = 30
	DMARCDays      = 7
)

Days of history a sync reads.

View Source
const CallbackPath = "/api/v1/integrations/hostrepute/callback"

CallbackPath is where HostRepute sends the browser back after consent. It is fixed per instance (not per workspace) so one redirect URI is registered; the state names the workspace.

View Source
const DefaultTimeout = 30 * time.Second

DefaultTimeout is the per-request timeout of HostRepute calls.

View Source
const DemoAPIURL = "demo:"

DemoAPIURL marks a connection served by the built-in demo HostRepute.

View Source
const DemoLimit = 3

DemoLimit is the sample plan's monitoring limit (3 assets).

View Source
const DemoTeam = "Acme Inc"

DemoTeam is the sample HostRepute team.

Variables

View Source
var (
	// ErrUnauthorized: HostRepute rejected the token (revoked or expired).
	ErrUnauthorized = errors.New("hostrepute: token rejected")
	// ErrForbidden: the token lacks a scope the call needs.
	ErrForbidden = errors.New("hostrepute: missing scope")
	// ErrUnavailable: HostRepute couldn't be reached (network, timeouts, 5xx).
	ErrUnavailable = errors.New("hostrepute: unreachable")
	// ErrNotFound: the asset, check or report doesn't exist at HostRepute.
	ErrNotFound = errors.New("hostrepute: not found")
)

Errors returned by clients.

View Source
var DemoMonitored = []string{"news.acme.io", "acme.io", "203.0.113.25"}

DemoMonitored is what the sample team monitors.

View Source
var ScopeUse = map[string]string{
	ScopeMonitorRead: "blocklist, Postmaster, SNDS and DMARC data",
	ScopeAlertsRead:  "incidents",
	ScopeAssetsWrite: "add domains and IPs to monitoring",
}

ScopeUse explains a scope in the product's words.

Scopes in the order they are requested and shown.

Functions

func DemoLastCheck

func DemoLastCheck(now time.Time) time.Time

DemoLastCheck is HostRepute's last full check (hourly, at :40).

func GuessType

func GuessType(asset string) string

GuessType says whether an asset is an IP or a domain name.

func NewVerifier

func NewVerifier() string

NewVerifier returns a fresh PKCE code verifier.

func Register

func Register(h huma.API, s *Service)

Register adds the HostRepute and Settings › Integrations operations.

func ServerHostname

func ServerHostname(adapter string, config json.RawMessage) string

ServerHostname is the hostname of a self-hosted sending server (Postal's server URL, an SMTP relay's host); empty for API providers.

Types

type APIError

type APIError struct {
	Status int
	Code   string
	Detail string
}

APIError is any other non-2xx answer.

func (*APIError) Error

func (e *APIError) Error() string

type Account

type Account struct {
	ID     string   `json:"id"`
	Email  string   `json:"email"`
	Team   Team     `json:"team"`
	Scopes []string `json:"scopes"`
	// Sources is how many blocklists HostRepute checks (84).
	Sources              int `json:"sources"`
	CheckIntervalMinutes int `json:"check_interval_minutes"`
	// DMARCRua is the address that receives aggregate reports for the team.
	DMARCRua string `json:"dmarc_rua"`
}

Account is the HostRepute account and team behind a token (GET /me).

func DemoAccount

func DemoAccount(monitored int) Account

DemoAccount is the account behind the demo token.

type Alert

type Alert struct {
	ID        string    `json:"id"`
	CreatedAt time.Time `json:"created_at"`
	// Kind: listed, delisted, reputation_drop, dmarc_failure, auth_change.
	Kind      string `json:"kind"`
	Severity  string `json:"severity"` // info, ok, warn, bad
	Asset     string `json:"asset"`
	Source    string `json:"source,omitempty"`
	Title     string `json:"title"`
	Detail    string `json:"detail"`
	DelistURL string `json:"delist_url,omitempty"`
}

Alert is something HostRepute noticed: a new listing, a delisting, a reputation drop, a DMARC failure spike.

func Apply

func Apply(ctx context.Context, tx pgx.Tx, ws uuid.UUID, snap Snapshot, now time.Time) ([]Alert, error)

Apply writes a snapshot into the workspace's tables in tx: blocklist results (replacing the previous HostRepute ones), Postmaster, SNDS and DMARC data, alerts as incidents (each once), and the connection's account, monitored assets and sync time. It returns the alerts that were new.

func DemoAlerts

func DemoAlerts(now time.Time) []Alert

DemoAlerts are the sample team's HostRepute alerts.

type Asset

type Asset struct {
	ID    string `json:"id"`
	Asset string `json:"asset"`
	Type  string `json:"type"`
	// Status of HostRepute's monitoring: synced, pending (first check
	// running) or error.
	Status string `json:"status"`
	// Score is HostRepute's 0–100 reputation score with its verdict word.
	Score         *int       `json:"score,omitempty"`
	Verdict       string     `json:"verdict,omitempty"`
	LastCheckedAt *time.Time `json:"last_checked_at,omitempty"`
	Listings      int        `json:"listings"`
}

Asset is a monitored domain, IP or hostname.

func DemoAssets

func DemoAssets(now time.Time, names []string) []Asset

DemoAssets returns the demo assets for the monitored names.

type AssetStatus

type AssetStatus struct {
	Sources              int
	Listings             []string
	PostmasterReputation string
	DMARCPolicy          string
	DMARCAligned         *float64
}

AssetStatus is what Deliverability knows about an asset, shown next to it in Settings › Integrations.

type BlocklistResult

type BlocklistResult struct {
	Asset     string `json:"asset"`
	AssetType string `json:"asset_type"` // domain or ip
	Source    string `json:"source"`
	// Impact on inbox placement when listed: high, medium or low.
	Impact      string     `json:"impact"`
	Rank        int        `json:"rank"`
	Listed      bool       `json:"listed"`
	ListedSince *time.Time `json:"listed_since,omitempty"`
	DelistURL   string     `json:"delist_url"`
	Detail      string     `json:"detail,omitempty"`
	Delisting   *Delisting `json:"delisting,omitempty"`
	CheckedAt   time.Time  `json:"checked_at"`
}

BlocklistResult is one asset on one source.

type Blocklists

type Blocklists struct {
	Sources   int               `json:"sources"`
	CheckedAt time.Time         `json:"checked_at"`
	Results   []BlocklistResult `json:"results"`
}

Blocklists is every source checked for every monitored asset.

func DemoBlocklists

func DemoBlocklists(now time.Time, monitored []string) Blocklists

DemoBlocklists checks the monitored assets on the 84 demo sources. The Postal IP is listed on UCEPROTECT Level 3 (a network-range listing) since five days ago, with a delisting request pending since the next day.

type CallbackParams

type CallbackParams struct {
	Code, State, Error, ErrorDescription string
	// Self is the callback URL as requested, to come back after signing in.
	Self string
}

CallbackParams are what HostRepute sends back to the redirect URI.

type Candidate

type Candidate struct {
	Asset string
	Type  string // domain, ip, hostname
	Role  string
	// Provider sends from the IP or runs on the hostname ("Postal").
	ProviderID *uuid.UUID
	Provider   string
	// Shared is true for what connecting shares by default: sending and
	// organization domains and dedicated IPs. Server hostnames are suggested.
	Shared bool
}

Candidate is a domain, IP or hostname of the workspace that HostRepute can monitor. Only candidates are ever sent to HostRepute.

func Candidates

func Candidates(ctx context.Context, q *store.Queries, workspaceID uuid.UUID) ([]Candidate, error)

Candidates lists the workspace's assets: sending domains, their organization domains, dedicated IPs and self-hosted server hostnames.

type Check

type Check struct {
	ID         string     `json:"id"`
	Status     string     `json:"status"` // running, done, failed
	Total      int        `json:"total"`
	Answered   int        `json:"answered"`
	StartedAt  time.Time  `json:"started_at"`
	FinishedAt *time.Time `json:"finished_at,omitempty"`
}

Check is an on-demand re-check of monitored assets.

type Client

type Client interface {
	Account(ctx context.Context) (Account, error)
	Assets(ctx context.Context) ([]Asset, error)
	// AddAsset starts monitoring an asset; it fails with *LimitError when the
	// team's plan is full.
	AddAsset(ctx context.Context, asset, typ, label string) (Asset, error)
	RemoveAsset(ctx context.Context, id string) error
	Blocklists(ctx context.Context) (Blocklists, error)
	Postmaster(ctx context.Context, domain string, from, to time.Time) ([]PostmasterDay, error)
	SNDS(ctx context.Context, ip string, from, to time.Time) ([]SNDSDay, error)
	DMARCReports(ctx context.Context, domain string, from, to time.Time) ([]DMARCReport, error)
	Alerts(ctx context.Context, since time.Time) ([]Alert, error)
	StartCheck(ctx context.Context, assets []string) (Check, error)
	Check(ctx context.Context, id string) (Check, error)
	RequestDelisting(ctx context.Context, asset, source string) (Delisting, error)
	// Revoke invalidates the token at HostRepute (disconnect).
	Revoke(ctx context.Context) error
}

Client is everything ReputeCast asks HostRepute. Implementations must be safe for concurrent use.

type DMARCRecord

type DMARCRecord struct {
	SourceIP    string `json:"source_ip"`
	PTR         string `json:"ptr,omitempty"`
	Count       int64  `json:"count"`
	Disposition string `json:"disposition"` // none, quarantine, reject
	DKIM        string `json:"dkim"`        // DMARC-evaluated: pass or fail
	SPF         string `json:"spf"`
	// DKIMResult / SPFResult are the raw auth results: pass, fail, none…
	DKIMResult string `json:"dkim_result,omitempty"`
	SPFResult  string `json:"spf_result,omitempty"`
	HeaderFrom string `json:"header_from"`
	DKIMDomain string `json:"dkim_domain,omitempty"`
	SPFDomain  string `json:"spf_domain,omitempty"`
}

DMARCRecord is one row of an aggregate report: a source IP and what happened to its messages.

type DMARCReport

type DMARCReport struct {
	Domain    string            `json:"domain"`
	OrgName   string            `json:"org_name"`
	ReportID  string            `json:"report_id"`
	DateBegin time.Time         `json:"date_begin"`
	DateEnd   time.Time         `json:"date_end"`
	Policy    map[string]string `json:"policy"`
	Records   []DMARCRecord     `json:"records"`
}

DMARCReport is one aggregate (rua) report.

func DemoDMARC

func DemoDMARC(now time.Time, domain string) []DMARCReport

DemoDMARC is a week of aggregate reports for news.acme.io: every provider aligned, plus 612 messages from an unknown host that failed and were quarantined.

type Delisting

type Delisting struct {
	ID          string    `json:"id,omitempty"`
	Status      string    `json:"status"` // requested, pending, delisted, denied
	RequestedAt time.Time `json:"requested_at"`
	URL         string    `json:"url,omitempty"`
}

Delisting is HostRepute's delisting request for a listing.

type DemoClient

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

DemoClient is the offline HostRepute. Monitoring changes (Add to monitoring, swap) live in the client and are persisted by the caller in the connection's monitored assets.

func NewDemoClient

func NewDemoClient(now func() time.Time, monitored []string) *DemoClient

NewDemoClient returns the demo HostRepute for the monitored assets.

func (*DemoClient) Account

func (d *DemoClient) Account(context.Context) (Account, error)

Account implements Client.

func (*DemoClient) AddAsset

func (d *DemoClient) AddAsset(_ context.Context, asset, typ, _ string) (Asset, error)

AddAsset implements Client; the demo plan monitors three assets.

func (*DemoClient) Alerts

func (d *DemoClient) Alerts(_ context.Context, since time.Time) ([]Alert, error)

Alerts implements Client.

func (*DemoClient) Assets

func (d *DemoClient) Assets(context.Context) ([]Asset, error)

Assets implements Client.

func (*DemoClient) Blocklists

func (d *DemoClient) Blocklists(context.Context) (Blocklists, error)

Blocklists implements Client.

func (*DemoClient) Check

func (d *DemoClient) Check(_ context.Context, id string) (Check, error)

Check implements Client.

func (*DemoClient) DMARCReports

func (d *DemoClient) DMARCReports(_ context.Context, domain string, _, _ time.Time) ([]DMARCReport, error)

DMARCReports implements Client.

func (*DemoClient) Monitored

func (d *DemoClient) Monitored() []string

Monitored returns the assets the demo team monitors now.

func (*DemoClient) Postmaster

func (d *DemoClient) Postmaster(_ context.Context, domain string, _, _ time.Time) ([]PostmasterDay, error)

Postmaster implements Client.

func (*DemoClient) RemoveAsset

func (d *DemoClient) RemoveAsset(_ context.Context, id string) error

RemoveAsset implements Client.

func (*DemoClient) RequestDelisting

func (d *DemoClient) RequestDelisting(_ context.Context, asset, source string) (Delisting, error)

RequestDelisting implements Client.

func (*DemoClient) Revoke

func (d *DemoClient) Revoke(context.Context) error

Revoke implements Client.

func (*DemoClient) SNDS

func (d *DemoClient) SNDS(_ context.Context, ip string, _, _ time.Time) ([]SNDSDay, error)

SNDS implements Client.

func (*DemoClient) StartCheck

func (d *DemoClient) StartCheck(context.Context, []string) (Check, error)

StartCheck implements Client: the demo check answers 84 sources over about eight seconds.

type HTTPClient

type HTTPClient struct {
	// BaseURL is the API root, e.g. https://api.hostrepute.com/v1.
	BaseURL string
	Tokens  oauth2.TokenSource
	HTTP    *http.Client
	// Attempts per call (default 3) and the wait before each retry.
	Attempts int
	Wait     func(attempt int) time.Duration
	// RevokeURL and ClientID are used by Revoke (RFC 7009).
	RevokeURL string
	ClientID  string
}

HTTPClient implements Client against HostRepute's REST API (docs/integrations/hostrepute.md). Requests carry the OAuth access token or the API key as a bearer token; network errors, 429 and 5xx answers are retried before the call fails with ErrUnavailable.

func NewHTTPClient

func NewHTTPClient(baseURL string, tokens oauth2.TokenSource, httpClient *http.Client) *HTTPClient

NewHTTPClient returns a client with ReputeCast's defaults: 30 s per request, 3 attempts.

func (*HTTPClient) Account

func (c *HTTPClient) Account(ctx context.Context) (Account, error)

Account implements Client.

func (*HTTPClient) AddAsset

func (c *HTTPClient) AddAsset(ctx context.Context, asset, typ, label string) (Asset, error)

AddAsset implements Client.

func (*HTTPClient) Alerts

func (c *HTTPClient) Alerts(ctx context.Context, since time.Time) ([]Alert, error)

Alerts implements Client.

func (*HTTPClient) Assets

func (c *HTTPClient) Assets(ctx context.Context) ([]Asset, error)

Assets implements Client.

func (*HTTPClient) Blocklists

func (c *HTTPClient) Blocklists(ctx context.Context) (Blocklists, error)

Blocklists implements Client.

func (*HTTPClient) Check

func (c *HTTPClient) Check(ctx context.Context, id string) (Check, error)

Check implements Client.

func (*HTTPClient) DMARCReports

func (c *HTTPClient) DMARCReports(ctx context.Context, domain string, from, to time.Time) ([]DMARCReport, error)

DMARCReports implements Client.

func (*HTTPClient) Postmaster

func (c *HTTPClient) Postmaster(ctx context.Context, domain string, from, to time.Time) ([]PostmasterDay, error)

Postmaster implements Client.

func (*HTTPClient) RemoveAsset

func (c *HTTPClient) RemoveAsset(ctx context.Context, id string) error

RemoveAsset implements Client.

func (*HTTPClient) RequestDelisting

func (c *HTTPClient) RequestDelisting(ctx context.Context, asset, source string) (Delisting, error)

RequestDelisting implements Client.

func (*HTTPClient) Revoke

func (c *HTTPClient) Revoke(ctx context.Context) error

Revoke implements Client: RFC 7009 token revocation. API keys can't be revoked from ReputeCast; they are only forgotten.

func (*HTTPClient) SNDS

func (c *HTTPClient) SNDS(ctx context.Context, ip string, from, to time.Time) ([]SNDSDay, error)

SNDS implements Client.

func (*HTTPClient) StartCheck

func (c *HTTPClient) StartCheck(ctx context.Context, assets []string) (Check, error)

StartCheck implements Client.

type HostReputeAsset

type HostReputeAsset struct {
	Asset string `json:"asset"`
	Type  string `json:"type" enum:"domain,ip,hostname"`
	Role  string `json:"role" enum:"sending_domain,organization_domain,dedicated_ip,server_hostname,other"`
	// Provider sends from the IP or runs on the hostname ("Postal").
	Provider   string     `json:"provider,omitempty"`
	Monitored  bool       `json:"monitored"`
	Status     string     `json:"status,omitempty" enum:"synced,pending,error"`
	LastSyncAt *time.Time `json:"lastSyncAt,omitempty"`
	Score      *int       `json:"score,omitempty"`
	Verdict    string     `json:"verdict,omitempty"`
	// Sources is how many blocklists check the asset; Listings names the
	// ones it is listed on.
	Sources              int      `json:"sources"`
	Listings             []string `json:"listings"`
	PostmasterReputation string   `json:"postmasterReputation,omitempty"`
	DMARCPolicy          string   `json:"dmarcPolicy,omitempty"`
	DMARCAligned         *float64 `json:"dmarcAligned,omitempty" doc:"Percent of DMARC-aligned mail in the last 7 days"`
}

HostReputeAsset is one row of the monitored assets table.

type HostReputeConnection

type HostReputeConnection struct {
	Status string `json:"status" enum:"not_connected,connected,revoked,expired,error"`
	Method string `json:"method,omitempty" enum:"oauth,api_key"`
	// Demo is true for connections served by the built-in demo HostRepute.
	Demo         bool       `json:"demo"`
	TeamName     string     `json:"teamName,omitempty"`
	AccountEmail string     `json:"accountEmail,omitempty"`
	Plan         string     `json:"plan,omitempty"`
	ConnectedAt  *time.Time `json:"connectedAt,omitempty"`
	ConnectedBy  string     `json:"connectedBy,omitempty"`
	// TokenRejectedAt is when HostRepute rejected the token: data is stale since.
	TokenRejectedAt *time.Time `json:"tokenRejectedAt,omitempty"`
	LastSyncAt      *time.Time `json:"lastSyncAt,omitempty"`
	// LastCheckAt is HostRepute's last full check of the monitored assets.
	LastCheckAt *time.Time `json:"lastCheckAt,omitempty"`
	// SyncError is set while HostRepute can't be reached ("Couldn't reach
	// api.hostrepute.com (timeout after 30 s, 3 attempts)").
	SyncError   string     `json:"syncError,omitempty"`
	SyncErrorAt *time.Time `json:"syncErrorAt,omitempty"`
	// Syncing is true while a sync (the first one after connecting) runs.
	Syncing              bool              `json:"syncing"`
	Scopes               []HostReputeScope `json:"scopes"`
	MonitorLimit         *int32            `json:"monitorLimit,omitempty"`
	MonitorUsed          int               `json:"monitorUsed"`
	Sources              int32             `json:"sources"`
	CheckIntervalMinutes int32             `json:"checkIntervalMinutes"`
	DMARCRua             string            `json:"dmarcRua,omitempty"`
	// AlertsToNotifications: HostRepute alerts become ReputeCast notifications.
	AlertsToNotifications bool `json:"alertsToNotifications"`
	// Assets are the workspace's domains, IPs and hostnames with their
	// monitoring status (monitored ones first, then suggestions).
	Assets []HostReputeAsset `json:"assets"`
	// Shared is exactly what connecting shares with HostRepute.
	Shared HostReputeShared `json:"shared"`
}

HostReputeConnection is a workspace's connection to HostRepute as shown in Settings › Integrations and the connect flow. Tokens are never included.

type HostReputeDataSource

type HostReputeDataSource struct {
	Via string `json:"via" enum:"hostrepute,direct,none"`
}

HostReputeDataSource says where Postmaster or SNDS data comes from.

type HostReputeIntegrationsMCP

type HostReputeIntegrationsMCP struct {
	Agents int64 `json:"agents"`
}

HostReputeIntegrationsMCP counts active MCP agents.

type HostReputeIntegrationsOverview

type HostReputeIntegrationsOverview struct {
	HostRepute HostReputeConnection           `json:"hostRepute"`
	Webhooks   HostReputeIntegrationsWebhooks `json:"webhooks"`
	MCP        HostReputeIntegrationsMCP      `json:"mcp"`
	// Postmaster and SNDS say where that data comes from.
	Postmaster HostReputeDataSource `json:"postmaster"`
	SNDS       HostReputeDataSource `json:"snds"`
}

HostReputeIntegrationsOverview is Settings › Integrations.

type HostReputeIntegrationsWebhooks

type HostReputeIntegrationsWebhooks struct {
	Endpoints int64 `json:"endpoints"`
	Failing   int64 `json:"failing"`
}

HostReputeIntegrationsWebhooks counts outgoing webhook endpoints.

type HostReputeOAuthStart

type HostReputeOAuthStart struct {
	AuthorizeURL string `json:"authorizeUrl" format:"uri"`
}

HostReputeOAuthStart is where to send the browser for HostRepute's consent page.

type HostReputeScope

type HostReputeScope struct {
	Key     string `json:"key"`
	Use     string `json:"use"`
	Granted bool   `json:"granted"`
}

HostReputeScope is a granted (or requested) OAuth scope.

type HostReputeShared

type HostReputeShared struct {
	Domains []string `json:"domains"`
	IPs     []string `json:"ips"`
}

HostReputeShared lists what is sent to HostRepute. Contacts, email content and reports are never sent.

type HostReputeSyncQueued

type HostReputeSyncQueued struct {
	RunID     string    `json:"runId"`
	StartedAt time.Time `json:"startedAt"`
}

HostReputeSyncQueued is the check run a sync fills in.

type JobInserter

type JobInserter interface {
	InsertTx(ctx context.Context, tx pgx.Tx, args river.JobArgs, opts *river.InsertOpts) (*rivertype.JobInsertResult, error)
}

JobInserter enqueues River jobs inside a transaction (*jobs.Client).

type LimitError

type LimitError struct {
	Limit int
	Used  int
	Team  string
}

LimitError means the team's plan monitors as many assets as it allows. It's a HostRepute limit; ReputeCast stays fully usable.

func (*LimitError) Error

func (e *LimitError) Error() string

type OAuth

type OAuth struct {

	// HTTP is used for token exchange and refresh (tests inject a client).
	HTTP *http.Client
	// contains filtered or unexported fields
}

OAuth runs the authorization-code flow with PKCE against HostRepute.

func NewOAuth

func NewOAuth(c config.HostReputeConfig, publicURL string) *OAuth

NewOAuth builds the OAuth configuration for an instance. publicURL is the instance's external base URL; the redirect URI is publicURL+CallbackPath.

func (*OAuth) AuthCodeURL

func (o *OAuth) AuthCodeURL(state, verifier string) string

AuthCodeURL is the consent page on app.hostrepute.com, with the S256 code challenge of verifier. In demo mode consent is instant: the URL goes straight back to the callback with a demo code.

func (*OAuth) Demo

func (o *OAuth) Demo() bool

Demo reports whether connections made through this OAuth are demo ones.

func (*OAuth) Exchange

func (o *OAuth) Exchange(ctx context.Context, code, verifier string) (*oauth2.Token, error)

Exchange trades the authorization code (and the verifier) for tokens.

func (*OAuth) RedirectURL

func (o *OAuth) RedirectURL() string

RedirectURL is the redirect URI sent to HostRepute.

func (*OAuth) TokenSource

func (o *OAuth) TokenSource(ctx context.Context, tok *oauth2.Token) oauth2.TokenSource

TokenSource refreshes tok when it expires.

type PostmasterDay

type PostmasterDay struct {
	Day              string   `json:"day"` // YYYY-MM-DD
	SpamRate         *float64 `json:"spam_rate,omitempty"`
	DomainReputation string   `json:"domain_reputation,omitempty"` // HIGH, MEDIUM, LOW, BAD
	IPReputation     string   `json:"ip_reputation,omitempty"`
	SPFRate          *float64 `json:"spf_rate,omitempty"`
	DKIMRate         *float64 `json:"dkim_rate,omitempty"`
	DMARCRate        *float64 `json:"dmarc_rate,omitempty"`
	TLSRate          *float64 `json:"tls_rate,omitempty"`
	DeliveryErrors   *float64 `json:"delivery_errors,omitempty"`
	FBLFlagged       *int     `json:"fbl_flagged,omitempty"`
}

PostmasterDay is one day of Google Postmaster Tools data for a domain.

func DemoPostmaster

func DemoPostmaster(now time.Time, domain string) []PostmasterDay

DemoPostmaster is 30 days of Postmaster Tools data for news.acme.io.

type SNDSDay

type SNDSDay struct {
	Day           string   `json:"day"`
	FilterResult  string   `json:"filter_result"` // green, yellow, red
	ComplaintRate *float64 `json:"complaint_rate,omitempty"`
	TrapHits      int      `json:"trap_hits"`
	Messages      int64    `json:"messages"`
	JMRPReports   int      `json:"jmrp_reports"`
}

SNDSDay is one day of Microsoft SNDS data for an IP.

func DemoSNDS

func DemoSNDS(now time.Time, ip string) []SNDSDay

DemoSNDS is Microsoft SNDS data for the Postal IP since it started sending.

type ScheduleArgs

type ScheduleArgs struct{}

ScheduleArgs is the hourly job that queues a sync for every connected workspace.

func (ScheduleArgs) InsertOpts

func (ScheduleArgs) InsertOpts() river.InsertOpts

InsertOpts runs the scheduler once per period.

func (ScheduleArgs) Kind

func (ScheduleArgs) Kind() string

Kind implements river.JobArgs.

type ScheduleWorker

type ScheduleWorker struct {
	river.WorkerDefaults[ScheduleArgs]
	S *Service
}

ScheduleWorker runs ScheduleArgs.

func (*ScheduleWorker) Work

Work implements river.Worker.

type Service

type Service struct {
	Pool  *pgxpool.Pool
	Q     *store.Queries
	Audit *audit.Logger
	Box   *secrets.Box
	Cfg   *config.Config
	Log   *slog.Logger
	Jobs  JobInserter
	// PublicURL is the instance's public URL (the OAuth redirect is built on
	// it); nil uses http.public_url.
	PublicURL func() string
	// HTTP carries HostRepute API and OAuth calls; tests inject one.
	HTTP *http.Client
	Now  func() time.Time
	// Status adds Deliverability's findings to the asset rows (wired by the app).
	Status func(ctx context.Context, workspaceID uuid.UUID) (map[string]AssetStatus, error)
	// Fallback queues Deliverability's built-in checks when HostRepute data
	// stops coming (disconnect, token rejected, HostRepute unreachable).
	Fallback func(ctx context.Context, tx pgx.Tx, workspaceID uuid.UUID, trigger string) error
}

Service manages a workspace's HostRepute connection.

func (*Service) AddAsset

func (s *Service) AddAsset(ctx context.Context, ws *store.Workspace, asset string) (HostReputeConnection, error)

AddAsset adds one of the workspace's domains, IPs or hostnames to HostRepute monitoring. A full plan answers 409 monitor_limit_reached with the limit and a swap suggestion.

func (*Service) CompleteOAuth

func (s *Service) CompleteOAuth(ctx context.Context, user *store.User, p CallbackParams) string

CompleteOAuth finishes the handoff and returns where to send the browser: the connect screen with the result. The signed-in person must be the one who started it and still hold integrations:hostrepute.

func (*Service) ConnectAPIKey

func (s *Service) ConnectAPIKey(ctx context.Context, ws *store.Workspace, key string) (HostReputeConnection, error)

ConnectAPIKey connects with a HostRepute API key (the alternative to the browser handoff). The key is verified against HostRepute before it is stored, encrypted; it is never returned.

func (*Service) Connection

func (s *Service) Connection(ctx context.Context, ws uuid.UUID) (HostReputeConnection, error)

Connection returns the connection view (status not_connected when there is none, with what connecting would share).

func (*Service) Disconnect

func (s *Service) Disconnect(ctx context.Context, ws *store.Workspace) error

Disconnect forgets the token (revoking it at HostRepute when possible), deletes the data synced from HostRepute and queues the built-in checks. The HostRepute team and its monitoring keep running on hostrepute.com.

func (*Service) Overview

Overview returns Settings › Integrations.

func (*Service) QueueRecheck

func (s *Service) QueueRecheck(ctx context.Context, tx pgx.Tx, ws uuid.UUID, by *uuid.UUID) error

QueueRecheck asks HostRepute to re-check every monitored asset now and syncs the result (Deliverability's "Run all checks now").

func (*Service) RequestDelisting

func (s *Service) RequestDelisting(ctx context.Context, ws uuid.UUID, asset, source string) (Delisting, error)

RequestDelisting asks HostRepute to request the delisting of an asset from a blocklist (HostRepute's delisting workflow).

func (*Service) StartOAuth

func (s *Service) StartOAuth(ctx context.Context, ws *store.Workspace, user *store.User) (string, error)

StartOAuth begins the browser handoff: it stores a single-use state bound to the person and workspace with an encrypted PKCE verifier, and returns HostRepute's consent URL.

func (*Service) SwapAsset

func (s *Service) SwapAsset(ctx context.Context, ws *store.Workspace, remove, add string) (HostReputeConnection, error)

SwapAsset stops monitoring one asset and monitors another instead, for a full plan ("swap acme.io for mta.acme.io").

func (*Service) Sync

func (s *Service) Sync(ctx context.Context, args SyncArgs, lastAttempt bool) error

Sync reads HostRepute and writes the workspace's data. A rejected token marks the connection revoked (or expired) and notifies who can reconnect; an unreachable HostRepute is recorded for the Deliverability error state and, on the last attempt, the built-in checks take over.

func (*Service) SyncNow

SyncNow queues a sync of the HostRepute data ("Sync now").

type Snapshot

type Snapshot struct {
	Account    Account
	Assets     []Asset
	Blocklists Blocklists
	// Postmaster by domain, SNDS by IP.
	Postmaster map[string][]PostmasterDay
	SNDS       map[string][]SNDSDay
	DMARC      []DMARCReport
	Alerts     []Alert
}

Snapshot is everything one sync reads from HostRepute.

func Fetch

func Fetch(ctx context.Context, c Client, now, alertsSince time.Time) (Snapshot, error)

Fetch reads a snapshot. Calls that need a scope the token lacks are skipped; any other error fails the fetch.

type SyncArgs

type SyncArgs struct {
	WorkspaceID uuid.UUID `json:"workspace_id" river:"unique"`
	// RunID is the check run to keep up to date (manual and connect syncs).
	RunID *uuid.UUID `json:"run_id,omitempty" river:"unique"`
	// Recheck asks HostRepute to check every source now before reading.
	Recheck bool `json:"recheck,omitempty"`
	// Initial is the first sync after connecting: no notifications for
	// alerts from before the connection.
	Initial bool `json:"initial,omitempty"`
}

SyncArgs is the River job that syncs one workspace with HostRepute.

func (SyncArgs) InsertOpts

func (SyncArgs) InsertOpts() river.InsertOpts

InsertOpts keeps one pending sync per workspace (and run).

func (SyncArgs) Kind

func (SyncArgs) Kind() string

Kind implements river.JobArgs.

type SyncWorker

type SyncWorker struct {
	river.WorkerDefaults[SyncArgs]
	S *Service
}

SyncWorker runs SyncArgs.

func (*SyncWorker) Timeout

func (w *SyncWorker) Timeout(*river.Job[SyncArgs]) time.Duration

Timeout leaves room for a re-check of 80+ sources.

func (*SyncWorker) Work

func (w *SyncWorker) Work(ctx context.Context, job *river.Job[SyncArgs]) error

Work implements river.Worker.

type Team

type Team struct {
	ID   string `json:"id"`
	Name string `json:"name"`
	Plan string `json:"plan"`
	// MonitorLimit is how many assets the plan monitors; 0 means unlimited.
	MonitorLimit int `json:"monitor_limit"`
	Monitored    int `json:"monitored"`
}

Team is the HostRepute team, with its plan's monitoring limit.

type UnavailableError

type UnavailableError struct {
	Host     string
	Attempts int
	Reason   string // "timeout after 30 s", "connection refused", "HTTP 503"
}

UnavailableError explains why HostRepute couldn't be reached. It wraps ErrUnavailable.

func (*UnavailableError) Error

func (e *UnavailableError) Error() string

func (*UnavailableError) Unwrap

func (e *UnavailableError) Unwrap() error

Unwrap makes errors.Is(err, ErrUnavailable) true.

Directories

Path Synopsis
Package hrtest is a fake HostRepute (API and OAuth server) for tests.
Package hrtest is a fake HostRepute (API and OAuth server) for tests.

Jump to

Keyboard shortcuts

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