Documentation
¶
Overview ¶
Package registry loads the realm/database/collection tree from CONFIG_DIR into an immutable, validated registry used by routing, validation and provisioning.
Index ¶
- Constants
- Variables
- func AnonymizeRules(rl *Realm, overrides map[string]AnonOverride) (map[string]*AnonRule, error)
- func BlindField(path string) string
- func CheckMigrationImports(path string) error
- func ClientIDListProblems(field string, list []string) []string
- func ClientIDProblem(provider, id string) string
- func DomainProblem(domain string) string
- func EnvelopeProblem(id string) string
- func FormatRate(r ratelimit.Rate) string
- func HasSchema(dir string) bool
- func IsAuditAction(name string) bool
- func IsRateClass(name string) bool
- func MarkerField(path string) string
- func MigrationSourceHash(db *Database) (string, error)
- func NormalizeEmail(v string) (string, error)
- func OrgProviderCallbackPath(realm, orgID, provider string) string
- func ParamsFingerprint(p imaging.Params) string
- func ParseAnonymizeConfig(data []byte) (map[string]AnonOverride, error)
- func ParseRate(s string) (ratelimit.Rate, error)
- func ProviderCallbackPath(realm, provider string) string
- func RealmPath(realmPath string, parts ...string) string
- func RealtimeChanged(old, next *Registry) map[string]bool
- func SameBucket(a, b *StorageSettings) bool
- func SchemaMigrationFile(n int) string
- func SchemaVersionFile(n int) string
- func SearchLanguage(locale string) string
- func SourceHash(dir string) (string, error)
- func TenantProblem(tenant string, shared bool) string
- func ValidName(name string) bool
- func ValidSecretName(name string) bool
- func ValidateVersionParams(p imaging.Params) []string
- type AccountSettings
- type AdminAccess
- type AdminRights
- type Aggregate
- type AggregateLimits
- type AnonOverride
- type AnonRule
- type AppConfig
- type AuditAction
- type CachePolicy
- type Collection
- func (c *Collection) AggregateIndexWarnings() []string
- func (c *Collection) ApplyDefaults(doc map[string]any) map[string]any
- func (c *Collection) ArrayField(path string) bool
- func (c *Collection) CompatibilityFindings() ([]CompatFinding, error)
- func (c *Collection) ConfigPath() string
- func (c *Collection) DateField(path string) bool
- func (c *Collection) DatesToStorage(doc map[string]any) map[string]any
- func (c *Collection) EncryptedAt(path string) (EncryptedField, bool)
- func (c *Collection) HasPublicFiles() bool
- func (c *Collection) InOrganizations() bool
- func (c *Collection) InTeams() bool
- func (c *Collection) IsEncrypted(path string) bool
- func (c *Collection) IsKnownField(path string) bool
- func (c *Collection) IsSearchable(path string) bool
- func (c *Collection) NeedsEvents() bool
- func (c *Collection) ParentTargets() []*Reference
- func (c *Collection) RevealUsesConfig() bool
- func (c *Collection) RevealUsesOrgs() bool
- func (c *Collection) Revealing() []EncryptedField
- func (c *Collection) ScalarField(path string) bool
- func (c *Collection) Searchable() []EncryptedField
- func (c *Collection) StampSchemaVersion(meta map[string]any)
- func (c *Collection) StampSchemaVersionAs(meta map[string]any, version int)
- func (c *Collection) VersionSchema(n int) (map[string]any, error)
- type CompatFinding
- type ComplianceSettings
- type ConfigPath
- type Consent
- type ConsentRef
- type ConsentText
- type ConsentVersion
- type CookieSettings
- type CustomID
- type Database
- type Default
- type EmailLimits
- type EmailSettings
- type EncryptedField
- type ErasurePolicy
- type EventCollection
- type ExpandLimits
- type Field
- type FileField
- type Function
- type FunctionPush
- type Functions
- type Index
- type IndexKey
- type IssuerPattern
- type LoginThrottle
- type MFASettings
- type MagicLinkSettings
- type Manifest
- type ManifestBundle
- type MigrationManifest
- type NamedHook
- type Networks
- type OnComplete
- type OrgCaps
- type OrgDomainsSettings
- type OrgHook
- type OrgHooks
- type OrgRole
- type OrgSSOSettings
- type OrgSettings
- func (o *OrgSettings) CapsOf(roles []string) OrgCaps
- func (o *OrgSettings) CreateRuleAllows(u *rules.User, now time.Time) (bool, error)
- func (o *OrgSettings) Declared(role string) bool
- func (o *OrgSettings) InvitationURL(token, org string) string
- func (o *OrgSettings) RoleNames() []string
- func (o *OrgSettings) RolesWith(caps OrgCaps) []string
- func (o *OrgSettings) StaleRoles(roles []string) []string
- func (o *OrgSettings) TeamRoleDeclared(role string) bool
- func (o *OrgSettings) TeamRoleNames() []string
- type PasskeySettings
- type PersonalData
- type Provider
- type PushDelivery
- type PushLimits
- type PushPlatform
- type PushSettings
- type RateLimit
- type RateSettings
- type ReadAccess
- type Realm
- type RealmSettings
- func (s RealmSettings) ActiveRoles(held []string, strategy string) (active, inactive []string)
- func (s RealmSettings) AdminAccess(roles []string) AdminAccess
- func (s RealmSettings) AdminRights(roles []string) AdminRights
- func (s RealmSettings) AdminRoles() []string
- func (s RealmSettings) AppConfigTTL() time.Duration
- func (s RealmSettings) AuditEnabled(action string) bool
- func (s RealmSettings) BestLocale(tags ...string) string
- func (s RealmSettings) ConsentNames() []string
- func (s RealmSettings) ConsentsPastDeadline(held map[string]string, now time.Time) []ConsentRef
- func (s RealmSettings) ConsentsToAccept(held map[string]string) []ConsentRef
- func (s RealmSettings) FullAdminRoles() []string
- func (s RealmSettings) IsAdmin(roles []string) bool
- func (s RealmSettings) Languages() (def string, list []string)
- func (s RealmSettings) ListedLocale(tag string) string
- func (s RealmSettings) ReauthLifetime() time.Duration
- func (s RealmSettings) SignInRedirectAllowed(raw string) bool
- func (s RealmSettings) StorageFor(public bool) *StorageSettings
- func (s RealmSettings) StrategyByName(name string) (Strategy, bool)
- func (s RealmSettings) StrategyFor(name, first string) (Strategy, error)
- func (s RealmSettings) TOTPRequired(roles []string) bool
- func (s RealmSettings) TOTPRoles() (roles []string, everyone bool)
- func (s RealmSettings) Throttle() LoginThrottle
- func (s RealmSettings) TriggerLimits(instance TriggerLimits) TriggerLimits
- type RealtimeSettings
- type Reference
- type Registry
- func (r *Registry) AggregateWarnings() []string
- func (r *Registry) AuthRealms() []string
- func (r *Registry) CheckAggregateLimits(instance AggregateLimits) error
- func (r *Registry) CheckBundles() error
- func (r *Registry) CheckExpandLimits(instanceMaxArray int) error
- func (r *Registry) CheckImageLimits(instance int64) error
- func (r *Registry) CheckTriggerLimits(instance TriggerLimits) error
- func (r *Registry) Collection(realm, database, collection string) (*Collection, bool)
- func (r *Registry) CompatibilityFindings() ([]CompatFinding, error)
- func (r *Registry) Databases() []*Database
- func (r *Registry) EventCollections() []EventCollection
- func (r *Registry) Fingerprint() (string, error)
- func (r *Registry) FunctionRealms(authEnabled bool) []string
- func (r *Registry) RealmNames() []string
- func (r *Registry) SortedRealms() []*Realm
- type Retry
- type Role
- type SchemaFiles
- type ScopeEntry
- type SecretRef
- type SoftDelete
- type Steps
- type StorageSettings
- type Strategy
- type TeamRole
- type TextField
- type TextIndex
- type Trigger
- type TriggerLimits
- type TriggerSettings
- type UserNetworks
- type Version
Constants ¶
const ( MethodPassword = "password" MethodPasskey = "passkey" MethodTOTP = "totp" MethodMagicLink = "magic_link" // MethodSSO is the sign-in through an organization's own connection (organizations.sso). MethodSSO = "sso" )
The methods a strategy is made of besides the names of providers (design/auth-strategies.md §2).
const ( ProofIP = "ip" ProofUserAgent = "user_agent" )
ConsentProof names what a consent record stores besides time, method and text hash.
const ( // MaxIDLength is the longest id any collection accepts. MaxIDLength = 128 // DefaultDuplicateLimit is how many duplicate creates a caller may attempt per minute when // the collection doesn't say. DefaultDuplicateLimit = 20 // MaxDuplicateLimit is the largest duplicate_limit. MaxDuplicateLimit = 1000 )
const ( ErasureDelete = "delete" ErasureAnonymize = "anonymize" )
Erasure actions on the documents a user owns.
const ( MatchEmail = "email" MatchID = "id" )
What a `pull` or `unset` field holds: the user's email or their id.
const ( UploadProxy = "proxy" // streamed through backd UploadDirect = "direct" // a signed PUT straight to the bucket )
Upload modes.
const ( FunctionsDir = "_functions" // one Deno project per database BuildDir = ".build" // bundles and their manifest, written by `backd-server functions build` // TypesFile is the generated registry of the project's types (`backd types --functions`): it // shapes no bundle, so it is not part of the source hash or the config fingerprint. TypesFile = "backd.d.ts" // RuntimeDir holds what `defineFunction` runs on (a hidden folder, never part of the config). RuntimeDir = ".backd" ManifestFile = "manifest.json" FunctionFile = "function.yaml" InputSchemaFile = "input.schema.json" OutputSchemaFile = "output.schema.json" )
Function layout inside a database directory.
const ( ModeSync = "sync" ModeAsync = "async" ModeWebhook = "webhook" )
Function modes.
const ( DefaultSyncTimeout = 10 * time.Second DefaultAsyncTimeout = 15 * time.Minute MaxSyncTimeout = 60 * time.Second MaxAsyncTimeout = 24 * time.Hour DefaultMemory = 128 << 20 DefaultMaxOutput = 1 << 20 MaxSyncOutput = 64 << 20 // MaxAsyncOutput keeps an async job's result within one MongoDB // document (16 MiB, minus room for the job's other fields). MaxAsyncOutput = 15 << 20 DefaultConcurrency = 10 )
Defaults and bounds of function.yaml values.
const ( CompleteOK = "ok" // the function returned CompleteFailed = "failed" // any other result: an error, a timeout, a crash CompleteCancelled = "cancelled" // an administrator cancelled the job )
The endings a job's on_complete notification can be limited to (`on`).
const ( OverlapAllow = "allow" OverlapSkip = "skip" )
What a scheduled time does while the function's previous run hasn't finished.
const ( StoreKeyword = "x-backd-store" StoreDate = "date" )
StoreKeyword is the schema.json keyword, on a property, that picks how its value is stored. The only choice is StoreDate: a `format: date-time` string is stored as a BSON Date, so queries and sorting compare dates.
const ( DefaultAccountThreshold = 5 DefaultIPThreshold = 50 DefaultThrottleWindow = 15 * time.Minute DefaultMaxDelay = 15 * time.Minute )
Defaults of login_throttle in realm.yaml: failures are counted per account and per client address in a sliding window, and past a threshold each new attempt waits twice as long as the one before, up to MaxDelay.
const ( DefaultOrgCreateRule = "user.email_verified" DefaultMaxCreatedPerUser = 5 DefaultMaxMembershipsPerUser = 100 DefaultMaxTeamsPerOrg = 100 DefaultMaxTeamsPerMember = 20 DefaultMaxPendingInvitations = 500 // MaxOrgClaimsBytes is the largest claims object of an organization. MaxOrgClaimsBytes = 1024 MembersVisibleToMembers = "members" MembersVisibleToManagers = "managers" // DefaultOrgInvitationTTL is how long an invitation lasts when the request doesn't say. DefaultOrgInvitationTTL = 7 * 24 * time.Hour // MaxOrgInvitationTTL is the longest an invitation may last. MaxOrgInvitationTTL = 30 * 24 * time.Hour )
Defaults of the organizations section.
const ( OrgNone = "none" OrgOptional = "optional" OrgRequired = "required" // OrgDelete and OrgKeep are on_org_delete.action. OrgDelete = "delete" OrgKeep = "keep" // InOrgKeep and InOrgApply are on_owner_delete.in_org. InOrgKeep = "keep" InOrgApply = "apply" // TeamNone, TeamOptional and TeamRequired are collection.yaml's team. TeamNone = "none" TeamOptional = "optional" TeamRequired = "required" )
Organization policies of a collection (collection.yaml's organization).
const ( ExportInclude = "include" ExportExclude = "exclude" )
What a collection contributes to a user's personal data export.
const ( PlatformAndroid = "android" PlatformIOS = "ios" PlatformWeb = "web" )
The platforms a device can be registered for.
const ( PushProviderFCM = "fcm" PushProviderAPNs = "apns" PushProviderWebPush = "webpush" PushProviderCapture = "capture" )
The built-in push providers.
const ( DefaultMaxDevicesPerUser = 10 DefaultDeviceStaleAfter = 60 * 24 * time.Hour )
Defaults of push.devices.
const ( DefaultPushTimeout = 60 * time.Second DefaultPushAttempts = 5 DefaultPushBackoff = 30 * time.Second DefaultPushParallelism = 20 DefaultPushPerMinute = 5 DefaultPushPerDay = 24 DefaultPushSendRetention = 30 * 24 * time.Hour )
Defaults of push.delivery, push.limits and push.send_retention.
const ( RateAnonymous = "anonymous" // a request without credentials, by client address RateRead = "read" // GET and HEAD, by principal RateWrite = "write" // everything else on the data routes, by principal RateAuth = "auth" // /_auth, before the caller is known, by client address RateFiles = "files" // file transfers, by principal RateAdmin = "admin" // /_admin, by principal )
The request classes of the built-in rate limiter (design/rate-limiting.md §3).
const ( SignupOpen = "open" SignupInvite = "invite" SignupClosed = "closed" )
Signup modes.
const ( DefaultIdleTimeout = 30 * 24 * time.Hour DefaultMaxLifetime = 90 * 24 * time.Hour DefaultAuditRetention = 365 * 24 * time.Hour // DefaultAppConfigCacheTTL is how long a client may use the app configuration without asking. DefaultAppConfigCacheTTL = 5 * time.Minute // DefaultLogRetention is functions.log_retention's default: a short // debugging window, not a log archive (see the docs). DefaultLogRetention = 7 * 24 * time.Hour // DefaultJobRetention is functions.job_retention's default: how long // an async job's result is kept once done (roadmap F11). DefaultJobRetention = 24 * time.Hour DefaultPasswordMinLength = 12 )
Defaults for realm settings left out of realm.yaml.
const ( DefaultEmailPerKindPerHour = 3 DefaultEmailPerDay = 10 DefaultEmailPerIPPerHour = 20 // The caps of custom emails from functions. DefaultEmailPerFunctionPerHour = 200 DefaultEmailPerInvocation = 50 DefaultEmailRecipientsPerMessage = 10 // DefaultLocale is the realm's default_locale when it sets none. DefaultLocale = "en" )
Defaults of email.limits.
const ( // CompatRefuses: version N refuses a write that version N-1 allowed (apps on N-1 get 400). CompatRefuses = "refuses" // CompatDrops: version N no longer declares a field N-1 declared (apps on N-1 read documents without it). CompatDrops = "drops" // CompatType: version N changes a field's type (both of the above). CompatType = "type" // CompatUnsure: a keyword the check can't compare soundly. CompatUnsure = "unsure" )
Kinds of compatibility finding (design/schema-versioning.md §6.2).
const ( DefaultDomainsPerOrg = 10 MaxDomainsPerOrg = 100 DefaultDomainRecheck = 7 * 24 * time.Hour MinDomainRecheck = time.Hour DefaultDomainLapseAfter = 3 MaxDomainLapseAfter = 20 )
Defaults and limits of organizations.domains.
const ( ProviderGoogle = "google" ProviderMicrosoft = "microsoft" ProviderApple = "apple" ProviderGitHub = "github" )
The built-in providers, which are reserved names. A built-in provider's kind is its name.
const ( ProviderTypeOIDC = "oidc" ProviderTypeOAuth2 = "oauth2" )
The `type:` of a generic provider, which any name may take: OpenID Connect, or a plain OAuth 2 service described field by field.
const ( MetaDeletedAt = "_meta.deleted_at" MetaDeletedBy = "_meta.deleted_by" MetaPurgeAt = "_meta.purge_at" )
The _meta fields of a soft-deleted document: when it was deleted, by whom, and when it goes for good (only with a retention).
const ( DefaultPresignedTTL = 5 * time.Minute DefaultPendingTTL = time.Hour // Download modes. DownloadPresigned = "presigned" DownloadProxy = "proxy" )
Storage defaults and bounds (storage in realm.yaml).
const ( TriggerCreated = "created" TriggerUpdated = "updated" TriggerRemoved = "removed" )
The events of a trigger, in the vocabulary realtime shares (design/triggers-and-realtime.md §1).
const AppConfigDir = "config"
AppConfigDir is the folder of _realm that declares the realm's app configuration: <realm>/_realm/config/schema.json and rules.yaml.
const AppConfigMaxBytes = 64 << 10
AppConfigMaxBytes is the most the whole configuration, defaults included, may take once encoded.
const AuditEntriesChanged = "audit.entries_changed"
AuditEntriesChanged is recorded at start when `audit.entries` changed since the last start. It is how a change to the trail is itself visible, so it can't be switched off and is not in AuditActions.
const BlindPrefix = "_bidx."
BlindPrefix starts the name of every blind index field.
const BlindRoot = "_bidx"
BlindRoot is the document field that holds the blind indexes.
const CollectionFile = "collection.yaml"
CollectionFile is the optional file next to a collection's schema.json holding its data policy for an erased user.
const ComplianceDir = "compliance"
ComplianceDir is the folder of _realm that holds the realm's compliance files: today the README templates of personal data exports (_realm/compliance/readme/<locale>.html).
const ConsentPseudonymSecret = "BACKD_CONSENT_PSEUDONYM_KEY"
ConsentPseudonymSecret is the realm secret that keys the pseudonym consent records keep of an erased person (design/compliance.md §8).
const ConsentsDir = "consents"
ConsentsDir is the folder of _realm that holds the consent texts: <realm>/_realm/consents/<name>/<version>/<locale>.md.
const DefaultConsentRetention = 3 * 365 * 24 * time.Hour
DefaultConsentRetention is how long consent records are kept after their user was erased, when the realm doesn't say (compliance.consent_retention).
const DefaultExpandMaxArray = 100
DefaultExpandMaxArray is the most ids of one `many` reference an expansion follows when the instance sets no other value (BACKD_EXPAND_MAX_ARRAY).
const DefaultExportRetention = 7 * 24 * time.Hour
DefaultExportRetention is how long a personal data export is kept before it is deleted.
const DefaultReauthTTL = 5 * time.Minute
DefaultReauthTTL is how long a re-authentication token works when the realm doesn't say.
const DefaultRedirectDelay = 3 * time.Second
DefaultRedirectDelay is email.redirect_delay when not set.
const DefaultResetPasswordTTL = time.Hour
DefaultResetPasswordTTL is account.tokens.reset_password when not set.
const DefaultVerifyEmailTTL = 48 * time.Hour
DefaultVerifyEmailTTL is account.tokens.verify_email when not set.
const DenoVersion = "2.9.8"
DenoVersion is the Deno version functions are bundled and run with. `backd-server functions build` requires exactly this version, and the executor image is built from it.
const EncRoot = "_enc"
EncRoot is the document field that records, per encrypted field, the id of the data key its value is sealed with, so a count can tell current values from old ones without opening them.
const FilesLinkKeySecret = "BACKD_FILES_LINK_KEY"
FilesLinkKeySecret is the realm secret that signs backd's own links to files.
const IndexTextName = "backd_text"
IndexTextName is the name of the collection's text index in MongoDB.
const MaxAggregateGroupBy = 3
MaxAggregateGroupBy is how many fields one aggregation may group by.
const MaxCacheAge = 3600
MaxCacheAge is the longest `cache.max_age` a collection may declare, in seconds.
const MaxCallChain = 4
MaxCallChain is the longest chain of functions calling each other, the entry function included.
const ( // MaxMultipartFileSize is the largest direct upload where the provider takes a multipart one: // 1000 parts of at most about 4.2 GiB (a part may be 5 GiB). MaxMultipartFileSize = 4 << 40 )
const MaxTeamRolesPerMember = 50
MaxTeamRolesPerMember is the most team role grants one member may hold in an organization.
const MaxTriggerChain = 64
MaxTriggerChain is the highest depth any configuration may allow.
const MetaOrg = "_meta.org"
MetaOrg is the system field that holds the organization a document belongs to. It exists only in collections that can belong to one (collection.yaml's organization).
const MetaSchemaVersion = "_meta.schema_version"
MetaSchemaVersion is the stamp of the schema version a document was written under.
const MetaTeam = "_meta.team"
MetaTeam is the system field that holds the team a document belongs to, within its organization. It exists only in collections with `team` set.
const MigrationsDir = "_migrations"
MigrationsDir is the folder of a database that holds the built migration bundles, in MigrationsDir/BuildDir. It is a build output, not a folder anyone writes in: the sources are the schema.v<N>.ts files of each collection (design/schema-versioning.md §6.1).
const RealmDir = "_realm"
RealmDir is the folder of a realm that holds what the realm shows and configures, as opposed to its data: the email templates and hosted pages, the push templates, the consent texts, the compliance files and the app configuration (design/realm-layout.md). realm.yaml stays next to it. A folder of a realm whose name starts with "_" is never a database: this is the only one defined.
const RealmFile = "realm.yaml"
RealmFile is the name of the required realm settings file.
const (
// SchemaFile is the name of a collection's schema file.
SchemaFile = schemaFile
)
const SearchEquality = "equality"
SearchEquality is the only kind of search an encrypted field offers.
const SystemDatabaseSuffix = "___system"
SystemDatabaseSuffix is appended to a realm name to form the MongoDB database holding the realm's users, sessions and keys.
const TextSearchField = "_search_lang"
TextSearchField is the stored field that holds a document's text-search language: the language_field's value mapped to a language the database knows. It is server-owned and never part of a document's API shape.
Variables ¶
var ( // ErrStrategyRequired: the call named no strategy and more than one starts with its method. ErrStrategyRequired = errors.New("strategy is required: more than one strategy starts with this method") // ErrUnknownStrategy: no strategy of that name, or it does not start with the method of // the call. The same answer for both, so it tells nothing else. ErrUnknownStrategy = errors.New("unknown strategy") )
The errors of choosing a strategy to sign in with.
var AllMethods = []string{MethodPassword, MethodPasskey, MethodTOTP, MethodMagicLink, MethodSSO}
AllMethods lists the Method constants.
var AuditActions = []AuditAction{}/* 138 elements not displayed */
AuditActions lists every configurable audit action, grouped for the template.
var AuditGroups = []string{
"sign-in",
"users, roles, sessions and keys",
"second factors and passkeys",
"sign-in methods",
"organizations",
"data, export and import",
"operations",
}
AuditGroups lists the groups of AuditActions in the order the template writes them.
var BuiltinProviders = []string{ProviderApple, ProviderGitHub, ProviderGoogle, ProviderMicrosoft}
BuiltinProviders are the providers backd knows, sorted.
var DefaultAggregateLimits = AggregateLimits{Time: 5 * time.Second, MaxGroups: 1000}
DefaultAggregateLimits are the limits when the instance sets none.
var DefaultExpandLimits = ExpandLimits{MaxDepth: 2, MaxPaths: 5, MaxArray: 100, MaxDocs: 2000}
DefaultExpandLimits are the limits when the instance sets none.
var DefaultRates = map[string]ratelimit.Rate{ RateAnonymous: {Limit: 120, Window: time.Minute}, RateRead: {Limit: 600, Window: time.Minute}, RateWrite: {Limit: 120, Window: time.Minute}, RateAuth: {Limit: 30, Window: time.Minute}, RateFiles: {Limit: 120, Window: time.Minute}, RateAdmin: {Limit: 300, Window: time.Minute}, }
DefaultRates are the limits of each class when nothing sets them: generous enough that a normal app never meets them, low enough to stop a loop in a script.
var DefaultSSOProviders = []string{ProviderGoogle, ProviderMicrosoft}
DefaultSSOProviders are the ones organization sign-in offers when organizations.sso names none: generic OpenID Connect needs the realm's list of issuers, so it is asked for.
var DefaultTriggerLimits = TriggerLimits{MaxChain: 16, MaxChainedPerMinute: 60, MaxPerCollection: 20, MaxBacklog: 100000}
DefaultTriggerLimits are the limits when nothing sets them.
var DefaultWebEndpointHosts = []string{
"fcm.googleapis.com",
"updates.push.services.mozilla.com",
"web.push.apple.com",
"*.notify.windows.com",
}
DefaultWebEndpointHosts are the push services of the major browsers.
var Normalizations = []string{"trim", "lower", "upper"}
Normalizations a blind index applies before hashing, by name.
var Platforms = []string{PlatformAndroid, PlatformIOS, PlatformWeb}
Platforms lists the platforms in the order they are shown.
var PublicTypes = []string{"image/jpeg", "image/png"}
PublicTypes are the only content types a public field takes (design/public-files.md).
var RateClasses = []string{RateAnonymous, RateRead, RateWrite, RateAuth, RateFiles, RateAdmin}
RateClasses lists the classes in the order the documentation and the start-up log give them.
var RealmFolders = []string{email.DirName, email.PagesDirName, push.DirName, ConsentsDir, ComplianceDir, AppConfigDir}
RealmFolders are the folders _realm may hold.
var ReferenceSources = []string{"_meta.owner", "_meta.created_by"}
ReferenceSources are the system fields a reference may read its value from.
var ReservedProviderNames = []string{"password", "email", "sso", kindOIDC, kindOAuth2}
ReservedProviderNames are the names no provider may take: backd's own sign-in methods (an identity's provider is `password`, magic links record `email`, a strategy method is `sso`) and the kinds still to come.
var SSOProviders = func() []string { var out []string for _, name := range append(slices.Clone(BuiltinProviders), kindOIDC) { if kindSpecs[name].orgs { out = append(out, name) } } slices.Sort(out) return out }()
SSOProviders are the providers an organization may connect, sorted: the built-in providers that can tell a company's people from anyone else's (Google by Workspace, Microsoft by tenant) and generic OpenID Connect, which a verified domain does.
SharedMicrosoftTenants are the tenant values that admit people of any organization.
var SystemFields = []string{"id", "_meta.created_at", "_meta.updated_at", "_meta.version", MetaSchemaVersion, "_meta.owner", "_meta.created_by", "_meta.updated_by", MetaDeletedAt, MetaDeletedBy, MetaPurgeAt}
SystemFields are the server-owned fields that can be queried, sorted and indexed in addition to the schema's fields.
Functions ¶
func AnonymizeRules ¶ added in v0.9.1
AnonymizeRules works out, for every collection of the realm that has one, what an anonymized export does: the collection's erase policy (its `remove` and `replace`, whatever its action) with the overrides on top. An override is checked against the collection's schema like an erase policy is; the problems of all of them are reported together.
func BlindField ¶ added in v0.9.1
BlindField is the hidden field of a document that holds the blind index of the encrypted field at path: `_bidx.` followed by the path with its dots replaced (a field name has none).
func CheckMigrationImports ¶ added in v0.9.11
CheckMigrationImports refuses a migration file with any import other than `import type { ... } from "./schema.d.ts"` (design §5.1): a value import would need a runtime and could pull code from anywhere. The error names the file and the line.
func ClientIDListProblems ¶ added in v0.9.3
ClientIDListProblems checks a list of extra audiences (native app client ids): each a valid id, none twice. Messages start with field[index].
func ClientIDProblem ¶ added in v0.9.3
ClientIDProblem checks the client id of a Google or Microsoft application (Microsoft: a GUID).
func DomainProblem ¶ added in v0.9.3
DomainProblem checks a lower-case domain name such as acme.example: a Google Workspace domain or an email domain.
func EnvelopeProblem ¶ added in v0.8.2
EnvelopeProblem checks what every custom id must satisfy whatever the collection's pattern: 1 to 128 characters, only letters, digits and - . _ ~ : @, not starting with _ or . and without "..". It returns "" when id is inside the envelope.
func FormatRate ¶ added in v0.9.12
FormatRate is a Rate as ParseRate reads it.
func HasSchema ¶ added in v0.9.11
HasSchema reports whether dir holds a collection's schema: a schema.json or a schema.vN.json.
func IsAuditAction ¶ added in v0.9.12
IsAuditAction reports whether name is an audit action that audit.entries can name.
func IsRateClass ¶ added in v0.9.12
IsRateClass reports whether name is a request class.
func MarkerField ¶ added in v0.9.1
MarkerField is the name an encrypted field has inside the BlindRoot and EncRoot maps.
func MigrationSourceHash ¶ added in v0.9.11
MigrationSourceHash hashes the migration sources of db: the name and content of every schema.v<N>.ts of its collections. The generated schema.d.ts shapes no bundle, so it is out.
func NormalizeEmail ¶
NormalizeEmail trims and lowercases an email address and checks its basic shape (one "@" with text on both sides, no spaces). The reserved ".invalid" top-level domain (RFC 2606) is refused: it never receives mail, and erased users' placeholder addresses live there, so nobody may take one. Characters that delimit addresses or break a header (commas, angle brackets, quotes, control characters...) are refused as well: a delivery function that joins recipients with commas must never see one address that is really two.
func OrgProviderCallbackPath ¶ added in v0.9.3
OrgProviderCallbackPath is where a provider sends the user back to after an organization's sign-in, relative to backd's public address: the URL a manager registers in the provider's console. It always names the organization by its id.
func ParamsFingerprint ¶ added in v0.8.1
ParamsFingerprint is Fingerprint for parameters that aren't a declared version's, such as the ones a function generates with.
func ParseAnonymizeConfig ¶ added in v0.9.1
func ParseAnonymizeConfig(data []byte) (map[string]AnonOverride, error)
ParseAnonymizeConfig reads an --anonymize-config file:
collections:
<database>/<collection>:
remove: [field, …]
replace: {field: value}
func ParseRate ¶ added in v0.9.12
ParseRate reads "<requests>/<window>", such as "600/1m" or "30/10s". "none" is no limit (the zero Rate). Requests is a positive integer and the window a duration of at least a second.
func ProviderCallbackPath ¶ added in v0.8.2
ProviderCallbackPath is where a provider sends the user back to, relative to backd's public address: the URL to register in the provider's console.
func RealmPath ¶ added in v0.9.2
RealmPath returns a path inside the _realm folder of the realm at realmPath.
func RealtimeChanged ¶ added in v0.8.5
RealtimeChanged lists the realtime collections of old (as "<mongo database>\x00<name>") whose subscriptions no longer follow the configuration in next: they lost the opt-in, were removed, or what shows their documents changed.
func SameBucket ¶ added in v0.9.5
func SameBucket(a, b *StorageSettings) bool
SameBucket reports whether two storages are the same bucket on the same endpoint: a public storage there would publish the private files.
func SchemaMigrationFile ¶ added in v0.9.11
SchemaMigrationFile is the name of the migration to version n.
func SchemaVersionFile ¶ added in v0.9.11
SchemaVersionFile is the name of version n's schema file.
func SearchLanguage ¶ added in v0.8.4
SearchLanguage maps a locale code (`es`, `es-MX`, `pt_BR`) to the language the database uses to stem it, or "none" when it has none (the text is then indexed without stemming).
func SourceHash ¶
SourceHash hashes every file of a functions project, except hidden entries (such as .build), so any change to code, shared lib/, deno.json, deno.lock or schemas changes it.
func TenantProblem ¶ added in v0.9.3
TenantProblem checks a Microsoft tenant: a tenant id (GUID), and with shared also common, organizations and consumers. An organization's connection must name its own tenant.
func ValidSecretName ¶
ValidSecretName reports whether name is a valid secret NAME (upper-case letters, digits and _, starting with a letter) — the same rule function.yaml's secrets list is checked against, without the leading "realm." a reference may carry.
func ValidateVersionParams ¶ added in v0.8.1
ValidateVersionParams reports what is wrong with parameters given at run time (by a function), with the same rules `versions:` is parsed with.
Types ¶
type AccountSettings ¶ added in v0.4.0
type AccountSettings struct {
// RequireVerifiedEmail: no session until the address is verified.
RequireVerifiedEmail bool
// WelcomeEmail sends the welcome email once the address is verified.
WelcomeEmail bool
// VerifyEmailTTL is how long a verification link works (account.tokens.verify_email).
VerifyEmailTTL time.Duration
// AllowEmailChange lets users change their own address (`POST /_auth/email`).
AllowEmailChange bool
// ChangeEmailTTL and RevertEmailChangeTTL are how long the confirmation
// and the undo link of an email change work.
ChangeEmailTTL, RevertEmailChangeTTL time.Duration
// ResetPasswordTTL is how long a reset link works (account.tokens.reset_password).
ResetPasswordTTL time.Duration
// PurgeUnverifiedAfter deletes accounts that never verified; 0 is off.
PurgeUnverifiedAfter time.Duration
// OnSignup is the internal, async function (<database>/<function>) called for every
// new user (account.on_signup), to create the app's profile document; OnSignupTimeout
// is its timeout.
OnSignup string
OnSignupTimeout time.Duration
}
AccountSettings are the account lifecycle settings of a realm.
func (AccountSettings) OnSignupDatabaseAndName ¶ added in v0.8.2
func (a AccountSettings) OnSignupDatabaseAndName() (string, string)
OnSignupDatabaseAndName splits OnSignup.
func (AccountSettings) TokenLifetime ¶ added in v0.4.0
func (a AccountSettings) TokenLifetime(p email.Purpose) time.Duration
TokenLifetime is how long a token of this purpose works in the realm.
type AdminAccess ¶ added in v0.7.0
type AdminAccess struct {
Write AdminRights
ReadAll bool
}
AdminAccess is what a user's admin roles let them do in the admin API: change some areas, and/or read every area (a read-only level, `admin: read`). Roles add up.
func (AdminAccess) Any ¶ added in v0.7.0
func (a AdminAccess) Any() bool
Any reports whether the access makes someone an administrator at all.
func (AdminAccess) CanRead ¶ added in v0.7.0
func (a AdminAccess) CanRead(s RealmSettings, want AdminRights) bool
CanRead reports whether the areas in want may be read: what the access changes it reads too; a read-only level reads every area except users and data, which realm.yaml's admin.read_access has to grant.
func (AdminAccess) CanWrite ¶ added in v0.7.0
func (a AdminAccess) CanWrite(want AdminRights) bool
CanWrite reports whether the areas in want may be changed.
func (AdminAccess) Covers ¶ added in v0.7.0
func (a AdminAccess) Covers(b AdminAccess) bool
Covers reports whether a can do everything b can: nobody hands out, or changes someone who holds, more than they have.
func (AdminAccess) Full ¶ added in v0.7.0
func (a AdminAccess) Full() bool
Full reports whether it is `admin: true`: every area, to change.
func (AdminAccess) String ¶ added in v0.7.0
func (a AdminAccess) String() string
String describes the access, for messages.
type AdminRights ¶ added in v0.6.0
type AdminRights uint8
AdminRights is the part of the admin API a role opens: a set of areas. `admin: true` in realm.yaml is every area (and any area added later); `admin: [users, invitations]` is just those. The zero value is none.
const ( RightUsers AdminRights = 1 << iota // users, their roles, passwords, addresses, networks, erasure RightInvitations // invitations RightAPIKeys // API keys RightSecrets // secrets RightAudit // the audit trail RightFunctions // running functions by hand, their invocations and every job RightData // the admin data route: documents, past their collections' rules RightConfig // the read-only view of the realm's configuration // AllRights is `admin: true`. AllRights = RightUsers | RightInvitations | RightAPIKeys | RightSecrets | RightAudit | RightFunctions | RightData | RightConfig )
func RightNamed ¶ added in v0.6.0
func RightNamed(name string) (AdminRights, bool)
RightNamed is the right of a name used in realm.yaml and the docs.
func (AdminRights) Any ¶ added in v0.6.0
func (r AdminRights) Any() bool
Any reports whether r opens anything: whether holding it makes someone an administrator.
func (AdminRights) Has ¶ added in v0.6.0
func (r AdminRights) Has(want AdminRights) bool
Has reports whether r includes every right in want.
func (AdminRights) Names ¶ added in v0.6.0
func (r AdminRights) Names() []string
Names lists the rights by name, in the documented order; "all" for every right.
func (AdminRights) String ¶ added in v0.6.0
func (r AdminRights) String() string
String is the names, comma separated ("none" for no right).
type Aggregate ¶ added in v0.8.4
type Aggregate struct {
GroupBy []string // fields a request may group by, in declaration order
Metrics []string // numeric (and date) fields a request may sum, average, min or max
// Time and MaxGroups lower the instance's limits for this collection; 0 uses the instance's.
Time time.Duration
MaxGroups int
}
Aggregate is collection.yaml's `aggregate:`: which fields of the collection can be grouped and measured by the aggregate endpoint. A collection without it can't be aggregated.
func (*Aggregate) EffectiveMaxGroups ¶ added in v0.8.4
func (a *Aggregate) EffectiveMaxGroups(instance AggregateLimits) int
EffectiveMaxGroups is the group limit of one aggregation of c.
func (*Aggregate) EffectiveTime ¶ added in v0.8.4
func (a *Aggregate) EffectiveTime(instance AggregateLimits) time.Duration
EffectiveTime is the time limit of one aggregation of c: the collection's, never above the instance's.
type AggregateLimits ¶ added in v0.8.4
type AggregateLimits struct {
Time time.Duration // the most time one aggregation may run
MaxGroups int // the most groups one aggregation may return
}
AggregateLimits are what an aggregation may cost on this instance; a collection may only lower them (collection.yaml's aggregate.limits).
func (AggregateLimits) OrDefault ¶ added in v0.8.4
func (l AggregateLimits) OrDefault() AggregateLimits
OrDefault fills the limits that are zero with the defaults.
type AnonOverride ¶ added in v0.9.1
type AnonOverride struct {
Remove []string `yaml:"remove"`
Replace map[string]any `yaml:"replace"`
}
AnonOverride is one collection's entry of an --anonymize-config file.
type AnonRule ¶ added in v0.9.1
type AnonRule struct {
Remove []string
Replace map[string]any
// Emails are fields (strings, or arrays of strings) that hold the email of a user: the
// `pull` and `unset` fields of the collection's erase policy that say `email`.
Emails []string
}
AnonRule is what an anonymized export does to every document of one collection: the fields it removes, the fields it sets to a fixed value and the fields that hold a user's email, whose addresses are rewritten like the users'.
type AppConfig ¶ added in v0.8.2
type AppConfig struct {
SchemaPath string
RulesPath string // rules.yaml, whether or not the file exists
RawSchema map[string]any
Schema *jsonschema.Schema
// Paths holds every declared path (dot notation, `features.reports.enabled`);
// a path is a branch (an object) or a leaf (a value).
Paths map[string]ConfigPath
// Defaults is the whole configuration with every leaf at its default.
Defaults map[string]any
// Rules are the read rules by path, as written; use Effective for what applies.
Rules map[string]*rules.Rule
}
AppConfig is a realm's declared app configuration (<realm>/_realm/config/): the keys, their types and defaults, and who may read which path.
func (*AppConfig) Effective ¶ added in v0.8.2
Effective returns the rules that apply to a path: its own rule and those of every ancestor, all of which must allow the read. It reports false when nothing in the chain has a rule, which means clients can't read the path.
func (*AppConfig) HasPath ¶ added in v0.8.2
HasPath reports whether the path is declared, as a branch or as a leaf.
func (*AppConfig) SortedPaths ¶ added in v0.8.2
SortedPaths lists the declared paths in order.
type AuditAction ¶ added in v0.9.12
type AuditAction struct {
Name string
Group string // the heading the template writes it under
// Off is true for the actions that are not recorded unless the realm turns them on.
Off bool
}
AuditAction is one entry of the audit trail that a realm can switch on or off with `audit.entries` in realm.yaml (design/sign-in-audit.md). Every action the server records is in AuditActions; a test fails when one is recorded that is not, which is what lets the setting cover actions added later.
type CachePolicy ¶ added in v0.8.2
CachePolicy is collection.yaml's cache: the collection's anonymous reads may be stored by shared caches (CDNs) for MaxAge seconds. Everything else stays private, no-cache.
type Collection ¶
type Collection struct {
Realm string
Database string
MongoDatabase string // <realm>__<database>
Name string
SchemaPath string // path of the current schema file, for error messages
// SchemaVersion is the current version: the highest schema.vN.json, 1 for a plain schema.json.
// Versioned is true with schema.vN.json files: only then are documents stamped with
// _meta.schema_version (a missing stamp reads as 1). MinSchemaVersion is collection.yaml's
// min_schema_version, 0 when unset. SchemaVersions lists the kept versions.
SchemaVersion int
Versioned bool
MinSchemaVersion int
SchemaVersions []int
// Migrations lists the N of every schema.vN.ts: the step from N-1 to N. Dir is the
// collection's folder.
Migrations []int
Dir string
RawSchema map[string]any // decoded schema.json (numbers as json.Number)
Schema *jsonschema.Schema // compiled draft 2020-12 schema
Fields map[string]Field // dot path → field info, for query checks
Defaults []Default // schema.json's `default` values, parents first; filled in on create and PUT
Indexes []Index // declared in indexes.json
IndexPath string // path of indexes.json, when present
Rules *rules.Set // from collection.yaml's rules:; nil allows nothing
Erasure *ErasurePolicy // from collection.yaml; nil: an erase leaves the collection alone
ErasurePath string // path of collection.yaml, for error messages
SoftDelete *SoftDelete // from collection.yaml; nil: DELETE removes the document
PersonalData *PersonalData // from collection.yaml's personal_data:; nil: owned documents, whole
Cache *CachePolicy // from collection.yaml's cache:; nil: responses are private, no-cache
CustomID *CustomID // from collection.yaml's custom_id:; nil: the server generates the ids
References map[string]*Reference // from collection.yaml's references:, by name; nil: none
Aggregate *Aggregate // from collection.yaml's aggregate:; nil: not aggregatable
Text *TextIndex // from indexes.json's text entry; nil: no full-text search
Realtime bool // from collection.yaml's realtime:; its changes may be streamed to clients
Triggers []*Trigger // from collection.yaml's triggers:, by name; nil: none
// Organization is collection.yaml's organization: OrgRequired, OrgOptional or OrgNone (also ""
// for collections loaded without the section). OnOrgDelete is OrgDelete or OrgKeep, and
// OwnerDeleteInOrg InOrgKeep or InOrgApply, both only with an organization.
Organization string
OnOrgDelete string
OwnerDeleteInOrg string
// Team is collection.yaml's team: TeamRequired, TeamOptional or TeamNone (needs an
// organization); OnTeamDelete is OrgDelete or OrgKeep, set with a team.
Team string
OnTeamDelete string
Encrypted []EncryptedField // collection.yaml's fields:, sorted by path; nil: none
Files map[string]*FileField // file fields from collection.yaml's files:; their schema is already in Schema and RawSchema
// contains filtered or unexported fields
}
Collection is a set of documents validated by one JSON Schema.
func (*Collection) AggregateIndexWarnings ¶ added in v0.8.4
func (c *Collection) AggregateIndexWarnings() []string
AggregateIndexWarnings names the group_by fields that no index of the collection leads with, with the index to add: grouping on them scans every matching document, unsorted.
func (*Collection) ApplyDefaults ¶ added in v0.9.12
func (c *Collection) ApplyDefaults(doc map[string]any) map[string]any
ApplyDefaults fills the schema's `default` values into doc (user fields only) wherever the field is absent. An explicit null is a value and is kept. A default inside an object is applied only when that object is present, or was itself just filled. It returns doc.
func (*Collection) ArrayField ¶
func (c *Collection) ArrayField(path string) bool
ArrayField reports whether path is declared as an array (only), with no array on the way to it.
func (*Collection) CompatibilityFindings ¶ added in v0.9.11
func (c *Collection) CompatibilityFindings() ([]CompatFinding, error)
CompatibilityFindings compares each kept schema.vN.json of a versioned collection with the one below it, statically, and lists what a change breaks for the apps still on the lower version. It is a sound subset of JSON Schema comparison, not a full one: keywords it can't compare are reported as "can't tell, check by hand" rather than guessed. It never fails the build.
func (*Collection) ConfigPath ¶ added in v0.8.4
func (c *Collection) ConfigPath() string
ConfigPath is the collection.yaml of c, for messages.
func (*Collection) DateField ¶ added in v0.5.0
func (c *Collection) DateField(path string) bool
DateField reports whether path is stored as a BSON Date.
func (*Collection) DatesToStorage ¶ added in v0.5.0
func (c *Collection) DatesToStorage(doc map[string]any) map[string]any
DatesToStorage returns doc with the date fields converted to time.Time. doc itself is left alone (a request may be retried with the same body). A field that is absent or null stays so.
func (*Collection) EncryptedAt ¶ added in v0.9.1
func (c *Collection) EncryptedAt(path string) (EncryptedField, bool)
EncryptedField returns the encrypted field at path.
func (*Collection) HasPublicFiles ¶ added in v0.9.5
func (c *Collection) HasPublicFiles() bool
HasPublicFiles reports whether any file field of the collection is public.
func (*Collection) InOrganizations ¶ added in v0.8.3
func (c *Collection) InOrganizations() bool
InOrganizations reports whether documents of the collection can belong to an organization.
func (*Collection) InTeams ¶ added in v0.8.3
func (c *Collection) InTeams() bool
InTeams reports whether documents of the collection can belong to a team.
func (*Collection) IsEncrypted ¶ added in v0.9.1
func (c *Collection) IsEncrypted(path string) bool
IsEncrypted reports whether path is an encrypted field or inside one.
func (*Collection) IsKnownField ¶
func (c *Collection) IsKnownField(path string) bool
IsKnownField reports whether path is a system field or declared in the schema.
func (*Collection) IsSearchable ¶ added in v0.9.1
func (c *Collection) IsSearchable(path string) bool
IsSearchable reports whether path is an encrypted field with a blind index.
func (*Collection) NeedsEvents ¶ added in v0.8.5
func (c *Collection) NeedsEvents() bool
NeedsEvents reports whether the collection's changes are read from the change stream: it is realtime, or it has triggers. Such a collection needs pre-change images.
func (*Collection) ParentTargets ¶ added in v0.9.8
func (c *Collection) ParentTargets() []*Reference
ParentTargets are the references the collection's read rule follows with parent(), in the order the rule uses them.
func (*Collection) RevealUsesConfig ¶ added in v0.9.1
func (c *Collection) RevealUsesConfig() bool
RevealUsesConfig reports whether a reveal rule reads the app configuration.
func (*Collection) RevealUsesOrgs ¶ added in v0.9.1
func (c *Collection) RevealUsesOrgs() bool
RevealUsesOrgs reports whether a reveal rule needs the caller's organization memberships.
func (*Collection) Revealing ¶ added in v0.9.1
func (c *Collection) Revealing() []EncryptedField
Revealing lists the encrypted fields that have a reveal rule.
func (*Collection) ScalarField ¶
func (c *Collection) ScalarField(path string) bool
ScalarField reports whether path holds a single value: a system field, or a declared field whose types exclude "array", with no array on the way to it.
func (*Collection) Searchable ¶ added in v0.9.1
func (c *Collection) Searchable() []EncryptedField
Searchable lists the encrypted fields that have a blind index.
func (*Collection) StampSchemaVersion ¶ added in v0.9.11
func (c *Collection) StampSchemaVersion(meta map[string]any)
StampSchemaVersion sets meta's schema_version to the collection's current version when it has versioned schema files (an unversioned collection stamps nothing). Writes call it for the content they store: create, PUT, PATCH and the batch operations.
func (*Collection) StampSchemaVersionAs ¶ added in v0.9.11
func (c *Collection) StampSchemaVersionAs(meta map[string]any, version int)
StampSchemaVersionAs is StampSchemaVersion with the version the app declared for the write (design §9.2): a v1 app editing a document stores it as v1, and the migration job moves it up again.
func (*Collection) VersionSchema ¶ added in v0.9.11
func (c *Collection) VersionSchema(n int) (map[string]any, error)
VersionSchema reads the schema of one kept version as the author wrote it (numbers as json.Number). It is for the tools that look at old versions (backd types and the compatibility check): the server compiles and keeps only the current schema.
type CompatFinding ¶ added in v0.9.11
type CompatFinding struct {
Collection string // <database>/<collection>
From, To int // the versions compared: To is From+1 in the kept chain
Kind string
Path string // the field, dotted; "" for the document itself
Rule string // the keyword
Message string
// Note is true when min_schema_version already turns the affected apps away: the finding is
// what the developer chose, not a surprise.
Note bool
}
CompatFinding is one way a schema version breaks the one below it.
func (CompatFinding) String ¶ added in v0.9.11
func (f CompatFinding) String() string
type ComplianceSettings ¶ added in v0.8.2
type ComplianceSettings struct {
// ConsentProof lists what each consent record stores besides time, method and
// text hash: ProofIP and ProofUserAgent. Both by default.
ConsentProof []string
// ConsentRetention is how long records are kept after erasure; 0 deletes them at erasure.
ConsentRetention time.Duration
// ConsentRetentionSet says whether realm.yaml chose a retention (0 is a choice).
ConsentRetentionSet bool
// Export turns on the export of a user's personal data (compliance.export): users can
// ask for their data and support can produce it. It needs the realm's file storage.
Export bool
// ExportPage is the app's page the "your export is ready" email links to; it is within
// the realm's allowed redirects. ExportRetention is how long a package is kept.
ExportPage string
ExportRetention time.Duration
}
ComplianceSettings are the realm's compliance settings (compliance in realm.yaml).
func (ComplianceSettings) ExportKeep ¶ added in v0.9.2
func (c ComplianceSettings) ExportKeep() time.Duration
ExportKeep is how long a personal data export is kept: the realm's choice, or the default.
func (ComplianceSettings) Proof ¶ added in v0.8.2
func (c ComplianceSettings) Proof(what string) bool
Proof reports whether records store the given proof ("ip" or "user_agent").
func (ComplianceSettings) Retention ¶ added in v0.8.2
func (c ComplianceSettings) Retention() time.Duration
Retention is how long consent records outlive their user: the realm's choice, or the default.
type ConfigPath ¶ added in v0.8.2
ConfigPath is one declared path of the configuration.
type Consent ¶ added in v0.8.2
type Consent struct {
Name string
// Required consents must be accepted to have an account; optional ones can be
// given and withdrawn at will.
Required bool
// Current is the version new accounts accept.
Current string
// Versions are the versions realm.yaml says something about, plus the current one.
Versions map[string]*ConsentVersion
// Texts holds the loaded texts by version and locale.
Texts map[string]map[string]ConsentText
}
Consent is one consent a realm asks for (consents in realm.yaml): a name, the version in force, and the texts of every version, per language.
type ConsentRef ¶ added in v0.8.2
type ConsentRef struct{ Name, Version string }
ConsentRef names a consent and a version of it.
type ConsentText ¶ added in v0.8.2
ConsentText is the exact text of a version in one language, with its SHA-256.
type ConsentVersion ¶ added in v0.8.2
type ConsentVersion struct {
// Reaccept asks users who accepted an earlier version to accept this one.
Reaccept bool
// ReacceptBy is the date after which open sessions of users who haven't accepted are
// refused; the zero time means sessions continue until the user signs in again.
ReacceptBy time.Time
}
ConsentVersion is what realm.yaml says about one version of a consent.
type CookieSettings ¶ added in v0.5.0
type CookieSettings struct {
Enabled bool
// SameSite is lax (default), strict or none. none is for apps on another
// site than the API (another registrable domain); lax and strict also work
// for an app on a sibling subdomain.
SameSite string
}
CookieSettings are the realm's session cookies.
type CustomID ¶ added in v0.8.2
type CustomID struct {
// User means the id must equal the id of the user creating the document.
User bool
// Pattern is the declared pattern as written; empty with User.
Pattern string
// DuplicateLimit is how many creates of an id that exists a caller may attempt per minute.
DuplicateLimit int
// contains filtered or unexported fields
}
CustomID is collection.yaml's custom_id: the collection takes the id of a new document from the client, which must match Pattern (or be the creating user's id) and the safety envelope.
type Database ¶
type Database struct {
Realm string
Name string
MongoName string // <realm>__<database>
Dir string // the database's folder
Collections map[string]*Collection
Functions *Functions // from _functions/; nil when the database has none
// contains filtered or unexported fields
}
Database is one application's data, stored in one MongoDB database.
func (*Database) MigratingCollections ¶ added in v0.9.11
func (db *Database) MigratingCollections() []*Collection
MigratingCollections lists the collections of db with at least one migration step, in name order: the ones the build bundles and startup expects a bundle for.
func (*Database) MigrationBundlePath ¶ added in v0.9.11
func (db *Database) MigrationBundlePath(m MigrationManifest, collection string) string
MigrationBundlePath is the file of the collection's bundle, as the manifest records it.
func (*Database) MigrationsBuildDir ¶ added in v0.9.11
MigrationsBuildDir is where the database's migration bundles and manifest are written.
func (*Database) SortedCollections ¶
func (d *Database) SortedCollections() []*Collection
SortedCollections returns the database's collections sorted by name.
type Default ¶ added in v0.9.12
type Default struct {
Path []string // the property names from the document's top, e.g. ["address", "country"]
Value any
}
Default is a value schema.json declares with `default` on a property: a create (and a PUT, which replaces the whole document) fills it in when the request doesn't send the field.
type EmailLimits ¶ added in v0.4.0
type EmailLimits struct {
PerKindPerHour int // emails of one kind to one recipient, per hour
PerDay int // emails to one recipient, per day
PerIPPerHour int // email-sending requests from one client address, per hour
// The caps of custom emails from functions (ctx.email.send), whoever the
// recipients are.
PerFunctionPerHour int // messages one function sends, per hour
PerInvocation int // messages one invocation sends
RecipientsPerMessage int // to, cc and bcc of one message
}
EmailLimits bound how many emails one address, and one client address, can cause.
type EmailSettings ¶ added in v0.4.0
type EmailSettings struct {
Function string // <database>/<function>: internal and async
From string // "Name <address>" or an address
ReplyTo string // optional
PublicURL string // overrides BACKD_URL for this realm's links; no trailing slash
Limits EmailLimits
// RedirectDelay is how long a hosted result page waits before it sends the
// user on (email.redirect_delay).
RedirectDelay time.Duration
// Redirects are where the hosted pages send users afterwards, by flow
// (verify_email, reset_password, change_email, invitation), when the
// request that caused the email named no other place.
Redirects map[string]string
// AllowedRedirects are the origins (https://app.example.com) and app
// schemes (acme://) that redirect_to, redirects and links may point at.
AllowedRedirects []string
// Links replace the hosted page of a flow with a page of the app: the
// link in the email is this URL, with {token} replaced.
Links map[string]string
// Timeout is the delivery function's own timeout, set when the config is
// loaded; email jobs lease for it.
Timeout time.Duration
// Customizable are the kinds of email an organization may write its own template of
// (email.customizable); OverridePermission is the organization capability that edits them.
Customizable []string
OverridePermission OrgCaps
// DataHook is the internal, sync function (<database>/<function>) backd calls before it
// renders a system email, to fill in {{.App}} (design/team-access.md §10); "" for none.
DataHook string
}
EmailSettings are the email settings of a realm: which function delivers its messages and who they come from. backd renders the messages and never sends one itself.
func (EmailSettings) AllowedRedirect ¶ added in v0.4.0
func (e EmailSettings) AllowedRedirect(raw string) bool
AllowedRedirect reports whether raw is an absolute URL on one of the allowed origins or app schemes: where a page may send a user.
func (EmailSettings) DatabaseAndName ¶ added in v0.4.0
func (e EmailSettings) DatabaseAndName() (string, string)
DatabaseAndName splits Function into the database and the function name.
type EncryptedField ¶ added in v0.9.1
type EncryptedField struct {
Path string
Key string
// Search is "" (the field can't be queried) or SearchEquality: a blind index lets `where`
// and read rules compare the field for equality.
Search string
// Normalize is applied to the value before its blind index is computed (and to the value
// searched for): "trim", "lower" or "upper", in order. Only with Search.
Normalize []string
// Unique makes the blind index unique: two documents can't hold the same value.
Unique bool
// Reveal decides, per document, whether a caller who may read it sees the field; nil: every
// reader does. RevealSource is its text.
Reveal *rules.Rule
RevealSource string
}
EncryptedField is a field of a collection stored encrypted (collection.yaml's fields.<path>.encrypt, design/field-encryption.md §3.2). Key names the realm's `key` secret the field's data keys are wrapped with.
type ErasurePolicy ¶ added in v0.4.0
type ErasurePolicy struct {
// Action applies to the documents whose _meta.owner is the user: "" leaves
// them, ErasureDelete removes them, ErasureAnonymize applies Remove and
// Replace and clears the owner.
Action string
Remove []string // fields removed (anonymize)
Replace map[string]any // fields set to a fixed value (anonymize)
// Pull and Unset act on every document of the collection, whoever owns it:
// the user is removed from the array field / cleared from the field. The
// value says what the field holds: MatchEmail or MatchID.
Pull map[string]string
Unset map[string]string
// InOrg is InOrgKeep (the default) or InOrgApply: whether documents that belong to an
// organization follow Action (apply) or stay with the organization, owner cleared (keep).
InOrg string
}
ErasurePolicy is what an erase does to a collection (collection.yaml's on_owner_delete). A collection without the file is left alone.
func (*ErasurePolicy) Fields ¶ added in v0.4.0
func (p *ErasurePolicy) Fields() []string
Fields lists every field the policy touches, for the indexes it needs.
func (*ErasurePolicy) IndexedFields ¶ added in v0.4.0
func (p *ErasurePolicy) IndexedFields() []string
IndexedFields are the fields an erase searches by: the arrays and fields that hold the user (pull and unset), which need an index to be found without scanning the collection.
type EventCollection ¶ added in v0.8.5
type EventCollection struct {
Realm string
Database string
MongoDatabase string
Name string
Realtime bool
Triggers int // how many triggers it declares
}
EventCollection names a collection whose changes the change feed watches.
type ExpandLimits ¶ added in v0.8.4
type ExpandLimits struct {
MaxDepth int // levels of references followed, at most 2
MaxPaths int // entries of one `expand`
MaxArray int // ids of one `many` reference followed
MaxDocs int // expanded documents in one response
}
ExpandLimits are what a reference expansion may cost on this instance (BACKD_EXPAND_MAX_*); a reference may only lower MaxArray with its max_expand.
func (ExpandLimits) OrDefault ¶ added in v0.8.4
func (l ExpandLimits) OrDefault() ExpandLimits
OrDefault fills the limits that are zero with the defaults.
type Field ¶
type Field struct {
Types []string // JSON Schema types; empty when the schema doesn't constrain it
ItemTypes []string // for arrays: the types of the items, when declared
// Date marks a field stored as a BSON Date (x-backd-store: date in
// schema.json): clients send and read RFC 3339 strings, queries compare
// dates.
Date bool
// Encrypted marks a field stored encrypted (collection.yaml's fields.<path>.encrypt), and the
// fields inside it: queries refuse them, rules can't compare them.
Encrypted bool
// Searchable marks an encrypted field with a blind index: equality only.
Searchable bool
}
Field describes one property path declared in a collection schema.
type FileField ¶ added in v0.8.0
type FileField struct {
Name string
Public bool // files are stored in the realm's public_storage and read at their url
Multiple bool // an array of files; otherwise at most one
MaxFiles int // for a multiple field
MaxSize int64 // bytes, per file
// Types are the allowed content types, detected from the bytes (never the
// client's claim): "image/png", or "image/*" for a family. Empty allows any.
Types []string
// Upload is UploadProxy or UploadDirect.
Upload string
// Download is DownloadPresigned or DownloadProxy; "" follows the realm's.
Download string
// PresignedTTL is how long this field's links last; 0 follows the realm's.
PresignedTTL time.Duration
// Cache is the Cache-Control max-age of proxied downloads of anonymously
// readable documents; 0 means no caching.
Cache time.Duration
// Versions are the resized copies of an image the field declares, by name order.
Versions []Version
// MaxPixels lowers the instance's image pixel limit for this field; 0 follows it.
MaxPixels int64
// KeepMetadata stores the JPEG and PNG pictures of the field as they were sent. By default
// their metadata (EXIF with the GPS position, XMP, comments, text chunks) is removed.
KeepMetadata bool
}
FileField is one file field of a collection, from collection.yaml.
type Function ¶
type Function struct {
Realm, Database, Name string
Dir string // the function's folder
Entry string // index.js or index.ts, relative to the project (slash-separated)
Mode string
Timeout time.Duration
Memory int64 // bytes
MaxOutput int64 // bytes
Concurrency int
RateLimit *RateLimit // nil: none
Retry *Retry // nil: a single attempt
Idempotency string // optional or required
Invoke *rules.Rule // nil: only API keys may invoke
Admin bool // ctx.admin.db with full access
ConfigWrite bool // ctx.admin.config: may change the realm's app configuration
Internal bool // no HTTP route: only backd, scheduled runs and other functions call it
Email bool // ctx.email.send: may send custom emails through the realm's templates and delivery function
// Push is set by `push:` in function.yaml: the function may send pushes (ctx.push.send).
Push *FunctionPush
DevOnly bool // backd refuses to start with it unless BACKD_DEV=true (development helpers)
Calls []string // functions of the same database this one may ctx.call
Schedule *cron.Schedule // nil: not scheduled
ScheduleExpr string
OnComplete *OnComplete // nil: nothing is told when a job ends
Timezone string // IANA name the schedule is read in; "UTC" unless set. Empty when not scheduled
Overlap string // allow (default) or skip: what a scheduled time does while the previous run hasn't finished
Secrets []SecretRef
Network []string // hosts (host or host:port) the function may reach
InputSchema *jsonschema.Schema
OutputSchema *jsonschema.Schema
}
Function is one function, from its folder in _functions/.
type FunctionPush ¶ added in v0.8.2
type FunctionPush struct {
// Kinds are the template kinds the function declares; Restricted says `kinds:` was given.
Kinds []string
Restricted bool
Audience bool
}
FunctionPush is what a function's `push:` declares: that it may send pushes, which template kinds it sends (empty: any, and raw title and body), and whether it may address an audience rather than named users.
func (*FunctionPush) AllowsKind ¶ added in v0.8.2
func (f *FunctionPush) AllowsKind(kind string) bool
AllowsKind says whether the function may send the kind.
type Functions ¶
type Functions struct {
Dir string // the _functions directory
Functions map[string]*Function // by name
}
Functions is a database's Deno project of functions (`_functions/`).
type Index ¶
type Index struct {
Keys []IndexKey
Unique bool
// Blind marks the index of an encrypted field's blind index (hidden field `_bidx.<path>`):
// internal, created with a filter that leaves out documents without it.
Blind bool
// TTL makes MongoDB delete a document when the date its single key holds
// has passed (soft_delete.retention's purge_at).
TTL bool
}
Index is one index declared in indexes.json.
type IssuerPattern ¶ added in v0.9.13
IssuerPattern is one entry of organizations.sso.oidc.issuers: an https origin, with `*.` for the first label ("https://*.okta.com" matches one label only: https://acme.okta.com, never a.b.okta.com and never https://evil.okta.com.attacker.example).
func ParseIssuerPattern ¶ added in v0.9.13
func ParseIssuerPattern(raw string) (p IssuerPattern, msg string)
ParseIssuerPattern reads a pattern. msg says what is wrong with it, or "".
func (IssuerPattern) Matches ¶ added in v0.9.13
func (p IssuerPattern) Matches(issuer string) bool
Matches says whether an issuer URL is one the pattern allows: https, no credentials, port 443 or none.
func (IssuerPattern) String ¶ added in v0.9.13
func (p IssuerPattern) String() string
type LoginThrottle ¶ added in v0.6.0
type LoginThrottle struct {
// AccountThreshold is how many failed attempts an account gets before
// each new attempt must wait; IPThreshold is the same per client address
// (IPv6 per /64), higher because a network can hide many people.
AccountThreshold int
IPThreshold int
// Window is how long a failure counts: the counter of an account or an
// address expires this long after its last failure.
Window time.Duration
// MaxDelay is the longest anyone waits. It never exceeds Window.
MaxDelay time.Duration
}
LoginThrottle is how a realm slows down guessing of passwords (login_throttle). The zero value means the defaults.
type MFASettings ¶ added in v0.8.2
type MFASettings struct {
// Off says users may not turn TOTP on (auth.totp.enabled: false). Users that already have
// it still can use it where a strategy asks for it: switching the feature off never
// weakens an account.
Off bool
// Issuer is the name authenticator apps show; the realm's name when empty.
Issuer string
}
MFASettings are the realm's TOTP settings (auth.totp in realm.yaml).
type MagicLinkSettings ¶ added in v0.8.2
type MagicLinkSettings struct {
// Enabled turns the endpoints on; it needs the realm's email.
Enabled bool
// Signup lets an address that has no account make one (verified, by redeeming the link
// or code), when the realm's own sign-up is open.
Signup bool
}
MagicLinkSettings are the realm's magic-link settings.
type Manifest ¶
type Manifest struct {
Deno string `json:"deno"`
Source string `json:"source"` // SourceHash of the project when built
Functions map[string]ManifestBundle `json:"functions"`
}
Manifest describes the bundles `backd-server functions build` wrote for one functions project.
func ReadManifest ¶
ReadManifest reads a project's .build/manifest.json.
type ManifestBundle ¶
type ManifestBundle struct {
Bundle string `json:"bundle"` // file name in .build
SHA256 string `json:"sha256"`
}
ManifestBundle is one function's bundle.
type MigrationManifest ¶ added in v0.9.11
type MigrationManifest struct {
Deno string `json:"deno"`
Source string `json:"source"` // MigrationSourceHash of the database when built
Collections map[string]ManifestBundle `json:"collections"`
}
MigrationManifest describes the bundles `backd-server functions build` wrote for the migrations of one database: one bundle per collection that has any migration step.
func ReadMigrationManifest ¶ added in v0.9.11
func ReadMigrationManifest(db *Database) (MigrationManifest, error)
ReadMigrationManifest reads a database's _migrations/.build/manifest.json.
type Networks ¶
Networks is a list of IP networks. An empty list restricts nothing.
func ParseNetworks ¶
ParseNetworks parses IP addresses and CIDR networks, IPv4 or IPv6.
func (Networks) Allows ¶
Allows reports whether addr is in one of the networks; an empty list allows every address. addr is an IP address such as the one the HTTP layer resolves with TRUSTED_PROXIES; an unparsable one is refused by a non-empty list.
type OnComplete ¶ added in v0.8.0
type OnComplete struct {
Function string // a function of the same database
On []string // the endings that notify; every one when empty
}
OnComplete says which async function is queued, as a job of its own, when a job of this function ends.
func (*OnComplete) Notifies ¶ added in v0.8.0
func (o *OnComplete) Notifies(ending string) bool
Notifies reports whether an ending (CompleteOK, CompleteFailed or CompleteCancelled) is told.
type OrgCaps ¶ added in v0.8.3
type OrgCaps uint8
OrgCaps are the things an organization role lets its holders manage in the organization: the same idea as the admin areas a realm role opens, scoped to one organization.
const ( CapOrg OrgCaps = 1 << iota // rename, slug, require_mfa and deletion CapMembers // invite, remove members, revoke invitations CapRoles // grant or remove any role CapTeams // create, change and delete teams and their members CapSSO // set, replace and remove the organization's sign-in connections CapDomains // claim, prove and release the domains the organization owns // AllCaps is every capability. AllCaps = CapOrg | CapMembers | CapRoles | CapTeams | CapSSO | CapDomains )
func (OrgCaps) Any ¶ added in v0.8.3
Any reports whether c holds anything: whether holding it makes someone a manager.
func (OrgCaps) Covers ¶ added in v0.8.3
Covers reports whether c can do everything b can: nobody hands out, or changes someone who holds, more than they have (the rule realm roles follow for admin areas).
type OrgDomainsSettings ¶ added in v0.9.13
type OrgDomainsSettings struct {
// MaxPerOrg caps the claims of one organization, verified and pending.
MaxPerOrg int
// Recheck is how often a verified domain is checked again.
Recheck time.Duration
// LapseAfter is how many consecutive failed checks make a domain lapse.
LapseAfter int
// Blocked are more domains nobody may claim, added to the built-in list of free-mail providers.
Blocked []string
// Resolvers are the DNS servers (host:port) to ask; empty: the host's resolver.
Resolvers []string
}
OrgDomainsSettings is organizations.domains: the realm's switch for verified domains.
type OrgHook ¶ added in v0.8.3
type OrgHook struct {
Function string
// Timeout is the function's own, the lease of the job (zero: the default).
Timeout time.Duration
}
OrgHook is a function called when membership changes (organizations.hooks): an internal, async function, <database>/<function>.
type OrgHooks ¶ added in v0.8.3
type OrgHooks struct {
OnMemberJoined, OnMemberLeft, OnRolesChanged OrgHook
}
OrgHooks are the functions called when people join, leave or change roles in an organization.
type OrgRole ¶ added in v0.8.3
type OrgRole struct {
Description string
// Manage is what holders may manage in the organization.
Manage OrgCaps
// RequireMFA makes the role count only for sessions with a second factor.
RequireMFA bool
}
OrgRole is an organization role declared in realm.yaml.
type OrgSSOSettings ¶ added in v0.9.3
type OrgSSOSettings struct {
// Providers are the ones an organization may connect.
Providers []string
// MaxPerOrg caps the connections of one organization.
MaxPerOrg int
// OIDCIssuers are the patterns an organization's OpenID Connect issuer must match
// (organizations.sso.oidc.issuers); none: organizations cannot use OpenID Connect.
OIDCIssuers []IssuerPattern
}
OrgSSOSettings is organizations.sso: the realm's switch for organization sign-in.
func (*OrgSSOSettings) Allows ¶ added in v0.9.3
func (s *OrgSSOSettings) Allows(provider string) bool
Allows reports whether organizations may connect the provider.
func (*OrgSSOSettings) AllowsIssuer ¶ added in v0.9.13
func (s *OrgSSOSettings) AllowsIssuer(issuer string, dev bool) bool
AllowsIssuer says whether an organization may connect an OpenID Connect server with this issuer: one that matches a pattern of the realm. In development (BACKD_DEV) a server on this machine (localhost or a loopback address, any port, http too) is allowed as well, so a local Keycloak can be tried without a public name.
type OrgSettings ¶ added in v0.8.3
type OrgSettings struct {
Roles map[string]OrgRole
// TeamRoles are the roles held within a team.
TeamRoles map[string]TeamRole
// CreateRule is the expression deciding who may create organizations (it sees `user`);
// "false" leaves it to realm admins and functions.
CreateRule string
CreatorRoles []string
// DefaultRoles are held by every member without being granted.
DefaultRoles []string
MaxCreatedPerUser int
MaxMembershipsPerUser int
MaxTeamsPerOrg int
MaxTeamsPerMember int
MaxPendingInvitations int
AllowRequireMFA bool
MembersVisibleTo string
// Hooks are called through the job queue when membership changes.
Hooks OrgHooks
// InvitationLink is where invitation links point: it holds {token} and may hold {org}.
InvitationLink string
// SigninLink is where the sign-in page of an organization is, for the email that tells a
// person which organizations they belong to (design/scoped-sessions.md §5.4): it holds {slug}
// (the id for an organization with none) and may hold {org}. Empty: the realm has no such email.
SigninLink string
// SSO is the organization sign-in section (design/sso.md §9); nil when the realm doesn't
// let organizations set up their own providers.
SSO *OrgSSOSettings
// Domains is the verified-domains section (design/sso.md §10); nil when the realm doesn't
// let organizations prove the domains they own.
Domains *OrgDomainsSettings
// contains filtered or unexported fields
}
OrgSettings is the realm's organizations section; nil in RealmSettings when the realm doesn't enable organizations.
func (*OrgSettings) CapsOf ¶ added in v0.8.3
func (o *OrgSettings) CapsOf(roles []string) OrgCaps
CapsOf is what the roles let their holder manage, added up. Roles the realm doesn't declare (any more) grant nothing.
func (*OrgSettings) CreateRuleAllows ¶ added in v0.8.3
CreateRuleAllows evaluates the create rule for user.
func (*OrgSettings) Declared ¶ added in v0.8.3
func (o *OrgSettings) Declared(role string) bool
Declared reports whether role is declared.
func (*OrgSettings) InvitationURL ¶ added in v0.8.3
func (o *OrgSettings) InvitationURL(token, org string) string
InvitationURL is the link for a token (and organization id).
func (*OrgSettings) RoleNames ¶ added in v0.8.3
func (o *OrgSettings) RoleNames() []string
RoleNames returns the declared roles, sorted.
func (*OrgSettings) RolesWith ¶ added in v0.8.3
func (o *OrgSettings) RolesWith(caps OrgCaps) []string
RolesWith returns the declared roles whose holders may manage everything in caps, sorted.
func (*OrgSettings) StaleRoles ¶ added in v0.8.3
func (o *OrgSettings) StaleRoles(roles []string) []string
StaleRoles returns the roles in roles that the organizations section doesn't declare.
func (*OrgSettings) TeamRoleDeclared ¶ added in v0.8.3
func (o *OrgSettings) TeamRoleDeclared(role string) bool
TeamRoleDeclared reports whether role is a declared team role.
func (*OrgSettings) TeamRoleNames ¶ added in v0.8.3
func (o *OrgSettings) TeamRoleNames() []string
TeamRoleNames returns the declared team roles, sorted.
type PasskeySettings ¶ added in v0.9.10
PasskeySettings are the realm's passkey settings (auth.passkeys in realm.yaml, design/passkeys.md §3). RPID and Origins are filled from sign_in.app_url when left out.
type PersonalData ¶ added in v0.8.2
type PersonalData struct {
Export string // ExportInclude (default) or ExportExclude
Fields []string // only these fields (plus id and _meta); nil: whole documents
Reason string // why: required to exclude, and to leave fields out
}
PersonalData is collection.yaml's personal_data: it overrides what the export of a user's data takes from the collection. Without it the export follows the erasure model: the documents the user owns, whole.
type Provider ¶ added in v0.8.2
type Provider struct {
Name string // what identities, URLs and the audit call it
// Kind is how it is spoken to and checked: google, microsoft, apple or oidc.
Kind string
// ClientID is the application's id with the provider (Apple: the Services ID);
// ClientSecret names the secret that holds its secret (Apple has none: it
// signs one from PrivateKey).
ClientID string
ClientSecret string
// NativeClientIDs (Apple: BundleIDs) are the extra audiences the ID-token
// endpoint accepts, the ids of the mobile apps.
NativeClientIDs []string
// Tenant is Microsoft's: common, organizations, consumers or a tenant id.
Tenant string
// Apple only: the team and key that sign the client secret, the secret that
// holds the private key, and whether a user's tokens are revoked when the
// account goes away.
TeamID, KeyID, PrivateKey string
RevokeOnDelete bool
// Generic OpenID Connect providers: the issuer its tokens name and its discovery document is
// under, the extra scopes asked for, whether its verified addresses link accounts, whether its
// hosts may be on the operator's private network, and whether the issuer is a plain http URL
// (only BACKD_DEV allows it).
Issuer string
Scopes []string
LinkByEmail bool
AllowPrivateNetwork bool
Insecure bool
// Plain OAuth 2: where to send the person, where to trade the code, where to read them, the map
// from the answer to the person, and whether a PKCE challenge is sent.
AuthorizeURL, TokenURL, UserInfoURL string
Claims map[string]string
NoPKCE bool
// Org is set on a provider built from an organization's connection (design/sso.md §9): the
// id of the organization. Its ClientSecret then names an organization secret, and the
// restrictions of the connection apply on top of the token checks.
Org string
}
Provider is an external identity provider a realm lets its users sign in with.
func (*Provider) Audiences ¶ added in v0.8.2
Audiences are the client ids an ID token may be issued to: the web client and, for the ID-token endpoint, the native ones.
func (*Provider) IssuerMatches ¶ added in v0.9.13
IssuerMatches says whether an identity vouched for by iss is one the provider signs in now: the provider's issuer is the one that vouched for it. An identity without an issuer (not recorded yet) matches.
func (*Provider) IssuerOf ¶ added in v0.9.13
IssuerOf is the issuer the provider's tokens must name, when it is fixed: the built-in providers', and a generic provider's. Microsoft's depends on the tenant of the person.
func (*Provider) SSO ¶ added in v0.9.13
SSO is the provider as the sign-in library speaks to it, with the endpoints of its kind.
func (*Provider) SecretNames ¶ added in v0.8.2
SecretNames are the realm secrets the provider needs.
func (*Provider) TrustsEmail ¶ added in v0.8.2
TrustsEmail says whether an address the provider asserts as verified may link an existing account on its own (Google and Apple; not Microsoft, whose address claim a tenant administrator controls).
type PushDelivery ¶ added in v0.8.2
type PushDelivery struct {
Timeout time.Duration
RetryAttempts int
RetryBackoff time.Duration
Parallelism int
}
PushDelivery is push.delivery: a delivery unit's time limit, the attempts a unit gets and the provider requests a worker keeps in flight.
type PushLimits ¶ added in v0.8.2
type PushLimits struct {
PerMinute, PerDay int
}
PushLimits are push.limits.per_user: the pushes a user gets in a minute and a day.
type PushPlatform ¶ added in v0.8.2
type PushPlatform struct {
Provider string
// FCM: the service-account JSON.
Credentials string
// APNs: the .p8 signing key, its id, the team and the app's bundle id; Sandbox targets
// api.sandbox.push.apple.com.
Key string
KeyID, TeamID string
Topic string
Sandbox bool
// Web Push: the VAPID private key and the contact URI (mailto: or https:).
PrivateKey string
Subject string
}
PushPlatform is one enabled platform: its provider and that provider's credentials. The secrets are named, never held: Credentials, Key, PrivateKey and Subject are names of realm secrets (written secret:NAME in realm.yaml).
func (PushPlatform) SecretNames ¶ added in v0.8.2
func (p PushPlatform) SecretNames() []string
SecretNames are the realm secrets the platform's provider needs.
type PushSettings ¶ added in v0.8.2
type PushSettings struct {
// Platforms holds the enabled platforms and their provider.
Platforms map[string]PushPlatform
// WebPublicKey is the VAPID public key (base64url, uncompressed P-256 point) browsers
// subscribe with; WebEndpointHosts the hosts a subscription may point at: an exact host,
// or `*.example.com` for any subdomain.
WebPublicKey string
WebEndpointHosts []string
// MaxDevicesPerUser caps a user's devices; StaleAfter removes devices not seen for that long.
MaxDevicesPerUser int
StaleAfter time.Duration
// Delivery tunes the built-in senders; Limits are the per-user limits; SendRetention is how
// long the record of a send is kept.
Delivery PushDelivery
Limits PushLimits
SendRetention time.Duration
}
PushSettings are the push settings of a realm.
func (*PushSettings) Enabled ¶ added in v0.8.2
func (p *PushSettings) Enabled(platform string) bool
Enabled says whether a device may be registered for the platform.
func (*PushSettings) SecretNames ¶ added in v0.8.2
func (p *PushSettings) SecretNames() []string
SecretNames are the realm secrets push needs, sorted and without repeats.
func (*PushSettings) WebHostAllowed ¶ added in v0.8.2
func (p *PushSettings) WebHostAllowed(host string) bool
WebHostAllowed says whether a web subscription may point at the host.
type RateSettings ¶ added in v0.9.12
RateSettings are the instance's limits (BACKD_RATE_LIMIT*): whether the limiter is on, and the rate of each class. A realm's `rate_limit:` and an API key's limit refine them.
func DefaultRateSettings ¶ added in v0.9.12
func DefaultRateSettings() RateSettings
DefaultRateSettings is the limiter on, with the default rates.
func (RateSettings) RateFor ¶ added in v0.9.12
func (s RateSettings) RateFor(realm *RealmSettings, class string) ratelimit.Rate
RateFor is the rate of class for a realm: the realm's own when it sets one, else the instance's.
type ReadAccess ¶ added in v0.7.0
ReadAccess is realm.yaml's admin.read_access: what read-only administrators may see beyond operations. Users and data hold personal data, so a realm opts in.
type Realm ¶
type Realm struct {
Name string
Settings RealmSettings // from realm.yaml
Databases map[string]*Database
// Email holds the parsed email templates of <realm>/email/; nil when the
// realm doesn't configure email.
Email *email.Templates
// Pages are the hosted pages the links in emails open (<realm>/pages/);
// nil when the realm doesn't configure email.
Pages *email.Pages
// Push holds the parsed push templates of <realm>/push/; nil when the realm has no push: section.
Push *push.Templates
// AppConfig is the realm's declared app configuration (<realm>/app-config/); nil when it has none.
AppConfig *AppConfig
// contains filtered or unexported fields
}
Realm groups databases and owns a user pool.
func (*Realm) EncryptionKeyNames ¶ added in v0.9.1
EncryptionKeyNames is the set of key secret names the realm's fields name.
func (*Realm) EncryptionKeyUses ¶ added in v0.9.1
EncryptionKeyUses lists where the realm's collections use the key secret name, as "database/collection.path", sorted.
func (*Realm) ExportReadme ¶ added in v0.9.2
ExportReadme returns the realm's own README template for a language, and whether it has one. Without it the export uses the built-in template of that language, or the English one.
func (*Realm) PersonalScope ¶ added in v0.8.2
func (r *Realm) PersonalScope() []ScopeEntry
PersonalScope lists, collection by collection, what the export of a user's data takes: the documents they own, those where they appear in a `pull` field, and the files those hold, minus what personal_data excludes.
type RealmSettings ¶
type RealmSettings struct {
AuthEnabled bool
Signup string
IdleTimeout time.Duration
MaxLifetime time.Duration
// AdminIdleTimeout and AdminMaxLifetime are the limits of the sessions of
// users who hold an admin role (sessions.admin_idle_timeout and
// sessions.admin_max_lifetime). 0 means the regular limit; set, they never
// exceed it.
AdminIdleTimeout time.Duration
AdminMaxLifetime time.Duration
// Cookie lets browser apps keep a session in an HttpOnly cookie, when
// their login asks for it (sessions.cookie).
Cookie CookieSettings
PasswordMinLength int
// LoginThrottle is login_throttle; read it through Throttle(), which
// fills in the defaults.
LoginThrottle LoginThrottle
CORSOrigins []string
Roles map[string]Role
// AdminNetworks restricts every admin API request (admin.allowed_networks);
// empty means unrestricted.
AdminNetworks Networks
// ReadAccess is what read-only administrators (`admin: read`) may see
// beyond operations (admin.read_access).
ReadAccess ReadAccess
// UserNetworks are the network restrictions realm.yaml sets per user
// email (in a role's user entries).
UserNetworks map[string]UserNetworks
// OpenAPIPublic makes the realm's OpenAPI document readable without credentials
// (openapi.public: true); otherwise only the realm's administrators read it.
OpenAPIPublic bool
// PagesDataHook is the internal, sync function (<database>/<function>) backd calls before
// it renders a hosted page, to fill in {{.App}} (pages.data_hook); "" for none.
PagesDataHook string
// AppConfigCacheTTL is how long clients treat the app configuration as fresh
// (app_config.cache_ttl); zero when not set: use AppConfigTTL.
AppConfigCacheTTL time.Duration
// AuditRetention is how long audit records are kept (audit.retention);
// DefaultAuditRetention when not set.
AuditRetention time.Duration
// RateLimits are realm.yaml's `rate_limit:`: the rate of the classes the realm sets, which
// replace the instance's for this realm (see RateSettings.RateFor).
RateLimits map[string]ratelimit.Rate
// AuditEntries are realm.yaml's `audit.entries`: for each audit action, whether it is recorded.
// Read them through AuditEnabled, which applies the defaults.
AuditEntries map[string]bool
// Triggers are realm.yaml's `triggers:` limits (design/triggers-and-realtime.md §7); read
// them through TriggerLimits, which applies the instance's.
Triggers TriggerSettings
// Realtime are realm.yaml's `realtime:` limits, which only lower the instance's
// (design/triggers-and-realtime.md §17); zero means the instance's.
Realtime RealtimeSettings
// FunctionsMaxConcurrency caps how many function calls may run at once
// on this backd instance (functions.max_concurrency); 0 means
// unlimited. Applies whether or not auth is enabled.
FunctionsMaxConcurrency int
// FunctionsLogRetention is how long invocation records (roadmap F10)
// are kept (functions.log_retention); DefaultLogRetention when not
// set. Needs auth enabled, like the rest of functions.* except
// max_concurrency: there's no system database to store them in
// otherwise.
FunctionsLogRetention time.Duration
// FunctionsJobRetention is how long an async job's result (roadmap
// F11) is kept once done (functions.job_retention); DefaultJobRetention
// when not set. Needs auth enabled, like FunctionsLogRetention.
FunctionsJobRetention time.Duration
// Email is how the realm sends email (email in realm.yaml); nil when it
// doesn't, and then no email is ever sent.
Email *EmailSettings
// Storage is where the realm's files live (storage in realm.yaml); nil
// when it has none, and then it can't declare file fields.
Storage *StorageSettings
// PublicStorage is where the realm's public files live (public_storage in realm.yaml):
// another bucket, possibly another provider, that browsers read from PublicStorage.URL.
// nil when the realm has none, and then no file field can be public.
PublicStorage *StorageSettings
// Account is how the realm's accounts behave (account in realm.yaml).
Account AccountSettings
// Providers are the external identity providers (providers in realm.yaml),
// by name; SignInRedirects are where a sign-in may send the user back to
// (sign_in.allowed_redirects, normalized like email.allowed_redirects).
Providers map[string]*Provider
SignInRedirects []string
// SignInAppURL (sign_in.app_url) is where a sign-in goes back to when its
// redirect_to is absent: the app's own address, within the allowed redirects.
SignInAppURL string
// MFA are the multi-factor settings (mfa in realm.yaml).
MFA MFASettings
// Organizations is the organizations section; nil when the realm doesn't enable them.
Organizations *OrgSettings
// Strategies are the named lists of methods a person signs in with, in the order the
// realm declares them (auth.strategies), and Passkeys the passkey settings.
Strategies []Strategy
Passkeys PasskeySettings
// ReauthTTL is how long a re-authentication token works (reauth.ttl).
ReauthTTL time.Duration
// DefaultLocale and Locales are the languages of the realm (default_locale and locales in
// realm.yaml): users' languages are mapped to them, and email and push templates exist for
// each. Read them with Languages.
DefaultLocale string
Locales []string
// Push holds the push notification settings: nil without a push: section.
Push *PushSettings
// MagicLink are the settings of sign-in by emailed link and code (magic_link in realm.yaml).
MagicLink MagicLinkSettings
// Consents are the consents the realm asks for (consents in realm.yaml), with the texts
// of every version once loaded; Compliance holds what their records keep and for how long.
Consents map[string]*Consent
Compliance ComplianceSettings
}
RealmSettings are the realm-level settings from realm.yaml, with defaults applied.
func (RealmSettings) ActiveRoles ¶ added in v0.9.10
func (s RealmSettings) ActiveRoles(held []string, strategy string) (active, inactive []string)
ActiveRoles splits the roles a user holds by a session made with strategy: a role is active when it lists no strategies or lists that one. A session without a strategy (made before strategies, or through an organization's connection) keeps every role.
func (RealmSettings) AdminAccess ¶ added in v0.7.0
func (s RealmSettings) AdminAccess(roles []string) AdminAccess
AdminAccess is what the roles let a user do in the admin API, added up.
func (RealmSettings) AdminRights ¶ added in v0.6.0
func (s RealmSettings) AdminRights(roles []string) AdminRights
AdminRights is what the roles let a user change together: the union of the areas each role opens.
func (RealmSettings) AdminRoles ¶
func (s RealmSettings) AdminRoles() []string
AdminRoles returns the names of the roles that open any part of the admin API (admin: true, or a list of areas), sorted.
func (RealmSettings) AppConfigTTL ¶ added in v0.8.2
func (s RealmSettings) AppConfigTTL() time.Duration
AppConfigTTL is how long clients may use the app configuration without asking again.
func (RealmSettings) AuditEnabled ¶ added in v0.9.12
func (s RealmSettings) AuditEnabled(action string) bool
AuditEnabled reports whether the realm records action: its audit.entries value, else the default (on, except for the actions marked Off). Actions that are not configurable (AuditEntriesChanged, and any action missing from the table) are always recorded.
func (RealmSettings) BestLocale ¶ added in v0.4.0
func (s RealmSettings) BestLocale(tags ...string) string
BestLocale maps the languages a person asked for, most wanted first, to the best language the realm lists, without ever failing: an exact match (es-MX), then the same language with its region dropped (es), then the default. The first tag that matches either way wins, so ["fr-CA", "es"] on a realm that lists es and en gives es.
func (RealmSettings) ConsentNames ¶ added in v0.8.2
func (s RealmSettings) ConsentNames() []string
ConsentNames returns the declared consents' names, sorted.
func (RealmSettings) ConsentsPastDeadline ¶ added in v0.8.2
func (s RealmSettings) ConsentsPastDeadline(held map[string]string, now time.Time) []ConsentRef
ConsentsPastDeadline is ConsentsToAccept restricted to the consents whose current version has a reaccept_by date that has passed: from then on a user who hasn't accepted them is refused until they do.
func (RealmSettings) ConsentsToAccept ¶ added in v0.8.2
func (s RealmSettings) ConsentsToAccept(held map[string]string) []ConsentRef
ConsentsToAccept lists the required consents a user must accept (again) to be let in: the ones they hold no version of, and the ones they hold an older version of when the current version asks for re-acceptance. held maps a consent to the version the user accepted; the list is sorted by name.
func (RealmSettings) FullAdminRoles ¶ added in v0.6.0
func (s RealmSettings) FullAdminRoles() []string
FullAdminRoles returns the names of the roles that open every area (`admin: true`), sorted: the ones that can recover a realm whatever else is lost.
func (RealmSettings) IsAdmin ¶
func (s RealmSettings) IsAdmin(roles []string) bool
IsAdmin reports whether roles include an admin role of the realm.
func (RealmSettings) Languages ¶ added in v0.4.0
func (s RealmSettings) Languages() (def string, list []string)
Languages returns a realm's default language and the languages it supports: the top-level default_locale and locales of realm.yaml, or just English when it sets none.
func (RealmSettings) ListedLocale ¶ added in v0.4.0
func (s RealmSettings) ListedLocale(tag string) string
ListedLocale returns the listed language equal to tag, ignoring case (es-mx finds es-MX), or "" when the realm doesn't list it.
func (RealmSettings) ReauthLifetime ¶ added in v0.8.2
func (s RealmSettings) ReauthLifetime() time.Duration
ReauthLifetime is the lifetime of a re-authentication token: the realm's, or the default.
func (RealmSettings) SignInRedirectAllowed ¶ added in v0.8.2
func (s RealmSettings) SignInRedirectAllowed(raw string) bool
SignInRedirectAllowed says whether a sign-in may send the user to raw: it is on sign_in.allowed_redirects, or, when the realm has none, on email.allowed_redirects.
func (RealmSettings) StorageFor ¶ added in v0.9.5
func (s RealmSettings) StorageFor(public bool) *StorageSettings
StorageFor returns the settings of the realm's private (public false) or public storage; nil when the realm has none of that kind.
func (RealmSettings) StrategyByName ¶ added in v0.9.10
func (s RealmSettings) StrategyByName(name string) (Strategy, bool)
StrategyByName returns the strategy with that name.
func (RealmSettings) StrategyFor ¶ added in v0.9.10
func (s RealmSettings) StrategyFor(name, first string) (Strategy, error)
StrategyFor chooses the strategy a first-step call signs in with. name may be empty when exactly one strategy starts with first (the call's method: password, magic_link or a provider). Settings built by hand without strategies (tests) answer an unnamed strategy of that one method; a parsed realm always has strategies.
func (RealmSettings) TOTPRequired ¶ added in v0.9.10
func (s RealmSettings) TOTPRequired(roles []string) bool
TOTPRequired says whether a user with these roles has to enrol an authenticator: every strategy of the realm ends in a totp step, or one of the roles accepts only strategies that do.
func (RealmSettings) TOTPRoles ¶ added in v0.9.10
func (s RealmSettings) TOTPRoles() (roles []string, everyone bool)
TOTPRoles lists the roles that need a totp step, and whether every user does.
func (RealmSettings) Throttle ¶ added in v0.6.0
func (s RealmSettings) Throttle() LoginThrottle
Throttle is the realm's login throttling, with the defaults filled in for what is left out.
func (RealmSettings) TriggerLimits ¶ added in v0.8.5
func (s RealmSettings) TriggerLimits(instance TriggerLimits) TriggerLimits
TriggerLimits returns the limits in force for a realm: the instance's, lowered by what the realm says (never raised: CheckTriggerLimits refuses a realm that tries).
type RealtimeSettings ¶ added in v0.8.5
RealtimeSettings are a realm's own lower limits for streams; zero means the instance's.
type Reference ¶ added in v0.8.4
type Reference struct {
Name string
Field string // source field in this collection
Database string // target database
Collection string // target collection
Key string // target field that equals the source value: "id" or a uniquely indexed field
Many bool // the source is an array of values
// MaxExpand lowers the instance's per-array cap for this reference; 0 uses the instance's.
MaxExpand int
}
Reference is one declared relation of collection.yaml's `references:`: the value of Field in this collection is the Key of a document of Database/Collection of the same realm.
type Registry ¶
Registry is the loaded configuration. It is read-only after Load.
func Load ¶
Load walks root and builds the registry. Every problem found is reported, each naming the offending path.
func (*Registry) AggregateWarnings ¶ added in v0.8.4
AggregateWarnings are the index warnings of every collection of the registry.
func (*Registry) AuthRealms ¶ added in v0.4.0
AuthRealms returns the realms with auth enabled (the ones with users, and so with jobs), sorted.
func (*Registry) CheckAggregateLimits ¶ added in v0.8.4
func (r *Registry) CheckAggregateLimits(instance AggregateLimits) error
CheckAggregateLimits fails for a collection whose aggregate.limits are above the instance's.
func (*Registry) CheckBundles ¶
CheckBundles reports functions projects whose bundles are missing, were built by another Deno version, don't match the sources, or were changed since the build. Startup refuses to run with any of them.
func (*Registry) CheckExpandLimits ¶ added in v0.8.4
CheckExpandLimits fails for a reference whose max_expand is above what the instance follows per array (BACKD_EXPAND_MAX_ARRAY): a reference may only lower it.
func (*Registry) CheckImageLimits ¶ added in v0.8.1
CheckImageLimits reports the fields whose `max_pixels` is above the instance's limit (BACKD_IMAGE_MAX_PIXELS): a field may only lower it.
func (*Registry) CheckTriggerLimits ¶ added in v0.8.5
func (r *Registry) CheckTriggerLimits(instance TriggerLimits) error
CheckTriggerLimits checks the configuration against this instance's limits: a realm may only lower the depth of chains and the triggers per collection, and no collection may declare more triggers than its realm allows.
func (*Registry) Collection ¶
func (r *Registry) Collection(realm, database, collection string) (*Collection, bool)
Collection returns the collection at realm/database/collection, if configured.
func (*Registry) CompatibilityFindings ¶ added in v0.9.11
func (r *Registry) CompatibilityFindings() ([]CompatFinding, error)
CompatibilityFindings lists the findings of every versioned collection, in name order.
func (*Registry) EventCollections ¶ added in v0.8.5
func (r *Registry) EventCollections() []EventCollection
EventCollections lists every collection of every realm that needs the change feed, in a stable order.
func (*Registry) Fingerprint ¶
Fingerprint identifies the config: a SHA-256 over every file backd reads from CONFIG_DIR — realm.yaml, each collection's schema.json, indexes.json and collection.yaml, and each functions project with its bundles — by relative path, length and content. Files backd ignores (hidden entries such as .git, stray files) don't change it, so the same checkout always has the same fingerprint, on any machine.
func (*Registry) FunctionRealms ¶
FunctionRealms returns the realms with at least one function, sorted.
func (*Registry) RealmNames ¶
RealmNames returns every configured realm's name, sorted.
func (*Registry) SortedRealms ¶
SortedRealms returns every realm, sorted by name.
type Retry ¶ added in v0.4.0
type Retry struct {
Attempts int // total attempts, the first included
Backoff time.Duration // the wait after the first failure; doubles after each one
MaxBackoff time.Duration // the longest single wait
}
Retry is an async function's retry policy: how often a failed attempt is repeated and how long to wait between attempts.
type Role ¶
type Role struct {
Description string
// Admin is what the sessions of users holding the role may do in the
// admin API: AllRights for `admin: true`, some areas for a list, none.
Admin AdminRights
// AdminRead is `admin: read` (alone or in a list): every area may be read.
AdminRead bool
// Users are seed assignments: normalized (trimmed, lowercased) emails.
Users []string
// Strategies are the strategies that keep the role active in a session; nil means all.
Strategies []string
}
Role is a role declared in realm.yaml.
type SchemaFiles ¶ added in v0.9.11
type SchemaFiles struct {
// Current is the file the server compiles: schema.json, or the highest schema.vN.json.
Current string
// Version is the current version: N of the highest schema.vN.json, 1 for a plain schema.json.
Version int
// Versioned is true when the collection uses schema.vN.json files.
Versioned bool
// Versions lists the N of every kept schema.vN.json, ascending (empty when unversioned).
Versions []int
// Migrations lists the N of every schema.vN.ts, ascending: the step from N-1 to N.
Migrations []int
}
SchemaFiles is what a collection directory holds of its schema (design/schema-versioning.md §3).
type ScopeEntry ¶ added in v0.8.2
type ScopeEntry struct {
Database string
Collection string
// Export is ExportInclude or ExportExclude.
Export string
// Owned: documents whose _meta.owner is the user. Always true when included.
Owned bool
// Fields lists the exported fields when the export is partial; nil means whole documents.
Fields []string
// Pull lists the fields that hold the user (the arrays of `pull` and the fields of `unset` of
// the erase policy), whose documents are included whoever owns them.
Pull []string
// Files lists the file fields whose files are part of the export.
Files []string
Reason string
// Declared: personal_data is in the collection's collection.yaml.
Declared bool
// Organization: the documents belong to organizations and are exported whole, so they may
// hold the data of colleagues next to the user's own. The report flags it so that someone
// decides: narrow it with `fields`, or accept it.
Organization bool
}
ScopeEntry says what the export of a user's data takes from one collection.
type SecretRef ¶
SecretRef names a secret a function may read: its own database's (`NAME`) or the realm's (`realm.NAME`). Org names an organization's secret; only the sign-in code sets it, function.yaml has no syntax for it, so a function can't read one.
type SoftDelete ¶ added in v0.6.0
type SoftDelete struct {
// Retention is how long a deleted document is kept before MongoDB's TTL
// index removes it; 0 keeps it until it is purged by hand.
Retention time.Duration
}
SoftDelete is collection.yaml's soft_delete: DELETE hides a document instead of removing it, so it can be restored.
type Steps ¶ added in v0.9.10
type Steps struct{ First, Later bool }
Steps says where a method may stand in a strategy.
func MethodSteps ¶ added in v0.9.10
MethodSteps says where method may stand: a provider's name (anything not built in) can only be first.
type StorageSettings ¶ added in v0.8.0
type StorageSettings struct {
Provider string // storage.Provider's Name; LookupProvider gives its capabilities
// Endpoint and Region are what backd connects to, as the provider's rules
// resolve them; PublicEndpoint (providers that allow it) is only signed into
// links for browsers and never connected to.
Endpoint string
PublicEndpoint string
Region string
Bucket string
// Prefix starts every object key of this instance (<prefix>/<realm>/…): each
// backd instance sharing a bucket needs its own.
Prefix string
// AccessKey and SecretKey are the names of secrets of the realm's encrypted
// store (storage.access_key: secret:NAME), never values.
AccessKey, SecretKey string
Download string // DownloadPresigned or DownloadProxy: the default of the realm's fields
PresignedTTL time.Duration
PendingTTL time.Duration
// QuotaRealm and QuotaUser are the most bytes the files of all documents of the realm, and
// of the documents one user owns, may add up to; 0 is no limit. An upload that would pass
// either answers 413 quota_exceeded.
QuotaRealm, QuotaUser int64
// HTTP is true when Endpoint, PublicEndpoint or URL is plain http, which startup
// allows only in development.
HTTP bool
// Public is true for the realm's public_storage: files in it are served straight from the
// bucket or a CDN at URL, where browsers read them; backd writes to Endpoint and never
// connects to URL (design/public-files.md).
Public bool
// URL is the root of a public file's address: <URL>/<object key>. No trailing slash.
URL string
}
StorageSettings is where a realm keeps its files: its own S3-compatible bucket on one of the supported providers. backd has no storage of its own.
func (*StorageSettings) Label ¶ added in v0.9.5
func (s *StorageSettings) Label() string
Label is how messages name the storage: the section of realm.yaml it is read from.
func (*StorageSettings) ProviderEntry ¶ added in v0.8.0
func (s *StorageSettings) ProviderEntry() storage.Provider
ProviderEntry returns the provider's capabilities.
func (*StorageSettings) SecretNames ¶ added in v0.8.0
func (s *StorageSettings) SecretNames() []string
SecretNames are the realm secrets the storage needs.
type Strategy ¶ added in v0.9.10
Strategy is a named, ordered list of methods that a person completes to sign in. Every method must succeed, in order; the first one identifies the person.
func (Strategy) HasLaterStep ¶ added in v0.9.10
HasLaterStep says whether method is one of the steps after the first.
type TeamRole ¶ added in v0.8.3
type TeamRole struct {
Description string
// Grants are the team roles its holders may grant, change and revoke in the same team.
Grants []string
// RequireMFA makes the role count only for sessions with a second factor.
RequireMFA bool
}
TeamRole is a role held within one team of an organization, declared in realm.yaml's organizations.team_roles. Team roles are separate from organization roles: they grant nothing outside their team (design/team-access.md §3).
type TextIndex ¶ added in v0.8.4
type TextIndex struct {
// Fields are the indexed fields (strings or arrays of strings) with their weights, in
// field order.
Fields []TextField
// DefaultLanguage is the language of documents with none: a database language name, or "none".
DefaultLanguage string
// LanguageField is the declared string field that holds each document's locale code
// (`es`, `en-GB`), or "".
LanguageField string
}
TextIndex is a collection's full-text index, from indexes.json's `{"text": {...}}` entry.
type Trigger ¶ added in v0.8.5
type Trigger struct {
Name string
Events []string // created, updated, removed; sorted, at least one
// When is the compiled condition over `document`, `before`, `changed()`, `now` and
// appConfig; nil fires on every listed event.
When *rules.Rule
// Function is the internal, async function to run, as <database>/<function>.
Function string
// Fields says what rides in the job: none (ids, the version and what changed), a list of
// paths of the documents before and after, or ["*"] for them whole.
Fields []string
// Session adds `by`, the user who wrote, to the input; Ordered runs the jobs of one
// document one at a time.
Session bool
Ordered bool
// File is the collection.yaml it is declared in, for messages.
File string
}
Trigger is a collection's reactive rule: when a document changes in one of the listed ways and When holds, backd runs Function in the background (design §7).
type TriggerLimits ¶ added in v0.8.5
type TriggerLimits struct {
// MaxChain is how deep a chain of writes caused by trigger runs may go.
MaxChain int
// MaxChainedPerMinute caps, per trigger, the chained events it handles in a minute.
MaxChainedPerMinute int
// MaxPerCollection is how many triggers one collection may declare.
MaxPerCollection int
// MaxBacklog is how many queued trigger jobs a realm may have before further events are
// recorded as a gap instead of queued.
MaxBacklog int
}
TriggerLimits are the bounds on triggers, from the instance (BACKD_TRIGGER_MAX_CHAIN) and lowered by a realm's realm.yaml `triggers:`.
func (TriggerLimits) OrDefault ¶ added in v0.8.5
func (l TriggerLimits) OrDefault() TriggerLimits
OrDefault fills the limits that are zero with the defaults.
type TriggerSettings ¶ added in v0.8.5
type TriggerSettings struct {
MaxChain int
MaxChainedPerMinute int
MaxPerCollection int
MaxBacklog int
}
TriggerSettings is realm.yaml's `triggers:`; 0 leaves the instance's value.
type UserNetworks ¶
type UserNetworks struct {
Admin Networks // the user's admin API requests; within AdminNetworks
Login Networks // login and every request with the user's session
}
UserNetworks restricts where one user may act from.
type Version ¶ added in v0.8.1
type Version struct {
Name string
// Params are what workers make it with; zero (no max_width or max_height) for a
// version only functions make.
Params imaging.Params
// Writable lets functions make the version (with other parameters, too).
Writable bool
}
Version is one declared version of an image field (image versions, milestone 11).
func (Version) Fingerprint ¶ added in v0.8.1
Fingerprint identifies what a version is made with, so that a changed declaration can be told from the copies made before it. Defaults are written out, so spelling a default doesn't change it.
Source Files
¶
- adminrights.go
- aggregate.go
- anonymize.go
- appconfig.go
- auditactions.go
- auth_section.go
- cache.go
- consents.go
- customid.go
- dates.go
- defaults.go
- encrypt.go
- erasure.go
- exportreadme.go
- files.go
- fingerprint.go
- functions.go
- indexes.go
- load.go
- locale.go
- loginthrottle.go
- mfa.go
- migrations.go
- networks.go
- orgs.go
- personaldata.go
- push.go
- push_function.go
- ratelimit.go
- realm.go
- realtime.go
- references.go
- registry.go
- schemacompat.go
- schemaversion.go
- sections.go
- signin.go
- signin_fields.go
- signin_org.go
- signin_providers.go
- softdelete.go
- storage.go
- textindex.go
- triggers.go