Documentation
¶
Overview ¶
Package sms is the pluggable SMS-provider contract (design expansion phase 8, M31), on the sending-provider pattern: a catalog of adapters with capability badges from each adapter's manifest, one connection pattern with write-only credentials, health, and the shared contract-test suite in internal/sms/contracttest that every adapter passes.
Texts go through the workspace's own account: an adapter talks to that account with the workspace's own credentials, and ReputeCast adds nothing to what the provider charges. Adapters live in internal/sms/<name>; the SMS domain (internal/texting) talks to these interfaces only and finds adapters through the registry.
Required of every adapter: Send, delivery receipts and inbound messages (ParseWebhook) and their signatures (VerifyWebhook). Optional, declared in the manifest and checked by the contract suite: the account's numbers (SenderLister), webhook registration (WebhookRegistrar), opt-out sync (OptOutReader, OptOutSyncer), registration status (RegistrationReader) and pricing (PricingReader).
Index ¶
- Constants
- Variables
- func CanSend(status string) bool
- func Concat(v url.Values) string
- func Do(ctx context.Context, client *http.Client, c Call, out any) ([]byte, error)
- func E164Digits(e164 string) string
- func FixEncoding(s string) string
- func Hint(id string, prefix, suffix int) string
- func InGSM7(r rune) bool
- func NormalizeKeyword(w string) string
- func Quote(s string) string
- func Register(d Descriptor)
- func Segments(s string) int
- func SortedParams(v url.Values, keys ...string) string
- func TextIn(english string, t i18n.Text, l i18n.Lang) string
- func UTF16Len(s string) int
- type Account
- type Badge
- type Call
- type CallError
- type Capability
- type Config
- type Count
- type DeclaredText
- type Descriptor
- type Encoding
- type Event
- type EventKind
- type Field
- type Keywords
- type Manifest
- type Message
- type OptOut
- type OptOutReader
- type OptOutSyncer
- type Outside
- type PricingReader
- type Provider
- type Reason
- type Registration
- type RegistrationReader
- type SendError
- type SendResult
- type Sender
- type SenderLister
- type Support
- type WebhookHandshaker
- type WebhookRegistrar
- type WebhookSetup
- type Webhooks
Constants ¶
const ( KeywordOptOut = "opt_out" KeywordOptIn = "opt_in" KeywordHelp = "help" // KeywordYes confirms consent when the workspace asks people to reply // YES first. KeywordYes = "yes" // KeywordReply is any other reply: it goes on the contact's timeline // and into the campaign report. KeywordReply = "reply" )
Keyword kinds: what a reply asks for.
const ( GSM7Single = 160 GSM7Part = 153 UCS2Single = 70 UCS2Part = 67 )
Segment capacities. A text that fits one segment gets the whole of it; longer texts are split into parts that each carry a header, so they hold less.
Variables ¶
var ( ErrKeywordEmpty = errors.New("sms: a keyword can't be empty") ErrKeywordFormat = errors.New("sms: a keyword is one word of letters and digits, up to 20") ErrKeywordDuplicate = errors.New("sms: a keyword can only mean one thing") ErrKeywordRequired = errors.New("sms: STOP and HELP can't be removed") )
Errors from Validate.
var ( // ErrCredentialsRejected: the provider refused the credentials. ErrCredentialsRejected = errors.New("sms: the provider rejected the credentials") ErrUnavailable = errors.New("sms: provider unavailable") // ErrBadSignature: a webhook whose signature doesn't verify. ErrBadSignature = errors.New("sms: webhook signature verification failed") // ErrNotSupported: the adapter doesn't offer this. ErrNotSupported = errors.New("sms: not supported by this provider") )
Errors adapters return.
var Capabilities = []Capability{CapTollFree, Cap10DLC, CapSenderIDs, CapReceipts, CapInbound, CapOptOutSync, CapRegistration, CapPricing}
Capabilities lists every capability in display order.
var DefaultKeywords = Keywords{ OptOut: []string{"STOP", "STOPALL", "UNSUBSCRIBE", "CANCEL", "END", "QUIT", "OPTOUT", "REVOKE"}, OptIn: []string{"START", "UNSTOP"}, Help: []string{"HELP", "INFO"}, }
DefaultKeywords are the carriers' standard words.
Functions ¶
func Concat ¶
Concat writes form parameters the way several providers sign them: keys in byte order, each key followed by its values.
func Do ¶
Do sends a call and decodes a 2xx JSON answer into out (nil to skip). Any other answer is a *CallError carrying the body, which adapters read for the provider's own error code. A transport failure is ErrUnavailable.
func E164Digits ¶
E164Digits is a number without its +, as some APIs take it.
func FixEncoding ¶
FixEncoding replaces every character outside GSM-7 that has a lookalike (curly quotes, long dashes, ellipses, special spaces). Characters without one, such as emoji, are kept: removing them is the writer's call.
func Hint ¶
Hint keeps the start and the end of an id and hides the rest: "AC8e2c…e8d3f9" → "AC…3f9".
func NormalizeKeyword ¶
Normalize writes a keyword the way it's stored: trimmed, upper case.
func Register ¶
func Register(d Descriptor)
Register adds an adapter; adapters call it from their package's init.
func SortedParams ¶
SortedParams writes form parameters sorted by key, as key=value pairs joined by " · " for the Events tab: MessageStatus=delivered · ErrorCode=30007.
Types ¶
type Account ¶
type Account struct {
ID string `json:"id"`
Name string `json:"name"`
// Hint is the part of the account id or key that's safe to show
// ("AC…3f9", "…7c21").
Hint string `json:"hint"`
// Live is false for a provider's test credentials.
Live bool `json:"live"`
}
Account is what checking the credentials reads about the account.
type Badge ¶
type Badge struct {
Capability Capability `json:"capability" enum:"toll_free,10dlc,sender_ids,receipts,inbound,opt_out_sync,registration,pricing"`
Support Support `json:"support" enum:"yes,partial,no"`
// Note qualifies it: "outside US and Canada", "read only", "set by hand".
Note string `json:"note,omitempty"`
// NoteText is the message Note comes from (text.go).
NoteText i18n.Text `json:"-"`
}
Badge is one capability as the manifest declares it.
type Call ¶
type Call struct {
Op string
Method string
URL string
// Form is sent as application/x-www-form-urlencoded; JSON as JSON.
Form url.Values
JSON any
// Header is added to the request (auth).
Header http.Header
// BasicUser and BasicPass set HTTP basic auth.
BasicUser, BasicPass string
}
Call is one API request.
type Capability ¶
type Capability string
Capability is a badge on a provider's catalog card and provider card.
const ( CapTollFree Capability = "toll_free" Cap10DLC Capability = "10dlc" CapSenderIDs Capability = "sender_ids" CapReceipts Capability = "receipts" CapInbound Capability = "inbound" CapOptOutSync Capability = "opt_out_sync" CapRegistration Capability = "registration" CapPricing Capability = "pricing" )
Capabilities, in the order the cards show them.
type Config ¶
type Config struct {
ProviderID uuid.UUID
WorkspaceID uuid.UUID
// Settings are the non-secret fields (account id, region, live or test).
Settings map[string]string
// Credentials are the secret fields (write-only: never logged or returned).
Credentials map[string]string
// WebhookSecret checks the provider's webhook signatures where the
// provider signs with a secret ReputeCast holds.
WebhookSecret string
// BaseURL overrides the provider's API address (tests and the demo).
BaseURL string
// HTTP overrides the client (the SSRF guard, the demo's fakes).
HTTP *http.Client
// Now overrides the clock (tests).
Now func() time.Time
}
Config opens a provider.
type Count ¶
type Count struct {
// Characters counts what a person sees (code points).
Characters int `json:"characters"`
// Units are septets in GSM-7 or UTF-16 code units in UCS-2.
Units int `json:"units"`
Encoding Encoding `json:"encoding" enum:"gsm7,ucs2"`
Segments int `json:"segments"`
// Capacity is what each segment holds: 160 or 153 for GSM-7, 70 or 67
// for UCS-2.
Capacity int `json:"capacity"`
// Fill is the units in each segment, for the counter's bar.
Fill []int `json:"fill"`
// Left is what's left in the last segment.
Left int `json:"left"`
// Outside lists the characters that force UCS-2, in order of first use.
Outside []Outside `json:"outside"`
}
Count is how a text is encoded and split into segments.
type DeclaredText ¶
DeclaredText is one text of a manifest, for checks: its well-known key, its English and its message.
type Descriptor ¶
type Descriptor struct {
Manifest
// New opens a provider on an account.
New func(cfg Config) (Provider, error)
}
Descriptor is a registered adapter.
type Encoding ¶
type Encoding string
Encoding is how a text travels: the GSM 03.38 7-bit alphabet, or UCS-2 as soon as one character is outside it.
type Event ¶
type Event struct {
Kind EventKind
ProviderMessageID string
// MessageID is ReputeCast's id when the provider echoed it.
MessageID *uuid.UUID
// To and From in E.164 (From is the sender for receipts, the person
// for inbound texts).
To string
From string
// Body of an inbound text.
Body string
// Code is the provider's own code ("30007", "absent subscriber").
Code string
Reason Reason
// OptOut is the keyword the provider itself acted on ("STOP"), when it
// handles keywords.
OptOut string
// Price is the provider's price for the text, when it reports one.
Price *float64
Segments int
OccurredAt time.Time
// Summary is the raw event as the Events tab shows it:
// MessageStatus=undelivered · ErrorCode=30007.
Summary string
}
Event is one thing a provider reported: a receipt or an inbound text.
type Field ¶
type Field struct {
Key string `json:"key"`
Label string `json:"label"`
// Secret fields are sealed and never shown again.
Secret bool `json:"secret"`
Required bool `json:"required"`
Options []string `json:"options,omitempty"`
Help string `json:"help,omitempty"`
Default string `json:"default,omitempty"`
// LabelText and HelpText are the messages Label and Help come from.
LabelText i18n.Text `json:"-"`
HelpText i18n.Text `json:"-"`
}
Field is one input of the connection form.
type Keywords ¶
type Keywords struct {
OptOut []string `json:"optOut"`
OptIn []string `json:"optIn"`
Help []string `json:"help"`
}
Keywords are the replies ReputeCast acts on.
func (Keywords) Match ¶
Match reads a reply. A keyword matches when it's the whole reply, in any case; anything else is a reply. yes reports whether YES confirms consent (the workspace asks people to reply YES first).
func (Keywords) Normalized ¶
Normalized returns the lists in their stored form.
type Manifest ¶
type Manifest struct {
Adapter string
Name string
// Summary is the catalog card's line ("Pay as you go · numbers in 190
// countries").
Summary string
Badges []Badge
Fields []Field
// Webhooks is how receipts and inbound texts reach ReputeCast:
// "registered" (through the provider's API) or "manual" (an address and
// a secret to paste in the provider's console).
Webhooks string
// Console links to the provider's console for a kind of page
// ("registration", "numbers", "webhooks", "opt_outs") and an object.
Console func(kind, id string) string
Version string
Maintainer string
// SummaryText is the message Summary comes from, and Messages the
// adapter's catalog its texts come from (text.go).
SummaryText i18n.Text
Messages *i18n.Catalog
}
Manifest describes an adapter for the catalog, the connection step and the provider cards.
func (Manifest) Has ¶
func (m Manifest) Has(c Capability) Support
Has reports the support the manifest declares for c.
func (Manifest) In ¶
In returns a copy of the manifest with every text in the reader's language, for display.
func (Manifest) Texts ¶
func (m Manifest) Texts() []DeclaredText
Texts lists every text people read in a manifest.
type Message ¶
type Message struct {
// ID is ReputeCast's message id; adapters that can carry a reference
// pass it so receipts can be matched without the provider's id.
ID uuid.UUID
// To is the recipient in E.164.
To string
// From is the sender: an E.164 number or an alphanumeric sender ID.
From string
Body string
// Encoding is how the text travels; adapters that must be told (Vonage)
// use it.
Encoding Encoding
// StatusURL is where the provider should send this text's receipts,
// for APIs that take it per message.
StatusURL string
}
Message is one text to one number, already rendered.
type OptOutReader ¶
OptOutReader reads the provider's opt-out list ("Opt-out sync · read only").
type OptOutSyncer ¶
type OptOutSyncer interface {
OptOutReader
AddOptOuts(ctx context.Context, phones []string) error
RemoveOptOut(ctx context.Context, phone string) error
}
OptOutSyncer also adds numbers to it (two-way sync).
type Outside ¶
type Outside struct {
// Char is the character itself ("’").
Char string `json:"char"`
// Kind names it for the app ("curly_apostrophe", "emoji", "other").
Kind string `` /* 152-byte string literal not displayed */
// Replacement is the GSM-7 lookalike the fix puts in its place; empty
// when there's none (an emoji). A zero-width space is removed.
Replacement string `json:"replacement"`
// Removable is true when the fix removes it (zero-width spaces).
Removable bool `json:"removable"`
// Count is how many times it appears.
Count int `json:"count"`
// First is the character offset (in code points) of its first use.
First int `json:"first"`
}
Outside is a character that forces UCS-2.
type PricingReader ¶
type PricingReader interface {
Prices(ctx context.Context, countries []string) (map[string]float64, error)
}
PricingReader reads the price of one outbound segment per country.
type Provider ¶
type Provider interface {
Adapter() string
// Check validates the credentials and reads the account.
Check(ctx context.Context) (Account, error)
// Send hands one text to the provider.
Send(ctx context.Context, m Message) (SendResult, error)
// VerifyWebhook checks a webhook as it arrives: its signature, and the
// request it was signed for. It returns ErrBadSignature when it fails.
VerifyWebhook(ctx context.Context, r *http.Request, body []byte) error
// ParseWebhook reads a verified webhook into events. It runs later, in
// a job, from the stored request.
ParseWebhook(ctx context.Context, contentType string, body []byte) ([]Event, error)
}
Provider is an SMS account ReputeCast sends through.
type Reason ¶
type Reason string
Reason is what a failure means for ReputeCast: whether to retry, to suppress the number, or to count it toward the filtered threshold.
const ( // ReasonUnreachable: the phone is off or out of coverage. Temporary, // not suppressed. ReasonUnreachable Reason = "unreachable" // ReasonFiltered: carriers blocked the text (spam filtering). ReasonFiltered Reason = "filtered" // ReasonNotInService: the number doesn't exist. Suppressed. ReasonNotInService Reason = "not_in_service" // ReasonLandline: the number can't receive texts. Suppressed. ReasonLandline Reason = "landline" // ReasonInvalid: not a valid number. Suppressed. ReasonInvalid Reason = "invalid" // ReasonOptedOut: the provider's own opt-out list blocked it. ReasonOptedOut Reason = "opted_out" // ReasonRejected: the provider refused it (sender not registered, // content, a limit). ReasonRejected Reason = "rejected" ReasonOther Reason = "other" )
Reasons.
func (Reason) Suppresses ¶
Suppresses reports whether a failure for this reason puts the number on the SMS suppression list.
type Registration ¶
type Registration struct {
// Sender is the number or ID it belongs to.
Sender string
Kind string `json:"kind" enum:"toll_free,brand,campaign,sender_id"`
Country string
Name string
Status string `json:"status" enum:"not_registered,pending,verified,approved,rejected,allowed,not_supported"`
Reason string
Since *time.Time
// Details are what was submitted (use case, volume, opt-in, terms).
Details map[string]string
}
Registration is a sender's registration as the provider reports it.
type RegistrationReader ¶
type RegistrationReader interface {
Registrations(ctx context.Context, senders []Sender) ([]Registration, error)
}
RegistrationReader reads registration statuses (hourly, from the provider health job).
type SendError ¶
type SendError struct {
// Code is the provider's own code ("21211", "29").
Code string
Message string
Reason Reason
// Temporary errors are retried with back-off.
Temporary bool
// Throttled means the provider asked to slow down.
Throttled bool
}
SendError is a text the provider refused or couldn't take.
type SendResult ¶
type SendResult struct {
ProviderMessageID string
// Segments as the provider counted them (0 when it doesn't say).
Segments int
// Price per text when the provider reports it right away.
Price *float64
}
SendResult is the provider's answer to one text.
type Sender ¶
type Sender struct {
Kind string `json:"kind" enum:"toll_free,10dlc,local,mobile,sender_id"`
Value string `json:"value"`
// Countries the provider says it can text.
Countries []string `json:"countries"`
// Throughput in texts per second, as the provider reports it.
Throughput float64 `json:"throughput"`
ProviderRef string `json:"providerRef"`
}
Sender is a number or sender ID found in the account.
type SenderLister ¶
SenderLister lists the numbers already in the account (the wizard's "Import your senders").
type WebhookHandshaker ¶
type WebhookHandshaker interface {
Handshake(ctx context.Context, r *http.Request, body []byte) (handled bool, err error)
}
WebhookHandshaker answers a provider's subscription handshake (SNS).
type WebhookRegistrar ¶
type WebhookRegistrar interface {
RegisterWebhooks(ctx context.Context, hooks Webhooks, senders []Sender) (WebhookSetup, error)
}
WebhookRegistrar sets the receipt and inbound webhooks through the provider's API, on the account and on the given senders.
type WebhookSetup ¶
type WebhookSetup struct {
// Secret signs the provider's webhooks from now on, when the provider
// created one for ReputeCast (Twilio's shared keys); sealed by the caller.
Secret string
// Settings are non-secret values the adapter needs from now on (the
// SNS topic and configuration set it created); the caller keeps them
// with the provider's settings.
Settings map[string]string
}
WebhookSetup is what registering webhooks produced.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package awseum is the AWS End User Messaging SMS adapter (the pinpoint-sms-voice-v2 API, through aws-sdk-go-v2): texts from the workspace's own AWS account with a CloudFormation role or IAM keys, delivery events and two-way texts through an SNS topic ReputeCast subscribes to (SNS signatures checked against Amazon's certificates), phone numbers and sender IDs, registrations, and two-way sync with an opt-out list.
|
Package awseum is the AWS End User Messaging SMS adapter (the pinpoint-sms-voice-v2 API, through aws-sdk-go-v2): texts from the workspace's own AWS account with a CloudFormation role or IAM keys, delivery events and two-way texts through an SNS topic ReputeCast subscribes to (SNS signatures checked against Amazon's certificates), phone numbers and sender IDs, registrations, and two-way sync with an opt-out list. |
|
awseumtest
Package awseumtest is an in-memory AWS End User Messaging SMS (the pinpoint-sms-voice-v2 JSON protocol) and SNS (its query protocol), with the operations the adapter calls, failure modes, a signing certificate served where SNS serves its own, and helpers that publish SMS events and two-way texts as signed SNS notifications.
|
Package awseumtest is an in-memory AWS End User Messaging SMS (the pinpoint-sms-voice-v2 JSON protocol) and SNS (its query protocol), with the operations the adapter calls, failure modes, a signing certificate served where SNS serves its own, and helpers that publish SMS events and two-way texts as signed SNS notifications. |
|
Package contracttest is the shared contract suite every SMS adapter passes (brief §3.1): its manifest and the texts people read in every app language, sending, delivery receipts and inbound messages, signature checks, and the optional capabilities its manifest declares: the account's numbers, webhook registration, opt-out sync, registration status and pricing.
|
Package contracttest is the shared contract suite every SMS adapter passes (brief §3.1): its manifest and the texts people read in every app language, sending, delivery receipts and inbound messages, signature checks, and the optional capabilities its manifest declares: the account's numbers, webhook registration, opt-out sync, registration status and pricing. |
|
Package plivo is the Plivo SMS adapter: the Message API with the account's auth ID and token, status callbacks per text and inbound texts through a Plivo application on the account's numbers, both signed with Plivo's V3 signature (HMAC-SHA256 with the auth token and a nonce), 10DLC and toll-free verification statuses, and outbound prices.
|
Package plivo is the Plivo SMS adapter: the Message API with the account's auth ID and token, status callbacks per text and inbound texts through a Plivo application on the account's numbers, both signed with Plivo's V3 signature (HMAC-SHA256 with the auth token and a nonce), 10DLC and toll-free verification statuses, and outbound prices. |
|
plivotest
Package plivotest is an in-memory Plivo: the account, Message, Number, Application, 10DLC, toll-free verification and Pricing resources the adapter calls, answered from recorded payload shapes, with failure modes and helpers that sign callbacks and inbound texts with Plivo's V3 signature.
|
Package plivotest is an in-memory Plivo: the account, Message, Number, Application, 10DLC, toll-free verification and Pricing resources the adapter calls, answered from recorded payload shapes, with failure modes and helpers that sign callbacks and inbound texts with Plivo's V3 signature. |
|
Package smsfake holds what the SMS providers' fakes share: an in-process transport, so the demo's sample providers answer without any network, and a recorder of the requests a fake received.
|
Package smsfake holds what the SMS providers' fakes share: an in-process transport, so the demo's sample providers answer without any network, and a recorder of the requests a fake received. |
|
Package telnyx is the Telnyx SMS adapter (API v2): texts with an API key, webhooks on a messaging profile ReputeCast sets up, signed by Telnyx with Ed25519 (checked with the account's public key, and a timestamp so old requests can't be replayed), the account's numbers, its opt-out list (read only), and 10DLC and toll-free verification statuses.
|
Package telnyx is the Telnyx SMS adapter (API v2): texts with an API key, webhooks on a messaging profile ReputeCast sets up, signed by Telnyx with Ed25519 (checked with the account's public key, and a timestamp so old requests can't be replayed), the account's numbers, its opt-out list (read only), and 10DLC and toll-free verification statuses. |
|
telnyxtest
Package telnyxtest is an in-memory Telnyx (API v2): balance, messages, phone numbers, messaging profiles, opt-outs, 10DLC and toll-free verification, answered from recorded payload shapes, with failure modes and helpers that sign webhooks with an Ed25519 key as Telnyx does.
|
Package telnyxtest is an in-memory Telnyx (API v2): balance, messages, phone numbers, messaging profiles, opt-outs, 10DLC and toll-free verification, answered from recorded payload shapes, with failure modes and helpers that sign webhooks with an Ed25519 key as Telnyx does. |
|
Package twilio is the Twilio SMS adapter: Programmable Messaging with an API key (never the auth token, so ReputeCast's access can be revoked on its own), status callbacks and inbound webhooks signed with a webhook shared key ReputeCast creates through Twilio's API, the account's numbers, toll-free verification and A2P 10DLC statuses, and outbound prices.
|
Package twilio is the Twilio SMS adapter: Programmable Messaging with an API key (never the auth token, so ReputeCast's access can be revoked on its own), status callbacks and inbound webhooks signed with a webhook shared key ReputeCast creates through Twilio's API, the account's numbers, toll-free verification and A2P 10DLC statuses, and outbound prices. |
|
twiliotest
Package twiliotest is an in-memory Twilio: the parts of Programmable Messaging, Pricing, Messaging compliance and Webhooks the adapter calls, answered from recorded payload shapes, with failure modes and helpers that sign status callbacks and inbound texts as Twilio would.
|
Package twiliotest is an in-memory Twilio: the parts of Programmable Messaging, Pricing, Messaging compliance and Webhooks the adapter calls, answered from recorded payload shapes, with failure modes and helpers that sign status callbacks and inbound texts as Twilio would. |
|
Package vonage is the Vonage SMS adapter (the SMS API): texts with an API key and secret, delivery receipts and inbound texts on the account's callback addresses, set through the account API and signed with the account's signature secret (HMAC-SHA256), the account's numbers and outbound prices.
|
Package vonage is the Vonage SMS adapter (the SMS API): texts with an API key and secret, delivery receipts and inbound texts on the account's callback addresses, set through the account API and signed with the account's signature secret (HMAC-SHA256), the account's numbers and outbound prices. |
|
vonagetest
Package vonagetest is an in-memory Vonage SMS API: sending, the balance, numbers, account settings and pricing, answered from recorded payload shapes, with failure modes and helpers that sign delivery receipts and inbound texts as Vonage's signed webhooks do.
|
Package vonagetest is an in-memory Vonage SMS API: sending, the balance, numbers, account settings and pricing, answered from recorded payload shapes, with failure modes and helpers that sign delivery receipts and inbound texts as Vonage's signed webhooks do. |