Documentation
¶
Overview ¶
Package client is a stateless HTTP client for the Harbor API. It speaks the Harbor wire contract: JSON request/response bodies, the standard response envelopes, and the typed error model. See docs/conventions.md in the API repo for the authoritative contract.
Index ¶
- Constants
- func CollectionItems(data []byte) []json.RawMessage
- func DetectMIME(path string) string
- func ForgetServerNames()
- func IsMaintenance(err error) bool
- func NoteMetadataPath(id string) string
- func NotebookMetadataPath(id string) string
- func PrettyJSON(data []byte) (string, error)
- func SetServerNameStore(load func(baseURL string) (string, error), ...)
- func StackMetadataPath(name string) string
- func UnwrapData(data []byte) []byte
- type APIError
- type Client
- func (c *Client) AbortImportUpload(kind, jobID string) ([]byte, error)
- func (c *Client) AppendNote(id string, body map[string]any) ([]byte, error)
- func (c *Client) ApplyTemplate(id string, body map[string]any) ([]byte, error)
- func (c *Client) AttachTag(noteID string, body map[string]any) ([]byte, bool, error)
- func (c *Client) AuthorizationCodeGrant(clientID, code, redirectURI, codeVerifier string) ([]byte, *TokenResponse, error)
- func (c *Client) CancelAccountDeletion(currentPassword string) ([]byte, error)
- func (c *Client) ChangePassword(currentPassword, newPassword string) ([]byte, error)
- func (c *Client) CheckFile(hash string, size int64) ([]byte, error)
- func (c *Client) ClearMetadata(path string) ([]byte, error)
- func (c *Client) ClearReminder(noteID string) ([]byte, error)
- func (c *Client) ClientFlags() ([]byte, error)
- func (c *Client) CommitFile(hash string, size int64, mimeType, filename string, isEncrypted bool) ([]byte, error)
- func (c *Client) CompleteImportUpload(kind, jobID string, parts []ImportUploadPart) ([]byte, error)
- func (c *Client) CompleteReminder(noteID string, body map[string]any) ([]byte, error)
- func (c *Client) CompleteTask(id string, body map[string]any) ([]byte, error)
- func (c *Client) ConfirmEmailChange(token string) ([]byte, error)
- func (c *Client) ConvertNoteToEncrypted(id string, body map[string]any) ([]byte, error)
- func (c *Client) ConvertNoteToPlaintext(id string, body map[string]any) ([]byte, error)
- func (c *Client) CreateImportUpload(kind string, totalBytes int64, filename, targetNotebookID string, ...) ([]byte, error)
- func (c *Client) CreateNote(body map[string]any) ([]byte, error)
- func (c *Client) CreateNotebook(body map[string]any) ([]byte, error)
- func (c *Client) CreatePAT(name string, scopes []string, expiresIn int64) ([]byte, *PersonalAccessToken, error)
- func (c *Client) CreateShortcut(body map[string]any) ([]byte, error)
- func (c *Client) CreateTag(body map[string]any) ([]byte, error)
- func (c *Client) CreateTask(body map[string]any) ([]byte, error)
- func (c *Client) CreateTemplate(body map[string]any) ([]byte, error)
- func (c *Client) DeleteAccountExport(id string) ([]byte, error)
- func (c *Client) DeleteNote(id string, permanent bool) ([]byte, error)
- func (c *Client) DeleteNotebook(id, notesPolicy string) ([]byte, error)
- func (c *Client) DeleteShortcut(id string) ([]byte, error)
- func (c *Client) DeleteTag(id, childrenPolicy string) ([]byte, error)
- func (c *Client) DeleteTask(id string) ([]byte, error)
- func (c *Client) DeleteTemplate(id string) ([]byte, error)
- func (c *Client) DetachTag(noteID, tagID string) ([]byte, error)
- func (c *Client) EmptyTrash() ([]byte, error)
- func (c *Client) ExportENEX(notebookID string, noteIDs []string, includeResources bool) (*http.Response, error)
- func (c *Client) ExportNoteHTML(id string) (*http.Response, error)
- func (c *Client) ExportNoteMarkdown(id string, zip bool) (*http.Response, error)
- func (c *Client) ExportNotePDF(id, paperSize string) (*http.Response, error)
- func (c *Client) ExportPDF(noteIDs []string, pageBreak, paperSize string) (*http.Response, error)
- func (c *Client) ExpungeNote(id string) ([]byte, error)
- func (c *Client) FetchURL(rawURL string) (*http.Response, error)
- func (c *Client) ForgotPassword(email string) ([]byte, error)
- func (c *Client) GetAccountClear() ([]byte, error)
- func (c *Client) GetAccountExport(id string) ([]byte, error)
- func (c *Client) GetFileDownload(hash string) ([]byte, error)
- func (c *Client) GetMetadata(path string) ([]byte, error)
- func (c *Client) GetNote(id string, params map[string]string) ([]byte, error)
- func (c *Client) GetNoteHistoryVersion(noteID, versionID string) ([]byte, error)
- func (c *Client) GetNotebook(id string, includeDeleted bool) ([]byte, error)
- func (c *Client) GetProfile() ([]byte, error)
- func (c *Client) GetSettings() ([]byte, error)
- func (c *Client) GetShortcut(id string, includeDeleted bool) ([]byte, error)
- func (c *Client) GetSubscription() ([]byte, error)
- func (c *Client) GetTag(id string, includeDeleted bool) ([]byte, error)
- func (c *Client) GetTask(id string) ([]byte, error)
- func (c *Client) GetTemplate(id string, includeDeleted bool) ([]byte, error)
- func (c *Client) GetTrashEmptyJob(id string) ([]byte, error)
- func (c *Client) GetUsage() ([]byte, error)
- func (c *Client) Health() ([]byte, error)
- func (c *Client) ImportStatus(kind, jobID string) ([]byte, error)
- func (c *Client) ListAccountExports() ([]byte, error)
- func (c *Client) ListDevices() ([]byte, error)
- func (c *Client) ListFiles(params map[string]string) ([]byte, error)
- func (c *Client) ListNoteAudit(noteID string, params map[string]string) ([]byte, error)
- func (c *Client) ListNoteBacklinks(noteID string, params map[string]string) ([]byte, error)
- func (c *Client) ListNoteHistory(noteID string, params map[string]string) ([]byte, error)
- func (c *Client) ListNoteLinks(noteID string, params map[string]string) ([]byte, error)
- func (c *Client) ListNoteTags(noteID string, params map[string]string) ([]byte, error)
- func (c *Client) ListNoteTasks(noteID string, params map[string]string) ([]byte, error)
- func (c *Client) ListNotebooks(params map[string]string) ([]byte, error)
- func (c *Client) ListNotebooksQuery(q url.Values) ([]byte, error)
- func (c *Client) ListNotes(params map[string]string) ([]byte, error)
- func (c *Client) ListNotesQuery(q url.Values) ([]byte, error)
- func (c *Client) ListPlans(params map[string]string) ([]byte, error)
- func (c *Client) ListReminders(params map[string]string) ([]byte, error)
- func (c *Client) ListSessions(params map[string]string) ([]byte, error)
- func (c *Client) ListShortcuts(params map[string]string) ([]byte, error)
- func (c *Client) ListStacks(q url.Values) ([]byte, error)
- func (c *Client) ListTagNotes(tagID string, params map[string]string) ([]byte, error)
- func (c *Client) ListTags(q url.Values) ([]byte, error)
- func (c *Client) ListTasks(params map[string]string) ([]byte, error)
- func (c *Client) ListTemplates(params map[string]string) ([]byte, error)
- func (c *Client) ListTrash(params map[string]string) ([]byte, error)
- func (c *Client) Logout(allDevices bool) error
- func (c *Client) MergeMetadata(path string, patch map[string]any) ([]byte, error)
- func (c *Client) OpenAPI() ([]byte, error)
- func (c *Client) Origin() string
- func (c *Client) PresignImportParts(kind, jobID string, partNumbers []int) ([]byte, error)
- func (c *Client) PresignUpload(hash string, size int64, mimeType string, isEncrypted bool) (*PresignedUpload, error)
- func (c *Client) PublicNote(token string) ([]byte, error)
- func (c *Client) PublishShare(noteID string, body map[string]any) ([]byte, bool, error)
- func (c *Client) RawDownload(hash string) (*http.Response, error)
- func (c *Client) Ready() ([]byte, error)
- func (c *Client) RefreshGrant(clientID, refreshToken, scope string) ([]byte, *TokenResponse, error)
- func (c *Client) RegisterDevice(body map[string]any) ([]byte, error)
- func (c *Client) RemoveAvatar() ([]byte, error)
- func (c *Client) RemoveDevice(deviceID string) ([]byte, error)
- func (c *Client) RenameFile(hash, filename string) ([]byte, error)
- func (c *Client) ReorderShortcuts(order []string) ([]byte, error)
- func (c *Client) ReplaceMetadata(path string, obj map[string]any) ([]byte, error)
- func (c *Client) RequestAccountClear(currentPassword, confirm string) ([]byte, error)
- func (c *Client) RequestAccountDeletion(currentPassword, confirm string) ([]byte, error)
- func (c *Client) ResendVerification(email string) ([]byte, error)
- func (c *Client) ResetInboundEmail() ([]byte, error)
- func (c *Client) ResetPassword(token, password string) ([]byte, error)
- func (c *Client) RestoreNote(id string) ([]byte, error)
- func (c *Client) RevertNoteHistoryVersion(noteID, versionID string) ([]byte, error)
- func (c *Client) Revoke(token, tokenTypeHint string) error
- func (c *Client) RevokeSession(id string) ([]byte, error)
- func (c *Client) RevokeSessions(except string) ([]byte, error)
- func (c *Client) Search(params map[string]string) ([]byte, error)
- func (c *Client) SearchCoordinates(params map[string]string) ([]byte, error)
- func (c *Client) SetAvatar(hash string) ([]byte, error)
- func (c *Client) SetInboundEmailEnabled(enabled bool) ([]byte, error)
- func (c *Client) SetNotePinned(id string, pinned bool) ([]byte, error)
- func (c *Client) SetNoteTags(noteID string, tagIDs []string) ([]byte, error)
- func (c *Client) SetReminder(noteID string, reminderTimeMS int64) ([]byte, error)
- func (c *Client) StartAccountExport(format, notebookID, pageBreak, paperSize string) ([]byte, error)
- func (c *Client) SubmitSupportRequest(body map[string]any) ([]byte, error)
- func (c *Client) SyncAck(deviceID string, ackedUSN int64) ([]byte, error)
- func (c *Client) SyncPull(body map[string]any) ([]byte, error)
- func (c *Client) SyncPush(body map[string]any) ([]byte, error)
- func (c *Client) UncompleteTask(id string) ([]byte, error)
- func (c *Client) UnpublishShare(noteID string) ([]byte, error)
- func (c *Client) UpdateNote(id string, body map[string]any) ([]byte, error)
- func (c *Client) UpdateNotebook(id string, body map[string]any) ([]byte, error)
- func (c *Client) UpdateProfile(body map[string]any) ([]byte, error)
- func (c *Client) UpdateSettings(body map[string]any) ([]byte, error)
- func (c *Client) UpdateShortcut(id string, body map[string]any) ([]byte, error)
- func (c *Client) UpdateStack(name string, body map[string]any) ([]byte, error)
- func (c *Client) UpdateTag(id string, body map[string]any) ([]byte, error)
- func (c *Client) UpdateTask(id string, body map[string]any) ([]byte, error)
- func (c *Client) UpdateTemplate(id string, body map[string]any) ([]byte, error)
- func (c *Client) UploadBytes(ctx context.Context, content []byte, mimeType, filename string, ...) ([]byte, error)
- func (c *Client) UploadFile(ctx context.Context, path, mimeType, filename string, streamLimit int64) ([]byte, error)
- func (c *Client) UploadImportPart(ctx context.Context, url string, chunk io.ReaderAt, size int64) (string, error)
- func (c *Client) VerifyEmail(token string) ([]byte, error)
- func (c *Client) Version() ([]byte, error)
- type DownloadError
- type ImportUploadPart
- type Paging
- type PersonalAccessToken
- type PresignedUpload
- type StallError
- type StreamTooLargeError
- type TokenResponse
Constants ¶
const CodeMaintenance = "maintenance"
CodeMaintenance is the error code for a response that came from Harbor's downtime page rather than from the API server.
const MaintenanceMessage = "Harbor is down for maintenance. Try again in a few minutes."
MaintenanceMessage is the sentence every Harbor app shows when its servers are down for maintenance. The words are shared across apps, so keep them exactly as they are.
Variables ¶
This section is empty.
Functions ¶
func CollectionItems ¶
func CollectionItems(data []byte) []json.RawMessage
CollectionItems returns the raw JSON elements of a collection's data array. Returns nil when data is absent or not an array.
func DetectMIME ¶ added in v0.1.28
DetectMIME resolves a path's MIME type exactly as UploadFile would, so a caller that transforms the bytes before upload (client-side encryption) can still record the ORIGINAL type rather than the ciphertext's. Returns "" when it cannot do better than application/octet-stream.
func ForgetServerNames ¶ added in v0.1.54
func ForgetServerNames()
ForgetServerNames drops the in-memory names, so the next request reads the store again. Logout calls it after it removes the saved file.
func IsMaintenance ¶ added in v0.1.58
IsMaintenance reports whether err is Harbor's servers being down for maintenance. Nothing was decided by the server, so the same request can work once Harbor is back.
func NoteMetadataPath ¶ added in v0.1.42
NoteMetadataPath is the metadata route for one note.
func NotebookMetadataPath ¶ added in v0.1.42
NotebookMetadataPath is the metadata route for one notebook.
func PrettyJSON ¶
PrettyJSON pretty-prints raw JSON bytes with two-space indentation. Used for the --json output mode on every command.
It re-indents the server's bytes rather than decoding and re-encoding them. A decode turns every number into a float64, so a 64-bit id stored in metadata would come out rounded, and a re-encode would also rewrite `<` in a note body as \u003c. --json promises the server's answer, so it prints exactly that.
func SetServerNameStore ¶ added in v0.1.54
func SetServerNameStore(load func(baseURL string) (string, error), save func(baseURL, name string) error)
SetServerNameStore makes server names survive between commands, so the first request of a new command carries the name. load returns the saved name for a base URL ("" when there is none); save records one, and "" removes it. It also drops the in-memory cache, so the next request reads the store.
func StackMetadataPath ¶ added in v0.1.42
StackMetadataPath is the metadata route for one stack. A stack is addressed by its name, which is free text, so it is escaped — a space or `?` in a name would otherwise change what the URL means.
func UnwrapData ¶
UnwrapData returns the bytes of the "data" member when present (a wrapped or collection envelope), otherwise the original bytes unchanged (a bare resource). This lets display code treat all shapes uniformly.
Types ¶
type APIError ¶
type APIError struct {
Code string `json:"code"`
Message string `json:"message"`
Details map[string]any `json:"details"`
RequestID string `json:"request_id"`
Status int `json:"-"`
// RetryAfterSeconds is the response's Retry-After header in seconds, so a
// script reading --json can wait that long before it tries again. Nil when
// the response had no usable Retry-After.
RetryAfterSeconds *int `json:"retry_after_seconds,omitempty"`
}
APIError is the typed form of the Harbor error envelope:
{ "error": { "code", "message", "details", "request_id" } }
Commands branch on Code (e.g. invalid_token triggers refresh; sync_conflict; validation_failed shows Details). It implements error so errors.As recovers the typed value from a wrapped error chain.
func (*APIError) DetailLines ¶
DetailLines returns the validation details as sorted "field: message" lines, for friendly multi-line rendering. Non-string detail values are stringified.
func (*APIError) Error ¶
Error renders a concise single-line description. Richer rendering (bulleted details, dim request id) lives in the cmd display layer. A maintenance error is the message alone, because "maintenance: Harbor is down for maintenance" says the same thing twice wherever an error is printed inline.
type Client ¶
type Client struct {
// BaseURL includes the /api/v1 prefix (e.g. https://app.harbor.my/api/v1).
// Domain method paths are relative to it.
BaseURL string
// AccessToken is the bearer token sent on protected requests. It may be
// empty for public endpoints (login, password reset, public share, ops).
AccessToken string
// HTTPClient performs the requests. Defaults to a 30s-timeout client. A
// streamed download uses it without that timeout (see sendStreaming).
HTTPClient *http.Client
// StorageHTTPClient performs direct-to-storage transfers: the presigned part
// PUTs of a large import, presigned file uploads, and presigned downloads
// (FetchURL). It is separate from HTTPClient because that one's 30-second
// timeout is sized for small JSON calls and a big file on an ordinary
// connection takes longer than that. It carries no overall timeout: a part
// upload is bounded by the request context (Ctrl-C) and by the presigned URL's
// own expiry, and a file upload or a download by the stall timeout.
StorageHTTPClient *http.Client
// StallTimeout is how long a streamed transfer may go without moving a byte
// before it is given up. Zero means one minute.
StallTimeout time.Duration
// Verbose, when true, makes callers surface request ids / HTTP status.
Verbose bool
// with 401 invalid_token. It should refresh the token, persist the rotated
// pair, and return the new access token. ok=false aborts the retry. This is
// how transparent token refresh is wired without a config import cycle.
OnUnauthorized func() (newAccessToken string, ok bool)
// LastRequestID holds the X-Request-Id of the most recent response, for
// verbose error reporting.
LastRequestID string
// contains filtered or unexported fields
}
Client talks to a single Harbor API base URL using a bearer access token. The zero value is not usable; construct one with NewClient.
func NewClient ¶
NewClient creates a Harbor API client for the given base URL and access token. The base URL is trimmed of any trailing slash.
func (*Client) AbortImportUpload ¶ added in v0.1.33
AbortImportUpload cancels an upload that is still awaiting its bytes: the multipart upload is aborted so storage keeps no orphaned parts, and the job is marked aborted. It is only valid while the job is awaiting an upload — once complete has run the import belongs to the server.
func (*Client) AppendNote ¶
AppendNote appends a fragment to the end of a note's body and returns {note, usn}. Encrypted notes are rejected by the server.
func (*Client) ApplyTemplate ¶
ApplyTemplate instantiates a new note from a template and returns a {note, usn, notice} envelope — CreateNote's shape plus one advisory line.
notice is always present and is "" when there is nothing to say. It is populated when the template's own notebook was gone or encrypt-by-default and the note was filed in the account default instead, so it must be surfaced rather than dropped. The body fields (notebook_id, title, tags) are all optional overrides; an omitted tags inherits the template's, a sent one replaces them.
func (*Client) AttachTag ¶
AttachTag attaches a tag to a note by id (tag_id) or by name (tag_name, creating the tag if missing). It returns the junction bytes and a created flag: true when a new junction was made (201), false when a live junction already existed (200, idempotent).
func (*Client) AuthorizationCodeGrant ¶
func (c *Client) AuthorizationCodeGrant(clientID, code, redirectURI, codeVerifier string) ([]byte, *TokenResponse, error)
AuthorizationCodeGrant exchanges a PKCE authorization code for an access + refresh token pair — the token step of the browser login flow. redirectURI must be byte-identical to the loopback URI the code was minted against, and codeVerifier is the PKCE secret whose S256 challenge was sent to /oauth/authorize. Public (no bearer) and uses the no-refresh path, since this call is itself the token acquisition. The code is single-use and expires ~60s after issuance, so exchange it immediately on receipt.
func (*Client) CancelAccountDeletion ¶
CancelAccountDeletion cancels a pending deletion within the grace window, re-authenticating via current_password. Returns the data-wrapped reactivated status ({status: "active"}).
func (*Client) ChangePassword ¶
ChangePassword changes the account password (re-auth via current_password). The server revokes every other session on success.
func (*Client) CheckFile ¶
CheckFile reports whether a blob already exists for the given sha256 hash. A zero size is omitted.
func (*Client) ClearMetadata ¶ added in v0.1.42
ClearMetadata removes all of a record's metadata. Answers 204 with no body.
func (*Client) ClearReminder ¶
ClearReminder removes a note's reminder entirely (nulls both reminder_time and reminder_done_time), returning {note, usn}. It is idempotent.
func (*Client) ClientFlags ¶ added in v0.1.38
ClientFlags fetches the server's runtime flag document from the root /client-flags endpoint and returns the raw body.
Like the health probes it lives at the server ROOT (no /api/v1 prefix) and is public, so it is built from c.Origin() and dispatched through the low-level request method with allowRefresh false.
It carries the per-file upload policy — max_upload_bytes_plain, max_upload_bytes_encrypted (newer servers), max_upload_bytes (every server) and allowed_mime — which is the server's answer to "what will you accept?", published so a client can screen a file before spending a user's bandwidth on it. The document is a bare JSON object with no {"data": …} envelope, matching its root-level neighbours.
Every consumer must fail OPEN: an unreachable or older server means "do not pre-validate, send it and let the server decide", never a hardcoded fallback number that would refuse good files the day an operator raises the cap.
func (*Client) CommitFile ¶ added in v0.1.53
func (c *Client) CommitFile(hash string, size int64, mimeType, filename string, isEncrypted bool) ([]byte, error)
CommitFile registers bytes already in storage as a resource and returns the bare resource object. It is safe to repeat: a second commit of the same hash returns the existing row.
func (*Client) CompleteImportUpload ¶ added in v0.1.33
func (c *Client) CompleteImportUpload(kind, jobID string, parts []ImportUploadPart) ([]byte, error)
CompleteImportUpload assembles the staged object from its uploaded parts and enqueues the import, returning 202 with the job to poll. The server verifies the assembled size against the size declared at create and refuses a short object, so a missing part fails here rather than importing a truncated file.
func (*Client) CompleteReminder ¶
CompleteReminder marks a note's reminder done (sets reminder_done_time, defaulting to the server's current time), returning {note, usn}. When body is non-nil it may carry a done_time (epoch-ms) override.
func (*Client) CompleteTask ¶ added in v0.1.12
CompleteTask marks a task done, returning {task, usn}. When body is non-nil it may carry a done_time (epoch-ms) override; otherwise the server stamps the current time. Completing a RECURRING task advances it to its next occurrence instead of closing it, so the returned task has done_at unset and a rolled-forward due_at.
func (*Client) ConfirmEmailChange ¶
ConfirmEmailChange consumes a staged email-change token (public — no bearer).
func (*Client) ConvertNoteToEncrypted ¶ added in v0.1.23
ConvertNoteToEncrypted turns an existing plaintext note into an encrypted one: the same PATCH as UpdateNote, carrying `is_encrypted: true` plus the HRBC2 envelopes for title and content. It is a method of its own rather than a call to UpdateNote because the two say different things about the note — an update changes what a note holds, this changes how it is STORED — and a reader auditing where the CLI flips a note's encryption should find one name, not a map[string]any three call frames away.
IT DESTROYS DATA. The server hard-deletes every note_history snapshot that disagrees with the note's new is_encrypted state, so this call discards the note's entire version history — not a tombstone, and note_history does not sync, so nothing is recoverable from another device. Callers must confirm first, and both of them do: notesEncryptConfirmation in cmd/notes_convert.go for `notes encrypt`, and sealedMoveConfirmation in cmd/notes_move.go for a move into a notebook that encrypts by default.
func (*Client) ConvertNoteToPlaintext ¶ added in v0.1.23
ConvertNoteToPlaintext writes a decrypted note back to the server in the clear: `is_encrypted: false` with the opened title and content.
It is separate from UpdateNote for a stronger reason than its sibling above. This is the one note write that CANNOT be taken back — not because the note is destroyed (re-encrypting it is one command away), but because the plaintext reaches the server, where it is indexed for search and snapshotted into the note's version history. Re-encrypting the note afterwards does not unsend it. So it is named on its own, and cmd/confirm_test.go's irreversibleClientCalls registry lists it: any command whose RunE issues this call must consult a confirmation first, and the test fails if one ever does not.
func (*Client) CreateImportUpload ¶ added in v0.1.33
func (c *Client) CreateImportUpload(kind string, totalBytes int64, filename, targetNotebookID string, notifyEmail bool) ([]byte, error)
CreateImportUpload opens a direct-to-storage upload and returns the server's chunking plan (data-wrapped: import_job_id, status, part_size, part_count). It declares only the file's SIZE — the bytes go straight to object storage from here on, never through the API — so this is where the size cap, the target notebook and the encrypted-notebook refusal are all decided, before anything is transferred. filename and targetNotebookID are optional; empty values are omitted so the server's own defaults apply.
notifyEmail is always sent, never omitted. The server reads an ABSENT notify_email as true — a sensible default for a browser upload the user walks away from, and the wrong one for a command that prints the outcome itself, so the CLI states its choice rather than inheriting one.
func (*Client) CreateNote ¶
CreateNote creates a note and returns the {note, usn} mutation envelope.
func (*Client) CreateNotebook ¶
CreateNotebook creates a notebook from the given fields and returns the bare created object.
func (*Client) CreatePAT ¶
func (c *Client) CreatePAT(name string, scopes []string, expiresIn int64) ([]byte, *PersonalAccessToken, error)
CreatePAT mints a Personal Access Token for the signed-in user. It requires a bearer whose grant includes the profile scope. expiresIn is the lifetime in seconds; pass 0 to omit it and mint a token that NEVER expires — this is how the CLI obtains a long-lived credential after the browser login. The returned raw token is shown only once, so callers must persist it immediately.
func (*Client) CreateShortcut ¶
CreateShortcut creates a shortcut from the given fields and returns the bare created object (201).
func (*Client) CreateTask ¶ added in v0.1.12
CreateTask creates a task, returning the {task, usn} envelope with 201.
The body deliberately never carries note_id: linking a task to a note also has to write the note's <harbor-task> block, and a link without the block is deleted by the note's next save. See cmd/tasks.go for the full story and HarborMyNotes/app.harbor.my#1094 for the endpoint that does it safely.
func (*Client) CreateTemplate ¶
CreateTemplate creates a user template from the given fields and returns the bare created object (not wrapped in data).
func (*Client) DeleteAccountExport ¶ added in v0.1.14
DeleteAccountExport deletes an export's archive from the blob store and frees that format's slot so a new export can start immediately. It is idempotent: deleting an export whose archive is already gone returns 200 carrying the status it already has, so an expired export is reported back as expired rather than rewritten to deleted. An export that is still being built is refused with 409 export_in_progress — the queue has no per-job cancellation.
func (*Client) DeleteNote ¶
DeleteNote trashes a note (recoverable) by default, or expunges it directly when permanent is true.
func (*Client) DeleteNotebook ¶
DeleteNotebook tombstones a notebook. notesPolicy controls its live notes: "move_to_default" (default) reassigns them, "trash" tombstones them.
func (*Client) DeleteShortcut ¶
DeleteShortcut tombstones a shortcut (204) so the removal propagates via sync.
func (*Client) DeleteTag ¶
DeleteTag tombstones a tag. childrenPolicy is "reparent_to_grandparent" (default) or "orphan".
func (*Client) DeleteTask ¶ added in v0.1.12
DeleteTask soft-deletes (tombstones) a task so the deletion syncs to every device, returning 204 with an empty body. Deleting a note-linked task also strips its block from the owning note.
func (*Client) DeleteTemplate ¶
DeleteTemplate tombstones a user template. System templates are rejected by the server with 403 system_template_readonly.
func (*Client) DetachTag ¶
DetachTag detaches a tag from a note (idempotent; 204 even if not linked).
func (*Client) EmptyTrash ¶
EmptyTrash expunges every note currently in the trash. The server answers in one of two bare shapes:
- 200 {"expunged": N} for a small trash: the notes are already gone.
- 202 {"expunged": N, "job": {...}} for a big one: a background job deletes them, and N is how many it WILL delete. Poll the job with GetTrashEmptyJob until its status is completed or failed. If an Empty Trash is already running, the answer is that job; no second one starts.
func (*Client) ExportENEX ¶
func (c *Client) ExportENEX(notebookID string, noteIDs []string, includeResources bool) (*http.Response, error)
ExportENEX exports a notebook or an explicit note selection to a raw ENEX document. The response body is the .enex file bytes (not a JSON envelope), so it returns the live *http.Response for streaming — the caller MUST close the body, and reads the X-Skipped-Encrypted header off the response before draining it. Targeting is XOR: pass a non-empty notebookID OR a non-empty noteIDs slice (the server rejects both or neither with validation_failed). includeResources inlines each linked attachment as a base64 <resource> block.
func (*Client) ExportNoteHTML ¶ added in v0.1.44
ExportNoteHTML streams one note as a single self-contained HTML page: the stylesheet and every attachment are inlined, so it opens with no network. It returns the live *http.Response (the caller MUST close the body and take the file name from Content-Disposition). An encrypted note is refused with encrypted_not_exportable, and a page over the size cap with export_too_large.
func (*Client) ExportNoteMarkdown ¶ added in v0.1.36
ExportNoteMarkdown streams one note as a Markdown export.
TWO CONTENT TYPES COME BACK FROM THE ONE ENDPOINT, by design: text/markdown for a note with no attachments, application/zip for one that has them (the .md plus a files/ directory). zip forces the archive form for a caller that would rather handle one shape than two. So it returns the live *http.Response — the caller MUST close the body, and must take the filename from Content-Disposition rather than inferring an extension from the request.
The Markdown itself is rendered on the SERVER. There is deliberately no client-side HTML-to-Markdown converter anywhere in Harbor: a second renderer is a second set of answers about the same note, and the clients would drift apart within a year. The cost is that this needs a network connection even where a note is already held locally.
An encrypted note is refused with encrypted_not_exportable. The server holds only ciphertext for it and cannot render what it cannot read.
func (*Client) ExportNotePDF ¶ added in v0.1.44
ExportNotePDF streams one note rendered to a PDF on the server, with any embedded PDF attachments combined into it. It returns the live *http.Response — the caller MUST close the body — because two things ride in headers the caller needs: the file name (Content-Disposition) and how many attachments could not be combined (X-Skipped-Attachments). An encrypted note is refused with encrypted_not_exportable.
paperSize ("letter", "a4", …) picks the page size for this PDF only. An empty one is left off, so the server uses the account's paper size setting.
func (*Client) ExportPDF ¶ added in v0.1.57
ExportPDF builds one PDF of several notes, printed in the order of noteIDs. The body is the PDF itself, so it returns the live *http.Response and the caller MUST close the body. The file name (Content-Disposition) and the counts of encrypted notes and attached PDFs that were left out (X-Skipped-Encrypted, X-Skipped-Attachments) ride in headers, which the caller reads first. pageBreak is "new_page" or "continuous"; an empty one is omitted so the server's default applies. paperSize ("letter", "a4", …) is the page size for this PDF only; an empty one is omitted so the account's setting applies.
func (*Client) ExpungeNote ¶
ExpungeNote permanently deletes a note: it promotes the note to the canonical sync tombstone (deleted=1) so the deletion propagates to every device. It works whether or not the note is currently in the trash and returns no body (204 No Content).
func (*Client) FetchURL ¶
FetchURL performs an unauthenticated GET against a presigned URL (its credentials live in the query string), returning the live response for streaming. The caller must close the body. A non-2xx reply comes back as a *DownloadError carrying the status.
It goes through the storage client, which has no overall timeout, because a large file can take longer to arrive than any fixed limit. A download that stops receiving bytes is given up after the stall timeout instead.
func (*Client) ForgotPassword ¶
ForgotPassword starts a password reset. Always reports success (anti- enumeration). Public.
func (*Client) GetAccountClear ¶ added in v0.1.37
GetAccountClear returns the account's current (or last) clear job, in the same shape RequestAccountClear returns.
An account that has never been cleared answers 404 not_found. That is an ANSWER, not a failure — the caller decides what it means, because the same code means "no such export job" elsewhere in this domain.
func (*Client) GetAccountExport ¶
GetAccountExport polls an export job by id. When the job is completed and the result blob has not expired, the data-wrapped job includes a short-lived presigned download_url, the filename the archive should be saved as, and a result_expires_at. Progress is reported in NOTES via total_units/done_units, a queued job carries its 1-based queue_position, a completed one its completed_at and skipped_encrypted, and a failed one its error_text. A pdf export also carries its page_break and paper_size ("" means the account's setting).
func (*Client) GetFileDownload ¶
GetFileDownload returns the presigned download URL and basic metadata for a blob (no bytes).
func (*Client) GetMetadata ¶ added in v0.1.42
GetMetadata reads a record's metadata. Answers {"metadata": {…}}.
func (*Client) GetNote ¶
GetNote fetches one note. params may include deleted=true and format=markdown.
func (*Client) GetNoteHistoryVersion ¶
GetNoteHistoryVersion fetches one version's full snapshot — including title, content, and attributes_json — returned bare (not wrapped in data). The version must belong to noteID or the server returns 404.
func (*Client) GetNotebook ¶
GetNotebook fetches a single notebook by id. With includeDeleted, tombstoned notebooks are returned instead of 404.
func (*Client) GetProfile ¶
GetProfile fetches the authenticated user's profile (data-wrapped). The profile id doubles as the sync scope_id.
func (*Client) GetSettings ¶
GetSettings fetches the authenticated user's effective account preferences (theme, default notebook, sort, locale, timezone, and the nested notification_prefs / editor_prefs objects), data-wrapped. The stored document is overlaid on code-owned defaults, so the response is always complete even before the first write. Settings are NOT part of the sync stream.
func (*Client) GetShortcut ¶
GetShortcut fetches a single shortcut by id. With includeDeleted, a tombstoned shortcut is returned instead of a 404.
func (*Client) GetSubscription ¶ added in v0.1.16
GetSubscription fetches the caller's current entitlement snapshot (data-wrapped): the effective plan, where it comes from (free/stripe/apple/ google/comp), its status and period end, and — importantly for a client that cannot take payment — managed_by/manage_url, which say who owns billing and where to send the user to change it.
func (*Client) GetTask ¶ added in v0.1.12
GetTask fetches a single task by id, returning the {task, usn} envelope.
func (*Client) GetTemplate ¶
GetTemplate fetches a single template by id, including its content. With includeDeleted, tombstoned templates are returned instead of 404.
func (*Client) GetTrashEmptyJob ¶ added in v0.1.47
GetTrashEmptyJob returns one background Empty Trash job, data-wrapped: {"data": {id, status, total_notes, processed_notes, error, ...}}. status is queued, running, completed or failed; error is the sentence to show when it failed.
func (*Client) GetUsage ¶ added in v0.1.16
GetUsage fetches the caller's usage snapshot (data-wrapped): the effective plan, the whole-account read-only flag, and a { used, limit } pair for every plan-capped resource (notes, notebooks, tags, files, tasks). A limit of null means unlimited. Counts include live + trashed rows and exclude expunged ones, and they come from the same counting engine as the create-time plan_limit_reached guard, so the meter and the guard can never disagree.
func (*Client) Health ¶
Health probes the root /health liveness endpoint and returns the raw body.
Liveness touches no dependency, so it returns 200 as long as the process can serve HTTP. Because the probe lives at the server root (no /api/v1 prefix), it is built from c.Origin() and dispatched through the low-level request method rather than doGet (which would prepend the versioned base URL). It is public, so allowRefresh is false — there is no token to refresh.
func (*Client) ImportStatus ¶
ImportStatus polls an import job by id and returns the data-wrapped status document (live counters plus the per-note error list). A 404 surfaces as an APIError with code not_found when the job is unknown or not the caller's. The route names a kind, but the server looks a job up by id alone, so any kind's path answers for any of the caller's jobs.
func (*Client) ListAccountExports ¶ added in v0.1.14
ListAccountExports returns what this account's export slots hold right now: the most recent export per format (at most four entries — one ENEX, one HTML, one Markdown, one PDF), each in exactly the shape GetAccountExport returns, including a freshly minted download_url for a ready one. A format with no export history is simply absent from the array, and an account that has never exported returns an empty one.
This is how a client that did not start the export — a fresh shell, another machine — discovers it at all: export state lives on the server, so it has to be read from there rather than remembered locally.
func (*Client) ListDevices ¶
ListDevices lists the user's devices plus scope_max_usn and the GC floor. Note: this is a bare object with a top-level data array, not the standard {data, paging} collection envelope.
func (*Client) ListFiles ¶
ListFiles returns the user's files, each with its linked notes (collection envelope). Accepts mime, note_id, ocr_status, is_encrypted, updated_since, and the standard list params.
func (*Client) ListNoteAudit ¶
ListNoteAudit returns a note's append-only audit log as a collection envelope, newest-first by default. The trail outlives the note (it records the deletion itself), so a trashed/expunged note still returns its events. Accepts the standard list params (limit, offset, order) plus an optional action filter.
func (*Client) ListNoteBacklinks ¶
ListNoteBacklinks returns the live notes that link TO a note — its incoming edges — as a collection envelope. Trashed and expunged source notes are excluded by the server. Each row carries the source id and a trimmed source summary. Accepts the standard list params (limit, offset).
func (*Client) ListNoteHistory ¶
ListNoteHistory returns a note's version history as a metadata-only collection envelope (no content/attributes bodies). Accepts the standard list params: limit, offset, and order (-created_at default; created_at and usn_at_snapshot are sortable).
func (*Client) ListNoteLinks ¶
ListNoteLinks returns a note's outgoing links — the harbor:note edges its body contains — as a collection envelope. Each row carries the target id, a broken flag, and (when the target resolves) a trimmed target summary. Accepts the standard list params (limit, offset). Links are derived and read-only; there is no write endpoint.
func (*Client) ListNoteTags ¶
ListNoteTags lists the live tags attached to a note (collection of tag objects).
func (*Client) ListNoteTasks ¶ added in v0.1.12
ListNoteTasks returns the tasks owned by one note (its <harbor-task> blocks) as a collection envelope, ordered by in-note position. This is a READ of the note's task list — it cannot change which note a task belongs to. Accepts limit, offset, and order params.
func (*Client) ListNotebooks ¶
ListNotebooks returns the user's notebooks (collection envelope). Accepts the standard list params (limit, offset, order, stack, include_deleted).
func (*Client) ListNotebooksQuery ¶ added in v0.1.42
ListNotebooksQuery is ListNotebooks with a caller-built query, for the metadata filters: meta_has repeats and meta.KEY may carry an empty value, and the map form can express neither.
func (*Client) ListNotes ¶
ListNotes returns the user's notes (collection envelope). Accepts limit, offset, order, notebook_id, tag, updated_since, deleted, and fields params.
func (*Client) ListNotesQuery ¶ added in v0.1.42
ListNotesQuery is ListNotes with a caller-built query, for the metadata filters: meta_has repeats and meta.KEY may carry an empty value, and the map form can express neither.
func (*Client) ListPlans ¶ added in v0.1.16
ListPlans fetches the plans offerable to the caller (a standard collection envelope): the catalog behind a pricing grid, active + public only, ordered free first then cheapest monthly. Each plan carries its per-resource limits, where a null cap means unlimited.
func (*Client) ListReminders ¶
ListReminders returns the user's reminders — live, non-trashed notes whose reminder_time is set — as a collection envelope. Accepts limit, offset, order, status, and due_before params (empty values are dropped by doGet).
func (*Client) ListSessions ¶
ListSessions lists the user's active sessions (one per refresh-token family), marking the current one. Standard collection envelope.
func (*Client) ListShortcuts ¶
ListShortcuts returns the user's sidebar shortcuts (collection envelope), ordered by position ascending. Accepts the standard list params (limit, offset, order, include_deleted).
func (*Client) ListStacks ¶ added in v0.1.42
ListStacks returns the user's stacks (collection envelope): each one's name, live notebook count and metadata. The query is built by the caller because the metadata filters repeat a parameter (meta_has) and can carry an empty value (meta.KEY= means "equals the empty string"), which the map form would drop.
func (*Client) ListTagNotes ¶
ListTagNotes lists the live notes carrying a tag (collection of note objects).
func (*Client) ListTags ¶
ListTags returns the user's tags (collection envelope). The query is built by the caller so it can express the three parent_id modes: absent (all tags), empty (top-level only), or a specific parent (its direct children).
func (*Client) ListTasks ¶ added in v0.1.12
ListTasks returns the user's tasks as a collection envelope. Accepts limit, offset, order, status (active|today|done|all), and due_before (epoch-ms) params; empty values are dropped by doGet so server defaults apply.
func (*Client) ListTemplates ¶
ListTemplates returns the user's note templates (collection envelope). Accepts the standard list params (limit, offset, order) plus include_deleted and include_system.
func (*Client) ListTrash ¶
ListTrash returns the notes currently in the trash (collection envelope), most-recently-trashed first. Accepts the standard list params (limit, offset, order). Sortable orders: trashed_at, updated_at, created_at, title (prefix - for descending; the default is -trashed_at).
func (*Client) Logout ¶
Logout revokes the current session server-side (or every session when allDevices is true). Requires a bearer token.
func (*Client) MergeMetadata ¶ added in v0.1.42
MergeMetadata applies a JSON Merge Patch (RFC 7396) to the record's metadata: a key set to nil is removed, nested objects merge, anything else is set. Answers {"metadata": {…}} with the merged result.
func (*Client) OpenAPI ¶
OpenAPI fetches the generated OpenAPI 3.0 document. Unlike the health probes this endpoint IS under the versioned API surface (/api/v1/openapi.json), so it goes through doGet, which prepends the /api/v1 base URL. It is public.
func (*Client) Origin ¶
Origin returns the scheme+host root of the API by stripping the trailing /api/v1 suffix from the base URL. The root-level operational probes (/health, /ready, /version) live there rather than under /api/v1.
func (*Client) PresignImportParts ¶ added in v0.1.33
PresignImportParts asks for a batch of presigned part URLs (data-wrapped: parts[{part_number,url}], expires_in_seconds). Part numbers are 1-based and must fall inside the plan's part_count; the server caps a single batch at 1000, which is why a large upload requests them incrementally.
func (*Client) PresignUpload ¶ added in v0.1.53
func (c *Client) PresignUpload(hash string, size int64, mimeType string, isEncrypted bool) (*PresignedUpload, error)
PresignUpload asks for a presigned link to PUT one new blob straight to storage. size must be positive: the server cannot sign a link for zero bytes.
func (*Client) PublicNote ¶
PublicNote resolves and renders a shared note by its public token. This is a PUBLIC endpoint: it requires no bearer token or scope, so the calling client should be built with no credentials (newAnonymousClient). The response is the data-wrapped public render (title, content_html, attachments, view_count). Every failure mode collapses server-side to a single generic 404 not_found (anti-enumeration).
func (*Client) PublishShare ¶
PublishShare publishes a note as a public, read-only page and returns the data-wrapped share object plus a fresh flag: true when a new share was minted (201 Created), false when the note was already public and the existing live share was returned unchanged (200 OK, idempotent). The body is optional and may carry a custom slug; pass nil to publish with a generated slug. Requires the notes scope.
func (*Client) RawDownload ¶
RawDownload streams the blob bytes straight through the API (the caller must close the response body). Used when a presigned URL cannot be followed.
func (*Client) Ready ¶
Ready probes the root /ready readiness endpoint and returns the raw body.
Readiness checks every backing dependency (system DB, blob store) and returns 200 only when all pass, otherwise 503 with the same JSON shape. A 503 surfaces here as an *APIError, so callers that want the body on a not-ready response should inspect that error. Like /health it lives at the root and is public.
func (*Client) RefreshGrant ¶
func (c *Client) RefreshGrant(clientID, refreshToken, scope string) ([]byte, *TokenResponse, error)
RefreshGrant rotates a single-use refresh token into a new access + refresh pair. scope, when set, may only narrow the existing grant. Presenting an already-rotated token returns invalid_grant and revokes the whole family.
func (*Client) RegisterDevice ¶
RegisterDevice upserts a device by its client UUID and returns the bare device object.
func (*Client) RemoveAvatar ¶
RemoveAvatar clears the avatar reference.
func (*Client) RemoveDevice ¶
RemoveDevice deregisters a device so it stops pinning the tombstone GC floor.
func (*Client) RenameFile ¶ added in v0.1.45
RenameFile gives a file a new name and returns the bare resource object. filename is the full name, extension included: the server refuses one that does not end with the file's current extension.
func (*Client) ReorderShortcuts ¶
ReorderShortcuts bulk-reorders the user's shortcuts. The order slice must reference every live shortcut id exactly once; the server renumbers to clean integer gaps and returns the reordered collection.
func (*Client) ReplaceMetadata ¶ added in v0.1.42
ReplaceMetadata stores obj as the record's whole metadata object (PUT). Answers {"metadata": {…}} as stored.
func (*Client) RequestAccountClear ¶ added in v0.1.37
RequestAccountClear empties the account without deleting it: every note, notebook, tag, task, file and the encryption keystore go, and the account, its plan, its sessions and its tokens stay. Returns the data-wrapped job ({clear_job_id, status, started_at, finished_at}) with status 202 Accepted.
IT IS NOT DELETE. There is no grace period and nothing to cancel — the work starts immediately, which is why the server demands both a re-auth proof and a confirmation phrase of its own. The phrase is compared byte for byte, so send exactly what the user typed rather than a trimmed or upper-cased copy; normalising it here would turn a phrase the server rejects into one it accepts.
The 202 is the job being QUEUED, not the account being empty. A large account spends minutes deleting attachment blobs, so a caller that reports success off this response tells the user their notes are gone while the server still has them. Poll GetAccountClear.
func (*Client) RequestAccountDeletion ¶
RequestAccountDeletion schedules a grace-period account deletion. It requires re-auth via current_password AND the exact confirmation phrase (sent verbatim as confirm). No data is destroyed now: the response carries the scheduled status, purge_after, grace_days, and can_cancel_until window.
func (*Client) ResendVerification ¶
ResendVerification requests a fresh verification email. When a bearer is present the server uses it; otherwise the email body is required (and the response is always "sent", to avoid account enumeration).
func (*Client) ResetInboundEmail ¶
ResetInboundEmail rotates the account's email-to-note address, regenerating the random token half while preserving the human-readable slug. The old address stops resolving immediately, so this is the revocation path for an address that leaked. Takes no body and does not change the on/off switch. Returns { "data": { "inbound_email_address": "…" } }.
func (*Client) ResetPassword ¶
ResetPassword completes a password reset with a reset token and new password. Revokes all sessions on success. Public.
func (*Client) RestoreNote ¶
RestoreNote returns a note from the trash to the live set, clearing in_trash and bumping its USN. It returns the restored note object (bare, not wrapped in a data envelope).
func (*Client) RevertNoteHistoryVersion ¶
RevertNoteHistoryVersion restores a past version as a new current version and returns the {note, usn} mutation envelope (the same shape as the note write endpoints). The note must be live and not in the trash; the request has no body.
func (*Client) Revoke ¶
Revoke revokes a token (RFC 7009 style). A refresh token revokes its whole family; an access token revokes just itself. Always succeeds server-side, even for an unknown token (no validity leak).
func (*Client) RevokeSession ¶
RevokeSession revokes a single session (family) by its id.
func (*Client) RevokeSessions ¶
RevokeSessions revokes multiple sessions: every session (except == "") or all but the current one (except == "current").
func (*Client) Search ¶
Search runs a search query and returns mixed note/attachment hits (collection envelope). params carries q, types, notebook_id, order, snippet, and the standard list params.
func (*Client) SearchCoordinates ¶
SearchCoordinates returns OCR word boxes for matched terms on one attachment (single data resource). params carries resource_id, q or terms, page, and max_boxes.
func (*Client) SetAvatar ¶
SetAvatar points the avatar at an already-uploaded image blob, by its content sha256 hash. Returns the updated profile.
func (*Client) SetInboundEmailEnabled ¶
SetInboundEmailEnabled turns the account's email-to-note address on or off. It is a plain preference — no re-auth — and never touches the stored address, so disabling and re-enabling yields the SAME address. Returns the updated profile.
func (*Client) SetNotePinned ¶ added in v0.1.63
SetNotePinned pins a note to the top of its lists (pinned true) or unpins it, and returns {note, usn}. The PATCH carries only "pinned", so the server treats it as a setting: updated_at stays put and no history version is made.
func (*Client) SetNoteTags ¶
SetNoteTags replaces a note's complete tag set with the given tag ids ([] clears all). Returns the resulting live junctions as a collection.
func (*Client) SetReminder ¶
SetReminder sets or updates a note's reminder_time, returning the {note, usn} mutation envelope. The server treats PUT and POST equivalently for this route; we use PUT. The reminderTimeMS value is UTC epoch milliseconds.
func (*Client) StartAccountExport ¶
func (c *Client) StartAccountExport(format, notebookID, pageBreak, paperSize string) ([]byte, error)
StartAccountExport starts an export job. Every argument is optional: all empty starts a whole-account ENEX export. format selects the kind — "enex" (the GDPR ZIP: one ENEX per notebook, the attachment bytes, a manifest), "html" (a self-contained, browsable offline website), "markdown" (one .md per note in folders matching the notebooks, attachments alongside) or "pdf" (one PDF of a single notebook, oldest note first) — and notebookID scopes the export to a single notebook. "pdf" needs a notebookID; the server refuses it without one. pageBreak ("new_page" or "continuous") and paperSize ("letter", "a4", …) apply to "pdf" only. Empty values are omitted so the server's defaults apply; for paperSize that is the account's paper size setting, read when the job runs. Returns the data-wrapped job ({export_job_id, status, format, notebook_id, notebook_name}); the response status is 202 Accepted.
An account holds at most one live export PER FORMAT, and scope does not create a slot of its own. A queued/running export of the same format is handed back rather than started twice; a completed, unexpired one is refused with 409 export_exists whose details carry export_job_id, format, scope, notebook_id, notebook_name and result_expires_at — everything needed to explain the refusal without a second request.
func (*Client) SubmitSupportRequest ¶
SubmitSupportRequest files an in-app Contact Support request against the authenticated endpoint. The body carries category/subject/message plus an optional metadata object and attachments array (see cmd/support.go for the shape). The caller's name, email, and account are derived server-side from the bearer session and must NOT be sent. On success the server returns { "data": { "received": true, "reference": "..." } }.
func (*Client) SyncAck ¶
SyncAck advances a device's last_acked_usn after a fully-applied pull chain.
func (*Client) SyncPull ¶
SyncPull returns server changes since a cursor. The body carries scope_id, after_usn, limit, and optionally device_id (advances that device's cursor).
func (*Client) SyncPush ¶
SyncPush uploads a batch of local change envelopes and returns per-change results. The body carries scope_id, device_id, and changes[].
func (*Client) UncompleteTask ¶ added in v0.1.12
UncompleteTask reopens a completed task (nulls done_at), returning {task, usn}. It is idempotent and does not rewind recurrence.
func (*Client) UnpublishShare ¶
UnpublishShare revokes a note's public link. It is idempotent: a note that is already private, was never shared, or does not even exist still returns 204 No Content. Requires the notes scope.
func (*Client) UpdateNote ¶
UpdateNote applies a partial update and returns {note, usn}.
func (*Client) UpdateNotebook ¶
UpdateNotebook applies a partial update (only the fields present in body) and returns the bare updated object.
func (*Client) UpdateProfile ¶
UpdateProfile applies a profile update (name/locale/timezone immediately; an email change is staged and requires current_password). Only the fields in body are touched. Returns the updated profile.
func (*Client) UpdateSettings ¶
UpdateSettings applies a partial (or full) preferences update. Provided top-level scalars overwrite; the two nested objects (notification_prefs, editor_prefs) deep-merge field by field on the server, so a client can set just one nested sub-field without clearing the rest. default_notebook_id is nullable: omit to leave unchanged, send a string to adopt, or an explicit nil to clear. Returns the full merged preferences object (data-wrapped).
func (*Client) UpdateShortcut ¶
UpdateShortcut applies a partial update (only the fields present in body) and returns the bare updated object.
func (*Client) UpdateStack ¶ added in v0.1.59
UpdateStack changes a stack addressed by its current name and answers the stack's list object. The name is free text, so it is escaped — a space or `?` in a name would otherwise change what the URL means.
func (*Client) UpdateTag ¶
UpdateTag renames, re-parents and/or recolors a tag and returns the bare updated object.
func (*Client) UpdateTask ¶ added in v0.1.12
UpdateTask applies a partial update to a task, returning {task, usn}. Only the fields present in body are changed; the clear_due_at / clear_reminder_at / clear_recurrence booleans null a nullable column.
func (*Client) UpdateTemplate ¶
UpdateTemplate applies a partial update (only the fields present in body) and returns the bare updated object. System templates are rejected by the server with 403 system_template_readonly.
func (*Client) UploadBytes ¶ added in v0.1.28
func (c *Client) UploadBytes(ctx context.Context, content []byte, mimeType, filename string, isEncrypted bool) ([]byte, error)
UploadBytes uploads content already held in memory, with the same presigned flow as UploadFile. It exists for client-side encryption: the bytes on the wire are the HRBC2 envelope, not what is on disk, and the caller has already resolved the MIME type and filename from the original.
Those two stay PLAINTEXT on the resource record, matching every other Harbor client. The hash covers the ciphertext.
func (*Client) UploadFile ¶
func (c *Client) UploadFile(ctx context.Context, path, mimeType, filename string, streamLimit int64) ([]byte, error)
UploadFile uploads the file at path and returns the bare resource object.
The bytes go straight to storage with a presigned link, read from the open file piece by piece, so the file's size sets neither the memory used nor a time limit. The file is read twice: once to hash it, once to send it.
mimeType and filename are optional. When mimeType is empty the type is detected from the file. This matters: the server picks thumbnails and OCR by the recorded type, so a PDF declared as application/octet-stream gets neither.
streamLimit caps how much of a pipe is copied (0 means no cap); a pipe that goes past it returns a *StreamTooLargeError. A regular file's size is the caller's to check, before calling.
func (*Client) UploadImportPart ¶ added in v0.1.33
func (c *Client) UploadImportPart(ctx context.Context, url string, chunk io.ReaderAt, size int64) (string, error)
UploadImportPart PUTs one chunk straight to object storage and returns the ETag the store answered with.
The presigned URL carries its own credentials in the query string, so this request must NOT be signed again — sending an Authorization header alongside a presigned URL is rejected by S3-compatible stores as two auth mechanisms. Each attempt reads chunk through its own section reader, so a retry sends the same bytes even while the transport is still reading the failed attempt's body. Content-Length is set explicitly: the store requires a length up front, and net/http cannot infer one from a section reader.
func (*Client) VerifyEmail ¶
VerifyEmail consumes an email-verification token. Public.
type DownloadError ¶ added in v0.1.14
type DownloadError struct {
Status int
}
DownloadError is a non-2xx response from a presigned storage URL. Those URLs answer in raw S3 XML rather than the Harbor error envelope, so there is no *APIError to branch on — the HTTP status is all the caller gets, and it is worth keeping: a 403/404 means "the object is gone", which for an account export is a cue to re-read the status endpoint rather than to report a broken download (the archive may have been deleted or expired from another device).
func (*DownloadError) Error ¶ added in v0.1.14
func (e *DownloadError) Error() string
Error renders the status-only message this used to return as a flat error, so existing callers that only print it read exactly as before.
func (*DownloadError) Gone ¶ added in v0.1.14
func (e *DownloadError) Gone() bool
Gone reports whether the failure means the object itself is missing (403 or 404) rather than the request being at fault.
type ImportUploadPart ¶ added in v0.1.33
ImportUploadPart pairs a 1-based part number with the ETag object storage returned when that chunk was PUT. The complete call reassembles the staged object from this list, so an ETag is passed back exactly as received — surrounding quotes included, because that is what the store signed.
type Paging ¶
type Paging struct {
Limit int64 `json:"limit"`
Offset int64 `json:"offset"`
Total int64 `json:"total"`
HasMore bool `json:"has_more"`
NextCursor string `json:"next_cursor,omitempty"`
}
Paging is the collection pagination block. Harbor uses offset mode ({limit, offset, total, has_more}) by default and cursor mode ({limit, next_cursor, has_more}) on opt-in endpoints.
func DecodePaging ¶
DecodePaging extracts the paging block from a collection response. The bool reports whether a paging block was present.
type PersonalAccessToken ¶
type PersonalAccessToken struct {
ID string `json:"id"`
Token string `json:"token"`
Name string `json:"name"`
Scopes []string `json:"scopes"`
TokenKind string `json:"token_kind"`
ExpiresAt *int64 `json:"expires_at"`
CreatedAt int64 `json:"created_at"`
}
PersonalAccessToken is the response from minting a PAT (POST /tokens). Token holds the raw hbp_… secret, which the server reveals exactly once at creation. ExpiresAt is nil for a never-expiring token.
type PresignedUpload ¶ added in v0.1.53
type PresignedUpload struct {
URL string `json:"upload_url"`
Method string `json:"method"`
Headers map[string]string `json:"headers"`
}
PresignedUpload is the server's permit for one PUT straight to storage. The link is signed for the exact size and Content-Type that were declared, so the headers must be sent exactly as given.
type StallError ¶ added in v0.1.48
type StallError struct {
After time.Duration
// Upload is true when the stalled request was sending a body, so the
// message does not talk about data arriving.
Upload bool
}
StallError is a streamed transfer that moved nothing for the stall timeout. It reports itself as a network timeout, so the CLI gives it the network exit code: the same command can work on a better connection.
func (*StallError) Error ¶ added in v0.1.48
func (e *StallError) Error() string
Error says how long the transfer waited.
func (*StallError) Temporary ¶ added in v0.1.48
func (e *StallError) Temporary() bool
Temporary reports true: a stall says nothing about the request itself.
func (*StallError) Timeout ¶ added in v0.1.48
func (e *StallError) Timeout() bool
Timeout reports true, which makes StallError a net.Error timeout.
type StreamTooLargeError ¶ added in v0.1.53
type StreamTooLargeError struct {
Limit int64
}
StreamTooLargeError is a pipe that went on past the size limit while it was being copied. Its size is not known, only that it is over Limit.
func (*StreamTooLargeError) Error ¶ added in v0.1.53
func (e *StreamTooLargeError) Error() string
Error says the input is over the limit.
type TokenResponse ¶
type TokenResponse struct {
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
TokenType string `json:"token_type"`
ExpiresIn int64 `json:"expires_in"`
Scope string `json:"scope"`
}
TokenResponse is the bare OAuth2 token object returned by POST /oauth/token (not wrapped in a data envelope, per the OAuth2 spec). expires_in is in seconds (the one exception to Harbor's epoch-ms convention).
func DecodeToken ¶
func DecodeToken(data []byte) (*TokenResponse, error)
DecodeToken parses the bare OAuth token object.
Source Files
¶
- account.go
- auth.go
- client.go
- envelope.go
- errors.go
- files.go
- history.go
- importexport.go
- insights.go
- metadata.go
- note_tags.go
- notebooks.go
- notes.go
- operational.go
- plan.go
- profile.go
- reminders.go
- search.go
- servername.go
- sessions.go
- settings.go
- share.go
- shortcuts.go
- stacks.go
- support.go
- sync.go
- tags.go
- tasks.go
- templates.go
- trash.go