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 ¶
- func CollectionItems(data []byte) []json.RawMessage
- func DetectMIME(path string) string
- func PrettyJSON(data []byte) (string, error)
- 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) ClearReminder(noteID string) ([]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) ExportNoteMarkdown(id string, zip bool) (*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) 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) 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) ListNotes(params map[string]string) ([]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) 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) OpenAPI() ([]byte, error)
- func (c *Client) Origin() string
- func (c *Client) PresignImportParts(kind, jobID string, partNumbers []int) ([]byte, 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) ReorderShortcuts(order []string) ([]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) SetNoteTags(noteID string, tagIDs []string) ([]byte, error)
- func (c *Client) SetReminder(noteID string, reminderTimeMS int64) ([]byte, error)
- func (c *Client) StartAccountExport(format, notebookID 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) 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(content []byte, mimeType, filename string, isEncrypted bool) ([]byte, error)
- func (c *Client) UploadFile(path, mimeType, filename string, isEncrypted bool) ([]byte, error)
- func (c *Client) UploadImportPart(ctx context.Context, url string, chunk io.ReadSeeker, 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 TokenResponse
Constants ¶
This section is empty.
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 PrettyJSON ¶
PrettyJSON pretty-prints raw JSON bytes with two-space indentation. Used for the --json output mode on every command.
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:"-"`
}
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.
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.
HTTPClient *http.Client
// StorageHTTPClient performs direct-to-storage transfers — today the
// presigned part PUTs of a large import. It is separate from HTTPClient
// because that one's 30-second timeout is sized for small JSON calls and a
// single 64 MiB chunk 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.
StorageHTTPClient *http.Client
// 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 the {note, usn} mutation envelope (the same shape as CreateNote). The body fields (notebook_id, title, tags) are all optional overrides.
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) ClearReminder ¶
ClearReminder removes a note's reminder entirely (nulls both reminder_time and reminder_done_time), returning {note, usn}. It is idempotent.
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) ([]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.
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. It returns the bare {"expunged": N} object reporting how many notes were permanently deleted.
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) 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) 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.
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 a failed one its error_text.
func (*Client) GetFileDownload ¶
GetFileDownload returns the presigned download URL and basic metadata for a blob (no bytes).
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) 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 three entries — one ENEX, one HTML, one Markdown), 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) ListNotes ¶
ListNotes returns the user's notes (collection envelope). Accepts limit, offset, order, notebook_id, tag, updated_since, deleted, and fields params.
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) 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) 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) 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) 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) 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 full-text 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) 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 ¶
StartAccountExport starts an export job. Both arguments are optional: an empty pair starts a whole-account ENEX export. format selects the archive kind — "enex" (the GDPR ZIP: one ENEX per notebook, the attachment bytes, a manifest), "html" (a self-contained, browsable offline website) or "markdown" (one .md per note in folders matching the notebooks, attachments alongside) — and notebookID scopes the export to a single notebook, for any format. 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) UpdateTag ¶
UpdateTag renames and/or re-parents 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(content []byte, mimeType, filename string, isEncrypted bool) ([]byte, error)
UploadBytes uploads content already held in memory. It exists for the client-side-encryption path: the bytes on the wire are the HRBC2 envelope, not what is on disk, so there is no file to stream 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 — an accepted metadata leak. The server hashes whatever it receives, so the resulting content address covers the ciphertext.
func (*Client) UploadFile ¶
UploadFile uploads a file via the direct multipart endpoint. The server computes the sha256 and returns the bare resource object. mimeType/filename are optional (filename defaults to the base name). The CLI intentionally does NOT use the internal presign-upload/commit endpoints.
When the caller does not pin a mimeType, we detect one from the file and send it as the `mime` form field. This matters: the server records that MIME, and without it the upload would be stored as application/octet-stream — which skips the thumbnail and OCR pipelines (those run only for image/* and PDFs). The `mime` field is also necessary because Go's multipart CreateFormFile always stamps the file part's Content-Type as application/octet-stream.
func (*Client) UploadImportPart ¶ added in v0.1.33
func (c *Client) UploadImportPart(ctx context.Context, url string, chunk io.ReadSeeker, 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. chunk is re-seeked before every attempt so a retry sends the same bytes, and 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 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.