Documentation
¶
Overview ¶
Package service holds the Hemmelig operations that the CLI commands and the MCP server share. All encryption and decryption happen here, on the client, so plaintext never reaches the server.
Index ¶
- Constants
- Variables
- func ExpirationName(seconds int) string
- func ParseDuration(value string) (int, error)
- func ParseExpiration(name string) (int, error)
- func ParseSettings(section string, pairs []string) (map[string]any, error)
- func SectionKeys(section string) []string
- func SectionNames() []string
- type APIKey
- type Activity
- type ActivityList
- type AdminUser
- type Analytics
- type AuditEntry
- type AuditList
- type CreateSecretInput
- type CreateSecretResult
- type CreateUserInput
- type FileInput
- type Health
- type InboxSendInput
- type InboxSendResult
- type Invite
- type LoginResult
- type Member
- type NotReleasedError
- type OrgDomain
- type Organization
- type Page
- type ReadSecretInput
- type ReadSecretResult
- type SecondFactor
- type SecretFile
- type SecretList
- type SecretSummary
- type Service
- func (s *Service) Account(ctx context.Context) (*User, error)
- func (s *Service) AddDomain(ctx context.Context, orgRef, domain string) (*OrgDomain, error)
- func (s *Service) BanUser(ctx context.Context, ref, reason string, expiresInSeconds int) (*AdminUser, error)
- func (s *Service) BurnSecrets(ctx context.Context, ids []string, all bool) (int, error)
- func (s *Service) ChangePassword(ctx context.Context, current, next string) error
- func (s *Service) CreateAPIKey(ctx context.Context, name string, expiresInDays int) (*APIKey, error)
- func (s *Service) CreateInvite(ctx context.Context, maxUses, expiresInDays int) (*Invite, error)
- func (s *Service) CreateSecret(ctx context.Context, in CreateSecretInput) (*CreateSecretResult, error)
- func (s *Service) CreateUser(ctx context.Context, in CreateUserInput) (*AdminUser, error)
- func (s *Service) DeactivateInvite(ctx context.Context, ref string) error
- func (s *Service) DeleteAccount(ctx context.Context) error
- func (s *Service) DeleteSecret(ctx context.Context, refValue string) error
- func (s *Service) DeleteUser(ctx context.Context, ref string) error
- func (s *Service) DisableTwoFactor(ctx context.Context, password string) error
- func (s *Service) EnableTwoFactor(ctx context.Context, password string) (*TwoFactorSetup, error)
- func (s *Service) ExportAudit(ctx context.Context, orgRef, category string) ([]byte, error)
- func (s *Service) FindOrganization(ctx context.Context, ref string) (*Organization, error)
- func (s *Service) GetAnalytics(ctx context.Context, timeRange string) (*Analytics, error)
- func (s *Service) GetHealth(ctx context.Context) (*Health, error)
- func (s *Service) InstanceSettings(ctx context.Context, section string) (map[string]any, error)
- func (s *Service) ListAPIKeys(ctx context.Context) ([]APIKey, error)
- func (s *Service) ListActivity(ctx context.Context, page, limit int) (*ActivityList, error)
- func (s *Service) ListAudit(ctx context.Context, orgRef, category string, page, limit int) (*AuditList, error)
- func (s *Service) ListDomains(ctx context.Context, orgRef string) ([]OrgDomain, error)
- func (s *Service) ListInvites(ctx context.Context) ([]Invite, error)
- func (s *Service) ListMembers(ctx context.Context, orgRef string) ([]Member, error)
- func (s *Service) ListOrganizations(ctx context.Context) ([]Organization, error)
- func (s *Service) ListSecrets(ctx context.Context, page, limit int) (*SecretList, error)
- func (s *Service) ListUsers(ctx context.Context, search string, page, pageSize int) (*UserList, error)
- func (s *Service) Logout(ctx context.Context) error
- func (s *Service) ReadSecret(ctx context.Context, in ReadSecretInput) (*ReadSecretResult, error)
- func (s *Service) RemoveDomain(ctx context.Context, orgRef, domain string) error
- func (s *Service) ResolveUser(ctx context.Context, ref string) (string, error)
- func (s *Service) RevokeAPIKey(ctx context.Context, id string) error
- func (s *Service) SendInboxMessage(ctx context.Context, in InboxSendInput) (*InboxSendResult, error)
- func (s *Service) Session(ctx context.Context) (*User, error)
- func (s *Service) SetUserPassword(ctx context.Context, ref, password string) error
- func (s *Service) TwoFactorStatus(ctx context.Context) (bool, error)
- func (s *Service) UnbanUser(ctx context.Context, ref string) (*AdminUser, error)
- func (s *Service) UpdateAccount(ctx context.Context, username, email string) (*User, error)
- func (s *Service) UpdateInstanceSettings(ctx context.Context, values map[string]any) (map[string]any, error)
- func (s *Service) UpdateUser(ctx context.Context, ref string, in UpdateUserInput) (*AdminUser, error)
- func (s *Service) VerifyDomain(ctx context.Context, orgRef, domain string) (*OrgDomain, error)
- func (s *Service) VerifyTwoFactor(ctx context.Context, code string) error
- type SettingKind
- type TokenStore
- type TwoFactorSetup
- type UpdateUserInput
- type User
- type UserList
Constants ¶
const ( MinReleaseSeconds = 60 MaxReleaseSeconds = 30 * 24 * 3600 MaxRecipients = 20 )
The server limits for the v7 options.
const MaxBurnIDs = 500
MaxBurnIDs is the most secrets in one burn request.
const (
MaxInboxFiles = 10
)
The server limits for inbox messages.
Variables ¶
var AnalyticsRanges = []string{"7d", "14d", "30d"}
AnalyticsRanges are the time ranges that the analytics API accepts.
var AuditCategories = []string{"secrets", "people", "settings", "keys"}
AuditCategories are the filters of an audit log.
var ErrAdminRequired = errors.New("this action needs an admin account: the API key or the session does not belong to an admin")
ErrAdminRequired means that the credential does not belong to an admin.
var ErrNoKey = errors.New("the link has no decryption key: give the key with --key")
ErrNoKey means that the link has no decryption key.
var ErrPasswordRequired = errors.New("this secret is password protected: give the password with --password")
ErrPasswordRequired means that the secret needs a password.
var ErrSessionRequired = errors.New("this action needs a signed-in session: run hemmelig login first")
ErrSessionRequired means that the action changes credentials. API keys cannot do that, so that a leaked key cannot take over the account.
var Expirations = map[string]int{
"5m": 300, "30m": 1800, "1h": 3600, "4h": 14400, "12h": 43200,
"1d": 86400, "3d": 259200, "7d": 604800, "14d": 1209600, "28d": 2419200,
}
Expirations are the secret lifetimes that the API accepts, in seconds.
var SettingSections = map[string]map[string]SettingKind{ "general": { "instanceName": KindString, "instanceDescription": KindString, "instanceLogo": KindString, "instanceLogoDark": KindString, "defaultTheme": KindString, "allowRegistration": KindBool, "requireEmailVerification": KindBool, "maxSecretsPerUser": KindInt, "defaultSecretExpiration": KindInt, "defaultMaxViews": KindInt, "maxSecretSize": KindInt, "importantMessage": KindString, }, "security": { "allowPasswordProtection": KindBool, "allowIpRestriction": KindBool, "allowFileUploads": KindBool, "maxPasswordAttempts": KindInt, "sessionTimeout": KindInt, "enableRateLimiting": KindBool, "rateLimitRequests": KindInt, "rateLimitWindow": KindInt, }, "organization": { "requireInviteCode": KindBool, "allowedEmailDomains": KindString, "requireRegisteredUser": KindBool, "disableEmailPasswordSignup": KindBool, }, "webhook": { "webhookEnabled": KindBool, "webhookUrl": KindString, "webhookSecret": KindString, "webhookOnView": KindBool, "webhookOnBurn": KindBool, }, "metrics": { "metricsEnabled": KindBool, "metricsSecret": KindString, }, }
SettingSections groups the instance settings as the admin dashboard does.
Functions ¶
func ExpirationName ¶
ExpirationName converts seconds back to a name, or returns the seconds.
func ParseDuration ¶
ParseDuration converts a duration such as 30m, 2h or 7d to seconds.
func ParseExpiration ¶
ParseExpiration converts a name such as "1d" to seconds.
func ParseSettings ¶
ParseSettings converts key=value pairs of a section to typed values.
func SectionKeys ¶
SectionKeys returns the keys of a section in alphabetical order.
func SectionNames ¶
func SectionNames() []string
SectionNames returns the section names in dashboard order.
Types ¶
type APIKey ¶
type APIKey struct {
ID string `json:"id"`
Name string `json:"name"`
KeyPrefix string `json:"keyPrefix"`
LastUsedAt *string `json:"lastUsedAt"`
ExpiresAt *string `json:"expiresAt"`
CreatedAt string `json:"createdAt"`
// Key is the full key. The API returns it only once, at creation.
Key string `json:"key,omitempty"`
}
APIKey is an API key without its secret value.
type Activity ¶
type Activity struct {
ID string `json:"id"`
Action string `json:"action"`
SecretID string `json:"secretId"`
CreatedAt string `json:"createdAt"`
ViewsRemaining *int `json:"viewsRemaining"`
// Count is the number of secrets in a bulk burn.
Count *int `json:"count"`
// Viewer is set for organization secrets and for secrets with recipients.
Viewer string `json:"viewer"`
Organization string `json:"organization"`
IsOwnAction bool `json:"isOwnAction"`
}
Activity is one entry of the view receipts of the signed-in user.
type ActivityList ¶
ActivityList is one page of view receipts.
type AdminUser ¶
type AdminUser struct {
ID string `json:"id"`
Username string `json:"username"`
Email string `json:"email"`
Name *string `json:"name,omitempty"`
Role *string `json:"role"`
Banned *bool `json:"banned"`
BanReason *string `json:"banReason,omitempty"`
BanExpires *string `json:"banExpires,omitempty"`
CreatedAt string `json:"createdAt"`
}
AdminUser is a user as an admin sees it.
type Analytics ¶
type Analytics struct {
Range string `json:"range"`
Secrets map[string]any `json:"secrets"`
Visitors []any `json:"visitors"`
}
Analytics holds the secret statistics and the daily visitor statistics.
type AuditEntry ¶
type AuditEntry struct {
ID string `json:"id"`
Action string `json:"action"`
TargetType string `json:"targetType"`
TargetID string `json:"targetId"`
Metadata map[string]any `json:"metadata"`
CreatedAt string `json:"createdAt"`
Actor *struct {
ID string `json:"id"`
Username string `json:"username"`
Email string `json:"email"`
} `json:"actor"`
Organization *struct {
Name string `json:"name"`
Slug string `json:"slug"`
} `json:"organization"`
}
AuditEntry is one entry of an audit log. It holds metadata only.
type AuditList ¶
type AuditList struct {
Data []AuditEntry `json:"data"`
Meta Page `json:"meta"`
}
AuditList is one page of an audit log.
type CreateSecretInput ¶
type CreateSecretInput struct {
Text string
Title string
// ExpiresIn is the lifetime in seconds. Use a value from Expirations.
ExpiresIn int
// Views is the view limit. It is ignored when NoViewLimit is true.
Views int
// NoViewLimit keeps the secret until it expires, however many times
// people open it. The web app calls this "Burn after time".
NoViewLimit bool
// Burnable sends the "burned" webhook when the last view is used.
Burnable bool
Password string
IPRange string
Files []FileInput
// NotifyOnView emails the creator each time someone opens the secret. It
// needs a signed-in creator and email delivery on the instance.
NotifyOnView bool
// ReleaseIn keeps the secret closed for this many seconds. 0 opens it now.
ReleaseIn int
// Recipients are the email addresses that can open the secret. Each
// recipient must sign in with a verified address.
Recipients []string
// OrgOnly lets only the members of Organization open the secret.
OrgOnly bool
// Organization is the ID or the slug of an organization that owns the
// secret. The creator must be a member.
Organization string
}
CreateSecretInput describes a new secret.
type CreateSecretResult ¶
type CreateSecretResult struct {
ID string `json:"id"`
Link string `json:"link"`
ExpiresIn string `json:"expiresIn"`
Views *int `json:"views"`
PasswordProtected bool `json:"passwordProtected"`
IPRange string `json:"ipRange,omitempty"`
Files []string `json:"files"`
CanDelete bool `json:"canDelete"`
NotifyOnView bool `json:"notifyOnView,omitempty"`
ReleaseIn int `json:"releaseInSeconds,omitempty"`
Recipients []string `json:"recipients,omitempty"`
OrgOnly bool `json:"orgOnly,omitempty"`
Organization string `json:"organization,omitempty"`
}
CreateSecretResult is the created secret.
type CreateUserInput ¶
type CreateUserInput struct {
Username string `json:"username"`
Email string `json:"email"`
Password string `json:"password"`
Name string `json:"name,omitempty"`
Role string `json:"role,omitempty"`
}
CreateUserInput describes a new user.
type Health ¶
type Health struct {
Status string `json:"status"`
Checks map[string]any `json:"checks,omitempty"`
}
Health is the readiness report of the instance.
type InboxSendInput ¶
type InboxSendInput struct {
// Inbox is the slug of the organization, @slug, or the inbox link
// https://host/@slug/inbox.
Inbox string
Subject string
Message string
// From is an optional name or contact. Only the organization sees it.
From string
Files []FileInput
}
InboxSendInput is a message for the encrypted inbox of an organization.
type InboxSendResult ¶
type InboxSendResult struct {
ID string `json:"id"`
Organization string `json:"organization"`
Files []string `json:"files"`
}
InboxSendResult is a delivered message.
type Invite ¶
type Invite struct {
ID string `json:"id"`
Code string `json:"code"`
Uses int `json:"uses"`
MaxUses *int `json:"maxUses"`
ExpiresAt *string `json:"expiresAt"`
CreatedBy string `json:"createdBy"`
CreatedAt string `json:"createdAt"`
IsActive bool `json:"isActive"`
}
Invite is an invite code.
type LoginResult ¶
LoginResult is a new session.
func Login ¶
func Login(ctx context.Context, baseURL, userAgent, username, password string, secondFactor SecondFactor) (*LoginResult, error)
Login signs in with a username and a password and returns the session cookie. When the account has 2FA, it calls secondFactor for a code.
type Member ¶
type Member struct {
MembershipID string `json:"membershipId"`
UserID string `json:"userId"`
Username string `json:"username"`
Email string `json:"email"`
Role string `json:"role"`
JoinedAt string `json:"joinedAt"`
TwoFactorEnabled bool `json:"twoFactorEnabled"`
HasPasskey bool `json:"hasPasskey"`
}
Member is a member of an organization.
type NotReleasedError ¶
type NotReleasedError struct {
AvailableAt string
}
NotReleasedError means that a scheduled secret is still closed. Opening it uses no view.
func (*NotReleasedError) Error ¶
func (e *NotReleasedError) Error() string
type OrgDomain ¶
type OrgDomain struct {
ID string `json:"id"`
Domain string `json:"domain"`
Verified bool `json:"verified"`
VerifiedAt *string `json:"verifiedAt"`
Record struct {
Name string `json:"name"`
Value string `json:"value"`
} `json:"record"`
}
OrgDomain is an email domain whose users join the organization.
type Organization ¶
type Organization struct {
ID string `json:"id"`
Name string `json:"name"`
Slug string `json:"slug"`
Plan string `json:"plan"`
Role string `json:"role"`
JoinedAt string `json:"joinedAt"`
}
Organization is an organization of the signed-in user.
type Page ¶
type Page struct {
Total int `json:"total"`
Page int `json:"page"`
TotalPages int `json:"totalPages"`
}
Page is the pagination data of a list.
type ReadSecretInput ¶
type ReadSecretInput struct {
// Ref is a secret link or a secret ID.
Ref string
// Key overrides the key in the link.
Key string
Password string
// SkipFiles does not download the attachments.
SkipFiles bool
}
ReadSecretInput describes a secret to open. Opening a secret uses a view.
type ReadSecretResult ¶
type ReadSecretResult struct {
ID string `json:"id"`
Title string `json:"title"`
Content string `json:"content"`
ViewsRemaining *int `json:"viewsRemaining"`
ExpiresAt string `json:"expiresAt,omitempty"`
Files []SecretFile `json:"files"`
CanDelete bool `json:"canDelete"`
}
ReadSecretResult is a decrypted secret.
type SecondFactor ¶
SecondFactor asks for a 2FA code during sign-in. It returns the code and true when the code is a backup code.
type SecretFile ¶
type SecretFile struct {
ID string `json:"id"`
Name string `json:"name"`
Size int `json:"size"`
Data []byte `json:"-"`
}
SecretFile is a decrypted attachment.
type SecretList ¶
type SecretList struct {
Data []SecretSummary `json:"data"`
Meta Page `json:"meta"`
}
SecretList is one page of secrets.
type SecretSummary ¶
type SecretSummary struct {
ID string `json:"id"`
CreatedAt string `json:"createdAt"`
ExpiresAt string `json:"expiresAt"`
Views *int `json:"views"`
IsPasswordProtected bool `json:"isPasswordProtected"`
IPRange string `json:"ipRange"`
IsBurnable bool `json:"isBurnable"`
FileCount int `json:"fileCount"`
NotifyOnView bool `json:"notifyOnView"`
AvailableAt string `json:"availableAt"`
RecipientLock string `json:"recipientLock"`
OpenCount int `json:"openCount"`
LastOpenedAt string `json:"lastOpenedAt"`
}
SecretSummary is one secret in a list. The server knows only metadata.
type Service ¶
type Service struct {
API *api.Client
Tokens TokenStore
}
Service runs operations against one Hemmelig instance.
func (*Service) Account ¶
Account returns the account of the current credential. /api/account returns the role and the 2FA state for a session and for an API key. A session also adds the display name.
func (*Service) AddDomain ¶
AddDomain adds an email domain. Verify it with the TXT record in the result.
func (*Service) BanUser ¶
func (s *Service) BanUser(ctx context.Context, ref, reason string, expiresInSeconds int) (*AdminUser, error)
BanUser bans a user. Zero seconds bans the user until an admin unbans them.
func (*Service) BurnSecrets ¶
BurnSecrets deletes secrets of the signed-in user at once. Without IDs, it deletes all active secrets of the user. It returns the number of deleted secrets.
func (*Service) ChangePassword ¶
ChangePassword changes the password of the signed-in user.
func (*Service) CreateAPIKey ¶
func (s *Service) CreateAPIKey(ctx context.Context, name string, expiresInDays int) (*APIKey, error)
CreateAPIKey creates an API key. It needs a session. Zero days means that the key does not expire.
func (*Service) CreateInvite ¶
CreateInvite creates an invite code. Zero days means no expiry.
func (*Service) CreateSecret ¶
func (s *Service) CreateSecret(ctx context.Context, in CreateSecretInput) (*CreateSecretResult, error)
CreateSecret encrypts the input locally and stores the ciphertext.
func (*Service) CreateUser ¶
CreateUser creates a user.
func (*Service) DeactivateInvite ¶
DeactivateInvite stops an invite code. It accepts the ID or the code.
func (*Service) DeleteAccount ¶
DeleteAccount deletes the signed-in user and all of their data.
func (*Service) DeleteSecret ¶
DeleteSecret deletes a secret. It uses a stored delete token when this CLI created or opened the secret, and owner authentication otherwise.
func (*Service) DeleteUser ¶
DeleteUser deletes a user and the data of the user.
func (*Service) DisableTwoFactor ¶
DisableTwoFactor turns off 2FA for the signed-in user.
func (*Service) EnableTwoFactor ¶
EnableTwoFactor starts the 2FA setup. Call VerifyTwoFactor with a code from the authenticator app to finish it.
func (*Service) ExportAudit ¶
ExportAudit returns the audit log as CSV, with at most 10,000 entries.
func (*Service) FindOrganization ¶
FindOrganization returns the organization with this ID or slug. A slug can start with @, as in the organization links.
func (*Service) GetAnalytics ¶
GetAnalytics returns the analytics for a time range.
func (*Service) GetHealth ¶
GetHealth calls the readiness probe. It returns the report also when the instance is unhealthy.
func (*Service) InstanceSettings ¶
InstanceSettings returns the instance settings, or one section of them.
func (*Service) ListAPIKeys ¶
ListAPIKeys lists the API keys of the current user.
func (*Service) ListActivity ¶
ListActivity lists when the secrets of the signed-in user were opened, burned or deleted. The receipts stay after the secrets are gone.
func (*Service) ListAudit ¶
func (s *Service) ListAudit(ctx context.Context, orgRef, category string, page, limit int) (*AuditList, error)
ListAudit lists the audit log of the instance (orgRef "", admins only) or of an organization (owners and admins).
func (*Service) ListDomains ¶
ListDomains lists the email domains of an organization. It needs a session.
func (*Service) ListInvites ¶
ListInvites lists the invite codes.
func (*Service) ListMembers ¶
ListMembers lists the members of an organization.
func (*Service) ListOrganizations ¶
func (s *Service) ListOrganizations(ctx context.Context) ([]Organization, error)
ListOrganizations lists the organizations of the signed-in user. The server also adds the user to organizations of a verified email domain.
func (*Service) ListSecrets ¶
ListSecrets lists the secrets of the signed-in user.
func (*Service) ListUsers ¶
func (s *Service) ListUsers(ctx context.Context, search string, page, pageSize int) (*UserList, error)
ListUsers lists the users. Search matches the username, the email and the name.
func (*Service) ReadSecret ¶
func (s *Service) ReadSecret(ctx context.Context, in ReadSecretInput) (*ReadSecretResult, error)
ReadSecret opens a secret, decrypts it locally and downloads its files.
func (*Service) RemoveDomain ¶
RemoveDomain removes a domain. The current members stay.
func (*Service) ResolveUser ¶
ResolveUser finds the ID of a user from an ID, a username or an email.
func (*Service) RevokeAPIKey ¶
RevokeAPIKey deletes an API key.
func (*Service) SendInboxMessage ¶
func (s *Service) SendInboxMessage(ctx context.Context, in InboxSendInput) (*InboxSendResult, error)
SendInboxMessage encrypts a message with the public key of the inbox and delivers it. Attachments need an API key or a session, as in the web app.
func (*Service) Session ¶
Session returns the user of the session cookie, or nil when the session is missing or expired.
func (*Service) SetUserPassword ¶
SetUserPassword sets a new password for a user.
func (*Service) TwoFactorStatus ¶
TwoFactorStatus reports whether 2FA is on for the signed-in user.
func (*Service) UpdateAccount ¶
UpdateAccount changes the username and the email. The API needs both, so an empty value keeps the current one.
func (*Service) UpdateInstanceSettings ¶
func (s *Service) UpdateInstanceSettings(ctx context.Context, values map[string]any) (map[string]any, error)
UpdateInstanceSettings changes instance settings and returns the result.
func (*Service) UpdateUser ¶
func (s *Service) UpdateUser(ctx context.Context, ref string, in UpdateUserInput) (*AdminUser, error)
UpdateUser changes the username, the email or the role of a user.
func (*Service) VerifyDomain ¶
VerifyDomain checks the DNS TXT record of a domain.
type SettingKind ¶
type SettingKind int
SettingKind is the JSON type of an instance setting.
const ( KindString SettingKind = iota KindBool KindInt )
The kinds of instance settings.
type TokenStore ¶
type TokenStore interface {
Save(baseURL, id, token string) error
Get(baseURL, id string) string
Forget(baseURL, id string) error
}
TokenStore keeps delete tokens so that a later delete works.
type TwoFactorSetup ¶
type TwoFactorSetup struct {
TOTPURI string `json:"totpURI"`
BackupCodes []string `json:"backupCodes"`
}
TwoFactorSetup is the data to add the account to an authenticator app.
type UpdateUserInput ¶
type UpdateUserInput struct {
Username string `json:"username,omitempty"`
Email string `json:"email,omitempty"`
Role string `json:"role,omitempty"`
}
UpdateUserInput changes a user. Empty fields keep their value.