service

package
v2.0.0 Latest Latest
Warning

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

Go to latest
Published: Oct 8, 2026 License: MIT Imports: 19 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

View Source
const (
	MinReleaseSeconds = 60
	MaxReleaseSeconds = 30 * 24 * 3600
	MaxRecipients     = 20
)

The server limits for the v7 options.

View Source
const MaxBurnIDs = 500

MaxBurnIDs is the most secrets in one burn request.

View Source
const (
	MaxInboxFiles = 10
)

The server limits for inbox messages.

Variables

View Source
var AnalyticsRanges = []string{"7d", "14d", "30d"}

AnalyticsRanges are the time ranges that the analytics API accepts.

View Source
var AuditCategories = []string{"secrets", "people", "settings", "keys"}

AuditCategories are the filters of an audit log.

View Source
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.

View Source
var ErrNoKey = errors.New("the link has no decryption key: give the key with --key")

ErrNoKey means that the link has no decryption key.

View Source
var ErrPasswordRequired = errors.New("this secret is password protected: give the password with --password")

ErrPasswordRequired means that the secret needs a password.

View Source
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.

View Source
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.

View Source
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

func ExpirationName(seconds int) string

ExpirationName converts seconds back to a name, or returns the seconds.

func ParseDuration

func ParseDuration(value string) (int, error)

ParseDuration converts a duration such as 30m, 2h or 7d to seconds.

func ParseExpiration

func ParseExpiration(name string) (int, error)

ParseExpiration converts a name such as "1d" to seconds.

func ParseSettings

func ParseSettings(section string, pairs []string) (map[string]any, error)

ParseSettings converts key=value pairs of a section to typed values.

func SectionKeys

func SectionKeys(section string) []string

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

type ActivityList struct {
	Data []Activity `json:"data"`
	Meta Page       `json:"meta"`
}

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 FileInput

type FileInput struct {
	Name string
	Data []byte
}

FileInput is a file to attach to a new secret.

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

type LoginResult struct {
	Cookie string
	User   *User
}

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

type SecondFactor func() (code string, backup bool, err error)

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

func (s *Service) Account(ctx context.Context) (*User, error)

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

func (s *Service) AddDomain(ctx context.Context, orgRef, domain string) (*OrgDomain, error)

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

func (s *Service) BurnSecrets(ctx context.Context, ids []string, all bool) (int, error)

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

func (s *Service) ChangePassword(ctx context.Context, current, next string) error

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

func (s *Service) CreateInvite(ctx context.Context, maxUses, expiresInDays int) (*Invite, error)

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

func (s *Service) CreateUser(ctx context.Context, in CreateUserInput) (*AdminUser, error)

CreateUser creates a user.

func (*Service) DeactivateInvite

func (s *Service) DeactivateInvite(ctx context.Context, ref string) error

DeactivateInvite stops an invite code. It accepts the ID or the code.

func (*Service) DeleteAccount

func (s *Service) DeleteAccount(ctx context.Context) error

DeleteAccount deletes the signed-in user and all of their data.

func (*Service) DeleteSecret

func (s *Service) DeleteSecret(ctx context.Context, refValue string) error

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

func (s *Service) DeleteUser(ctx context.Context, ref string) error

DeleteUser deletes a user and the data of the user.

func (*Service) DisableTwoFactor

func (s *Service) DisableTwoFactor(ctx context.Context, password string) error

DisableTwoFactor turns off 2FA for the signed-in user.

func (*Service) EnableTwoFactor

func (s *Service) EnableTwoFactor(ctx context.Context, password string) (*TwoFactorSetup, error)

EnableTwoFactor starts the 2FA setup. Call VerifyTwoFactor with a code from the authenticator app to finish it.

func (*Service) ExportAudit

func (s *Service) ExportAudit(ctx context.Context, orgRef, category string) ([]byte, error)

ExportAudit returns the audit log as CSV, with at most 10,000 entries.

func (*Service) FindOrganization

func (s *Service) FindOrganization(ctx context.Context, ref string) (*Organization, error)

FindOrganization returns the organization with this ID or slug. A slug can start with @, as in the organization links.

func (*Service) GetAnalytics

func (s *Service) GetAnalytics(ctx context.Context, timeRange string) (*Analytics, error)

GetAnalytics returns the analytics for a time range.

func (*Service) GetHealth

func (s *Service) GetHealth(ctx context.Context) (*Health, error)

GetHealth calls the readiness probe. It returns the report also when the instance is unhealthy.

func (*Service) InstanceSettings

func (s *Service) InstanceSettings(ctx context.Context, section string) (map[string]any, error)

InstanceSettings returns the instance settings, or one section of them.

func (*Service) ListAPIKeys

func (s *Service) ListAPIKeys(ctx context.Context) ([]APIKey, error)

ListAPIKeys lists the API keys of the current user.

func (*Service) ListActivity

func (s *Service) ListActivity(ctx context.Context, page, limit int) (*ActivityList, error)

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

func (s *Service) ListDomains(ctx context.Context, orgRef string) ([]OrgDomain, error)

ListDomains lists the email domains of an organization. It needs a session.

func (*Service) ListInvites

func (s *Service) ListInvites(ctx context.Context) ([]Invite, error)

ListInvites lists the invite codes.

func (*Service) ListMembers

func (s *Service) ListMembers(ctx context.Context, orgRef string) ([]Member, error)

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

func (s *Service) ListSecrets(ctx context.Context, page, limit int) (*SecretList, error)

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) Logout

func (s *Service) Logout(ctx context.Context) error

Logout ends the session on the server.

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

func (s *Service) RemoveDomain(ctx context.Context, orgRef, domain string) error

RemoveDomain removes a domain. The current members stay.

func (*Service) ResolveUser

func (s *Service) ResolveUser(ctx context.Context, ref string) (string, error)

ResolveUser finds the ID of a user from an ID, a username or an email.

func (*Service) RevokeAPIKey

func (s *Service) RevokeAPIKey(ctx context.Context, id string) error

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

func (s *Service) Session(ctx context.Context) (*User, error)

Session returns the user of the session cookie, or nil when the session is missing or expired.

func (*Service) SetUserPassword

func (s *Service) SetUserPassword(ctx context.Context, ref, password string) error

SetUserPassword sets a new password for a user.

func (*Service) TwoFactorStatus

func (s *Service) TwoFactorStatus(ctx context.Context) (bool, error)

TwoFactorStatus reports whether 2FA is on for the signed-in user.

func (*Service) UnbanUser

func (s *Service) UnbanUser(ctx context.Context, ref string) (*AdminUser, error)

UnbanUser removes the ban of a user.

func (*Service) UpdateAccount

func (s *Service) UpdateAccount(ctx context.Context, username, email string) (*User, error)

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

func (s *Service) VerifyDomain(ctx context.Context, orgRef, domain string) (*OrgDomain, error)

VerifyDomain checks the DNS TXT record of a domain.

func (*Service) VerifyTwoFactor

func (s *Service) VerifyTwoFactor(ctx context.Context, code string) error

VerifyTwoFactor checks a TOTP code for the signed-in user. It finishes the 2FA setup.

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.

type User

type User struct {
	ID               string `json:"id,omitempty"`
	Username         string `json:"username"`
	Email            string `json:"email"`
	Name             string `json:"name,omitempty"`
	Role             string `json:"role,omitempty"`
	TwoFactorEnabled *bool  `json:"twoFactorEnabled,omitempty"`
}

User is the signed-in user.

type UserList

type UserList struct {
	Users      []AdminUser `json:"users"`
	Total      int         `json:"total"`
	Page       int         `json:"page"`
	PageSize   int         `json:"pageSize"`
	TotalPages int         `json:"totalPages"`
}

UserList is one page of users.

Jump to

Keyboard shortcuts

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