replace http basic auth for web interfaces with session cookie & csrf-based auth

the http basic auth we had was very simple to reason about, and to implement.
but it has a major downside:

there is no way to logout, browsers keep sending credentials. ideally, browsers
themselves would show a button to stop sending credentials.

a related downside: the http auth mechanism doesn't indicate for which server
paths the credentials are.

another downside: the original password is sent to the server with each
request. though sending original passwords to web servers seems to be
considered normal.

our new approach uses session cookies, along with csrf values when we can. the
sessions are server-side managed, automatically extended on each use. this
makes it easy to invalidate sessions and keeps the frontend simpler (than with
long- vs short-term sessions and refreshing). the cookies are httponly,
samesite=strict, scoped to the path of the web interface. cookies are set
"secure" when set over https. the cookie is set by a successful call to Login.
a call to Logout invalidates a session. changing a password invalidates all
sessions for a user, but keeps the session with which the password was changed
alive. the csrf value is also random, and associated with the session cookie.
the csrf must be sent as header for api calls, or as parameter for direct form
posts (where we cannot set a custom header). rest-like calls made directly by
the browser, e.g. for images, don't have a csrf protection. the csrf value is
returned by the Login api call and stored in localstorage.

api calls without credentials return code "user:noAuth", and with bad
credentials return "user:badAuth". the api client recognizes this and triggers
a login. after a login, all auth-failed api calls are automatically retried.
only for "user:badAuth" is an error message displayed in the login form (e.g.
session expired).

in an ideal world, browsers would take care of most session management. a
server would indicate authentication is needed (like http basic auth), and the
browsers uses trusted ui to request credentials for the server & path. the
browser could use safer mechanism than sending original passwords to the
server, such as scram, along with a standard way to create sessions.  for now,
web developers have to do authentication themselves: from showing the login
prompt, ensuring the right session/csrf cookies/localstorage/headers/etc are
sent with each request.

webauthn is a newer way to do authentication, perhaps we'll implement it in the
future. though hardware tokens aren't an attractive option for many users, and
it may be overkill as long as we still do old-fashioned authentication in smtp
& imap where passwords can be sent to the server.

for issue #58
This commit is contained in:
Mechiel Lukkien
2024-01-04 13:10:48 +01:00
parent c930a400be
commit 0f8bf2f220
50 changed files with 3560 additions and 832 deletions

View File

@ -10,6 +10,7 @@ import (
"context"
"crypto"
"crypto/ed25519"
cryptorand "crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/tls"
@ -32,7 +33,6 @@ import (
_ "embed"
"golang.org/x/crypto/bcrypt"
"golang.org/x/exp/maps"
"golang.org/x/exp/slog"
@ -63,6 +63,7 @@ import (
"github.com/mjl-/mox/store"
"github.com/mjl-/mox/tlsrpt"
"github.com/mjl-/mox/tlsrptdb"
"github.com/mjl-/mox/webauth"
)
var pkglog = mlog.New("webadmin", nil)
@ -85,8 +86,6 @@ var webadminFile = &mox.WebappFile{
var adminDoc = mustParseAPI("admin", adminapiJSON)
var adminSherpaHandler http.Handler
func mustParseAPI(api string, buf []byte) (doc sherpadoc.Section) {
err := json.Unmarshal(buf, &doc)
if err != nil {
@ -95,139 +94,98 @@ func mustParseAPI(api string, buf []byte) (doc sherpadoc.Section) {
return doc
}
var sherpaHandlerOpts *sherpa.HandlerOpts
func makeSherpaHandler(cookiePath string, isForwarded bool) (http.Handler, error) {
return sherpa.NewHandler("/api/", moxvar.Version, Admin{cookiePath, isForwarded}, &adminDoc, sherpaHandlerOpts)
}
func init() {
collector, err := sherpaprom.NewCollector("moxadmin", nil)
if err != nil {
pkglog.Fatalx("creating sherpa prometheus collector", err)
}
adminSherpaHandler, err = sherpa.NewHandler("/api/", moxvar.Version, Admin{}, &adminDoc, &sherpa.HandlerOpts{Collector: collector, AdjustFunctionNames: "none"})
sherpaHandlerOpts = &sherpa.HandlerOpts{Collector: collector, AdjustFunctionNames: "none", NoCORS: true}
// Just to validate.
_, err = makeSherpaHandler("", false)
if err != nil {
pkglog.Fatalx("sherpa handler", err)
}
}
// Handler returns a handler for the webadmin endpoints, customized for the
// cookiePath.
func Handler(cookiePath string, isForwarded bool) func(w http.ResponseWriter, r *http.Request) {
sh, err := makeSherpaHandler(cookiePath, isForwarded)
return func(w http.ResponseWriter, r *http.Request) {
if err != nil {
http.Error(w, "500 - internal server error - cannot handle requests", http.StatusInternalServerError)
return
}
handle(sh, isForwarded, w, r)
}
}
// Admin exports web API functions for the admin web interface. All its methods are
// exported under api/. Function calls require valid HTTP Authentication
// credentials of a user.
type Admin struct{}
// We keep a cache for authentication so we don't bcrypt for each incoming HTTP request with HTTP basic auth.
// We keep track of the last successful password hash and Authorization header.
// The cache is cleared periodically, see below.
var authCache struct {
sync.Mutex
lastSuccessHash, lastSuccessAuth string
type Admin struct {
cookiePath string // From listener, for setting authentication cookies.
isForwarded bool // From listener, whether we look at X-Forwarded-* headers.
}
// started when we start serving. not at package init time, because we don't want
// to make goroutines that early.
func ManageAuthCache() {
for {
authCache.Lock()
authCache.lastSuccessHash = ""
authCache.lastSuccessAuth = ""
authCache.Unlock()
time.Sleep(15 * time.Minute)
}
type ctxKey string
var requestInfoCtxKey ctxKey = "requestInfo"
type requestInfo struct {
SessionToken store.SessionToken
Response http.ResponseWriter
Request *http.Request // For Proto and TLS connection state during message submit.
}
// check whether authentication from the config (passwordfile with bcrypt hash)
// matches the authorization header "authHdr". we don't care about any username.
// on (auth) failure, a http response is sent and false returned.
func checkAdminAuth(ctx context.Context, passwordfile string, w http.ResponseWriter, r *http.Request) bool {
log := pkglog.WithContext(ctx)
respondAuthFail := func() bool {
// note: browsers don't display the realm to prevent users getting confused by malicious realm messages.
w.Header().Set("WWW-Authenticate", `Basic realm="mox admin - login with empty username and admin password"`)
http.Error(w, "http 401 - unauthorized - mox admin - login with empty username and admin password", http.StatusUnauthorized)
return false
}
authResult := "error"
start := time.Now()
var addr *net.TCPAddr
defer func() {
metrics.AuthenticationInc("webadmin", "httpbasic", authResult)
if authResult == "ok" && addr != nil {
mox.LimiterFailedAuth.Reset(addr.IP, start)
}
}()
var err error
var remoteIP net.IP
addr, err = net.ResolveTCPAddr("tcp", r.RemoteAddr)
if err != nil {
log.Errorx("parsing remote address", err, slog.Any("addr", r.RemoteAddr))
} else if addr != nil {
remoteIP = addr.IP
}
if remoteIP != nil && !mox.LimiterFailedAuth.Add(remoteIP, start, 1) {
metrics.AuthenticationRatelimitedInc("webadmin")
http.Error(w, "429 - too many auth attempts", http.StatusTooManyRequests)
return false
}
authHdr := r.Header.Get("Authorization")
if !strings.HasPrefix(authHdr, "Basic ") || passwordfile == "" {
return respondAuthFail()
}
buf, err := os.ReadFile(passwordfile)
if err != nil {
log.Errorx("reading admin password file", err, slog.String("path", passwordfile))
return respondAuthFail()
}
passwordhash := strings.TrimSpace(string(buf))
authCache.Lock()
defer authCache.Unlock()
if passwordhash != "" && passwordhash == authCache.lastSuccessHash && authHdr != "" && authCache.lastSuccessAuth == authHdr {
authResult = "ok"
return true
}
auth, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(authHdr, "Basic "))
if err != nil {
return respondAuthFail()
}
t := strings.SplitN(string(auth), ":", 2)
if len(t) != 2 || len(t[1]) < 8 {
log.Info("failed authentication attempt", slog.String("username", "admin"), slog.Any("remote", remoteIP))
return respondAuthFail()
}
if err := bcrypt.CompareHashAndPassword([]byte(passwordhash), []byte(t[1])); err != nil {
authResult = "badcreds"
log.Info("failed authentication attempt", slog.String("username", "admin"), slog.Any("remote", remoteIP))
return respondAuthFail()
}
authCache.lastSuccessHash = passwordhash
authCache.lastSuccessAuth = authHdr
authResult = "ok"
return true
}
func Handle(w http.ResponseWriter, r *http.Request) {
func handle(apiHandler http.Handler, isForwarded bool, w http.ResponseWriter, r *http.Request) {
ctx := context.WithValue(r.Context(), mlog.CidKey, mox.Cid())
if !checkAdminAuth(ctx, mox.ConfigDirPath(mox.Conf.Static.AdminPasswordFile), w, r) {
// Response already sent.
return
}
if lw, ok := w.(interface{ AddAttr(a slog.Attr) }); ok {
lw.AddAttr(slog.Bool("authadmin", true))
}
log := pkglog.WithContext(ctx).With(slog.String("adminauth", ""))
// HTML/JS can be retrieved without authentication.
if r.URL.Path == "/" {
switch r.Method {
case "GET", "HEAD":
webadminFile.Serve(ctx, log, w, r)
default:
http.Error(w, "405 - method not allowed - use get", http.StatusMethodNotAllowed)
return
case "GET", "HEAD":
}
webadminFile.Serve(ctx, pkglog.WithContext(ctx), w, r)
return
}
adminSherpaHandler.ServeHTTP(w, r.WithContext(ctx))
isAPI := strings.HasPrefix(r.URL.Path, "/api/")
// Only allow POST for calls, they will not work cross-domain without CORS.
if isAPI && r.URL.Path != "/api/" && r.Method != "POST" {
http.Error(w, "405 - method not allowed - use post", http.StatusMethodNotAllowed)
return
}
// All other URLs, except the login endpoint require some authentication.
var sessionToken store.SessionToken
if r.URL.Path != "/api/LoginPrep" && r.URL.Path != "/api/Login" {
var ok bool
_, sessionToken, _, ok = webauth.Check(ctx, log, webauth.Admin, "webadmin", isForwarded, w, r, isAPI, isAPI, false)
if !ok {
// Response has been written already.
return
}
}
if isAPI {
reqInfo := requestInfo{sessionToken, w, r}
ctx = context.WithValue(ctx, requestInfoCtxKey, reqInfo)
apiHandler.ServeHTTP(w, r.WithContext(ctx))
return
}
http.NotFound(w, r)
}
func xcheckf(ctx context.Context, err error, format string, args ...any) {
@ -254,6 +212,45 @@ func xcheckuserf(ctx context.Context, err error, format string, args ...any) {
panic(&sherpa.Error{Code: "user:error", Message: errmsg})
}
// LoginPrep returns a login token, and also sets it as cookie. Both must be
// present in the call to Login.
func (w Admin) LoginPrep(ctx context.Context) string {
log := pkglog.WithContext(ctx)
reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
var data [8]byte
_, err := cryptorand.Read(data[:])
xcheckf(ctx, err, "generate token")
loginToken := base64.RawURLEncoding.EncodeToString(data[:])
webauth.LoginPrep(ctx, log, "webadmin", w.cookiePath, w.isForwarded, reqInfo.Response, reqInfo.Request, loginToken)
return loginToken
}
// Login returns a session token for the credentials, or fails with error code
// "user:badLogin". Call LoginPrep to get a loginToken.
func (w Admin) Login(ctx context.Context, loginToken, password string) store.CSRFToken {
log := pkglog.WithContext(ctx)
reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
csrfToken, err := webauth.Login(ctx, log, webauth.Admin, "webadmin", w.cookiePath, w.isForwarded, reqInfo.Response, reqInfo.Request, loginToken, "", password)
if _, ok := err.(*sherpa.Error); ok {
panic(err)
}
xcheckf(ctx, err, "login")
return csrfToken
}
// Logout invalidates the session token.
func (w Admin) Logout(ctx context.Context) {
log := pkglog.WithContext(ctx)
reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
err := webauth.Logout(ctx, log, webauth.Admin, "webadmin", w.cookiePath, w.isForwarded, reqInfo.Response, reqInfo.Request, "", reqInfo.SessionToken)
xcheckf(ctx, err, "logout")
}
type Result struct {
Errors []string
Warnings []string

View File

@ -32,7 +32,7 @@ fieldset { border: 0; }
</style>
</head>
<body>
<div id="page"><div style="padding: 1em">Loading...</div></div>
<div id="page"><div style="padding: 1em; text-align: center">Loading...</div></div>
<script>/* placeholder */</script>
</body>
</html>

View File

@ -215,6 +215,8 @@ const [dom, style, attr, prop] = (function () {
name: (s) => _attr('name', s),
min: (s) => _attr('min', s),
max: (s) => _attr('max', s),
action: (s) => _attr('action', s),
method: (s) => _attr('method', s),
};
const style = (x) => { return { _styles: x }; };
const prop = (x) => { return { _props: x }; };
@ -325,7 +327,7 @@ var api;
SPFResult["SPFPermerror"] = "permerror";
})(SPFResult = api.SPFResult || (api.SPFResult = {}));
api.structTypes = { "AuthResults": true, "AutoconfCheckResult": true, "AutodiscoverCheckResult": true, "AutodiscoverSRV": true, "CheckResult": true, "ClientConfigs": true, "ClientConfigsEntry": true, "DANECheckResult": true, "DKIMAuthResult": true, "DKIMCheckResult": true, "DKIMRecord": true, "DMARCCheckResult": true, "DMARCRecord": true, "DMARCSummary": true, "DNSSECResult": true, "DateRange": true, "Directive": true, "Domain": true, "DomainFeedback": true, "Evaluation": true, "EvaluationStat": true, "Extension": true, "FailureDetails": true, "IPDomain": true, "IPRevCheckResult": true, "Identifiers": true, "MTASTSCheckResult": true, "MTASTSRecord": true, "MX": true, "MXCheckResult": true, "Modifier": true, "Msg": true, "Pair": true, "Policy": true, "PolicyEvaluated": true, "PolicyOverrideReason": true, "PolicyPublished": true, "PolicyRecord": true, "Record": true, "Report": true, "ReportMetadata": true, "ReportRecord": true, "Result": true, "ResultPolicy": true, "Reverse": true, "Row": true, "SMTPAuth": true, "SPFAuthResult": true, "SPFCheckResult": true, "SPFRecord": true, "SRV": true, "SRVConfCheckResult": true, "STSMX": true, "Summary": true, "SuppressAddress": true, "TLSCheckResult": true, "TLSRPTCheckResult": true, "TLSRPTDateRange": true, "TLSRPTRecord": true, "TLSRPTSummary": true, "TLSRPTSuppressAddress": true, "TLSReportRecord": true, "TLSResult": true, "Transport": true, "TransportSMTP": true, "TransportSocks": true, "URI": true, "WebForward": true, "WebHandler": true, "WebRedirect": true, "WebStatic": true, "WebserverConfig": true };
api.stringsTypes = { "Align": true, "Alignment": true, "DKIMResult": true, "DMARCPolicy": true, "DMARCResult": true, "Disposition": true, "IP": true, "Localpart": true, "Mode": true, "PolicyOverride": true, "PolicyType": true, "RUA": true, "ResultType": true, "SPFDomainScope": true, "SPFResult": true };
api.stringsTypes = { "Align": true, "Alignment": true, "CSRFToken": true, "DKIMResult": true, "DMARCPolicy": true, "DMARCResult": true, "Disposition": true, "IP": true, "Localpart": true, "Mode": true, "PolicyOverride": true, "PolicyType": true, "RUA": true, "ResultType": true, "SPFDomainScope": true, "SPFResult": true };
api.intsTypes = {};
api.types = {
"CheckResult": { "Name": "CheckResult", "Docs": "", "Fields": [{ "Name": "Domain", "Docs": "", "Typewords": ["string"] }, { "Name": "DNSSEC", "Docs": "", "Typewords": ["DNSSECResult"] }, { "Name": "IPRev", "Docs": "", "Typewords": ["IPRevCheckResult"] }, { "Name": "MX", "Docs": "", "Typewords": ["MXCheckResult"] }, { "Name": "TLS", "Docs": "", "Typewords": ["TLSCheckResult"] }, { "Name": "DANE", "Docs": "", "Typewords": ["DANECheckResult"] }, { "Name": "SPF", "Docs": "", "Typewords": ["SPFCheckResult"] }, { "Name": "DKIM", "Docs": "", "Typewords": ["DKIMCheckResult"] }, { "Name": "DMARC", "Docs": "", "Typewords": ["DMARCCheckResult"] }, { "Name": "HostTLSRPT", "Docs": "", "Typewords": ["TLSRPTCheckResult"] }, { "Name": "DomainTLSRPT", "Docs": "", "Typewords": ["TLSRPTCheckResult"] }, { "Name": "MTASTS", "Docs": "", "Typewords": ["MTASTSCheckResult"] }, { "Name": "SRVConf", "Docs": "", "Typewords": ["SRVConfCheckResult"] }, { "Name": "Autoconf", "Docs": "", "Typewords": ["AutoconfCheckResult"] }, { "Name": "Autodiscover", "Docs": "", "Typewords": ["AutodiscoverCheckResult"] }] },
@ -400,6 +402,7 @@ var api;
"SuppressAddress": { "Name": "SuppressAddress", "Docs": "", "Fields": [{ "Name": "ID", "Docs": "", "Typewords": ["int64"] }, { "Name": "Inserted", "Docs": "", "Typewords": ["timestamp"] }, { "Name": "ReportingAddress", "Docs": "", "Typewords": ["string"] }, { "Name": "Until", "Docs": "", "Typewords": ["timestamp"] }, { "Name": "Comment", "Docs": "", "Typewords": ["string"] }] },
"TLSResult": { "Name": "TLSResult", "Docs": "", "Fields": [{ "Name": "ID", "Docs": "", "Typewords": ["int64"] }, { "Name": "PolicyDomain", "Docs": "", "Typewords": ["string"] }, { "Name": "DayUTC", "Docs": "", "Typewords": ["string"] }, { "Name": "RecipientDomain", "Docs": "", "Typewords": ["string"] }, { "Name": "Created", "Docs": "", "Typewords": ["timestamp"] }, { "Name": "Updated", "Docs": "", "Typewords": ["timestamp"] }, { "Name": "IsHost", "Docs": "", "Typewords": ["bool"] }, { "Name": "SendReport", "Docs": "", "Typewords": ["bool"] }, { "Name": "SentToRecipientDomain", "Docs": "", "Typewords": ["bool"] }, { "Name": "RecipientDomainReportingAddresses", "Docs": "", "Typewords": ["[]", "string"] }, { "Name": "SentToPolicyDomain", "Docs": "", "Typewords": ["bool"] }, { "Name": "Results", "Docs": "", "Typewords": ["[]", "Result"] }] },
"TLSRPTSuppressAddress": { "Name": "TLSRPTSuppressAddress", "Docs": "", "Fields": [{ "Name": "ID", "Docs": "", "Typewords": ["int64"] }, { "Name": "Inserted", "Docs": "", "Typewords": ["timestamp"] }, { "Name": "ReportingAddress", "Docs": "", "Typewords": ["string"] }, { "Name": "Until", "Docs": "", "Typewords": ["timestamp"] }, { "Name": "Comment", "Docs": "", "Typewords": ["string"] }] },
"CSRFToken": { "Name": "CSRFToken", "Docs": "", "Values": null },
"DMARCPolicy": { "Name": "DMARCPolicy", "Docs": "", "Values": [{ "Name": "PolicyEmpty", "Value": "", "Docs": "" }, { "Name": "PolicyNone", "Value": "none", "Docs": "" }, { "Name": "PolicyQuarantine", "Value": "quarantine", "Docs": "" }, { "Name": "PolicyReject", "Value": "reject", "Docs": "" }] },
"Align": { "Name": "Align", "Docs": "", "Values": [{ "Name": "AlignStrict", "Value": "s", "Docs": "" }, { "Name": "AlignRelaxed", "Value": "r", "Docs": "" }] },
"RUA": { "Name": "RUA", "Docs": "", "Values": null },
@ -489,6 +492,7 @@ var api;
SuppressAddress: (v) => api.parse("SuppressAddress", v),
TLSResult: (v) => api.parse("TLSResult", v),
TLSRPTSuppressAddress: (v) => api.parse("TLSRPTSuppressAddress", v),
CSRFToken: (v) => api.parse("CSRFToken", v),
DMARCPolicy: (v) => api.parse("DMARCPolicy", v),
Align: (v) => api.parse("Align", v),
RUA: (v) => api.parse("RUA", v),
@ -511,16 +515,50 @@ var api;
let defaultOptions = { slicesNullable: true, mapsNullable: true, nullableOptional: true };
class Client {
baseURL;
authState;
options;
constructor(baseURL = api.defaultBaseURL, options) {
this.baseURL = baseURL;
this.options = options;
if (!options) {
this.options = defaultOptions;
}
constructor() {
this.authState = {};
this.options = { ...defaultOptions };
this.baseURL = this.options.baseURL || api.defaultBaseURL;
}
withAuthToken(token) {
const c = new Client();
c.authState.token = token;
c.options = this.options;
return c;
}
withOptions(options) {
return new Client(this.baseURL, { ...this.options, ...options });
const c = new Client();
c.authState = this.authState;
c.options = { ...this.options, ...options };
return c;
}
// LoginPrep returns a login token, and also sets it as cookie. Both must be
// present in the call to Login.
async LoginPrep() {
const fn = "LoginPrep";
const paramTypes = [];
const returnTypes = [["string"]];
const params = [];
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// Login returns a session token for the credentials, or fails with error code
// "user:badLogin". Call LoginPrep to get a loginToken.
async Login(loginToken, password) {
const fn = "Login";
const paramTypes = [["string"], ["string"]];
const returnTypes = [["CSRFToken"]];
const params = [loginToken, password];
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// Logout invalidates the session token.
async Logout() {
const fn = "Logout";
const paramTypes = [];
const returnTypes = [];
const params = [];
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// CheckDomain checks the configuration for the domain, such as MX, SMTP STARTTLS,
// SPF, DKIM, DMARC, TLSRPT, MTASTS, autoconfig, autodiscover.
@ -529,7 +567,7 @@ var api;
const paramTypes = [["string"]];
const returnTypes = [["CheckResult"]];
const params = [domainName];
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params);
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// Domains returns all configured domain names, in UTF-8 for IDNA domains.
async Domains() {
@ -537,7 +575,7 @@ var api;
const paramTypes = [];
const returnTypes = [["[]", "Domain"]];
const params = [];
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params);
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// Domain returns the dns domain for a (potentially unicode as IDNA) domain name.
async Domain(domain) {
@ -545,7 +583,7 @@ var api;
const paramTypes = [["string"]];
const returnTypes = [["Domain"]];
const params = [domain];
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params);
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// ParseDomain parses a domain, possibly an IDNA domain.
async ParseDomain(domain) {
@ -553,7 +591,7 @@ var api;
const paramTypes = [["string"]];
const returnTypes = [["Domain"]];
const params = [domain];
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params);
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// DomainLocalparts returns the encoded localparts and accounts configured in domain.
async DomainLocalparts(domain) {
@ -561,7 +599,7 @@ var api;
const paramTypes = [["string"]];
const returnTypes = [["{}", "string"]];
const params = [domain];
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params);
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// Accounts returns the names of all configured accounts.
async Accounts() {
@ -569,7 +607,7 @@ var api;
const paramTypes = [];
const returnTypes = [["[]", "string"]];
const params = [];
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params);
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// Account returns the parsed configuration of an account.
async Account(account) {
@ -577,7 +615,7 @@ var api;
const paramTypes = [["string"]];
const returnTypes = [["{}", "any"]];
const params = [account];
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params);
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// ConfigFiles returns the paths and contents of the static and dynamic configuration files.
async ConfigFiles() {
@ -585,7 +623,7 @@ var api;
const paramTypes = [];
const returnTypes = [["string"], ["string"], ["string"], ["string"]];
const params = [];
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params);
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// MTASTSPolicies returns all mtasts policies from the cache.
async MTASTSPolicies() {
@ -593,7 +631,7 @@ var api;
const paramTypes = [];
const returnTypes = [["[]", "PolicyRecord"]];
const params = [];
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params);
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// TLSReports returns TLS reports overlapping with period start/end, for the given
// policy domain (or all domains if empty). The reports are sorted first by period
@ -603,7 +641,7 @@ var api;
const paramTypes = [["timestamp"], ["timestamp"], ["string"]];
const returnTypes = [["[]", "TLSReportRecord"]];
const params = [start, end, policyDomain];
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params);
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// TLSReportID returns a single TLS report.
async TLSReportID(domain, reportID) {
@ -611,7 +649,7 @@ var api;
const paramTypes = [["string"], ["int64"]];
const returnTypes = [["TLSReportRecord"]];
const params = [domain, reportID];
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params);
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// TLSRPTSummaries returns a summary of received TLS reports overlapping with
// period start/end for one or all domains (when domain is empty).
@ -621,7 +659,7 @@ var api;
const paramTypes = [["timestamp"], ["timestamp"], ["string"]];
const returnTypes = [["[]", "TLSRPTSummary"]];
const params = [start, end, policyDomain];
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params);
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// DMARCReports returns DMARC reports overlapping with period start/end, for the
// given domain (or all domains if empty). The reports are sorted first by period
@ -631,7 +669,7 @@ var api;
const paramTypes = [["timestamp"], ["timestamp"], ["string"]];
const returnTypes = [["[]", "DomainFeedback"]];
const params = [start, end, domain];
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params);
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// DMARCReportID returns a single DMARC report.
async DMARCReportID(domain, reportID) {
@ -639,7 +677,7 @@ var api;
const paramTypes = [["string"], ["int64"]];
const returnTypes = [["DomainFeedback"]];
const params = [domain, reportID];
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params);
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// DMARCSummaries returns a summary of received DMARC reports overlapping with
// period start/end for one or all domains (when domain is empty).
@ -649,7 +687,7 @@ var api;
const paramTypes = [["timestamp"], ["timestamp"], ["string"]];
const returnTypes = [["[]", "DMARCSummary"]];
const params = [start, end, domain];
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params);
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// LookupIP does a reverse lookup of ip.
async LookupIP(ip) {
@ -657,7 +695,7 @@ var api;
const paramTypes = [["string"]];
const returnTypes = [["Reverse"]];
const params = [ip];
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params);
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// DNSBLStatus returns the IPs from which outgoing connections may be made and
// their current status in DNSBLs that are configured. The IPs are typically the
@ -671,7 +709,7 @@ var api;
const paramTypes = [];
const returnTypes = [["{}", "{}", "string"]];
const params = [];
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params);
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// DomainRecords returns lines describing DNS records that should exist for the
// configured domain.
@ -680,7 +718,7 @@ var api;
const paramTypes = [["string"]];
const returnTypes = [["[]", "string"]];
const params = [domain];
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params);
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// DomainAdd adds a new domain and reloads the configuration.
async DomainAdd(domain, accountName, localpart) {
@ -688,7 +726,7 @@ var api;
const paramTypes = [["string"], ["string"], ["string"]];
const returnTypes = [];
const params = [domain, accountName, localpart];
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params);
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// DomainRemove removes an existing domain and reloads the configuration.
async DomainRemove(domain) {
@ -696,7 +734,7 @@ var api;
const paramTypes = [["string"]];
const returnTypes = [];
const params = [domain];
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params);
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// AccountAdd adds existing a new account, with an initial email address, and
// reloads the configuration.
@ -705,7 +743,7 @@ var api;
const paramTypes = [["string"], ["string"]];
const returnTypes = [];
const params = [accountName, address];
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params);
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// AccountRemove removes an existing account and reloads the configuration.
async AccountRemove(accountName) {
@ -713,7 +751,7 @@ var api;
const paramTypes = [["string"]];
const returnTypes = [];
const params = [accountName];
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params);
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// AddressAdd adds a new address to the account, which must already exist.
async AddressAdd(address, accountName) {
@ -721,7 +759,7 @@ var api;
const paramTypes = [["string"], ["string"]];
const returnTypes = [];
const params = [address, accountName];
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params);
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// AddressRemove removes an existing address.
async AddressRemove(address) {
@ -729,7 +767,7 @@ var api;
const paramTypes = [["string"]];
const returnTypes = [];
const params = [address];
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params);
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// SetPassword saves a new password for an account, invalidating the previous password.
// Sessions are not interrupted, and will keep working. New login attempts must use the new password.
@ -739,7 +777,7 @@ var api;
const paramTypes = [["string"], ["string"]];
const returnTypes = [];
const params = [accountName, password];
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params);
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// SetAccountLimits set new limits on outgoing messages for an account.
async SetAccountLimits(accountName, maxOutgoingMessagesPerDay, maxFirstTimeRecipientsPerDay, maxMsgSize) {
@ -747,7 +785,7 @@ var api;
const paramTypes = [["string"], ["int32"], ["int32"], ["int64"]];
const returnTypes = [];
const params = [accountName, maxOutgoingMessagesPerDay, maxFirstTimeRecipientsPerDay, maxMsgSize];
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params);
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// ClientConfigsDomain returns configurations for email clients, IMAP and
// Submission (SMTP) for the domain.
@ -756,7 +794,7 @@ var api;
const paramTypes = [["string"]];
const returnTypes = [["ClientConfigs"]];
const params = [domain];
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params);
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// QueueList returns the messages currently in the outgoing queue.
async QueueList() {
@ -764,7 +802,7 @@ var api;
const paramTypes = [];
const returnTypes = [["[]", "Msg"]];
const params = [];
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params);
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// QueueSize returns the number of messages currently in the outgoing queue.
async QueueSize() {
@ -772,7 +810,7 @@ var api;
const paramTypes = [];
const returnTypes = [["int32"]];
const params = [];
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params);
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// QueueKick initiates delivery of a message from the queue and sets the transport
// to use for delivery.
@ -781,7 +819,7 @@ var api;
const paramTypes = [["int64"], ["string"]];
const returnTypes = [];
const params = [id, transport];
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params);
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// QueueDrop removes a message from the queue.
async QueueDrop(id) {
@ -789,7 +827,7 @@ var api;
const paramTypes = [["int64"]];
const returnTypes = [];
const params = [id];
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params);
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// QueueSaveRequireTLS updates the requiretls field for a message in the queue,
// to be used for the next delivery.
@ -798,7 +836,7 @@ var api;
const paramTypes = [["int64"], ["nullable", "bool"]];
const returnTypes = [];
const params = [id, requireTLS];
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params);
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// LogLevels returns the current log levels.
async LogLevels() {
@ -806,7 +844,7 @@ var api;
const paramTypes = [];
const returnTypes = [["{}", "string"]];
const params = [];
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params);
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// LogLevelSet sets a log level for a package.
async LogLevelSet(pkg, levelStr) {
@ -814,7 +852,7 @@ var api;
const paramTypes = [["string"], ["string"]];
const returnTypes = [];
const params = [pkg, levelStr];
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params);
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// LogLevelRemove removes a log level for a package, which cannot be the empty string.
async LogLevelRemove(pkg) {
@ -822,7 +860,7 @@ var api;
const paramTypes = [["string"]];
const returnTypes = [];
const params = [pkg];
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params);
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// CheckUpdatesEnabled returns whether checking for updates is enabled.
async CheckUpdatesEnabled() {
@ -830,7 +868,7 @@ var api;
const paramTypes = [];
const returnTypes = [["bool"]];
const params = [];
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params);
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// WebserverConfig returns the current webserver config
async WebserverConfig() {
@ -838,7 +876,7 @@ var api;
const paramTypes = [];
const returnTypes = [["WebserverConfig"]];
const params = [];
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params);
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// WebserverConfigSave saves a new webserver config. If oldConf is not equal to
// the current config, an error is returned.
@ -847,7 +885,7 @@ var api;
const paramTypes = [["WebserverConfig"], ["WebserverConfig"]];
const returnTypes = [["WebserverConfig"]];
const params = [oldConf, newConf];
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params);
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// Transports returns the configured transports, for sending email.
async Transports() {
@ -855,7 +893,7 @@ var api;
const paramTypes = [];
const returnTypes = [["{}", "Transport"]];
const params = [];
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params);
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// DMARCEvaluationStats returns a map of all domains with evaluations to a count of
// the evaluations and whether those evaluations will cause a report to be sent.
@ -864,7 +902,7 @@ var api;
const paramTypes = [];
const returnTypes = [["{}", "EvaluationStat"]];
const params = [];
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params);
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// DMARCEvaluationsDomain returns all evaluations for aggregate reports for the
// domain, sorted from oldest to most recent.
@ -873,7 +911,7 @@ var api;
const paramTypes = [["string"]];
const returnTypes = [["Domain"], ["[]", "Evaluation"]];
const params = [domain];
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params);
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// DMARCRemoveEvaluations removes evaluations for a domain.
async DMARCRemoveEvaluations(domain) {
@ -881,7 +919,7 @@ var api;
const paramTypes = [["string"]];
const returnTypes = [];
const params = [domain];
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params);
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// DMARCSuppressAdd adds a reporting address to the suppress list. Outgoing
// reports will be suppressed for a period.
@ -890,7 +928,7 @@ var api;
const paramTypes = [["string"], ["timestamp"], ["string"]];
const returnTypes = [];
const params = [reportingAddress, until, comment];
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params);
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// DMARCSuppressList returns all reporting addresses on the suppress list.
async DMARCSuppressList() {
@ -898,7 +936,7 @@ var api;
const paramTypes = [];
const returnTypes = [["[]", "SuppressAddress"]];
const params = [];
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params);
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// DMARCSuppressRemove removes a reporting address record from the suppress list.
async DMARCSuppressRemove(id) {
@ -906,7 +944,7 @@ var api;
const paramTypes = [["int64"]];
const returnTypes = [];
const params = [id];
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params);
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// DMARCSuppressExtend updates the until field of a suppressed reporting address record.
async DMARCSuppressExtend(id, until) {
@ -914,7 +952,7 @@ var api;
const paramTypes = [["int64"], ["timestamp"]];
const returnTypes = [];
const params = [id, until];
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params);
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// TLSRPTResults returns all TLSRPT results in the database.
async TLSRPTResults() {
@ -922,7 +960,7 @@ var api;
const paramTypes = [];
const returnTypes = [["[]", "TLSResult"]];
const params = [];
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params);
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// TLSRPTResultsPolicyDomain returns the TLS results for a domain.
async TLSRPTResultsDomain(isRcptDom, policyDomain) {
@ -930,7 +968,7 @@ var api;
const paramTypes = [["bool"], ["string"]];
const returnTypes = [["Domain"], ["[]", "TLSResult"]];
const params = [isRcptDom, policyDomain];
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params);
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// LookupTLSRPTRecord looks up a TLSRPT record and returns the parsed form, original txt
// form from DNS, and error with the TLSRPT record as a string.
@ -939,7 +977,7 @@ var api;
const paramTypes = [["string"]];
const returnTypes = [["nullable", "TLSRPTRecord"], ["string"], ["string"]];
const params = [domain];
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params);
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// TLSRPTRemoveResults removes the TLS results for a domain for the given day. If
// day is empty, all results are removed.
@ -948,7 +986,7 @@ var api;
const paramTypes = [["bool"], ["string"], ["string"]];
const returnTypes = [];
const params = [isRcptDom, domain, day];
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params);
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// TLSRPTSuppressAdd adds a reporting address to the suppress list. Outgoing
// reports will be suppressed for a period.
@ -957,7 +995,7 @@ var api;
const paramTypes = [["string"], ["timestamp"], ["string"]];
const returnTypes = [];
const params = [reportingAddress, until, comment];
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params);
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// TLSRPTSuppressList returns all reporting addresses on the suppress list.
async TLSRPTSuppressList() {
@ -965,7 +1003,7 @@ var api;
const paramTypes = [];
const returnTypes = [["[]", "TLSRPTSuppressAddress"]];
const params = [];
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params);
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// TLSRPTSuppressRemove removes a reporting address record from the suppress list.
async TLSRPTSuppressRemove(id) {
@ -973,7 +1011,7 @@ var api;
const paramTypes = [["int64"]];
const returnTypes = [];
const params = [id];
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params);
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// TLSRPTSuppressExtend updates the until field of a suppressed reporting address record.
async TLSRPTSuppressExtend(id, until) {
@ -981,7 +1019,7 @@ var api;
const paramTypes = [["int64"], ["timestamp"]];
const returnTypes = [];
const params = [id, until];
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params);
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
}
api.Client = Client;
@ -1169,7 +1207,7 @@ var api;
}
}
}
const _sherpaCall = async (baseURL, options, paramTypes, returnTypes, name, params) => {
const _sherpaCall = async (baseURL, authState, options, paramTypes, returnTypes, name, params) => {
if (!options.skipParamCheck) {
if (params.length !== paramTypes.length) {
return Promise.reject({ message: 'wrong number of parameters in sherpa call, saw ' + params.length + ' != expected ' + paramTypes.length });
@ -1211,14 +1249,36 @@ var api;
if (json) {
await simulate(json);
}
// Immediately create promise, so options.aborter is changed before returning.
const promise = new Promise((resolve, reject) => {
const fn = (resolve, reject) => {
let resolve1 = (v) => {
resolve(v);
resolve1 = () => { };
reject1 = () => { };
};
let reject1 = (v) => {
if ((v.code === 'user:noAuth' || v.code === 'user:badAuth') && options.login) {
const login = options.login;
if (!authState.loginPromise) {
authState.loginPromise = new Promise((aresolve, areject) => {
login(v.code === 'user:badAuth' ? (v.message || '') : '')
.then((token) => {
authState.token = token;
authState.loginPromise = undefined;
aresolve();
}, (err) => {
authState.loginPromise = undefined;
areject(err);
});
});
}
authState.loginPromise
.then(() => {
fn(resolve, reject);
}, (err) => {
reject(err);
});
return;
}
reject(v);
resolve1 = () => { };
reject1 = () => { };
@ -1232,6 +1292,9 @@ var api;
};
}
req.open('POST', url, true);
if (options.csrfHeader && authState.token) {
req.setRequestHeader(options.csrfHeader, authState.token);
}
if (options.timeoutMsec) {
req.timeout = options.timeoutMsec;
}
@ -1305,19 +1368,92 @@ var api;
catch (err) {
reject1({ code: 'sherpa:badData', message: 'cannot marshal to JSON' });
}
});
return await promise;
};
return await new Promise(fn);
};
})(api || (api = {}));
// Javascript is generated from typescript, do not modify generated javascript because changes will be overwritten.
const client = new api.Client();
const login = async (reason) => {
return new Promise((resolve, _) => {
const origFocus = document.activeElement;
let reasonElem;
let fieldset;
let password;
const root = dom.div(style({ position: 'absolute', top: 0, right: 0, bottom: 0, left: 0, backgroundColor: '#eee', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: '1', animation: 'fadein .15s ease-in' }), dom.div(reasonElem = reason ? dom.div(style({ marginBottom: '2ex', textAlign: 'center' }), reason) : dom.div(), dom.div(style({ backgroundColor: 'white', borderRadius: '.25em', padding: '1em', boxShadow: '0 0 20px rgba(0, 0, 0, 0.1)', border: '1px solid #ddd', maxWidth: '95vw', overflowX: 'auto', maxHeight: '95vh', overflowY: 'auto', marginBottom: '20vh' }), dom.form(async function submit(e) {
e.preventDefault();
e.stopPropagation();
reasonElem.remove();
try {
fieldset.disabled = true;
const loginToken = await client.LoginPrep();
const token = await client.Login(loginToken, password.value);
try {
window.localStorage.setItem('webadmincsrftoken', token);
}
catch (err) {
console.log('saving csrf token in localStorage', err);
}
root.remove();
if (origFocus && origFocus instanceof HTMLElement && origFocus.parentNode) {
origFocus.focus();
}
resolve(token);
}
catch (err) {
console.log('login error', err);
window.alert('Error: ' + errmsg(err));
}
finally {
fieldset.disabled = false;
}
}, fieldset = dom.fieldset(dom.h1('Admin'), dom.label(style({ display: 'block', marginBottom: '2ex' }), dom.div('Password', style({ marginBottom: '.5ex' })), password = dom.input(attr.type('password'), attr.required(''))), dom.div(style({ textAlign: 'center' }), dom.submitbutton('Login')))))));
document.body.appendChild(root);
password.focus();
});
};
const localStorageGet = (k) => {
try {
return window.localStorage.getItem(k);
}
catch (err) {
return null;
}
};
const localStorageRemove = (k) => {
try {
return window.localStorage.removeItem(k);
}
catch (err) {
}
};
const client = new api.Client().withOptions({ csrfHeader: 'x-mox-csrf', login: login }).withAuthToken(localStorageGet('webadmincsrftoken') || '');
const green = '#1dea20';
const yellow = '#ffe400';
const red = '#ff7443';
const blue = '#8bc8ff';
const link = (href, anchorOpt) => dom.a(attr.href(href), attr.rel('noopener noreferrer'), anchorOpt || href);
const crumblink = (text, link) => dom.a(text, attr.href(link));
const crumbs = (...l) => [dom.h1(l.map((e, index) => index === 0 ? e : [' / ', e])), dom.br()];
const crumbs = (...l) => [
dom.div(style({ float: 'right' }), dom.clickbutton('Logout', attr.title('Logout, invalidating this session.'), async function click(e) {
const b = e.target;
try {
b.disabled = true;
await client.Logout();
}
catch (err) {
console.log('logout', err);
window.alert('Error: ' + errmsg(err));
}
finally {
b.disabled = false;
}
localStorageRemove('webadmincsrftoken');
// Reload so all state is cleared from memory.
window.location.reload();
})),
dom.h1(l.map((e, index) => index === 0 ? e : [' / ', e])),
dom.br()
];
const errmsg = (err) => '' + (err.message || '(no error message)');
const footer = dom.div(style({ marginTop: '6ex', opacity: 0.75 }), link('https://github.com/mjl-/mox', 'mox'), ' ', moxversion);
const age = (date, future, nowSecs) => {

View File

@ -4,7 +4,83 @@
declare let page: HTMLElement
declare let moxversion: string
const client = new api.Client()
const login = async (reason: string) => {
return new Promise<string>((resolve: (v: string) => void, _) => {
const origFocus = document.activeElement
let reasonElem: HTMLElement
let fieldset: HTMLFieldSetElement
let password: HTMLInputElement
const root = dom.div(
style({position: 'absolute', top: 0, right: 0, bottom: 0, left: 0, backgroundColor: '#eee', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: '1', animation: 'fadein .15s ease-in'}),
dom.div(
reasonElem=reason ? dom.div(style({marginBottom: '2ex', textAlign: 'center'}), reason) : dom.div(),
dom.div(
style({backgroundColor: 'white', borderRadius: '.25em', padding: '1em', boxShadow: '0 0 20px rgba(0, 0, 0, 0.1)', border: '1px solid #ddd', maxWidth: '95vw', overflowX: 'auto', maxHeight: '95vh', overflowY: 'auto', marginBottom: '20vh'}),
dom.form(
async function submit(e: SubmitEvent) {
e.preventDefault()
e.stopPropagation()
reasonElem.remove()
try {
fieldset.disabled = true
const loginToken = await client.LoginPrep()
const token = await client.Login(loginToken, password.value)
try {
window.localStorage.setItem('webadmincsrftoken', token)
} catch (err) {
console.log('saving csrf token in localStorage', err)
}
root.remove()
if (origFocus && origFocus instanceof HTMLElement && origFocus.parentNode) {
origFocus.focus()
}
resolve(token)
} catch (err) {
console.log('login error', err)
window.alert('Error: ' + errmsg(err))
} finally {
fieldset.disabled = false
}
},
fieldset=dom.fieldset(
dom.h1('Admin'),
dom.label(
style({display: 'block', marginBottom: '2ex'}),
dom.div('Password', style({marginBottom: '.5ex'})),
password=dom.input(attr.type('password'), attr.required('')),
),
dom.div(
style({textAlign: 'center'}),
dom.submitbutton('Login'),
),
),
)
)
)
)
document.body.appendChild(root)
password.focus()
})
}
const localStorageGet = (k: string): string | null => {
try {
return window.localStorage.getItem(k)
} catch (err) {
return null
}
}
const localStorageRemove = (k: string) => {
try {
return window.localStorage.removeItem(k)
} catch (err) {
}
}
const client = new api.Client().withOptions({csrfHeader: 'x-mox-csrf', login: login}).withAuthToken(localStorageGet('webadmincsrftoken') || '')
const green = '#1dea20'
const yellow = '#ffe400'
@ -14,7 +90,29 @@ const blue = '#8bc8ff'
const link = (href: string, anchorOpt?: string) => dom.a(attr.href(href), attr.rel('noopener noreferrer'), anchorOpt || href)
const crumblink = (text: string, link: string) => dom.a(text, attr.href(link))
const crumbs = (...l: ElemArg[]) => [dom.h1(l.map((e, index) => index === 0 ? e : [' / ', e])), dom.br()]
const crumbs = (...l: ElemArg[]) => [
dom.div(
style({float: 'right'}),
dom.clickbutton('Logout', attr.title('Logout, invalidating this session.'), async function click(e: MouseEvent) {
const b = e.target! as HTMLButtonElement
try {
b.disabled = true
await client.Logout()
} catch (err) {
console.log('logout', err)
window.alert('Error: ' + errmsg(err))
} finally {
b.disabled = false
}
localStorageRemove('webadmincsrftoken')
// Reload so all state is cleared from memory.
window.location.reload()
}),
),
dom.h1(l.map((e, index) => index === 0 ? e : [' / ', e])),
dom.br()
]
const errmsg = (err: unknown) => ''+((err as any).message || '(no error message)')

View File

@ -1,68 +1,205 @@
package webadmin
import (
"bytes"
"context"
"crypto/ed25519"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"runtime/debug"
"strings"
"testing"
"time"
"golang.org/x/crypto/bcrypt"
"github.com/mjl-/sherpa"
"github.com/mjl-/mox/config"
"github.com/mjl-/mox/dns"
"github.com/mjl-/mox/mlog"
"github.com/mjl-/mox/mox-"
"github.com/mjl-/mox/store"
"github.com/mjl-/mox/webauth"
)
var ctxbg = context.Background()
func init() {
mox.LimitersInit()
webauth.BadAuthDelay = 0
}
func tneedErrorCode(t *testing.T, code string, fn func()) {
t.Helper()
defer func() {
t.Helper()
x := recover()
if x == nil {
debug.PrintStack()
t.Fatalf("expected sherpa user error, saw success")
}
if err, ok := x.(*sherpa.Error); !ok {
debug.PrintStack()
t.Fatalf("expected sherpa error, saw %#v", x)
} else if err.Code != code {
debug.PrintStack()
t.Fatalf("expected sherpa error code %q, saw other sherpa error %#v", code, err)
}
}()
fn()
}
func tcheck(t *testing.T, err error, msg string) {
t.Helper()
if err != nil {
t.Fatalf("%s: %s", msg, err)
}
}
func readBody(r io.Reader) string {
buf, err := io.ReadAll(r)
if err != nil {
return fmt.Sprintf("read error: %s", err)
}
return fmt.Sprintf("data: %q", buf)
}
func TestAdminAuth(t *testing.T) {
test := func(passwordfile, authHdr string, expect bool) {
t.Helper()
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/ignored", nil)
if authHdr != "" {
r.Header.Add("Authorization", authHdr)
}
ok := checkAdminAuth(ctxbg, passwordfile, w, r)
if ok != expect {
t.Fatalf("got %v, expected %v", ok, expect)
}
}
const authOK = "Basic YWRtaW46bW94dGVzdDEyMw==" // admin:moxtest123
const authBad = "Basic YWRtaW46YmFkcGFzc3dvcmQ=" // admin:badpassword
const path = "../testdata/http-passwordfile"
os.Remove(path)
defer os.Remove(path)
test(path, authOK, false) // Password file does not exist.
os.RemoveAll("../testdata/webadmin/data")
mox.ConfigStaticPath = filepath.FromSlash("../testdata/webadmin/mox.conf")
mox.ConfigDynamicPath = filepath.Join(filepath.Dir(mox.ConfigStaticPath), "domains.conf")
mox.MustLoadConfig(true, false)
adminpwhash, err := bcrypt.GenerateFromPassword([]byte("moxtest123"), bcrypt.DefaultCost)
if err != nil {
t.Fatalf("generate bcrypt hash: %v", err)
tcheck(t, err, "generate bcrypt hash")
path := mox.ConfigDirPath(mox.Conf.Static.AdminPasswordFile)
err = os.WriteFile(path, adminpwhash, 0660)
tcheck(t, err, "write password file")
defer os.Remove(path)
api := Admin{cookiePath: "/admin/"}
apiHandler, err := makeSherpaHandler(api.cookiePath, false)
tcheck(t, err, "sherpa handler")
respRec := httptest.NewRecorder()
reqInfo := requestInfo{"", respRec, &http.Request{RemoteAddr: "127.0.0.1:1234"}}
ctx := context.WithValue(ctxbg, requestInfoCtxKey, reqInfo)
// Missing login token.
tneedErrorCode(t, "user:error", func() { api.Login(ctx, "", "moxtest123") })
// Login with loginToken.
loginCookie := &http.Cookie{Name: "webadminlogin"}
loginCookie.Value = api.LoginPrep(ctx)
reqInfo.Request.Header = http.Header{"Cookie": []string{loginCookie.String()}}
csrfToken := api.Login(ctx, loginCookie.Value, "moxtest123")
var sessionCookie *http.Cookie
for _, c := range respRec.Result().Cookies() {
if c.Name == "webadminsession" {
sessionCookie = c
break
}
}
if err := os.WriteFile(path, adminpwhash, 0660); err != nil {
t.Fatalf("write password file: %v", err)
if sessionCookie == nil {
t.Fatalf("missing session cookie")
}
// We loop to also exercise the auth cache.
for i := 0; i < 2; i++ {
test(path, "", false) // Empty/missing header.
test(path, "Malformed ", false) // Not "Basic"
test(path, "Basic malformed ", false) // Bad base64.
test(path, "Basic dGVzdA== ", false) // base64 is ok, but wrong tokens inside.
test(path, authBad, false) // Wrong password.
test(path, authOK, true)
// Valid loginToken, but bad credentials.
loginCookie.Value = api.LoginPrep(ctx)
reqInfo.Request.Header = http.Header{"Cookie": []string{loginCookie.String()}}
tneedErrorCode(t, "user:loginFailed", func() { api.Login(ctx, loginCookie.Value, "badauth") })
type httpHeaders [][2]string
ctJSON := [2]string{"Content-Type", "application/json; charset=utf-8"}
cookieOK := &http.Cookie{Name: "webadminsession", Value: sessionCookie.Value}
cookieBad := &http.Cookie{Name: "webadminsession", Value: "AAAAAAAAAAAAAAAAAAAAAA"}
hdrSessionOK := [2]string{"Cookie", cookieOK.String()}
hdrSessionBad := [2]string{"Cookie", cookieBad.String()}
hdrCSRFOK := [2]string{"x-mox-csrf", string(csrfToken)}
hdrCSRFBad := [2]string{"x-mox-csrf", "AAAAAAAAAAAAAAAAAAAAAA"}
testHTTP := func(method, path string, headers httpHeaders, expStatusCode int, expHeaders httpHeaders, check func(resp *http.Response)) {
t.Helper()
req := httptest.NewRequest(method, path, nil)
for _, kv := range headers {
req.Header.Add(kv[0], kv[1])
}
rr := httptest.NewRecorder()
rr.Body = &bytes.Buffer{}
handle(apiHandler, false, rr, req)
if rr.Code != expStatusCode {
t.Fatalf("got status %d, expected %d (%s)", rr.Code, expStatusCode, readBody(rr.Body))
}
resp := rr.Result()
for _, h := range expHeaders {
if resp.Header.Get(h[0]) != h[1] {
t.Fatalf("for header %q got value %q, expected %q", h[0], resp.Header.Get(h[0]), h[1])
}
}
if check != nil {
check(resp)
}
}
testHTTPAuthAPI := func(method, path string, expStatusCode int, expHeaders httpHeaders, check func(resp *http.Response)) {
t.Helper()
testHTTP(method, path, httpHeaders{hdrCSRFOK, hdrSessionOK}, expStatusCode, expHeaders, check)
}
userAuthError := func(resp *http.Response, expCode string) {
t.Helper()
var response struct {
Error *sherpa.Error `json:"error"`
}
err := json.NewDecoder(resp.Body).Decode(&response)
tcheck(t, err, "parsing response as json")
if response.Error == nil {
t.Fatalf("expected sherpa error with code %s, no error", expCode)
}
if response.Error.Code != expCode {
t.Fatalf("got sherpa error code %q, expected %s", response.Error.Code, expCode)
}
}
badAuth := func(resp *http.Response) {
t.Helper()
userAuthError(resp, "user:badAuth")
}
noAuth := func(resp *http.Response) {
t.Helper()
userAuthError(resp, "user:noAuth")
}
testHTTP("POST", "/api/Bogus", httpHeaders{}, http.StatusOK, nil, noAuth)
testHTTP("POST", "/api/Bogus", httpHeaders{hdrCSRFBad}, http.StatusOK, nil, noAuth)
testHTTP("POST", "/api/Bogus", httpHeaders{hdrSessionBad}, http.StatusOK, nil, noAuth)
testHTTP("POST", "/api/Bogus", httpHeaders{hdrCSRFBad, hdrSessionBad}, http.StatusOK, nil, badAuth)
testHTTP("POST", "/api/Bogus", httpHeaders{hdrCSRFOK}, http.StatusOK, nil, noAuth)
testHTTP("POST", "/api/Bogus", httpHeaders{hdrSessionOK}, http.StatusOK, nil, noAuth)
testHTTP("POST", "/api/Bogus", httpHeaders{hdrCSRFBad, hdrSessionOK}, http.StatusOK, nil, badAuth)
testHTTP("POST", "/api/Bogus", httpHeaders{hdrCSRFOK, hdrSessionBad}, http.StatusOK, nil, badAuth)
testHTTPAuthAPI("GET", "/api/Transports", http.StatusMethodNotAllowed, nil, nil)
testHTTPAuthAPI("POST", "/api/Transports", http.StatusOK, httpHeaders{ctJSON}, nil)
// Logout needs session token.
reqInfo.SessionToken = store.SessionToken(strings.SplitN(sessionCookie.Value, " ", 2)[0])
ctx = context.WithValue(ctxbg, requestInfoCtxKey, reqInfo)
api.Logout(ctx)
tneedErrorCode(t, "server:error", func() { api.Logout(ctx) })
}
func TestCheckDomain(t *testing.T) {

View File

@ -2,6 +2,51 @@
"Name": "Admin",
"Docs": "Admin exports web API functions for the admin web interface. All its methods are\nexported under api/. Function calls require valid HTTP Authentication\ncredentials of a user.",
"Functions": [
{
"Name": "LoginPrep",
"Docs": "LoginPrep returns a login token, and also sets it as cookie. Both must be\npresent in the call to Login.",
"Params": [],
"Returns": [
{
"Name": "r0",
"Typewords": [
"string"
]
}
]
},
{
"Name": "Login",
"Docs": "Login returns a session token for the credentials, or fails with error code\n\"user:badLogin\". Call LoginPrep to get a loginToken.",
"Params": [
{
"Name": "loginToken",
"Typewords": [
"string"
]
},
{
"Name": "password",
"Typewords": [
"string"
]
}
],
"Returns": [
{
"Name": "r0",
"Typewords": [
"CSRFToken"
]
}
]
},
{
"Name": "Logout",
"Docs": "Logout invalidates the session token.",
"Params": [],
"Returns": []
},
{
"Name": "CheckDomain",
"Docs": "CheckDomain checks the configuration for the domain, such as MX, SMTP STARTTLS,\nSPF, DKIM, DMARC, TLSRPT, MTASTS, autoconfig, autodiscover.",
@ -4159,6 +4204,11 @@
],
"Ints": [],
"Strings": [
{
"Name": "CSRFToken",
"Docs": "",
"Values": null
},
{
"Name": "DMARCPolicy",
"Docs": "Policy as used in DMARC DNS record for \"p=\" or \"sp=\".",

View File

@ -647,6 +647,8 @@ export interface TLSRPTSuppressAddress {
Comment: string
}
export type CSRFToken = string
// Policy as used in DMARC DNS record for "p=" or "sp=".
export enum DMARCPolicy {
PolicyEmpty = "", // Only for the optional Record.SubdomainPolicy.
@ -769,7 +771,7 @@ export type Localpart = string
export type IP = string
export const structTypes: {[typename: string]: boolean} = {"AuthResults":true,"AutoconfCheckResult":true,"AutodiscoverCheckResult":true,"AutodiscoverSRV":true,"CheckResult":true,"ClientConfigs":true,"ClientConfigsEntry":true,"DANECheckResult":true,"DKIMAuthResult":true,"DKIMCheckResult":true,"DKIMRecord":true,"DMARCCheckResult":true,"DMARCRecord":true,"DMARCSummary":true,"DNSSECResult":true,"DateRange":true,"Directive":true,"Domain":true,"DomainFeedback":true,"Evaluation":true,"EvaluationStat":true,"Extension":true,"FailureDetails":true,"IPDomain":true,"IPRevCheckResult":true,"Identifiers":true,"MTASTSCheckResult":true,"MTASTSRecord":true,"MX":true,"MXCheckResult":true,"Modifier":true,"Msg":true,"Pair":true,"Policy":true,"PolicyEvaluated":true,"PolicyOverrideReason":true,"PolicyPublished":true,"PolicyRecord":true,"Record":true,"Report":true,"ReportMetadata":true,"ReportRecord":true,"Result":true,"ResultPolicy":true,"Reverse":true,"Row":true,"SMTPAuth":true,"SPFAuthResult":true,"SPFCheckResult":true,"SPFRecord":true,"SRV":true,"SRVConfCheckResult":true,"STSMX":true,"Summary":true,"SuppressAddress":true,"TLSCheckResult":true,"TLSRPTCheckResult":true,"TLSRPTDateRange":true,"TLSRPTRecord":true,"TLSRPTSummary":true,"TLSRPTSuppressAddress":true,"TLSReportRecord":true,"TLSResult":true,"Transport":true,"TransportSMTP":true,"TransportSocks":true,"URI":true,"WebForward":true,"WebHandler":true,"WebRedirect":true,"WebStatic":true,"WebserverConfig":true}
export const stringsTypes: {[typename: string]: boolean} = {"Align":true,"Alignment":true,"DKIMResult":true,"DMARCPolicy":true,"DMARCResult":true,"Disposition":true,"IP":true,"Localpart":true,"Mode":true,"PolicyOverride":true,"PolicyType":true,"RUA":true,"ResultType":true,"SPFDomainScope":true,"SPFResult":true}
export const stringsTypes: {[typename: string]: boolean} = {"Align":true,"Alignment":true,"CSRFToken":true,"DKIMResult":true,"DMARCPolicy":true,"DMARCResult":true,"Disposition":true,"IP":true,"Localpart":true,"Mode":true,"PolicyOverride":true,"PolicyType":true,"RUA":true,"ResultType":true,"SPFDomainScope":true,"SPFResult":true}
export const intsTypes: {[typename: string]: boolean} = {}
export const types: TypenameMap = {
"CheckResult": {"Name":"CheckResult","Docs":"","Fields":[{"Name":"Domain","Docs":"","Typewords":["string"]},{"Name":"DNSSEC","Docs":"","Typewords":["DNSSECResult"]},{"Name":"IPRev","Docs":"","Typewords":["IPRevCheckResult"]},{"Name":"MX","Docs":"","Typewords":["MXCheckResult"]},{"Name":"TLS","Docs":"","Typewords":["TLSCheckResult"]},{"Name":"DANE","Docs":"","Typewords":["DANECheckResult"]},{"Name":"SPF","Docs":"","Typewords":["SPFCheckResult"]},{"Name":"DKIM","Docs":"","Typewords":["DKIMCheckResult"]},{"Name":"DMARC","Docs":"","Typewords":["DMARCCheckResult"]},{"Name":"HostTLSRPT","Docs":"","Typewords":["TLSRPTCheckResult"]},{"Name":"DomainTLSRPT","Docs":"","Typewords":["TLSRPTCheckResult"]},{"Name":"MTASTS","Docs":"","Typewords":["MTASTSCheckResult"]},{"Name":"SRVConf","Docs":"","Typewords":["SRVConfCheckResult"]},{"Name":"Autoconf","Docs":"","Typewords":["AutoconfCheckResult"]},{"Name":"Autodiscover","Docs":"","Typewords":["AutodiscoverCheckResult"]}]},
@ -844,6 +846,7 @@ export const types: TypenameMap = {
"SuppressAddress": {"Name":"SuppressAddress","Docs":"","Fields":[{"Name":"ID","Docs":"","Typewords":["int64"]},{"Name":"Inserted","Docs":"","Typewords":["timestamp"]},{"Name":"ReportingAddress","Docs":"","Typewords":["string"]},{"Name":"Until","Docs":"","Typewords":["timestamp"]},{"Name":"Comment","Docs":"","Typewords":["string"]}]},
"TLSResult": {"Name":"TLSResult","Docs":"","Fields":[{"Name":"ID","Docs":"","Typewords":["int64"]},{"Name":"PolicyDomain","Docs":"","Typewords":["string"]},{"Name":"DayUTC","Docs":"","Typewords":["string"]},{"Name":"RecipientDomain","Docs":"","Typewords":["string"]},{"Name":"Created","Docs":"","Typewords":["timestamp"]},{"Name":"Updated","Docs":"","Typewords":["timestamp"]},{"Name":"IsHost","Docs":"","Typewords":["bool"]},{"Name":"SendReport","Docs":"","Typewords":["bool"]},{"Name":"SentToRecipientDomain","Docs":"","Typewords":["bool"]},{"Name":"RecipientDomainReportingAddresses","Docs":"","Typewords":["[]","string"]},{"Name":"SentToPolicyDomain","Docs":"","Typewords":["bool"]},{"Name":"Results","Docs":"","Typewords":["[]","Result"]}]},
"TLSRPTSuppressAddress": {"Name":"TLSRPTSuppressAddress","Docs":"","Fields":[{"Name":"ID","Docs":"","Typewords":["int64"]},{"Name":"Inserted","Docs":"","Typewords":["timestamp"]},{"Name":"ReportingAddress","Docs":"","Typewords":["string"]},{"Name":"Until","Docs":"","Typewords":["timestamp"]},{"Name":"Comment","Docs":"","Typewords":["string"]}]},
"CSRFToken": {"Name":"CSRFToken","Docs":"","Values":null},
"DMARCPolicy": {"Name":"DMARCPolicy","Docs":"","Values":[{"Name":"PolicyEmpty","Value":"","Docs":""},{"Name":"PolicyNone","Value":"none","Docs":""},{"Name":"PolicyQuarantine","Value":"quarantine","Docs":""},{"Name":"PolicyReject","Value":"reject","Docs":""}]},
"Align": {"Name":"Align","Docs":"","Values":[{"Name":"AlignStrict","Value":"s","Docs":""},{"Name":"AlignRelaxed","Value":"r","Docs":""}]},
"RUA": {"Name":"RUA","Docs":"","Values":null},
@ -934,6 +937,7 @@ export const parser = {
SuppressAddress: (v: any) => parse("SuppressAddress", v) as SuppressAddress,
TLSResult: (v: any) => parse("TLSResult", v) as TLSResult,
TLSRPTSuppressAddress: (v: any) => parse("TLSRPTSuppressAddress", v) as TLSRPTSuppressAddress,
CSRFToken: (v: any) => parse("CSRFToken", v) as CSRFToken,
DMARCPolicy: (v: any) => parse("DMARCPolicy", v) as DMARCPolicy,
Align: (v: any) => parse("Align", v) as Align,
RUA: (v: any) => parse("RUA", v) as RUA,
@ -957,14 +961,57 @@ export const parser = {
let defaultOptions: ClientOptions = {slicesNullable: true, mapsNullable: true, nullableOptional: true}
export class Client {
constructor(private baseURL=defaultBaseURL, public options?: ClientOptions) {
if (!options) {
this.options = defaultOptions
}
private baseURL: string
public authState: AuthState
public options: ClientOptions
constructor() {
this.authState = {}
this.options = {...defaultOptions}
this.baseURL = this.options.baseURL || defaultBaseURL
}
withAuthToken(token: string): Client {
const c = new Client()
c.authState.token = token
c.options = this.options
return c
}
withOptions(options: ClientOptions): Client {
return new Client(this.baseURL, { ...this.options, ...options })
const c = new Client()
c.authState = this.authState
c.options = { ...this.options, ...options }
return c
}
// LoginPrep returns a login token, and also sets it as cookie. Both must be
// present in the call to Login.
async LoginPrep(): Promise<string> {
const fn: string = "LoginPrep"
const paramTypes: string[][] = []
const returnTypes: string[][] = [["string"]]
const params: any[] = []
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as string
}
// Login returns a session token for the credentials, or fails with error code
// "user:badLogin". Call LoginPrep to get a loginToken.
async Login(loginToken: string, password: string): Promise<CSRFToken> {
const fn: string = "Login"
const paramTypes: string[][] = [["string"],["string"]]
const returnTypes: string[][] = [["CSRFToken"]]
const params: any[] = [loginToken, password]
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as CSRFToken
}
// Logout invalidates the session token.
async Logout(): Promise<void> {
const fn: string = "Logout"
const paramTypes: string[][] = []
const returnTypes: string[][] = []
const params: any[] = []
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as void
}
// CheckDomain checks the configuration for the domain, such as MX, SMTP STARTTLS,
@ -974,7 +1021,7 @@ export class Client {
const paramTypes: string[][] = [["string"]]
const returnTypes: string[][] = [["CheckResult"]]
const params: any[] = [domainName]
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params) as CheckResult
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as CheckResult
}
// Domains returns all configured domain names, in UTF-8 for IDNA domains.
@ -983,7 +1030,7 @@ export class Client {
const paramTypes: string[][] = []
const returnTypes: string[][] = [["[]","Domain"]]
const params: any[] = []
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params) as Domain[] | null
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as Domain[] | null
}
// Domain returns the dns domain for a (potentially unicode as IDNA) domain name.
@ -992,7 +1039,7 @@ export class Client {
const paramTypes: string[][] = [["string"]]
const returnTypes: string[][] = [["Domain"]]
const params: any[] = [domain]
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params) as Domain
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as Domain
}
// ParseDomain parses a domain, possibly an IDNA domain.
@ -1001,7 +1048,7 @@ export class Client {
const paramTypes: string[][] = [["string"]]
const returnTypes: string[][] = [["Domain"]]
const params: any[] = [domain]
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params) as Domain
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as Domain
}
// DomainLocalparts returns the encoded localparts and accounts configured in domain.
@ -1010,7 +1057,7 @@ export class Client {
const paramTypes: string[][] = [["string"]]
const returnTypes: string[][] = [["{}","string"]]
const params: any[] = [domain]
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params) as { [key: string]: string }
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as { [key: string]: string }
}
// Accounts returns the names of all configured accounts.
@ -1019,7 +1066,7 @@ export class Client {
const paramTypes: string[][] = []
const returnTypes: string[][] = [["[]","string"]]
const params: any[] = []
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params) as string[] | null
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as string[] | null
}
// Account returns the parsed configuration of an account.
@ -1028,7 +1075,7 @@ export class Client {
const paramTypes: string[][] = [["string"]]
const returnTypes: string[][] = [["{}","any"]]
const params: any[] = [account]
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params) as { [key: string]: any }
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as { [key: string]: any }
}
// ConfigFiles returns the paths and contents of the static and dynamic configuration files.
@ -1037,7 +1084,7 @@ export class Client {
const paramTypes: string[][] = []
const returnTypes: string[][] = [["string"],["string"],["string"],["string"]]
const params: any[] = []
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params) as [string, string, string, string]
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as [string, string, string, string]
}
// MTASTSPolicies returns all mtasts policies from the cache.
@ -1046,7 +1093,7 @@ export class Client {
const paramTypes: string[][] = []
const returnTypes: string[][] = [["[]","PolicyRecord"]]
const params: any[] = []
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params) as PolicyRecord[] | null
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as PolicyRecord[] | null
}
// TLSReports returns TLS reports overlapping with period start/end, for the given
@ -1057,7 +1104,7 @@ export class Client {
const paramTypes: string[][] = [["timestamp"],["timestamp"],["string"]]
const returnTypes: string[][] = [["[]","TLSReportRecord"]]
const params: any[] = [start, end, policyDomain]
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params) as TLSReportRecord[] | null
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as TLSReportRecord[] | null
}
// TLSReportID returns a single TLS report.
@ -1066,7 +1113,7 @@ export class Client {
const paramTypes: string[][] = [["string"],["int64"]]
const returnTypes: string[][] = [["TLSReportRecord"]]
const params: any[] = [domain, reportID]
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params) as TLSReportRecord
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as TLSReportRecord
}
// TLSRPTSummaries returns a summary of received TLS reports overlapping with
@ -1077,7 +1124,7 @@ export class Client {
const paramTypes: string[][] = [["timestamp"],["timestamp"],["string"]]
const returnTypes: string[][] = [["[]","TLSRPTSummary"]]
const params: any[] = [start, end, policyDomain]
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params) as TLSRPTSummary[] | null
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as TLSRPTSummary[] | null
}
// DMARCReports returns DMARC reports overlapping with period start/end, for the
@ -1088,7 +1135,7 @@ export class Client {
const paramTypes: string[][] = [["timestamp"],["timestamp"],["string"]]
const returnTypes: string[][] = [["[]","DomainFeedback"]]
const params: any[] = [start, end, domain]
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params) as DomainFeedback[] | null
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as DomainFeedback[] | null
}
// DMARCReportID returns a single DMARC report.
@ -1097,7 +1144,7 @@ export class Client {
const paramTypes: string[][] = [["string"],["int64"]]
const returnTypes: string[][] = [["DomainFeedback"]]
const params: any[] = [domain, reportID]
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params) as DomainFeedback
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as DomainFeedback
}
// DMARCSummaries returns a summary of received DMARC reports overlapping with
@ -1108,7 +1155,7 @@ export class Client {
const paramTypes: string[][] = [["timestamp"],["timestamp"],["string"]]
const returnTypes: string[][] = [["[]","DMARCSummary"]]
const params: any[] = [start, end, domain]
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params) as DMARCSummary[] | null
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as DMARCSummary[] | null
}
// LookupIP does a reverse lookup of ip.
@ -1117,7 +1164,7 @@ export class Client {
const paramTypes: string[][] = [["string"]]
const returnTypes: string[][] = [["Reverse"]]
const params: any[] = [ip]
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params) as Reverse
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as Reverse
}
// DNSBLStatus returns the IPs from which outgoing connections may be made and
@ -1132,7 +1179,7 @@ export class Client {
const paramTypes: string[][] = []
const returnTypes: string[][] = [["{}","{}","string"]]
const params: any[] = []
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params) as { [key: string]: { [key: string]: string } }
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as { [key: string]: { [key: string]: string } }
}
// DomainRecords returns lines describing DNS records that should exist for the
@ -1142,7 +1189,7 @@ export class Client {
const paramTypes: string[][] = [["string"]]
const returnTypes: string[][] = [["[]","string"]]
const params: any[] = [domain]
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params) as string[] | null
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as string[] | null
}
// DomainAdd adds a new domain and reloads the configuration.
@ -1151,7 +1198,7 @@ export class Client {
const paramTypes: string[][] = [["string"],["string"],["string"]]
const returnTypes: string[][] = []
const params: any[] = [domain, accountName, localpart]
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params) as void
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as void
}
// DomainRemove removes an existing domain and reloads the configuration.
@ -1160,7 +1207,7 @@ export class Client {
const paramTypes: string[][] = [["string"]]
const returnTypes: string[][] = []
const params: any[] = [domain]
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params) as void
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as void
}
// AccountAdd adds existing a new account, with an initial email address, and
@ -1170,7 +1217,7 @@ export class Client {
const paramTypes: string[][] = [["string"],["string"]]
const returnTypes: string[][] = []
const params: any[] = [accountName, address]
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params) as void
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as void
}
// AccountRemove removes an existing account and reloads the configuration.
@ -1179,7 +1226,7 @@ export class Client {
const paramTypes: string[][] = [["string"]]
const returnTypes: string[][] = []
const params: any[] = [accountName]
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params) as void
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as void
}
// AddressAdd adds a new address to the account, which must already exist.
@ -1188,7 +1235,7 @@ export class Client {
const paramTypes: string[][] = [["string"],["string"]]
const returnTypes: string[][] = []
const params: any[] = [address, accountName]
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params) as void
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as void
}
// AddressRemove removes an existing address.
@ -1197,7 +1244,7 @@ export class Client {
const paramTypes: string[][] = [["string"]]
const returnTypes: string[][] = []
const params: any[] = [address]
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params) as void
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as void
}
// SetPassword saves a new password for an account, invalidating the previous password.
@ -1208,7 +1255,7 @@ export class Client {
const paramTypes: string[][] = [["string"],["string"]]
const returnTypes: string[][] = []
const params: any[] = [accountName, password]
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params) as void
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as void
}
// SetAccountLimits set new limits on outgoing messages for an account.
@ -1217,7 +1264,7 @@ export class Client {
const paramTypes: string[][] = [["string"],["int32"],["int32"],["int64"]]
const returnTypes: string[][] = []
const params: any[] = [accountName, maxOutgoingMessagesPerDay, maxFirstTimeRecipientsPerDay, maxMsgSize]
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params) as void
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as void
}
// ClientConfigsDomain returns configurations for email clients, IMAP and
@ -1227,7 +1274,7 @@ export class Client {
const paramTypes: string[][] = [["string"]]
const returnTypes: string[][] = [["ClientConfigs"]]
const params: any[] = [domain]
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params) as ClientConfigs
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as ClientConfigs
}
// QueueList returns the messages currently in the outgoing queue.
@ -1236,7 +1283,7 @@ export class Client {
const paramTypes: string[][] = []
const returnTypes: string[][] = [["[]","Msg"]]
const params: any[] = []
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params) as Msg[] | null
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as Msg[] | null
}
// QueueSize returns the number of messages currently in the outgoing queue.
@ -1245,7 +1292,7 @@ export class Client {
const paramTypes: string[][] = []
const returnTypes: string[][] = [["int32"]]
const params: any[] = []
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params) as number
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as number
}
// QueueKick initiates delivery of a message from the queue and sets the transport
@ -1255,7 +1302,7 @@ export class Client {
const paramTypes: string[][] = [["int64"],["string"]]
const returnTypes: string[][] = []
const params: any[] = [id, transport]
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params) as void
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as void
}
// QueueDrop removes a message from the queue.
@ -1264,7 +1311,7 @@ export class Client {
const paramTypes: string[][] = [["int64"]]
const returnTypes: string[][] = []
const params: any[] = [id]
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params) as void
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as void
}
// QueueSaveRequireTLS updates the requiretls field for a message in the queue,
@ -1274,7 +1321,7 @@ export class Client {
const paramTypes: string[][] = [["int64"],["nullable","bool"]]
const returnTypes: string[][] = []
const params: any[] = [id, requireTLS]
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params) as void
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as void
}
// LogLevels returns the current log levels.
@ -1283,7 +1330,7 @@ export class Client {
const paramTypes: string[][] = []
const returnTypes: string[][] = [["{}","string"]]
const params: any[] = []
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params) as { [key: string]: string }
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as { [key: string]: string }
}
// LogLevelSet sets a log level for a package.
@ -1292,7 +1339,7 @@ export class Client {
const paramTypes: string[][] = [["string"],["string"]]
const returnTypes: string[][] = []
const params: any[] = [pkg, levelStr]
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params) as void
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as void
}
// LogLevelRemove removes a log level for a package, which cannot be the empty string.
@ -1301,7 +1348,7 @@ export class Client {
const paramTypes: string[][] = [["string"]]
const returnTypes: string[][] = []
const params: any[] = [pkg]
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params) as void
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as void
}
// CheckUpdatesEnabled returns whether checking for updates is enabled.
@ -1310,7 +1357,7 @@ export class Client {
const paramTypes: string[][] = []
const returnTypes: string[][] = [["bool"]]
const params: any[] = []
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params) as boolean
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as boolean
}
// WebserverConfig returns the current webserver config
@ -1319,7 +1366,7 @@ export class Client {
const paramTypes: string[][] = []
const returnTypes: string[][] = [["WebserverConfig"]]
const params: any[] = []
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params) as WebserverConfig
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as WebserverConfig
}
// WebserverConfigSave saves a new webserver config. If oldConf is not equal to
@ -1329,7 +1376,7 @@ export class Client {
const paramTypes: string[][] = [["WebserverConfig"],["WebserverConfig"]]
const returnTypes: string[][] = [["WebserverConfig"]]
const params: any[] = [oldConf, newConf]
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params) as WebserverConfig
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as WebserverConfig
}
// Transports returns the configured transports, for sending email.
@ -1338,7 +1385,7 @@ export class Client {
const paramTypes: string[][] = []
const returnTypes: string[][] = [["{}","Transport"]]
const params: any[] = []
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params) as { [key: string]: Transport }
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as { [key: string]: Transport }
}
// DMARCEvaluationStats returns a map of all domains with evaluations to a count of
@ -1348,7 +1395,7 @@ export class Client {
const paramTypes: string[][] = []
const returnTypes: string[][] = [["{}","EvaluationStat"]]
const params: any[] = []
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params) as { [key: string]: EvaluationStat }
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as { [key: string]: EvaluationStat }
}
// DMARCEvaluationsDomain returns all evaluations for aggregate reports for the
@ -1358,7 +1405,7 @@ export class Client {
const paramTypes: string[][] = [["string"]]
const returnTypes: string[][] = [["Domain"],["[]","Evaluation"]]
const params: any[] = [domain]
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params) as [Domain, Evaluation[] | null]
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as [Domain, Evaluation[] | null]
}
// DMARCRemoveEvaluations removes evaluations for a domain.
@ -1367,7 +1414,7 @@ export class Client {
const paramTypes: string[][] = [["string"]]
const returnTypes: string[][] = []
const params: any[] = [domain]
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params) as void
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as void
}
// DMARCSuppressAdd adds a reporting address to the suppress list. Outgoing
@ -1377,7 +1424,7 @@ export class Client {
const paramTypes: string[][] = [["string"],["timestamp"],["string"]]
const returnTypes: string[][] = []
const params: any[] = [reportingAddress, until, comment]
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params) as void
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as void
}
// DMARCSuppressList returns all reporting addresses on the suppress list.
@ -1386,7 +1433,7 @@ export class Client {
const paramTypes: string[][] = []
const returnTypes: string[][] = [["[]","SuppressAddress"]]
const params: any[] = []
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params) as SuppressAddress[] | null
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as SuppressAddress[] | null
}
// DMARCSuppressRemove removes a reporting address record from the suppress list.
@ -1395,7 +1442,7 @@ export class Client {
const paramTypes: string[][] = [["int64"]]
const returnTypes: string[][] = []
const params: any[] = [id]
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params) as void
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as void
}
// DMARCSuppressExtend updates the until field of a suppressed reporting address record.
@ -1404,7 +1451,7 @@ export class Client {
const paramTypes: string[][] = [["int64"],["timestamp"]]
const returnTypes: string[][] = []
const params: any[] = [id, until]
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params) as void
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as void
}
// TLSRPTResults returns all TLSRPT results in the database.
@ -1413,7 +1460,7 @@ export class Client {
const paramTypes: string[][] = []
const returnTypes: string[][] = [["[]","TLSResult"]]
const params: any[] = []
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params) as TLSResult[] | null
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as TLSResult[] | null
}
// TLSRPTResultsPolicyDomain returns the TLS results for a domain.
@ -1422,7 +1469,7 @@ export class Client {
const paramTypes: string[][] = [["bool"],["string"]]
const returnTypes: string[][] = [["Domain"],["[]","TLSResult"]]
const params: any[] = [isRcptDom, policyDomain]
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params) as [Domain, TLSResult[] | null]
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as [Domain, TLSResult[] | null]
}
// LookupTLSRPTRecord looks up a TLSRPT record and returns the parsed form, original txt
@ -1432,7 +1479,7 @@ export class Client {
const paramTypes: string[][] = [["string"]]
const returnTypes: string[][] = [["nullable","TLSRPTRecord"],["string"],["string"]]
const params: any[] = [domain]
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params) as [TLSRPTRecord | null, string, string]
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as [TLSRPTRecord | null, string, string]
}
// TLSRPTRemoveResults removes the TLS results for a domain for the given day. If
@ -1442,7 +1489,7 @@ export class Client {
const paramTypes: string[][] = [["bool"],["string"],["string"]]
const returnTypes: string[][] = []
const params: any[] = [isRcptDom, domain, day]
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params) as void
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as void
}
// TLSRPTSuppressAdd adds a reporting address to the suppress list. Outgoing
@ -1452,7 +1499,7 @@ export class Client {
const paramTypes: string[][] = [["string"],["timestamp"],["string"]]
const returnTypes: string[][] = []
const params: any[] = [reportingAddress, until, comment]
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params) as void
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as void
}
// TLSRPTSuppressList returns all reporting addresses on the suppress list.
@ -1461,7 +1508,7 @@ export class Client {
const paramTypes: string[][] = []
const returnTypes: string[][] = [["[]","TLSRPTSuppressAddress"]]
const params: any[] = []
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params) as TLSRPTSuppressAddress[] | null
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as TLSRPTSuppressAddress[] | null
}
// TLSRPTSuppressRemove removes a reporting address record from the suppress list.
@ -1470,7 +1517,7 @@ export class Client {
const paramTypes: string[][] = [["int64"]]
const returnTypes: string[][] = []
const params: any[] = [id]
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params) as void
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as void
}
// TLSRPTSuppressExtend updates the until field of a suppressed reporting address record.
@ -1479,7 +1526,7 @@ export class Client {
const paramTypes: string[][] = [["int64"],["timestamp"]]
const returnTypes: string[][] = []
const params: any[] = [id, until]
return await _sherpaCall(this.baseURL, { ...this.options }, paramTypes, returnTypes, fn, params) as void
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as void
}
}
@ -1591,7 +1638,7 @@ class verifier {
const ensure = (ok: boolean, expect: string): any => {
if (!ok) {
error('got ' + JSON.stringify(v) + ', expected ' + expect)
error('got ' + JSON.stringify(v) + ', expected ' + expect)
}
return v
}
@ -1732,6 +1779,7 @@ class verifier {
export interface ClientOptions {
baseURL?: string
aborter?: {abort?: () => void}
timeoutMsec?: number
skipParamCheck?: boolean
@ -1739,9 +1787,16 @@ export interface ClientOptions {
slicesNullable?: boolean
mapsNullable?: boolean
nullableOptional?: boolean
csrfHeader?: string
login?: (reason: string) => Promise<string>
}
const _sherpaCall = async (baseURL: string, options: ClientOptions, paramTypes: string[][], returnTypes: string[][], name: string, params: any[]): Promise<any> => {
export interface AuthState {
token?: string // For csrf request header.
loginPromise?: Promise<void> // To let multiple API calls wait for a single login attempt, not each opening a login popup.
}
const _sherpaCall = async (baseURL: string, authState: AuthState, options: ClientOptions, paramTypes: string[][], returnTypes: string[][], name: string, params: any[]): Promise<any> => {
if (!options.skipParamCheck) {
if (params.length !== paramTypes.length) {
return Promise.reject({ message: 'wrong number of parameters in sherpa call, saw ' + params.length + ' != expected ' + paramTypes.length })
@ -1782,14 +1837,36 @@ const _sherpaCall = async (baseURL: string, options: ClientOptions, paramTypes:
await simulate(json)
}
// Immediately create promise, so options.aborter is changed before returning.
const promise = new Promise((resolve, reject) => {
let resolve1 = (v: { code: string, message: string }) => {
const fn = (resolve: (v: any) => void, reject: (v: any) => void) => {
let resolve1 = (v: any) => {
resolve(v)
resolve1 = () => { }
reject1 = () => { }
}
let reject1 = (v: { code: string, message: string }) => {
if ((v.code === 'user:noAuth' || v.code === 'user:badAuth') && options.login) {
const login = options.login
if (!authState.loginPromise) {
authState.loginPromise = new Promise((aresolve, areject) => {
login(v.code === 'user:badAuth' ? (v.message || '') : '')
.then((token) => {
authState.token = token
authState.loginPromise = undefined
aresolve()
}, (err: any) => {
authState.loginPromise = undefined
areject(err)
})
})
}
authState.loginPromise
.then(() => {
fn(resolve, reject)
}, (err: any) => {
reject(err)
})
return
}
reject(v)
resolve1 = () => { }
reject1 = () => { }
@ -1804,6 +1881,9 @@ const _sherpaCall = async (baseURL: string, options: ClientOptions, paramTypes:
}
}
req.open('POST', url, true)
if (options.csrfHeader && authState.token) {
req.setRequestHeader(options.csrfHeader, authState.token)
}
if (options.timeoutMsec) {
req.timeout = options.timeoutMsec
}
@ -1872,8 +1952,8 @@ const _sherpaCall = async (baseURL: string, options: ClientOptions, paramTypes:
} catch (err) {
reject1({ code: 'sherpa:badData', message: 'cannot marshal to JSON' })
}
})
return await promise
}
return await new Promise(fn)
}
}