core

package
v0.0.0-...-eb8b12f Latest Latest
Warning

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

Go to latest
Published: Jul 13, 2026 License: GPL-3.0 Imports: 26 Imported by: 0

Documentation

Overview

Package core provides Go HTTP client for interacting with Core API a.k.a. NordVPN API

Index

Constants

View Source
const (
	Online          = "online"
	Offline         = "offline"
	Maintenance     = "maintenance"
	VirtualLocation = "virtual_location"
)
View Source
const (
	HeaderDigest = "x-digest"

	// CDNURL is the url for NordCDN
	CDNURL = "https://downloads.nordcdn.com"

	// InsightsURL defines url to get information about ip
	// Used by JobInsights every 30mins to set the user country
	InsightsURL = "/v1/helpers/ips/insights"

	// PlanURL defines endpoint to fetch plans
	PlanURL = "/v1/plans?filters[plans.active]=1&filters[plans.type]=linux"

	// ServersURL defines url to get servers list
	// Used as a fallback if /v1/servers/recommendations returns
	// an empty list or a http error
	ServersURL = "/v1/servers"

	// ServersCountriesURL defines url to get servers countries list
	// Used by JobCountries every 6h to populate /var/lib/nordvpn/data/countries.dat
	ServersCountriesURL = ServersURL + "/countries"

	// RecommendedServersURL defines url for recommended servers list
	RecommendedServersURL = ServersURL + "/recommendations"

	// UsersURL defines url to create a new user
	UsersURL = "/v1/users"

	// TokensURL defines url to get user token
	TokensURL = UsersURL + "/tokens" // #nosec

	// ServicesURL defines url to check user's current/expired services
	ServicesURL = UsersURL + "/services"

	// CredentialsURL defines url to generate openvpn credentials
	CredentialsURL = ServicesURL + "/credentials"

	// CurrentUserURL defines url to check user's metadata
	CurrentUserURL = UsersURL + "/current"

	// TokenRenewURL defines url to renew user's token
	TokenRenewURL = UsersURL + "/tokens/renew" // #nosec

	TrustedPassTokenURL = UsersURL + "/oauth/tokens/trusted"

	MFAStatusURL = UsersURL + "/oauth/mfa/status"

	// ServersURLConnectQuery is all servers query optimized
	// for minimal dm size required
	// to create servers maps and calculate their penalty scores
	// so instead of downloading 15mb we download 1.5mb
	// and when connecting, download all info about specific server
	//
	// no problems with this logic so far
	ServersURLConnectQuery = "?limit=1073741824" +
		"&filters[servers.status]=online" +
		"&fields[servers.id]" +
		"&fields[servers.name]" +
		"&fields[servers.hostname]" +
		"&fields[servers.station]" +
		"&fields[servers.status]" +
		"&fields[servers.load]" +
		"&fields[servers.created_at]" +
		"&fields[servers.groups.id]" +
		"&fields[servers.groups.title]" +
		"&fields[servers.technologies.id]" +
		"&fields[servers.technologies.metadata]" +
		"&fields[servers.technologies.pivot.status]" +
		"&fields[servers.specifications.identifier]" +
		"&fields[servers.specifications.values.value]" +
		"&fields[servers.locations.country.id]" +
		"&fields[servers.locations.country.name]" +
		"&fields[servers.locations.country.code]" +
		"&fields[servers.locations.country.city.id]" +
		"&fields[servers.locations.country.city.name]" +
		"&fields[servers.locations.country.city.latitude]" +
		"&fields[servers.locations.country.city.longitude]" +
		"&fields[servers.locations.country.city.hub_score]" +
		"&fields[servers.ips]"

	RecommendedServersURLConnectQuery = "?limit=%d" +
		"&filters[servers.status]=online" +
		"&filters[servers_technologies]=%d" +
		"&filters[servers_technologies][pivot][status]=online" +
		"&fields[servers.id]" +
		"&fields[servers.name]" +
		"&fields[servers.hostname]" +
		"&fields[servers.station]" +
		"&fields[servers.status]" +
		"&fields[servers.load]" +
		"&fields[servers.created_at]" +
		"&fields[servers.groups.id]" +
		"&fields[servers.groups.title]" +
		"&fields[servers.technologies.id]" +
		"&fields[servers.technologies.metadata]" +
		"&fields[servers.technologies.pivot.status]" +
		"&fields[servers.specifications.identifier]" +
		"&fields[servers.specifications.values.value]" +
		"&fields[servers.locations.country.name]" +
		"&fields[servers.locations.country.code]" +
		"&fields[servers.locations.country.city.name]" +
		"&fields[servers.locations.country.city.latitude]" +
		"&fields[servers.locations.country.city.longitude]" +
		"&coordinates[longitude]=%f&coordinates[latitude]=%f" +
		"&fields[servers.ips]"

	RecommendedServersURLQuickConnectQuery = "?filters[servers_technologies]=%d" +
		"&filters[servers_technologies][pivot][status]=online" +
		"&fields[servers.id]" +
		"&fields[servers.name]" +
		"&fields[servers.hostname]" +
		"&fields[servers.station]" +
		"&fields[servers.status]" +
		"&fields[servers.load]" +
		"&fields[servers.created_at]" +
		"&fields[servers.groups.id]" +
		"&fields[servers.groups.title]" +
		"&fields[servers.technologies.id]" +
		"&fields[servers.technologies.metadata]" +
		"&fields[servers.technologies.pivot.status]" +
		"&fields[servers.specifications.identifier]" +
		"&fields[servers.specifications.values.value]" +
		"&fields[servers.locations.country.name]" +
		"&fields[servers.locations.country.code]" +
		"&fields[servers.locations.country.city.name]" +
		"&fields[servers.locations.country.city.latitude]" +
		"&fields[servers.locations.country.city.longitude]" +
		"&coordinates[longitude]=%f&coordinates[latitude]=%f" +
		"&fields[servers.ips]"

	RecommendedServersCountryFilter = "&filters[country_id]=%d"
	RecommendedServersCityFilter    = "&filters[country_city_id]=%d"
	RecommendedServersGroupsFilter  = "&filters[servers_groups]=%d"

	// ServersURLSpecificQuery defines query params for a specific server
	ServersURLSpecificQuery = "?filters[servers.id]=%d"

	// ThreatProtectionLiteURL defines url of the cybersec file
	ThreatProtectionLiteURL = "/configs/dns/cybersec.json"

	// DebFileinfoURLFormat is the path to debian repository's package information
	DebFileinfoURLFormat = "/deb/%s/debian/dists/stable/main/binary-%s/Packages.gz"

	// RpmRepoMdURLFormat is the path to rpm repository's information
	RpmRepoMdURLFormat = "/yum/%s/centos/%s/repodata/%s"

	// RpmRepoMdURL is the path to rpm repository's information file
	RpmRepoMdURL = "repomd.xml"

	// RepoTypeProduction defines production repo type
	RepoTypeProduction = "nordvpn"

	// RepoTypeTest defines non-production (qa, development) repo type
	RepoTypeTest = "nordvpn-test"

	DedicatedServersURL = "/v1/dedicated-servers"

	DevicesURL = DedicatedServersURL + "/devices"

	// /v1/dedicated-servers/devices/<device-uuid>
	DevicesUpdateURL = DevicesURL + "/%s"

	// /v1/dedicated-servers/<dedicated-server-uuid>/connect
	DedicatedServersConnectURL = DedicatedServersURL + "/%s/connect"
)
View Source
const NoAcceptedErrorCode = -1

Variables

View Source
var (
	// ErrBadRequest is returned for 400 HTTP responses.
	ErrBadRequest = errors.New(http.StatusText(http.StatusBadRequest))
	// ErrMaximumDeviceCount is returned for some of the 400 HTTP responses.
	ErrMaximumDeviceCount = errors.New("maximum device count reached")
	// error codes returned for meshnet nicknames, when 400 HTTP responses
	ErrRateLimitReach            = errors.New("reach max allowed nickname changes for a week")
	ErrNicknameTooLong           = errors.New("nickname is too long")
	ErrDuplicateNickname         = errors.New("nickname already exist")
	ErrContainsForbiddenWord     = errors.New("nickname contains forbidden word")
	ErrInvalidPrefixOrSuffix     = errors.New("nickname contains invalid prefix or suffix")
	ErrNicknameWithDoubleHyphens = errors.New("nickname contains double hyphens")
	ErrContainsInvalidChars      = errors.New("nickname contains invalid characters")

	ErrDedicatedServersDeviceNotFound         = errors.New("device not found")
	ErrDedicatedServersDeviceNotRegistered    = errors.New("device not registered")
	ErrDedicatedServersInvalidFormData        = errors.New("invalid form data")
	ErrDedicatedServersPublicKeyMismatch      = errors.New("public key mismatch")
	ErrDedicatedServersSessionMaxLimitReached = errors.New("reached limit of maximum active sessions")
	ErrDedicatedServersServerOffline          = errors.New("server is offline")
	ErrDedicatedServersServerNotFound         = errors.New("server not found")

	// ErrUnauthorized is returned for 401 HTTP responses.
	ErrUnauthorized = errors.New(http.StatusText(http.StatusUnauthorized))
	// ErrForbidden is returned for 403 HTTP responses.
	ErrForbidden = errors.New(http.StatusText(http.StatusForbidden))
	// ErrNotFound is returned for 404 HTTP responses.
	ErrNotFound = errors.New(http.StatusText(http.StatusNotFound))
	// ErrConflict is returned for 409 HTTP responses.
	ErrConflict = errors.New(http.StatusText(http.StatusConflict))
	// ErrTooManyRequests is returned for 429 HTTP responses.
	ErrTooManyRequests = errors.New(http.StatusText(http.StatusTooManyRequests))
	// ErrServerInternal is returned for 500 HTTP responses.
	ErrServerInternal = errors.New(http.StatusText(http.StatusInternalServerError))
)
View Source
var (
	// ErrPublicKeyNotProvided is returned when peer does not have a public key set.
	ErrPublicKeyNotProvided = errors.New("public key not provided")
	// ErrPeerOSNotProvided is returned when peer does not have os name or os version set.
	ErrPeerOSNotProvided = errors.New("os not provided")
	// ErrPeerEndpointsNotProvided is returned when peer has on endpoints.
	ErrPeerEndpointsNotProvided = errors.New("endpoints not provided")
)

Functions

func ByGroup

func ByGroup(s config.ServerGroup) func(Group) bool

ByGroup is a Comparison function meant for use with github.com/NordSecurity/nordvpn-linux/slices.ContainsFunc function.

func ByTag

func ByTag(tag string) func(Group) bool

ByTag is a Comparison function meant for use with github.com/NordSecurity/nordvpn-linux/slices.ContainsFunc function.

func DecompressGzip

func DecompressGzip(compressed []byte) ([]byte, error)

DecompressGzip decompresses gzip-encoded data, capping the decompressed size at internal.MaxDecompressedBytesLimit to guard against decompression ("zip") bombs.

Callers must apply MaxBytesReadAll to the compressed body first; this bounds the decompressed output separately, since a compressed body within MaxBytesLimit can still inflate to gigabytes.

func ExtractError

func ExtractError(resp *http.Response) error

ExtractError from the response if it exists

if an error was returned, do not try to read a response again.

func IsDedicatedIP

func IsDedicatedIP(server Server) bool

IsDedicatedIP reports whether the server belongs to the dedicated IP group.

func IsServerDedicated

func IsServerDedicated(server Server) bool

func MaxBytesReadAll

func MaxBytesReadAll(r io.Reader) ([]byte, error)

MaxBytesReadAll is a wrapper around io.ReadAll that limits the number of bytes read from the reader to internal.MaxBytesLimit.

If the reader exceeds the limit, the function returns an error.

func MaxBytesReadAllWithLimit

func MaxBytesReadAllWithLimit(r io.Reader, limit int64) ([]byte, error)

MaxBytesReadAllWithLimit is a wrapper around io.ReadAll that limits the number of bytes read from the reader to the given limit.

If the reader exceeds the limit, the function returns an *ErrMaxBytesLimit.

func PrepareRecommendedServersURL

func PrepareRecommendedServersURL(filter ServersFilter, longitude, latitude float64) string

Types

type Authentication

type Authentication interface {
	Login(bool) (string, error)
	Token(string) (*LoginResponse, error)
}

Authentication is responsible for verifying user's identity.

type CDN

type CDN interface {
	ThreatProtectionLite() (*NameServers, error)
	ConfigTemplate(isObfuscated bool, method string) (http.Header, []byte, error)
	RemoteStorage
}

CDN provides methods to interact with Nord's Content Delivery Network

type CDNAPI

type CDNAPI struct {
	sync.Mutex
	// contains filtered or unexported fields
}

func NewCDNAPI

func NewCDNAPI(
	agent string,
	baseURL string,
	client *http.Client,
	validator response.Validator,
) *CDNAPI

func (*CDNAPI) ConfigTemplate

func (api *CDNAPI) ConfigTemplate(isObfuscated bool, method string) (http.Header, []byte, error)

func (*CDNAPI) GetRemoteFile

func (api *CDNAPI) GetRemoteFile(name string) ([]byte, error)

func (*CDNAPI) ThreatProtectionLite

func (api *CDNAPI) ThreatProtectionLite() (*NameServers, error)

type CDNAPIResponse

type CDNAPIResponse struct {
	Headers http.Header
	Body    io.ReadCloser
}

type Cities

type Cities []City

type City

type City struct {
	ID        int64    `json:"id"`
	Name      string   `json:"name"`
	Latitude  float64  `json:"latitude"`
	Longitude float64  `json:"longitude"`
	HubScore  *float64 `json:"hub_score"`
}

type ClientAPI

func NewSmartClientAPI

func NewSmartClientAPI(client RawClientAPI, sessionStore session.TokenSessionStore) ClientAPI

NewSmartClientAPI creates new client instance of smart-API

type CombinedAPI

type CombinedAPI interface {
	InsightsAPI
	Base() string
	Plans() (*Plans, error)
	CreateUser(email, password string) (*UserCreateResponse, error)
}

type Countries

type Countries []Country

type Country

type Country struct {
	ID     int64  `json:"id"`
	Name   string `json:"name"`
	Code   string `json:"code"`
	City   `json:"city,omitempty"`
	Cities `json:"cities,omitempty"`
}

Country is a weird struct in that it is defined in two different ways by the backend. Server recommendations endpoint response has city field, while server countries endpoint response has cities field. Basically, only one of the city/cities field exists at a given time.

type CountryCode

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

func NewCountryCode

func NewCountryCode(code string) CountryCode

func (CountryCode) String

func (cc CountryCode) String() string

type CredentialsAPI

type CredentialsAPI interface {
	NotificationCredentials(appUserID string) (NotificationCredentialsResponse, error)
	NotificationCredentialsRevoke(appUserID string, purgeSession bool) (NotificationCredentialsRevokeResponse, error)
	ServiceCredentials(token string) (*CredentialsResponse, error)
	TokenRenew(renewalToken string, idempotencyKey uuid.UUID) (*TokenRenewResponse, error)
	Services() (ServicesResponse, error)
	CurrentUser() (*CurrentUserResponse, error)
	DeleteToken() error
	TrustedPassToken() (*TrustedPassTokenResponse, error)
	MultifactorAuthStatus() (*MultifactorAuthStatusResponse, error)
	Logout() error
}

type CredentialsResponse

type CredentialsResponse struct {
	ID                 int64  `json:"id"`
	CreatedAt          string `json:"created_at"`
	UpdatedAt          string `json:"updated_at"`
	Username           string `json:"username"`
	Password           string `json:"password"`
	NordlynxPrivateKey string `json:"nordlynx_private_key"`
}

type CurrentUserResponse

type CurrentUserResponse struct {
	Username  string `json:"username"`
	Email     string `json:"email"`
	CreatedOn string `json:"created_at"`
}

type DedicatedServer

type DedicatedServer struct {
	UUID     string                `json:"uuid"`
	Name     string                `json:"name"`
	Status   DedicatedServerStatus `json:"status"`
	IP       string                `json:"ip"`
	Location `json:"location"`
}

type DedicatedServerConnectRequest

type DedicatedServerConnectRequest struct {
	DeviceUUID      string `json:"device_uuid"`
	DevicePublicKey string `json:"device_public_key"`
}

type DedicatedServerConnectResponse

type DedicatedServerConnectResponse struct {
	ServerPublicKey string `json:"server_public_key"`
	ServerEndpoint  string `json:"server_endpoint"`
}

type DedicatedServerStatus

type DedicatedServerStatus string
const (
	DedicatedServerStatusNew      DedicatedServerStatus = "new"
	DedicatedServerStatusRunning  DedicatedServerStatus = "running"
	DedicatedServerStatusStopped  DedicatedServerStatus = "stopped"
	DedicatedServerStatusStopping DedicatedServerStatus = "stopping"
)

type DedicatedServers

type DedicatedServers []DedicatedServer

type DedicatedServersAPI

type DedicatedServersAPI interface {
	RegisterDevice(DevicesRequest) (DevicesResponse, error)
	UpdateDevice(uuid.UUID, UpdateDeviceRequest) (DevicesResponse, error)
	DedicatedServers() (DedicatedServers, error)
	DedicatedServerConnectCheck(serverUUID string, connectRequest DedicatedServerConnectRequest) (DedicatedServerConnectResponse, error)
}

type DevicesRequest

type DevicesRequest struct {
	HardwareIdentifier string `json:"hardware_identifier"`
	PublicKey          string `json:"public_key"`
	Os                 string `json:"os"`
	Type               string `json:"type"`
	Name               string `json:"name"`
}

type DevicesResponse

type DevicesResponse struct {
	UUID               string `json:"uuid"`
	HardwareIdentifier string `json:"hardware_identifier"`
	PublicKey          string `json:"public_key"`
	OS                 string `json:"os"`
	Type               string `json:"type"`
	Name               string `json:"name"`
}

type ErrMaxBytesLimit

type ErrMaxBytesLimit struct {
	Limit int64
}

func (*ErrMaxBytesLimit) Error

func (err *ErrMaxBytesLimit) Error() string

type ExpirationChecker

type ExpirationChecker interface {
	// IsExpired checks if date in '2006-01-02 15:04:05' format has passed
	IsExpired(date string) bool
}

type Group

type Group struct {
	ID    config.ServerGroup `json:"id"`
	Title string             `json:"title"`
}

type Groups

type Groups []Group

type Insights

type Insights struct {
	City        string  `json:"city"`
	Country     string  `json:"country"`
	Isp         string  `json:"isp"`
	IspAsn      int     `json:"isp_asn"`
	CountryCode string  `json:"country_code"`
	Longitude   float64 `json:"longitude"`
	Latitude    float64 `json:"latitude"`
	Protected   bool    `json:"protected"`
}

type InsightsAPI

type InsightsAPI interface {
	Insights() (*Insights, error)
}

type Location

type Location struct {
	Country `json:"country"`
}

type Locations

type Locations []Location

func (Locations) Country

func (l Locations) Country() (Country, error)

type LoginRequest

type LoginRequest struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

type LoginResponse

type LoginResponse struct {
	UserID     int64  `json:"user_id"`
	Token      string `json:"token"`
	RenewToken string `json:"renew_token"`
	ExpiresAt  string `json:"expires_at"`
}

type MultifactorAuthStatusResponse

type MultifactorAuthStatusResponse struct {
	Status string `json:"status"`
}

type NameServers

type NameServers struct {
	Servers []string `json:"servers"`
}

type NotificationCredentialsRequest

type NotificationCredentialsRequest struct {
	AppUserID  string `json:"app_user_uid"`
	PlatformID int    `json:"platform_id"`
}

type NotificationCredentialsResponse

type NotificationCredentialsResponse struct {
	Endpoint  string `json:"endpoint"`
	Username  string `json:"username"`
	Password  string `json:"password"`
	ExpiresIn int    `json:"expires_in"`
}

type NotificationCredentialsRevokeRequest

type NotificationCredentialsRevokeRequest struct {
	AppUserID    string `json:"app_user_uid"`
	PurgeSession bool   `json:"purge_session"`
}

type NotificationCredentialsRevokeResponse

type NotificationCredentialsRevokeResponse struct {
	Status string `json:"status"`
}

type OAuth2

type OAuth2 struct {
	sync.Mutex
	// contains filtered or unexported fields
}

func NewOAuth2

func NewOAuth2(client *http.Client, baseURL string, validator response.Validator) *OAuth2

func (*OAuth2) Login

func (o *OAuth2) Login(regularLogin bool) (string, error)

func (*OAuth2) Token

func (o *OAuth2) Token(exchangeToken string) (*LoginResponse, error)

Token to be used for further API requests.

type Order

type Order struct {
	ID       int    `json:"id,omitempty"`
	RemoteID int    `json:"remote_id,omitempty"`
	Status   string `json:"status,omitempty"`
	Plans    Plans  `json:"plans,omitempty"`
}

type Payer

type Payer struct {
	OrderID int `json:"order_id,omitempty"`
}

type Payment

type Payment struct {
	CreatedAt    time.Time    `json:"created_at,omitempty"`
	Subscription Subscription `json:"subscription,omitempty"`
	Status       string       `json:"status,omitempty"`
	Payer        Payer        `json:"payer,omitempty"`
	Amount       float32      `json:"amount,omitempty"`
	Currency     string       `json:"currency,omitempty"`
	Provider     string       `json:"provider,omitempty"`
}

func (*Payment) UnmarshalJSON

func (p *Payment) UnmarshalJSON(data []byte) error

type PaymentResponse

type PaymentResponse struct {
	Payment Payment `json:"payment,omitempty"`
}

type Pivot

type Pivot struct {
	Status Status `json:"status"`
}

type Plan

type Plan struct {
	ID         int32  `json:"id"`
	Identifier string `json:"identifier"`
	Type       string `json:"type"`
	Title      string `json:"title"`
	Cost       string `json:"cost"`
	Currency   string `json:"currency"`
}

type Plans

type Plans []Plan

type Predicate

type Predicate func(Server) bool

Predicate function used in algorithms like filter.

func IsConnectableVia

func IsConnectableVia(tech ServerTechnology) Predicate

IsConnectableVia returns true if it's possible to connect to server using a given technology.

func IsConnectableWithProtocol

func IsConnectableWithProtocol(tech config.Technology, proto config.Protocol) Predicate

IsConnectableWithProtocol behaves like IsConnectableVia, but also includes protocol.

func IsObfuscated

func IsObfuscated() Predicate

IsObfuscated returns a filter for keeping only obfuscated servers.

func IsOnline

func IsOnline() Predicate

IsOnline returns true for online servers.

type RawCombinedAPI

type RawCombinedAPI interface {
	RawInsightsAPI
	Base() string
	Plans() (*Plans, error)
	CreateUser(email, password string) (*UserCreateResponse, error)
}

type RawCredentialsAPI

type RawCredentialsAPI interface {
	NotificationCredentials(token, appUserID string) (NotificationCredentialsResponse, error)
	NotificationCredentialsRevoke(token, appUserID string, purgeSession bool) (NotificationCredentialsRevokeResponse, error)
	ServiceCredentials(token string) (*CredentialsResponse, error)
	TokenRenew(token string, idempotencyKey uuid.UUID) (*TokenRenewResponse, error)
	Services(token string) (ServicesResponse, error)
	CurrentUser(token string) (*CurrentUserResponse, error)
	DeleteToken(token string) error
	TrustedPassToken(token string) (*TrustedPassTokenResponse, error)
	MultifactorAuthStatus(token string) (*MultifactorAuthStatusResponse, error)
	Logout(token string) error
}

type RawDedicatedServersAPI

type RawDedicatedServersAPI interface {
	RegisterDevice(token string, request DevicesRequest) (DevicesResponse, error)
	UpdateDevice(token string, deviceUUID uuid.UUID, request UpdateDeviceRequest) (DevicesResponse, error)
	DedicatedServers(token string) (DedicatedServers, error)
	DedicatedServerConnectCheck(token string, serverUUID string, connectRequest DedicatedServerConnectRequest) (DedicatedServerConnectResponse, error)
}

type RawInsightsAPI

type RawInsightsAPI interface {
	Insights() (*Insights, error)
}

type RawServersAPI

type RawServersAPI interface {
	Servers() (Servers, http.Header, error)
	RecommendedServers(filter ServersFilter, longitude, latitude float64) (Servers, http.Header, error)
	Server(id int64) (*Server, error)
	ServersCountries() (Countries, http.Header, error)
}

type RawSubscriptionAPI

type RawSubscriptionAPI interface {
	// Orders returns a list of orders done by the user
	Orders(token string) ([]Order, error)
	// Payments returns a list of payments done by the user
	Payments(token string) ([]PaymentResponse, error)
}

SubscriptionAPI is responsible for fetching the subscription data of the user

type RemoteStorage

type RemoteStorage interface {
	GetRemoteFile(name string) ([]byte, error)
}

RemoteStorage interface to get remote files

type Server

type Server struct {
	ID                   int64  `json:"id"`
	CreatedAt            string `json:"created_at"`
	UpdatedAt            string `json:"updated_at"`
	Name                 string `json:"name"`
	Station              string `json:"station"`
	Hostname             string `json:"hostname"`
	Load                 int64  `json:"load"`
	Status               Status `json:"status"`
	Locations            `json:"locations"`
	Technologies         Technologies `json:"technologies"`
	Groups               `json:"groups"`
	Specifications       []Specification  `json:"specifications"`
	Distance             float64          `json:"distance"`
	Timestamp            int64            `json:"timestamp"`
	Penalty              float64          `json:"penalty"`
	PartialPenalty       float64          `json:"partial_penalty"`
	NordLynxPublicKey    string           `json:"-"`
	NordWhisperPort      int64            `json:"-"`
	DedicatedServersPort int64            `json:"-"`
	DedicatedServerUUID  string           `json:"-"`
	Keys                 []string         `json:"-"`
	IPRecords            []ServerIPRecord `json:"ips"`
}

func (*Server) Country

func (s *Server) Country() *Country

func (*Server) GenerateKeys

func (s *Server) GenerateKeys() []string

Compute a list of keys for each server to speedup the server picking process at connect

func (*Server) IPs

func (s *Server) IPs() []netip.Addr

func (*Server) IPv4

func (s *Server) IPv4() (netip.Addr, error)

func (*Server) IsValid

func (s *Server) IsValid() bool

IsValid returns true if server record is valid.

func (*Server) IsVirtualLocation

func (s *Server) IsVirtualLocation() bool

func (*Server) UnmarshalJSON

func (s *Server) UnmarshalJSON(b []byte) error

func (*Server) Version

func (s *Server) Version() string

type ServerBy

type ServerBy int
const (
	ServerByUnknown ServerBy = iota
	ServerBySpeed
	ServerByCountry
	ServerByCity
	ServerByName
)

type ServerIP

type ServerIP struct {
	IP      string `json:"ip"`
	Version uint8  `json:"version"`
}

type ServerIPRecord

type ServerIPRecord struct {
	ServerIP `json:"ip"`
	Type     string `json:"type"`
}

type ServerObfuscationStatus

type ServerObfuscationStatus int

ServerObfuscationStatus is the return status of IsServerObfuscated

const (
	// ServerObfuscated status returned when server is obfuscated
	ServerObfuscated ServerObfuscationStatus = iota
	// ServerNotObfuscated status returned when server is not obfuscated
	ServerNotObfuscated
	// NotAServerName returned when server with such name has not been found
	// (there is no hostname beginning with given server tag)
	NotAServerName
)

func IsServerObfuscated

func IsServerObfuscated(servers Servers, serverTag string) ServerObfuscationStatus

IsServerObfuscated returns ServerObfuscationStatus for a given server tag

type ServerTag

type ServerTag struct {
	Action ServerBy
	ID     int64
}

type ServerTechnology

type ServerTechnology int64

ServerTechnology represents the nordvpn server technology

const (
	// Unknown is used for invalid cases
	Unknown ServerTechnology = 0
	// OpenVPNUDP represents the OpenVPN udp technology
	OpenVPNUDP ServerTechnology = 3
	// OpenVPNTCP represents the OpenVpn tcp technology
	OpenVPNTCP ServerTechnology = 5
	// Socks5 represents the socks 5 technology
	Socks5 ServerTechnology = 7
	// HTTPProxy represents the http proxy technology
	HTTPProxy ServerTechnology = 9
	// PPTP represents the pptp technology
	PPTP ServerTechnology = 11
	// L2TP represents the l2tp technology
	L2TP ServerTechnology = 13
	// OpenVPNUDPObfuscated represents the openvpn udp obfuscated technology
	OpenVPNUDPObfuscated ServerTechnology = 15
	// OpenVPNTCPObfuscated represents the openvpn tcp obfuscated technology
	OpenVPNTCPObfuscated ServerTechnology = 17
	// WireguardTech represents wireguard technology
	WireguardTech ServerTechnology = 35
	// NordWhisperTech represents NordWhisper technology
	NordWhisperTech ServerTechnology = 51
)

type Servers

type Servers []Server

func (*Servers) Validate

func (s *Servers) Validate() error

type ServersAPI

type ServersAPI interface {
	Servers() (Servers, http.Header, error)
	RecommendedServers(filter ServersFilter, longitude, latitude float64) (Servers, http.Header, error)
	Server(id int64) (*Server, error)
	ServersCountries() (Countries, http.Header, error)
}

type ServersFilter

type ServersFilter struct {
	Limit int
	Tech  ServerTechnology
	Group config.ServerGroup
	Tag   ServerTag
}

type Service

type Service struct {
	ID   int64  `json:"id"`
	Name string `json:"name"`
}

type ServiceData

type ServiceData struct {
	ID        int64          `json:"ID"`
	ExpiresAt string         `json:"expires_at"`
	Service   Service        `json:"service"`
	Details   ServiceDetails `json:"details,omitempty"`
}

type ServiceDetails

type ServiceDetails struct {
	Servers []ServiceServer `json:"servers"`
}

type ServiceServer

type ServiceServer struct {
	ID int64 `json:"id"`
}

type ServicesResponse

type ServicesResponse []ServiceData

type SimpleClientAPI

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

func (*SimpleClientAPI) Accept

func (api *SimpleClientAPI) Accept(
	token string,
	self uuid.UUID,
	invitation uuid.UUID,
	doIAllowInbound bool,
	doIAllowRouting bool,
	doIAllowLocalNetwork bool,
	doIAllowFileshare bool,
) error

Accept invitation.

func (*SimpleClientAPI) Base

func (api *SimpleClientAPI) Base() string

func (*SimpleClientAPI) Configure

func (api *SimpleClientAPI) Configure(
	token string,
	id uuid.UUID,
	peerID uuid.UUID,
	peerUpdateInfo mesh.PeerUpdateRequest,
) error

Configure interaction with a specific peer.

func (*SimpleClientAPI) CreateUser

func (api *SimpleClientAPI) CreateUser(email, password string) (*UserCreateResponse, error)

CreateUser accepts email and password as arguments and creates the user

func (*SimpleClientAPI) CurrentUser

func (api *SimpleClientAPI) CurrentUser(token string) (*CurrentUserResponse, error)

CurrentUser returns metadata of current user

func (*SimpleClientAPI) DedicatedServerConnectCheck

func (api *SimpleClientAPI) DedicatedServerConnectCheck(token string, serverUUID string, connectRequest DedicatedServerConnectRequest) (DedicatedServerConnectResponse, error)

func (*SimpleClientAPI) DedicatedServers

func (api *SimpleClientAPI) DedicatedServers(token string) (DedicatedServers, error)

func (*SimpleClientAPI) DeleteToken

func (api *SimpleClientAPI) DeleteToken(token string) error

func (*SimpleClientAPI) Insights

func (api *SimpleClientAPI) Insights() (*Insights, error)

Insights returns insights about user

func (*SimpleClientAPI) Invite

func (api *SimpleClientAPI) Invite(
	token string,
	self uuid.UUID,
	email string,
	doIAllowInbound bool,
	doIAllowRouting bool,
	doIAllowLocalNetwork bool,
	doIAllowFileshare bool,
) error

Invite to mesh.

func (*SimpleClientAPI) List

func (api *SimpleClientAPI) List(token string, self uuid.UUID) (mesh.MachinePeers, error)

List peers in the mesh network for a given peer.

func (*SimpleClientAPI) Logout

func (api *SimpleClientAPI) Logout(token string) error

func (*SimpleClientAPI) Map

func (api *SimpleClientAPI) Map(token string, self uuid.UUID) (*mesh.MachineMap, error)

func (*SimpleClientAPI) MultifactorAuthStatus

func (api *SimpleClientAPI) MultifactorAuthStatus(token string) (*MultifactorAuthStatusResponse, error)

MultifactorAuthStatus queries and returns the status of MFA

func (*SimpleClientAPI) NotificationCredentials

func (api *SimpleClientAPI) NotificationCredentials(token, appUserID string) (NotificationCredentialsResponse, error)

NotificationCredentials retrieves the credentials for notification center appUserID

func (*SimpleClientAPI) NotificationCredentialsRevoke

func (api *SimpleClientAPI) NotificationCredentialsRevoke(token, appUserID string, purgeSession bool) (NotificationCredentialsRevokeResponse, error)

NotificationCredentialsRevoke revokes the credentials for notification center appUserID

func (*SimpleClientAPI) NotifyNewTransfer

func (api *SimpleClientAPI) NotifyNewTransfer(
	token string,
	self uuid.UUID,
	peer uuid.UUID,
	fileName string,
	fileCount int,
	transferID string,
) error

Notify peer about a new incoming transfer

func (*SimpleClientAPI) Orders

func (api *SimpleClientAPI) Orders(token string) ([]Order, error)

func (*SimpleClientAPI) Payments

func (api *SimpleClientAPI) Payments(token string) ([]PaymentResponse, error)

func (*SimpleClientAPI) Plans

func (api *SimpleClientAPI) Plans() (*Plans, error)

func (*SimpleClientAPI) Received

func (api *SimpleClientAPI) Received(token string, self uuid.UUID) (mesh.Invitations, error)

Received invitations from other users.

func (*SimpleClientAPI) RecommendedServers

func (api *SimpleClientAPI) RecommendedServers(filter ServersFilter, longitude, latitude float64) (Servers, http.Header, error)

RecommendedServers returns recommended servers list

func (*SimpleClientAPI) Register

func (api *SimpleClientAPI) Register(token string, peer mesh.Machine) (*mesh.Machine, error)

Register peer to the mesh network.

func (*SimpleClientAPI) RegisterDevice

func (api *SimpleClientAPI) RegisterDevice(token string, deviceRequest DevicesRequest) (DevicesResponse, error)

func (*SimpleClientAPI) Reject

func (api *SimpleClientAPI) Reject(token string, self uuid.UUID, invitation uuid.UUID) error

Reject invitation.

func (*SimpleClientAPI) Revoke

func (api *SimpleClientAPI) Revoke(token string, self uuid.UUID, invitation uuid.UUID) error

Revoke invitation.

func (*SimpleClientAPI) Sent

func (api *SimpleClientAPI) Sent(token string, self uuid.UUID) (mesh.Invitations, error)

Sent invitations to other users.

func (*SimpleClientAPI) Server

func (api *SimpleClientAPI) Server(id int64) (*Server, error)

Server returns specific server

func (*SimpleClientAPI) Servers

func (api *SimpleClientAPI) Servers() (Servers, http.Header, error)

Servers returns servers list

func (*SimpleClientAPI) ServersCountries

func (api *SimpleClientAPI) ServersCountries() (Countries, http.Header, error)

ServersCountries returns server countries list

func (*SimpleClientAPI) ServiceCredentials

func (api *SimpleClientAPI) ServiceCredentials(token string) (*CredentialsResponse, error)

ServiceCredentials returns service credentials

func (*SimpleClientAPI) Services

func (api *SimpleClientAPI) Services(token string) (ServicesResponse, error)

Services returns all previously and currently used services by the user

func (*SimpleClientAPI) TokenRenew

func (api *SimpleClientAPI) TokenRenew(token string, idempotencyKey uuid.UUID) (*TokenRenewResponse, error)

TokenRenew queries the renew token and returns new token data

func (*SimpleClientAPI) TrustedPassToken

func (api *SimpleClientAPI) TrustedPassToken(token string) (*TrustedPassTokenResponse, error)

TokenRenew queries the renew token and returns new token data

func (*SimpleClientAPI) Unpair

func (api *SimpleClientAPI) Unpair(token string, self uuid.UUID, peer uuid.UUID) error

Unpair a given peer.

func (*SimpleClientAPI) Unregister

func (api *SimpleClientAPI) Unregister(token string, self uuid.UUID) error

Unregister peer from the mesh network.

func (*SimpleClientAPI) Update

func (api *SimpleClientAPI) Update(token string, id uuid.UUID, info mesh.MachineUpdateRequest) error

Update publishes new endpoints.

func (*SimpleClientAPI) UpdateDevice

func (api *SimpleClientAPI) UpdateDevice(token string, deviceUUID uuid.UUID, updateDeviceRequest UpdateDeviceRequest) (DevicesResponse, error)

type Specification

type Specification struct {
	Identifier string `json:"identifier"`
	Values     []struct {
		Value string `json:"value"`
	} `json:"values"`
}

type Status

type Status string

Status is used by Server and Technology to communicate availability

type Subscription

type Subscription struct {
	MerchantID        int32  `json:"merchant_id,omitempty"`
	FrequencyInterval int32  `json:"frequency_interval,omitempty"`
	FrequencyUnit     string `json:"frequency_unit,omitempty"`
	Status            string `json:"status,omitempty"`
}

type SubscriptionAPI

type SubscriptionAPI interface {
	// Orders returns a list of orders done by the user
	Orders() ([]Order, error)
	// Payments returns a list of payments done by the user
	Payments() ([]PaymentResponse, error)
}

SubscriptionAPI is responsible for fetching the subscription data of the user

type Technologies

type Technologies []Technology

type Technology

type Technology struct {
	ID       ServerTechnology `json:"id"`
	Pivot    Pivot            `json:"pivot"`
	Metadata []struct {
		Name  string      `json:"name,omitempty"`
		Value interface{} `json:"value,omitempty"`
	} `json:"metadata"`
}

func (Technology) IsOnline

func (t Technology) IsOnline() bool

type TokenRenewResponse

type TokenRenewResponse struct {
	Token      string `json:"token"`
	RenewToken string `json:"renew_token"`
	ExpiresAt  string `json:"expires_at"`
	UpdatedAt  string `json:"updated_at"`
}

type TrustedPassTokenResponse

type TrustedPassTokenResponse struct {
	OwnerID string `json:"owner_id"`
	Token   string `json:"token"`
}

type UpdateDeviceRequest

type UpdateDeviceRequest struct {
	PublicKey string `json:"public_key"`
	Name      string `json:"name"`
}

type UserCreateRequest

type UserCreateRequest struct {
	Email    string `json:"email"`
	Password string `json:"password"`
}

type UserCreateResponse

type UserCreateResponse struct {
	ID        int64  `json:"id"`
	Email     string `json:"email"`
	Username  string `json:"username"`
	CreateAt  string `json:"create_at"`
	UpdatedAt string `json:"updated_at"`
}

Directories

Path Synopsis
Package mesh implements mesh related data structure conversions.
Package mesh implements mesh related data structure conversions.

Jump to

Keyboard shortcuts

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