proton

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Feb 9, 2023 License: MIT Imports: 41 Imported by: 2

README

Go Proton API

CI Status GoDoc Go Report Card License

This repository holds Go Proton API, a Go library implementing a client and development server for (a subset of) the Proton REST API.

The license can be found in the LICENSE file.

For the contribution policy, see CONTRIBUTING.

Environment variables

Most of the integration tests run locally. The ones that interact with Proton servers require the following environment variables set:

  • GO_PROTON_API_TEST_USERNAME
  • GO_PROTON_API_TEST_PASSWORD

Contribution

The library is maintained by Proton AG, and is not actively looking for contributors.

Documentation

Overview

Package proton implements types for accessing the Proton API.

Index

Examples

Constants

View Source
const (
	FieldPMScheme   = "X-PM-SCHEME"
	FieldPMSign     = "X-PM-SIGN"
	FieldPMEncrypt  = "X-PM-ENCRYPT"
	FieldPMMIMEType = "X-PM-MIMETYPE"
)
View Source
const (
	InboxLabel        = "0"
	AllDraftsLabel    = "1"
	AllSentLabel      = "2"
	TrashLabel        = "3"
	SpamLabel         = "4"
	AllMailLabel      = "5"
	ArchiveLabel      = "6"
	SentLabel         = "7"
	DraftsLabel       = "8"
	OutboxLabel       = "9"
	StarredLabel      = "10"
	AllScheduledLabel = "12"
)
View Source
const (
	// DefaultHostURL is the default host of the API.
	DefaultHostURL = "https://mail.proton.me/api"

	// DefaultAppVersion is the default app version used to communicate with the API.
	// This must be changed (using the WithAppVersion option) for production use.
	DefaultAppVersion = "go-proton-api"
)

Variables

View Source
var CharsetReader func(charset string, input io.Reader) (io.Reader, error)

CharsetReader returns a charset decoder for the given charset. If set, it will be used to decode non-utf8 encoded messages.

View Source
var ErrBadHeader = errors.New("bad header")
View Source
var ErrInvalidProof = errors.New("unexpected server proof")
View Source
var ErrJobCancelled = errors.New("job cancelled by surrounding context")

ErrJobCancelled indicates the job was cancelled.

View Source
var ErrNoSuchLabel = errors.New("no such label")
View Source
var ErrUndoTokenExpired = errors.New("undo token expired")

Functions

func BuildRFC822

func BuildRFC822(kr *crypto.KeyRing, msg Message, attData map[string][]byte) ([]byte, error)

func ClientIDFromContext

func ClientIDFromContext(ctx context.Context) (uint64, bool)

ClientIDFromContext returns true if this context was marked as originating from a client.

func DecodeKeyPacket

func DecodeKeyPacket(packet string) []byte

func EncryptRFC822

func EncryptRFC822(kr *crypto.KeyRing, literal []byte) ([]byte, error)

EncryptRFC822 encrypts the given message literal as a PGP attachment.

func InsecureTransport

func InsecureTransport() *http.Transport

InsecureTransport returns an http.Transport with InsecureSkipVerify set to true.

func NewDropConn added in v0.4.0

func NewDropConn(c net.Conn, l *Listener) net.Conn

func NewHangConn added in v0.4.0

func NewHangConn(c net.Conn, l *Listener) net.Conn

func Unlock

func Unlock(user User, addresses []Address, saltedKeyPass []byte) (*crypto.KeyRing, map[string]*crypto.KeyRing, error)

func WithClient

func WithClient(parent context.Context, clientID uint64) context.Context

WithClient marks this context as originating from the client with the given ID.

Types

type APIBool

type APIBool int

APIBool is the boolean type used by the API (0 or 1).

const (
	APIFalse APIBool = iota
	APITrue
)

type APIError added in v0.3.0

type APIError struct {
	// Status is the HTTP status code of the response that caused the error.
	Status int

	// Code is the error code returned by the API.
	Code Code

	// Message is the error message returned by the API.
	Message string `json:"Error"`
}

APIError represents an error returned by the API.

func (APIError) Error added in v0.3.0

func (err APIError) Error() string

type Address

type Address struct {
	ID    string
	Email string

	Send    Bool
	Receive Bool
	Status  AddressStatus

	Order       int
	DisplayName string

	Keys Keys
}

type AddressEvent

type AddressEvent struct {
	EventItem

	Address Address
}

type AddressStatus

type AddressStatus int
const (
	AddressStatusDisabled AddressStatus = iota
	AddressStatusEnabled
	AddressStatusDeleting
)

type Attachment

type Attachment struct {
	ID string

	Name        string
	Size        int64
	MIMEType    rfc822.MIMEType
	Disposition Disposition
	Headers     Headers

	KeyPackets string
	Signature  string
}

type AttachmentAllocator added in v0.4.0

type AttachmentAllocator interface {
	// NewBuffer should return a new byte buffer for use. Note that this function may be called from multiple go-routines.
	NewBuffer() *bytes.Buffer
}

AttachmentAllocator abstract the attachment download buffer creation.

type Attributes

type Attributes uint32

type Auth

type Auth struct {
	UserID string

	UID          string
	AccessToken  string
	RefreshToken string
	ServerProof  string

	Scope        string
	TwoFA        TwoFAInfo `json:"2FA"`
	PasswordMode PasswordMode
}

type Auth2FAReq

type Auth2FAReq struct {
	TwoFactorCode string   `json:",omitempty"`
	FIDO2         FIDO2Req `json:",omitempty"`
}

type AuthHandler

type AuthHandler func(Auth)

AuthHandler is given any new auths that are returned from the API due to an unexpected auth refresh.

type AuthInfo

type AuthInfo struct {
	Version         int
	Modulus         string
	ServerEphemeral string
	Salt            string
	SRPSession      string
	TwoFA           TwoFAInfo `json:"2FA"`
}

type AuthInfoReq

type AuthInfoReq struct {
	Username string
}

type AuthModulus added in v0.2.2

type AuthModulus struct {
	Modulus   string
	ModulusID string
}

type AuthRefreshReq

type AuthRefreshReq struct {
	UID          string
	RefreshToken string
	ResponseType string
	GrantType    string
	RedirectURI  string
	State        string
}

type AuthReq

type AuthReq struct {
	Auth2FAReq `json:",omitempty"`

	Username        string
	ClientEphemeral string
	ClientProof     string
	SRPSession      string
}

type AuthSession

type AuthSession struct {
	UID        string
	CreateTime int64

	ClientID  string
	MemberID  string
	Revocable Bool

	LocalizedClientName string
}

type AuthVerifier added in v0.2.2

type AuthVerifier struct {
	Version   int
	ModulusID string
	Salt      string
	Verifier  string
}

type Block

type Block struct {
	Index          int
	URL            string
	EncSignature   string
	SignatureEmail string
}

type Bool

type Bool bool

Bool is a convenience type for boolean values; it converts from APIBool to Go's builtin bool type.

func (Bool) MarshalJSON

func (b Bool) MarshalJSON() ([]byte, error)

func (*Bool) UnmarshalJSON

func (b *Bool) UnmarshalJSON(data []byte) error

type Calendar

type Calendar struct {
	ID          string
	Name        string
	Description string
	Color       string
	Display     Bool

	Type  CalendarType
	Flags CalendarFlag
}

type CalendarAttendee

type CalendarAttendee struct {
	ID          string
	Token       string
	Status      CalendarAttendeeStatus
	Permissions CalendarPermissions
}

type CalendarAttendeeStatus

type CalendarAttendeeStatus int

TODO: What is this?

const (
	CalendarAttendeeStatusPending CalendarAttendeeStatus = iota
	CalendarAttendeeStatusMaybe
	CalendarAttendeeStatusNo
	CalendarAttendeeStatusYes
)

type CalendarEvent

type CalendarEvent struct {
	ID            string
	UID           string
	CalendarID    string
	SharedEventID string

	CreateTime    int64
	LastEditTime  int64
	StartTime     int64
	StartTimezone string
	EndTime       int64
	EndTimezone   string
	FullDay       Bool

	Author      string
	Permissions CalendarPermissions
	Attendees   []CalendarAttendee

	SharedKeyPacket   string
	CalendarKeyPacket string

	SharedEvents    []CalendarEventPart
	CalendarEvents  []CalendarEventPart
	AttendeesEvents []CalendarEventPart
	PersonalEvents  []CalendarEventPart
}

type CalendarEventPart

type CalendarEventPart struct {
	MemberID string

	Type      CalendarEventType
	Data      string
	Signature string
	Author    string
}

TODO: Only personal events have MemberID; should we have a different type for that?

func (CalendarEventPart) Decode

func (part CalendarEventPart) Decode(calKR *crypto.KeyRing, addrKR *crypto.KeyRing, kp []byte) error

type CalendarEventType

type CalendarEventType int
const (
	CalendarEventTypeClear CalendarEventType = iota
	CalendarEventTypeEncrypted
	CalendarEventTypeSigned
)

type CalendarFlag

type CalendarFlag int64
const (
	CalendarFlagActive CalendarFlag = 1 << iota
	CalendarFlagUpdatePassphrase
	CalendarFlagResetNeeded
	CalendarFlagIncompleteSetup
	CalendarFlagLostAccess
)

type CalendarKey

type CalendarKey struct {
	ID           string
	CalendarID   string
	PassphraseID string
	PrivateKey   string
	Flags        CalendarKeyFlag
}

func (CalendarKey) Unlock

func (key CalendarKey) Unlock(passphrase []byte) (*crypto.Key, error)

type CalendarKeyFlag

type CalendarKeyFlag int64

TODO: What is this?

const (
	CalendarKeyFlagActive CalendarKeyFlag = 1 << iota
	CalendarKeyFlagPrimary
)

type CalendarKeys

type CalendarKeys []CalendarKey

func (CalendarKeys) Unlock

func (keys CalendarKeys) Unlock(passphrase []byte) (*crypto.KeyRing, error)

type CalendarMember

type CalendarMember struct {
	ID          string
	Permissions CalendarPermissions
	Email       string
	Color       string
	Display     Bool
	CalendarID  string
}

type CalendarPassphrase

type CalendarPassphrase struct {
	ID                string
	Flags             CalendarPassphraseFlag
	MemberPassphrases []MemberPassphrase
}

TODO: Support invitations.

func (CalendarPassphrase) Decrypt

func (passphrase CalendarPassphrase) Decrypt(memberID string, addrKR *crypto.KeyRing) ([]byte, error)

type CalendarPassphraseFlag

type CalendarPassphraseFlag int64

TODO: What is this?

type CalendarPermissions

type CalendarPermissions int

TODO: What is this?

type CalendarType

type CalendarType int
const (
	CalendarTypeNormal CalendarType = iota
	CalendarTypeSubscribed
)

type Card

type Card struct {
	Type      CardType
	Data      string
	Signature string
}

func NewCard

func NewCard(kr *crypto.KeyRing, cardType CardType) (*Card, error)

func (*Card) ChangeType

func (c *Card) ChangeType(kr *crypto.KeyRing, cardType CardType) error

func (*Card) DeleteGroup

func (c *Card) DeleteGroup(kr *crypto.KeyRing, groupKey, groupValue string) error

DeleteGroup removes all values in the group defined by the given key/value pair.

func (Card) Get

func (c Card) Get(kr *crypto.KeyRing, key string) ([]*vcard.Field, error)

func (Card) GetGroup

func (c Card) GetGroup(kr *crypto.KeyRing, groupKey, groupValue string) (CardGroup, error)

GetGroup returns a type to manipulate the group defined by the given key/value pair.

func (*Card) Set

func (c *Card) Set(kr *crypto.KeyRing, key, value string) error

type CardGroup

type CardGroup struct {
	Card
	// contains filtered or unexported fields
}

func (*CardGroup) Add

func (g *CardGroup) Add(key, value string, params vcard.Params) error

Add adds a value to the group.

func (CardGroup) Get

func (g CardGroup) Get(key string) ([]string, error)

Get returns the values in the group with the given key.

func (*CardGroup) Remove

func (g *CardGroup) Remove(key, value string) error

Remove removes the value in the group with the given key/value.

func (*CardGroup) RemoveAll

func (g *CardGroup) RemoveAll(key string) error

RemoveAll removes all values in the group with the given key.

func (*CardGroup) Set

func (g *CardGroup) Set(key, value string, params vcard.Params) error

Set sets the value in the group.

type CardType

type CardType int
const (
	CardTypeClear CardType = iota
	CardTypeEncrypted
	CardTypeSigned
)

type Cards

type Cards []*Card

func (*Cards) Get

func (c *Cards) Get(cardType CardType) (*Card, bool)

func (*Cards) Merge

func (c *Cards) Merge(kr *crypto.KeyRing) (vcard.Card, error)

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is the proton client.

func (*Client) AddAuthHandler

func (c *Client) AddAuthHandler(handler AuthHandler)
Example
ctx, cancel := context.WithCancel(context.Background())
defer cancel()

// Create a new manager.
m := proton.New()

// Create a new client.
c := m.NewClient("...uid...", "...acc...", "...ref...")
defer c.Close()

// Register an auth handler with the client.
// This could be used for example to save the auth to keychain.
c.AddAuthHandler(func(auth proton.Auth) {
	// Do something with auth.
})

if _, err := c.GetUser(ctx); err != nil {
	panic(err)
}
Output:

func (*Client) AddDeauthHandler

func (c *Client) AddDeauthHandler(handler Handler)

func (*Client) AddPostRequestHook

func (c *Client) AddPostRequestHook(hook resty.ResponseMiddleware)

func (*Client) AddPreRequestHook

func (c *Client) AddPreRequestHook(hook resty.RequestMiddleware)

func (*Client) Auth2FA

func (c *Client) Auth2FA(ctx context.Context, req Auth2FAReq) error

func (*Client) AuthDelete

func (c *Client) AuthDelete(ctx context.Context) error

func (*Client) AuthRevoke

func (c *Client) AuthRevoke(ctx context.Context, authUID string) error

func (*Client) AuthRevokeAll

func (c *Client) AuthRevokeAll(ctx context.Context) error

func (*Client) AuthSessions

func (c *Client) AuthSessions(ctx context.Context) ([]AuthSession, error)

func (*Client) Close

func (c *Client) Close()

func (*Client) CountCalendarEvents

func (c *Client) CountCalendarEvents(ctx context.Context, calendarID string) (int, error)

func (*Client) CountContactEmails

func (c *Client) CountContactEmails(ctx context.Context, email string) (int, error)

func (*Client) CountContacts

func (c *Client) CountContacts(ctx context.Context) (int, error)

func (*Client) CountMessages

func (c *Client) CountMessages(ctx context.Context) (int, error)

func (*Client) CreateAddressKey

func (c *Client) CreateAddressKey(ctx context.Context, req CreateAddressKeyReq) (Key, error)

func (*Client) CreateContacts

func (c *Client) CreateContacts(ctx context.Context, req CreateContactsReq) ([]CreateContactsRes, error)

func (*Client) CreateDraft

func (c *Client) CreateDraft(ctx context.Context, addrKR *crypto.KeyRing, req CreateDraftReq) (Message, error)

func (*Client) CreateLabel

func (c *Client) CreateLabel(ctx context.Context, req CreateLabelReq) (Label, error)

func (*Client) CreateLegacyAddressKey

func (c *Client) CreateLegacyAddressKey(ctx context.Context, req CreateAddressKeyReq) (Key, error)

func (*Client) DeleteAddress added in v0.2.2

func (c *Client) DeleteAddress(ctx context.Context, addressID string) error

func (*Client) DeleteAddressKey

func (c *Client) DeleteAddressKey(ctx context.Context, keyID string, keyList KeyList) error

func (*Client) DeleteContacts

func (c *Client) DeleteContacts(ctx context.Context, req DeleteContactsReq) error

func (*Client) DeleteLabel

func (c *Client) DeleteLabel(ctx context.Context, labelID string) error

func (*Client) DeleteMessage

func (c *Client) DeleteMessage(ctx context.Context, messageIDs ...string) error

func (*Client) DeleteUser added in v0.2.2

func (c *Client) DeleteUser(ctx context.Context, password []byte, req DeleteUserReq) error

func (*Client) DisableAddress added in v0.2.2

func (c *Client) DisableAddress(ctx context.Context, addressID string) error

func (*Client) EnableAddress added in v0.2.2

func (c *Client) EnableAddress(ctx context.Context, addressID string) error

func (*Client) GetAddress

func (c *Client) GetAddress(ctx context.Context, addressID string) (Address, error)

func (*Client) GetAddresses

func (c *Client) GetAddresses(ctx context.Context) ([]Address, error)

func (*Client) GetAllCalendarEvents

func (c *Client) GetAllCalendarEvents(ctx context.Context, calendarID string, filter url.Values) ([]CalendarEvent, error)

func (*Client) GetAllContactEmails

func (c *Client) GetAllContactEmails(ctx context.Context, email string) ([]ContactEmail, error)

func (*Client) GetAllContacts

func (c *Client) GetAllContacts(ctx context.Context) ([]Contact, error)

func (*Client) GetAttachment

func (c *Client) GetAttachment(ctx context.Context, attachmentID string) ([]byte, error)

func (*Client) GetAttachmentInto added in v0.4.0

func (c *Client) GetAttachmentInto(ctx context.Context, attachmentID string, reader io.ReaderFrom) error

func (*Client) GetBlock

func (c *Client) GetBlock(ctx context.Context, url string) (io.ReadCloser, error)

func (*Client) GetCalendar

func (c *Client) GetCalendar(ctx context.Context, calendarID string) (Calendar, error)

func (*Client) GetCalendarEvent

func (c *Client) GetCalendarEvent(ctx context.Context, calendarID, eventID string) (CalendarEvent, error)

func (*Client) GetCalendarEvents

func (c *Client) GetCalendarEvents(ctx context.Context, calendarID string, page, pageSize int, filter url.Values) ([]CalendarEvent, error)

TODO: For now, the query params are partially constant -- should they be configurable?

func (*Client) GetCalendarKeys

func (c *Client) GetCalendarKeys(ctx context.Context, calendarID string) (CalendarKeys, error)

func (*Client) GetCalendarMembers

func (c *Client) GetCalendarMembers(ctx context.Context, calendarID string) ([]CalendarMember, error)

func (*Client) GetCalendarPassphrase

func (c *Client) GetCalendarPassphrase(ctx context.Context, calendarID string) (CalendarPassphrase, error)

func (*Client) GetCalendars

func (c *Client) GetCalendars(ctx context.Context) ([]Calendar, error)

func (*Client) GetContact

func (c *Client) GetContact(ctx context.Context, contactID string) (Contact, error)

func (*Client) GetContactEmails

func (c *Client) GetContactEmails(ctx context.Context, email string, page, pageSize int) ([]ContactEmail, error)

func (*Client) GetContacts

func (c *Client) GetContacts(ctx context.Context, page, pageSize int) ([]Contact, error)

func (*Client) GetEvent

func (c *Client) GetEvent(ctx context.Context, eventID string) (Event, error)

func (*Client) GetFullMessage

func (c *Client) GetFullMessage(ctx context.Context, messageID string, scheduler Scheduler, storageProvider AttachmentAllocator) (FullMessage, error)

func (*Client) GetLabel

func (c *Client) GetLabel(ctx context.Context, labelID string, labelTypes ...LabelType) (Label, error)

func (*Client) GetLabels

func (c *Client) GetLabels(ctx context.Context, labelTypes ...LabelType) ([]Label, error)

func (*Client) GetLatestEventID

func (c *Client) GetLatestEventID(ctx context.Context) (string, error)
func (c *Client) GetLink(ctx context.Context, shareID, linkID string) (Link, error)

func (*Client) GetMailSettings

func (c *Client) GetMailSettings(ctx context.Context) (MailSettings, error)

func (*Client) GetMessage

func (c *Client) GetMessage(ctx context.Context, messageID string) (Message, error)

func (*Client) GetMessageIDs

func (c *Client) GetMessageIDs(ctx context.Context, afterID string) ([]string, error)

func (*Client) GetMessageMetadata

func (c *Client) GetMessageMetadata(ctx context.Context, filter MessageFilter) ([]MessageMetadata, error)

func (*Client) GetMessageMetadataPage added in v0.4.0

func (c *Client) GetMessageMetadataPage(ctx context.Context, page, pageSize int, filter MessageFilter) ([]MessageMetadata, error)

func (*Client) GetPublicKeys

func (c *Client) GetPublicKeys(ctx context.Context, address string) (PublicKeys, RecipientType, error)

func (*Client) GetRevision

func (c *Client) GetRevision(ctx context.Context, shareID, linkID, revisionID string) (Revision, error)

func (*Client) GetSalts

func (c *Client) GetSalts(ctx context.Context) (Salts, error)

func (*Client) GetShare

func (c *Client) GetShare(ctx context.Context, shareID string) (Share, error)

func (*Client) GetUser

func (c *Client) GetUser(ctx context.Context) (User, error)

func (*Client) ImportMessages

func (c *Client) ImportMessages(ctx context.Context, addrKR *crypto.KeyRing, workers, buffer int, req ...ImportReq) (stream.Stream[ImportRes], error)

func (*Client) LabelMessages

func (c *Client) LabelMessages(ctx context.Context, messageIDs []string, labelID string) error

func (*Client) ListChildren

func (c *Client) ListChildren(ctx context.Context, shareID, linkID string) ([]Link, error)

func (*Client) ListRevisions

func (c *Client) ListRevisions(ctx context.Context, shareID, linkID string) ([]Revision, error)

func (*Client) ListShares

func (c *Client) ListShares(ctx context.Context, all bool) ([]Share, error)

func (*Client) ListVolumes

func (c *Client) ListVolumes(ctx context.Context) ([]Volume, error)

func (*Client) MakeAddressKeyPrimary

func (c *Client) MakeAddressKeyPrimary(ctx context.Context, keyID string, keyList KeyList) error

func (*Client) MarkMessagesRead

func (c *Client) MarkMessagesRead(ctx context.Context, messageIDs ...string) error

func (*Client) MarkMessagesUnread

func (c *Client) MarkMessagesUnread(ctx context.Context, messageIDs ...string) error

func (*Client) NewEventStream

func (c *Client) NewEventStream(ctx context.Context, period, jitter time.Duration, lastEventID string) <-chan Event

NewEventStreamer returns a new event stream. It polls the API for new events at random intervals between `period` and `period+jitter`.

Example
m := proton.New()

ctx, cancel := context.WithCancel(context.Background())
defer cancel()

c, _, err := m.NewClientWithLogin(ctx, "...user...", []byte("...pass..."))
if err != nil {
	panic(err)
}
defer c.Close()

// Get the latest event ID.
fromEventID, err := c.GetLatestEventID(context.Background())
if err != nil {
	panic(err)
}

// Create a new event streamer.
for event := range c.NewEventStream(ctx, 20*time.Second, 20*time.Second, fromEventID) {
	fmt.Println(event.EventID)
}
Output:

func (*Client) OrderAddresses

func (c *Client) OrderAddresses(ctx context.Context, req OrderAddressesReq) error

func (*Client) SendDraft

func (c *Client) SendDraft(ctx context.Context, draftID string, req SendDraftReq) (Message, error)

func (*Client) SetAttachPublicKey

func (c *Client) SetAttachPublicKey(ctx context.Context, req SetAttachPublicKeyReq) (MailSettings, error)

func (*Client) SetDefaultPGPScheme

func (c *Client) SetDefaultPGPScheme(ctx context.Context, req SetDefaultPGPSchemeReq) (MailSettings, error)

func (*Client) SetDisplayName

func (c *Client) SetDisplayName(ctx context.Context, req SetDisplayNameReq) (MailSettings, error)

func (*Client) SetDraftMIMEType

func (c *Client) SetDraftMIMEType(ctx context.Context, req SetDraftMIMETypeReq) (MailSettings, error)

func (*Client) SetSignExternalMessages

func (c *Client) SetSignExternalMessages(ctx context.Context, req SetSignExternalMessagesReq) (MailSettings, error)

func (*Client) SetSignature

func (c *Client) SetSignature(ctx context.Context, req SetSignatureReq) (MailSettings, error)

func (*Client) UndoActions

func (c *Client) UndoActions(ctx context.Context, tokens ...UndoToken) ([]UndoRes, error)

func (*Client) UnlabelMessages

func (c *Client) UnlabelMessages(ctx context.Context, messageIDs []string, labelID string) error

func (*Client) UpdateContact

func (c *Client) UpdateContact(ctx context.Context, contactID string, req UpdateContactReq) (Contact, error)

func (*Client) UpdateDraft added in v0.1.5

func (c *Client) UpdateDraft(ctx context.Context, draftID string, addrKR *crypto.KeyRing, req UpdateDraftReq) (Message, error)

func (*Client) UpdateLabel

func (c *Client) UpdateLabel(ctx context.Context, labelID string, req UpdateLabelReq) (Label, error)

func (*Client) UploadAttachment

func (c *Client) UploadAttachment(ctx context.Context, addrKR *crypto.KeyRing, req CreateAttachmentReq) (Attachment, error)
func (c *Client) VisitLink(ctx context.Context, shareID string, link Link, kr *crypto.KeyRing, fn LinkWalkFunc) error

type ClientType

type ClientType int
const (
	ClientTypeEmail ClientType = iota + 1
	ClientTypeVPN
	ClientTypeCalendar
	ClientTypeDrive
)

type Code

type Code int
const (
	SuccessCode               Code = 1000
	MultiCode                 Code = 1001
	InvalidValue              Code = 2001
	AppVersionMissingCode     Code = 5001
	AppVersionBadCode         Code = 5003
	UsernameInvalid           Code = 6003 // Deprecated, but still used.
	PasswordWrong             Code = 8002
	HumanVerificationRequired Code = 9001
	PaidPlanRequired          Code = 10004
	AuthRefreshTokenInvalid   Code = 10013
)

type Contact

type Contact struct {
	ContactMetadata
	ContactCards
}

func (*Contact) GetSettings

func (c *Contact) GetSettings(kr *crypto.KeyRing, email string) (ContactSettings, error)

type ContactCards

type ContactCards struct {
	Cards Cards
}

type ContactEmail

type ContactEmail struct {
	ID        string
	Name      string
	Email     string
	Type      []string
	ContactID string
	LabelIDs  []string
}

type ContactMetadata

type ContactMetadata struct {
	ID            string
	Name          string
	UID           string
	Size          int64
	CreateTime    int64
	ModifyTime    int64
	ContactEmails []ContactEmail
	LabelIDs      []string
}

type ContactSettings

type ContactSettings struct {
	MIMEType *rfc822.MIMEType
	Scheme   *EncryptionScheme
	Sign     *bool
	Encrypt  *bool
	Keys     []*crypto.Key
}

type CreateAddressKeyReq

type CreateAddressKeyReq struct {
	AddressID     string
	PrivateKey    string
	Primary       Bool
	SignedKeyList KeyList

	// The following are only used in "migrated accounts"
	Token     string `json:",omitempty"`
	Signature string `json:",omitempty"`
}

type CreateAttachmentReq

type CreateAttachmentReq struct {
	MessageID string

	Filename    string
	MIMEType    rfc822.MIMEType
	Disposition Disposition
	ContentID   string

	Body []byte
}

type CreateContactsReq

type CreateContactsReq struct {
	Contacts  []ContactCards
	Overwrite int
	Labels    int
}

type CreateContactsRes

type CreateContactsRes struct {
	Index int

	Response struct {
		APIError
		Contact Contact
	}
}

type CreateDraftAction

type CreateDraftAction int
const (
	ReplyAction CreateDraftAction = iota
	ReplyAllAction
	ForwardAction
	AutoResponseAction
	ReadReceiptAction
)

type CreateDraftReq

type CreateDraftReq struct {
	Message              DraftTemplate
	AttachmentKeyPackets []string

	ParentID string `json:",omitempty"`
	Action   CreateDraftAction
}

type CreateLabelReq

type CreateLabelReq struct {
	Name  string
	Color string
	Type  LabelType

	ParentID string `json:",omitempty"`
}

type CreateUserReq

type CreateUserReq struct {
	Type     UserType
	Username string
	Domain   string
	Auth     AuthVerifier
}

type DefaultAttachmentAllocator added in v0.4.0

type DefaultAttachmentAllocator struct{}

func NewDefaultAttachmentAllocator added in v0.4.0

func NewDefaultAttachmentAllocator() *DefaultAttachmentAllocator

func (DefaultAttachmentAllocator) NewBuffer added in v0.4.0

type DeleteContactsReq

type DeleteContactsReq struct {
	IDs []string
}

type DeleteUserReq added in v0.2.2

type DeleteUserReq struct {
	Reason   string
	Feedback string
	Email    string
}

type Disposition

type Disposition string
const (
	InlineDisposition     Disposition = "inline"
	AttachmentDisposition Disposition = "attachment"
)

type DraftTemplate

type DraftTemplate struct {
	Subject  string
	Sender   *mail.Address
	ToList   []*mail.Address
	CCList   []*mail.Address
	BCCList  []*mail.Address
	Body     string
	MIMEType rfc822.MIMEType
	Unread   Bool

	ExternalID string `json:",omitempty"`
}

type EncryptionScheme

type EncryptionScheme int
const (
	InternalScheme EncryptionScheme = 1 << iota
	EncryptedOutsideScheme
	ClearScheme
	PGPInlineScheme
	PGPMIMEScheme
	ClearMIMEScheme
)

type Event

type Event struct {
	EventID string

	Refresh RefreshFlag

	User *User

	MailSettings *MailSettings

	Messages []MessageEvent

	Labels []LabelEvent

	Addresses []AddressEvent

	UsedSpace *int
}

func (Event) String

func (event Event) String() string

type EventAction

type EventAction int
const (
	EventDelete EventAction = iota
	EventCreate
	EventUpdate
	EventUpdateFlags
)

type EventItem

type EventItem struct {
	ID     string
	Action EventAction
}

type FIDO2Info added in v0.2.1

type FIDO2Info struct {
	AuthenticationOptions any
	RegisteredKeys        []RegisteredKey
}

type FIDO2Req added in v0.2.2

type FIDO2Req struct {
	AuthenticationOptions any
	ClientData            string
	AuthenticatorData     string
	Signature             string
	CredentialID          string
}

type FileProperties

type FileProperties struct {
	ContentKeyPacket string
	ActiveRevision   Revision
}

type FileRevisionState

type FileRevisionState int
const (
	DraftRevisionState FileRevisionState = iota
	ActiveRevisionState
	ObsoleteRevisionState
)

type FolderProperties

type FolderProperties struct{}

type FullMessage

type FullMessage struct {
	Message

	AttData [][]byte
}

type Future

type Future[T any] struct {
	// contains filtered or unexported fields
}

func NewFuture

func NewFuture[T any](fn func() (T, error)) *Future[T]

func (*Future[T]) Get

func (job *Future[T]) Get() (T, error)

func (*Future[T]) Then

func (job *Future[T]) Then(fn func(T, error))

type Group

type Group[T any] struct {
	// contains filtered or unexported fields
}

func NewGroup

func NewGroup[T any]() *Group[T]

func (*Group[T]) Add

func (group *Group[T]) Add(fn func() (T, error))

func (*Group[T]) ForEach

func (group *Group[T]) ForEach(fn func(T) error) error

func (*Group[T]) Result

func (group *Group[T]) Result() ([]T, error)

type Handler

type Handler func()

Handler is a generic function that can be registered for a certain event (e.g. deauth, API code).

type Headers

type Headers map[string][]string

func (*Headers) UnmarshalJSON

func (h *Headers) UnmarshalJSON(b []byte) error

type ImportMetadata

type ImportMetadata struct {
	AddressID string
	LabelIDs  []string
	Unread    Bool
	Flags     MessageFlag
}

type ImportReq

type ImportReq struct {
	Metadata ImportMetadata
	Message  []byte
}

type ImportRes

type ImportRes struct {
	APIError
	MessageID string
}

type Key

type Key struct {
	ID         string
	PrivateKey []byte
	Token      string
	Signature  string
	Primary    Bool
	Active     Bool
	Flags      KeyState
}

func (Key) MarshalJSON

func (key Key) MarshalJSON() ([]byte, error)

func (Key) Unlock

func (key Key) Unlock(passphrase []byte, userKR *crypto.KeyRing) (*crypto.Key, error)

func (*Key) UnmarshalJSON

func (key *Key) UnmarshalJSON(data []byte) error

type KeyList

type KeyList struct {
	Data      string
	Signature string
}

func NewKeyList

func NewKeyList(signer *crypto.KeyRing, entries []KeyListEntry) (KeyList, error)

type KeyListEntry

type KeyListEntry struct {
	Fingerprint        string
	SHA256Fingerprints []string
	Flags              KeyState
	Primary            Bool
}

type KeyState

type KeyState int
const (
	KeyStateTrusted KeyState = 1 << iota // 2^0 = 1 means the key is not compromised (i.e. if we can trust signatures coming from it)
	KeyStateActive                       // 2^1 = 2 means the key is still in use (i.e. not obsolete, we can encrypt messages to it)
)

type Keys

type Keys []Key

func (Keys) ByID

func (keys Keys) ByID(keyID string) Key

func (Keys) Primary

func (keys Keys) Primary() Key

func (Keys) TryUnlock

func (keys Keys) TryUnlock(passphrase []byte, userKR *crypto.KeyRing) *crypto.KeyRing

func (Keys) Unlock

func (keys Keys) Unlock(passphrase []byte, userKR *crypto.KeyRing) (*crypto.KeyRing, error)

type Label

type Label struct {
	ID    string
	Name  string
	Path  []string
	Color string
	Type  LabelType
}

func (Label) MarshalJSON

func (label Label) MarshalJSON() ([]byte, error)

func (*Label) UnmarshalJSON

func (label *Label) UnmarshalJSON(data []byte) error

type LabelEvent

type LabelEvent struct {
	EventItem

	Label Label
}

type LabelMessageRes

type LabelMessageRes struct {
	ID       string
	Response APIError
}

type LabelMessagesReq

type LabelMessagesReq struct {
	LabelID string
	IDs     []string
}

type LabelMessagesRes

type LabelMessagesRes struct {
	Responses []LabelMessageRes
	UndoToken UndoToken
}

type LabelType

type LabelType int
const (
	LabelTypeLabel LabelType = iota + 1
	LabelTypeContactGroup
	LabelTypeFolder
	LabelTypeSystem
)
type Link struct {
	LinkID         string // Encrypted file/folder ID
	ParentLinkID   string // Encrypted parent folder ID (LinkID)
	Type           LinkType
	Name           string    // Encrypted file name
	Hash           string    // HMAC of name encrypted with parent hash key
	State          LinkState // State of the link
	ExpirationTime int64
	Size           int64
	MIMEType       string
	Attributes     Attributes
	Permissions    Permissions

	NodeKey                 string
	NodePassphrase          string
	NodePassphraseSignature string
	SignatureAddress        string

	CreateTime int64
	ModifyTime int64

	FileProperties   FileProperties
	FolderProperties FolderProperties
}

func (Link) GetKeyRing

func (l Link) GetKeyRing(kr *crypto.KeyRing) (*crypto.KeyRing, error)

type LinkEvent

type LinkEvent struct {
	EventID    string        // Encrypted ID of the Event
	CreateTime int64         // Time stamp of the creation time of the Event
	EventType  LinkEventType // Type of event
}

type LinkEventType

type LinkEventType int
const (
	DeleteLinkEvent LinkEventType = iota
	CreateLinkEvent
	UpdateContentsLinkEvent
	UpdateMetadataLinkEvent
)

type LinkState

type LinkState int
const (
	DraftLinkState LinkState = iota
	ActiveLinkState
	TrashedLinkState
	DeletedLinkState
)

type LinkType

type LinkType int
const (
	FolderLinkType LinkType = iota + 1
	FileLinkType
)

type LinkWalkFunc

type LinkWalkFunc func([]string, Link, *crypto.KeyRing) error

type Listener added in v0.4.0

type Listener struct {
	net.Listener
	// contains filtered or unexported fields
}

Listener wraps a net.Listener. It can be configured to spawn connections that drop all reads or writes.

func NewListener added in v0.4.0

func NewListener(l net.Listener, newConn func(net.Conn, *Listener) net.Conn) *Listener

NewListener returns a new DropListener.

func (*Listener) Accept added in v0.4.0

func (l *Listener) Accept() (net.Conn, error)

func (*Listener) Close added in v0.4.0

func (l *Listener) Close() error

Close closes the listener.

func (*Listener) Done added in v0.4.0

func (l *Listener) Done() <-chan struct{}

Done returns a channel that is closed when the listener is closed.

func (*Listener) DropAll added in v0.4.0

func (l *Listener) DropAll()

DropAll closes all connections spawned by this listener.

func (*Listener) SetCanRead added in v0.4.0

func (l *Listener) SetCanRead(canRead bool)

SetCanRead sets whether the connections spawned by this listener can read.

func (*Listener) SetCanWrite added in v0.4.0

func (l *Listener) SetCanWrite(canWrite bool)

SetCanWrite sets whether the connections spawned by this listener can write.

type MailSettings

type MailSettings struct {
	DisplayName     string
	Signature       string
	DraftMIMEType   rfc822.MIMEType
	AttachPublicKey Bool
	Sign            SignExternalMessages
	PGPScheme       EncryptionScheme
}

type MakeAddressKeyPrimaryReq

type MakeAddressKeyPrimaryReq struct {
	SignedKeyList KeyList
}

type Manager

type Manager struct {
	// contains filtered or unexported fields
}

func New

func New(opts ...Option) *Manager

func (*Manager) AddErrorHandler

func (m *Manager) AddErrorHandler(code Code, handler Handler)

func (*Manager) AddPostRequestHook

func (m *Manager) AddPostRequestHook(hook resty.ResponseMiddleware)

func (*Manager) AddPreRequestHook

func (m *Manager) AddPreRequestHook(hook resty.RequestMiddleware)

func (*Manager) AddStatusObserver

func (m *Manager) AddStatusObserver(observer StatusObserver)

func (*Manager) AuthInfo added in v0.2.2

func (m *Manager) AuthInfo(ctx context.Context, req AuthInfoReq) (AuthInfo, error)

func (*Manager) AuthModulus added in v0.2.2

func (m *Manager) AuthModulus(ctx context.Context) (AuthModulus, error)

func (*Manager) Close

func (m *Manager) Close()

func (*Manager) CreateUser added in v0.2.2

func (m *Manager) CreateUser(ctx context.Context, req CreateUserReq) (User, error)

func (*Manager) DownloadAndVerify

func (m *Manager) DownloadAndVerify(ctx context.Context, kr *crypto.KeyRing, url, sig string) ([]byte, error)

func (*Manager) GetCaptcha added in v0.2.2

func (m *Manager) GetCaptcha(ctx context.Context, token string) ([]byte, error)

func (*Manager) GetDomains added in v0.2.2

func (m *Manager) GetDomains(ctx context.Context) ([]string, error)

func (*Manager) GetUsernameAvailable added in v0.2.2

func (m *Manager) GetUsernameAvailable(ctx context.Context, username string) error

func (*Manager) NewClient

func (m *Manager) NewClient(uid, acc, ref string) *Client
Example
// Create a new manager.
m := proton.New()

// If auth information is already known, it can be used to create a client straight away.
c := m.NewClient("...uid...", "...acc...", "...ref...")
defer c.Close()

// All API operations must be run within a context.
ctx, cancel := context.WithCancel(context.Background())
defer cancel()

// Do something with the client.
if _, err := c.GetUser(ctx); err != nil {
	panic(err)
}
Output:

func (*Manager) NewClientWithLogin

func (m *Manager) NewClientWithLogin(ctx context.Context, username string, password []byte) (*Client, Auth, error)
Example
// Create a new manager.
m := proton.New()

// All API operations must be run within a context.
ctx, cancel := context.WithCancel(context.Background())
defer cancel()

// Clients are created via username/password if auth information isn't already known.
c, auth, err := m.NewClientWithLogin(ctx, "...user...", []byte("...pass..."))
if err != nil {
	panic(err)
}
defer c.Close()

// If 2FA is necessary, an additional request is required.
if auth.TwoFA.Enabled&proton.HasTOTP != 0 {
	if err := c.Auth2FA(ctx, proton.Auth2FAReq{TwoFactorCode: "...TOTP..."}); err != nil {
		panic(err)
	}
}

// Do something with the client.
if _, err := c.GetUser(ctx); err != nil {
	panic(err)
}
Output:

func (*Manager) NewClientWithRefresh

func (m *Manager) NewClientWithRefresh(ctx context.Context, uid, ref string) (*Client, Auth, error)
Example
// Create a new manager.
m := proton.New()

// All API operations must be run within a context.
ctx, cancel := context.WithCancel(context.Background())
defer cancel()

// If UID/RefreshToken is already known, it can be used to create a new client straight away.
c, _, err := m.NewClientWithRefresh(ctx, "...uid...", "...ref...")
if err != nil {
	panic(err)
}
defer c.Close()

// Do something with the client.
if _, err := c.GetUser(ctx); err != nil {
	panic(err)
}
Output:

func (*Manager) Ping

func (m *Manager) Ping(ctx context.Context) error

func (*Manager) Quark added in v0.2.2

func (m *Manager) Quark(ctx context.Context, command string, args ...string) error

Quark runs a quark command.

func (*Manager) QuarkRes added in v0.2.2

func (m *Manager) QuarkRes(ctx context.Context, command string, args ...string) ([]byte, error)

QuarkRes is the same as Quark, but returns the content extracted from the response body.

func (*Manager) ReportBug

func (m *Manager) ReportBug(ctx context.Context, req ReportBugReq, atts ...ReportBugAttachment) error

func (*Manager) SendVerificationCode added in v0.2.2

func (m *Manager) SendVerificationCode(ctx context.Context, req SendVerificationCodeReq) error

type MemberPassphrase

type MemberPassphrase struct {
	MemberID   string
	Passphrase string
	Signature  string
}

type Message

type Message struct {
	MessageMetadata

	Header        string
	ParsedHeaders Headers
	Body          string
	MIMEType      rfc822.MIMEType
	Attachments   []Attachment
}

func (Message) Decrypt

func (m Message) Decrypt(kr *crypto.KeyRing) ([]byte, error)

func (Message) DecryptInto added in v0.4.0

func (m Message) DecryptInto(kr *crypto.KeyRing, buffer io.ReaderFrom) error

type MessageActionReq

type MessageActionReq struct {
	IDs []string
}

type MessageEvent

type MessageEvent struct {
	EventItem

	Message MessageMetadata
}

type MessageFilter

type MessageFilter struct {
	ID []string `json:",omitempty"`

	Subject    string `json:",omitempty"`
	AddressID  string `json:",omitempty"`
	ExternalID string `json:",omitempty"`
	LabelID    string `json:",omitempty"`
}

type MessageFlag

type MessageFlag int64
const (
	MessageFlagReceived    MessageFlag = 1 << 0
	MessageFlagSent        MessageFlag = 1 << 1
	MessageFlagInternal    MessageFlag = 1 << 2
	MessageFlagE2E         MessageFlag = 1 << 3
	MessageFlagAuto        MessageFlag = 1 << 4
	MessageFlagReplied     MessageFlag = 1 << 5
	MessageFlagRepliedAll  MessageFlag = 1 << 6
	MessageFlagForwarded   MessageFlag = 1 << 7
	MessageFlagAutoReplied MessageFlag = 1 << 8
	MessageFlagImported    MessageFlag = 1 << 9
	MessageFlagOpened      MessageFlag = 1 << 10
	MessageFlagReceiptSent MessageFlag = 1 << 11
	MessageFlagNotified    MessageFlag = 1 << 12
	MessageFlagTouched     MessageFlag = 1 << 13
	MessageFlagReceipt     MessageFlag = 1 << 14

	MessageFlagReceiptRequest MessageFlag = 1 << 16
	MessageFlagPublicKey      MessageFlag = 1 << 17
	MessageFlagSign           MessageFlag = 1 << 18
	MessageFlagUnsubscribed   MessageFlag = 1 << 19
	MessageFlagScheduledSend  MessageFlag = 1 << 20
	MessageFlagAlias          MessageFlag = 1 << 21

	MessageFlagDMARCPass      MessageFlag = 1 << 23
	MessageFlagSPFFail        MessageFlag = 1 << 24
	MessageFlagDKIMFail       MessageFlag = 1 << 25
	MessageFlagDMARCFail      MessageFlag = 1 << 26
	MessageFlagHamManual      MessageFlag = 1 << 27
	MessageFlagSpamAuto       MessageFlag = 1 << 28
	MessageFlagSpamManual     MessageFlag = 1 << 29
	MessageFlagPhishingAuto   MessageFlag = 1 << 30
	MessageFlagPhishingManual MessageFlag = 1 << 31
)

func (MessageFlag) Add

func (f MessageFlag) Add(flag MessageFlag) MessageFlag

func (MessageFlag) Has

func (f MessageFlag) Has(flag MessageFlag) bool

func (MessageFlag) HasAll

func (f MessageFlag) HasAll(flags ...MessageFlag) bool

func (MessageFlag) HasAny

func (f MessageFlag) HasAny(flags ...MessageFlag) bool

func (MessageFlag) Matches

func (f MessageFlag) Matches(flag MessageFlag) bool

func (MessageFlag) Remove

func (f MessageFlag) Remove(flag MessageFlag) MessageFlag

func (MessageFlag) Toggle

func (f MessageFlag) Toggle(flag MessageFlag) MessageFlag

type MessageMetadata

type MessageMetadata struct {
	ID         string
	AddressID  string
	LabelIDs   []string
	ExternalID string

	Subject  string
	Sender   *mail.Address
	ToList   []*mail.Address
	CCList   []*mail.Address
	BCCList  []*mail.Address
	ReplyTos []*mail.Address

	Flags        MessageFlag
	Time         int64
	Size         int
	Unread       Bool
	IsReplied    Bool
	IsRepliedAll Bool
	IsForwarded  Bool
}

func (MessageMetadata) IsDraft

func (meta MessageMetadata) IsDraft() bool

func (MessageMetadata) Seen

func (meta MessageMetadata) Seen() bool

func (MessageMetadata) Starred

func (meta MessageMetadata) Starred() bool

type MessagePackage

type MessagePackage struct {
	Addresses map[string]*MessageRecipient
	MIMEType  rfc822.MIMEType
	Type      EncryptionScheme
	Body      string

	BodyKey        *SessionKey            `json:",omitempty"`
	AttachmentKeys map[string]*SessionKey `json:",omitempty"`
}

type MessageRecipient

type MessageRecipient struct {
	Type      EncryptionScheme
	Signature SignatureType

	BodyKeyPacket        string            `json:",omitempty"`
	AttachmentKeyPackets map[string]string `json:",omitempty"`
}

type NetCtl

type NetCtl struct {
	// contains filtered or unexported fields
}

ctl can be used to control whether a dialer can dial, and whether the resulting connection can read or write.

func NewNetCtl

func NewNetCtl() *NetCtl

NewNetCtl returns a new ctl with all fields set to true.

func (*NetCtl) Disable

func (c *NetCtl) Disable()

Disable is equivalent to disallowing dial, read and write.

func (*NetCtl) Enable

func (c *NetCtl) Enable()

Enable is equivalent to allowing dial, read and write.

func (*NetCtl) NewRoundTripper added in v0.2.2

func (c *NetCtl) NewRoundTripper(tlsConfig *tls.Config) http.RoundTripper

NewDialer returns a new dialer controlled by the ctl.

func (*NetCtl) OnDial

func (c *NetCtl) OnDial(f func(net.Conn))

OnDial adds a callback that is called with the created connection when a dial is successful.

func (*NetCtl) OnRead

func (c *NetCtl) OnRead(fn func([]byte))

OnRead adds a callback that is called with the read bytes when a read is successful.

func (*NetCtl) OnWrite

func (c *NetCtl) OnWrite(fn func([]byte))

OnWrite adds a callback that is called with the written bytes when a write is successful.

func (*NetCtl) SetCanDial

func (c *NetCtl) SetCanDial(canDial bool)

SetCanDial sets whether the dialer can dial.

func (*NetCtl) SetCanRead

func (c *NetCtl) SetCanRead(canRead bool)

SetCanRead sets whether the connection can read.

func (*NetCtl) SetCanWrite

func (c *NetCtl) SetCanWrite(canWrite bool)

SetCanWrite sets whether the connection can write.

func (*NetCtl) SetDialLimit

func (c *NetCtl) SetDialLimit(limit uint64)

SetDialLimit sets the maximum number of times dialers using this controller can dial.

func (*NetCtl) SetReadLimit

func (c *NetCtl) SetReadLimit(limit uint64)

SetReadLimit sets the maximum number of bytes that can be read.

func (*NetCtl) SetReadSpeed added in v0.2.2

func (c *NetCtl) SetReadSpeed(speed int)

SetReadSpeed sets the maximum number of bytes that can be read per second.

func (*NetCtl) SetWriteLimit

func (c *NetCtl) SetWriteLimit(limit uint64)

SetWriteLimit sets the maximum number of bytes that can be written.

func (*NetCtl) SetWriteSpeed added in v0.2.2

func (c *NetCtl) SetWriteSpeed(speed int)

SetWriteSpeed sets the maximum number of bytes that can be written per second.

type NetError added in v0.3.0

type NetError struct {
	// Cause is the underlying error that caused the network error.
	Cause error

	// Message is an additional message that describes the network error.
	Message string
}

NetError represents a network error. It is returned when the API is unreachable.

func (*NetError) Error added in v0.3.0

func (err *NetError) Error() string

func (*NetError) Is added in v0.3.0

func (err *NetError) Is(target error) bool

func (*NetError) Unwrap added in v0.3.0

func (err *NetError) Unwrap() error

type Option

type Option interface {
	// contains filtered or unexported methods
}

Option represents a type that can be used to configure the manager.

func WithAppVersion

func WithAppVersion(appVersion string) Option

func WithCookieJar

func WithCookieJar(jar http.CookieJar) Option

func WithDebug

func WithDebug(debug bool) Option

func WithHostURL

func WithHostURL(hostURL string) Option

func WithLogger

func WithLogger(logger resty.Logger) Option

func WithRetryCount

func WithRetryCount(retryCount int) Option

func WithSkipVerifyProofs

func WithSkipVerifyProofs() Option

func WithTransport

func WithTransport(transport http.RoundTripper) Option

type OrderAddressesReq

type OrderAddressesReq struct {
	AddressIDs []string
}

type ParallelScheduler added in v0.4.0

type ParallelScheduler struct {
	// contains filtered or unexported fields
}

func NewParallelScheduler added in v0.4.0

func NewParallelScheduler(workers int) *ParallelScheduler

func (ParallelScheduler) Schedule added in v0.4.0

func (p ParallelScheduler) Schedule(ctx context.Context, attachmentIDs []string, storageProvider AttachmentAllocator, downloader func(context.Context, string, *bytes.Buffer) error) ([]*bytes.Buffer, error)

type PasswordMode

type PasswordMode int
const (
	OnePasswordMode PasswordMode = iota + 1
	TwoPasswordMode
)

type Permissions

type Permissions int
const (
	NoPermissions Permissions = 1 << iota
	ReadPermission
	WritePermission
	AdministerMembersPermission
	AdminPermission
	SuperAdminPermission
)

type Pool

type Pool[In comparable, Out any] struct {
	// contains filtered or unexported fields
}

Pool is a worker pool that handles input of type In and returns results of type Out.

func NewPool

func NewPool[In comparable, Out any](size int, work func(context.Context, In) (Out, error)) *Pool[In, Out]

New returns a new pool.

func (*Pool[In, Out]) Done

func (pool *Pool[In, Out]) Done()

func (*Pool[In, Out]) Process

func (pool *Pool[In, Out]) Process(ctx context.Context, reqs []In, fn func(int, In, Out, error) error) error

Process submits jobs to the pool. The callback provides access to the result, or an error if one occurred.

func (*Pool[In, Out]) ProcessAll

func (pool *Pool[In, Out]) ProcessAll(ctx context.Context, reqs []In) ([]Out, error)

ProcessAll submits jobs to the pool. All results are returned once available.

func (*Pool[In, Out]) ProcessOne

func (pool *Pool[In, Out]) ProcessOne(ctx context.Context, req In) (Out, error)

ProcessOne submits one job to the pool and returns the result.

type PublicKey

type PublicKey struct {
	Flags     KeyState
	PublicKey string
}

type PublicKeys

type PublicKeys []PublicKey

func (PublicKeys) GetKeyRing

func (keys PublicKeys) GetKeyRing() (*crypto.KeyRing, error)

type RecipientType

type RecipientType int
const (
	RecipientTypeInternal RecipientType = iota + 1
	RecipientTypeExternal
)

type RefreshFlag

type RefreshFlag uint8
const (
	RefreshMail RefreshFlag = 1 << iota // 1<<0 = 1

	RefreshAll RefreshFlag = 1<<iota - 1 // 1<<8 - 1 = 255
)

type RegisteredKey

type RegisteredKey struct {
	AttestationFormat string
	CredentialID      []int
	Name              string
}

type ReportBugAttachment

type ReportBugAttachment struct {
	Name     string
	Filename string
	MIMEType rfc822.MIMEType
	Body     []byte
}

type ReportBugReq

type ReportBugReq struct {
	OS        string
	OSVersion string

	Browser           string
	BrowserVersion    string
	BrowserExtensions string

	Resolution  string
	DisplayMode string

	Client        string
	ClientVersion string
	ClientType    ClientType

	Title       string
	Description string

	Username string
	Email    string

	Country string
	ISP     string
}

type Revision

type Revision struct {
	ID                string            // Encrypted Revision ID
	CreateTime        int64             //  Unix timestamp of the revision creation time
	Size              int64             //  Size of the file in bytes
	ManifestSignature string            // The signature of the root hash
	SignatureAddress  string            // The address used to sign the root hash
	State             FileRevisionState // State of revision
	Blocks            []Block
}

type Salt

type Salt struct {
	ID, KeySalt string
}

type Salts

type Salts []Salt

func (Salts) SaltForKey

func (salts Salts) SaltForKey(keyPass []byte, keyID string) ([]byte, error)

type Scheduler added in v0.4.0

type Scheduler interface {
	Schedule(ctx context.Context, attachmentIDs []string, storageProvider AttachmentAllocator, downloader func(context.Context, string, *bytes.Buffer) error) ([]*bytes.Buffer, error)
}

Scheduler allows the user to specify how the attachment data for the message should be downloaded.

type SendDraftReq

type SendDraftReq struct {
	Packages []*MessagePackage
}

func (*SendDraftReq) AddMIMEPackage

func (req *SendDraftReq) AddMIMEPackage(
	kr *crypto.KeyRing,
	mimeBody string,
	prefs map[string]SendPreferences,
) error

func (*SendDraftReq) AddTextPackage

func (req *SendDraftReq) AddTextPackage(
	kr *crypto.KeyRing,
	body string,
	mimeType rfc822.MIMEType,
	prefs map[string]SendPreferences,
	attKeys map[string]*crypto.SessionKey,
) error

type SendPreferences

type SendPreferences struct {
	// Encrypt indicates whether the email should be encrypted or not.
	// If it's encrypted, we need to know which public key to use.
	Encrypt bool

	// PubKey contains an OpenPGP key that can be used for encryption.
	PubKey *crypto.KeyRing

	// SignatureType indicates how the email should be signed.
	SignatureType SignatureType

	// EncryptionScheme indicates if we should encrypt body and attachments separately and
	// what MIME format to give the final encrypted email. The two standard PGP
	// schemes are PGP/MIME and PGP/Inline. However we use a custom scheme for
	// internal emails (including the so-called encrypted-to-outside emails,
	// which even though meant for external users, they don't really get out of
	// our platform). If the email is sent unencrypted, no PGP scheme is needed.
	EncryptionScheme EncryptionScheme

	// MIMEType is the MIME type to use for formatting the body of the email
	// (before encryption/after decryption). The standard possibilities are the
	// enriched HTML format, text/html, and plain text, text/plain. But it's
	// also possible to have a multipart/mixed format, which is typically used
	// for PGP/MIME encrypted emails, where attachments go into the body too.
	// Because of this, this option is sometimes called MIME format.
	MIMEType rfc822.MIMEType
}

type SendVerificationCodeReq

type SendVerificationCodeReq struct {
	Username    string
	Type        TokenType
	Destination TokenDestination
}

type SequentialScheduler added in v0.4.0

type SequentialScheduler struct{}

SequentialScheduler downloads the attachments one by one.

func NewSequentialScheduler added in v0.4.0

func NewSequentialScheduler() *SequentialScheduler

func (SequentialScheduler) Schedule added in v0.4.0

func (SequentialScheduler) Schedule(ctx context.Context, attachmentIDs []string, storageProvider AttachmentAllocator, downloader func(context.Context, string, *bytes.Buffer) error) ([]*bytes.Buffer, error)

type SessionKey

type SessionKey struct {
	Key       string
	Algorithm string
}

type SetAttachPublicKeyReq

type SetAttachPublicKeyReq struct {
	AttachPublicKey Bool
}

type SetDefaultPGPSchemeReq

type SetDefaultPGPSchemeReq struct {
	PGPScheme EncryptionScheme
}

type SetDisplayNameReq

type SetDisplayNameReq struct {
	DisplayName string
}

type SetDraftMIMETypeReq

type SetDraftMIMETypeReq struct {
	MIMEType rfc822.MIMEType
}

type SetSignExternalMessagesReq

type SetSignExternalMessagesReq struct {
	Sign SignExternalMessages
}

type SetSignatureReq

type SetSignatureReq struct {
	Signature string
}

type Share

type Share struct {
	ShareID             string      // Encrypted share ID
	Type                ShareType   // Type of share
	State               ShareState  // TODO: What is this?
	PermissionsMask     Permissions // Mask restricting member permissions on the share
	LinkID              string      // Encrypted link ID to which the share points (root of share).
	LinkType            LinkType    // TODO: What is this?
	VolumeID            string      // Encrypted volume ID on which the share is mounted
	Creator             string      // Creator address
	AddressID           string
	Flags               ShareFlags // The flag bitmap, with the following values
	BlockSize           int64      // TODO: What is this?
	Locked              bool       // TODO: What is this?
	Key                 string     // The private key, encrypted with a passphrase
	Passphrase          string     // The encrypted passphrase
	PassphraseSignature string     // The signature of the passphrase
}

func (Share) GetKeyRing

func (s Share) GetKeyRing(kr *crypto.KeyRing) (*crypto.KeyRing, error)

type ShareFlags

type ShareFlags int
const (
	NoFlags ShareFlags = iota
	PrimaryShare
)

type ShareState

type ShareState int

type ShareType

type ShareType int

type SignExternalMessages

type SignExternalMessages int
const (
	SignExternalMessagesDisabled SignExternalMessages = iota
	SignExternalMessagesEnabled
)

type Signature

type Signature struct {
	Hash string
	Data *crypto.PGPSignature
}

func ExtractSignatures

func ExtractSignatures(kr *crypto.KeyRing, arm string) ([]Signature, error)

type SignatureType

type SignatureType int
const (
	NoSignature SignatureType = iota
	DetachedSignature
	AttachedSignature
)

type Status

type Status int
const (
	StatusUp Status = iota
	StatusDown
)

func (Status) String

func (s Status) String() string

type StatusObserver

type StatusObserver func(Status)

type Ticker

type Ticker struct {
	C chan time.Time
	// contains filtered or unexported fields
}

func NewTicker

func NewTicker(period, jitter time.Duration) *Ticker

NewTicker returns a new ticker that ticks at a random time between period and period+jitter. It can be stopped by closing calling Stop().

func (*Ticker) Stop

func (t *Ticker) Stop()

type TokenDestination

type TokenDestination struct {
	Address string
	Phone   string
}

type TokenType

type TokenType string
const (
	EmailTokenType TokenType = "email"
	SMSTokenType   TokenType = "sms"
)

type TwoFAInfo

type TwoFAInfo struct {
	Enabled TwoFAStatus
	FIDO2   FIDO2Info
}

type TwoFAStatus

type TwoFAStatus int
const (
	HasTOTP TwoFAStatus = 1 << iota
	HasFIDO2
)

type UndoRes

type UndoRes struct {
	Messages []Message
}

type UndoToken

type UndoToken struct {
	Token      string
	ValidUntil int64
}

type UpdateContactReq

type UpdateContactReq struct {
	Cards Cards
}

type UpdateDraftReq added in v0.1.5

type UpdateDraftReq struct {
	Message              DraftTemplate
	AttachmentKeyPackets []string
}

type UpdateLabelReq

type UpdateLabelReq struct {
	Name  string
	Color string

	ParentID string `json:",omitempty"`
}

type User

type User struct {
	ID          string
	Name        string
	DisplayName string
	Email       string
	Keys        Keys

	UsedSpace int
	MaxSpace  int
	MaxUpload int

	Credit   int
	Currency string
}

type UserType

type UserType int
const (
	MailUserType UserType = iota + 1
	VPNUserType
)

type Volume

type Volume struct {
	ID          string      // Encrypted volume ID
	Name        string      // The volume name
	OwnerUserID string      // Encrypted owner user ID
	UsedSpace   int64       // Space used by files in the volume in bytes
	MaxSpace    int64       // Space limit for the volume in bytes
	State       VolumeState // TODO: What is this?
}

type VolumeState

type VolumeState int

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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