client

package
v0.1.35 Latest Latest
Warning

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

Go to latest
Published: Aug 25, 2026 License: MIT Imports: 18 Imported by: ? modules, 0 packages

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

Documentation

Overview

Package 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

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

func DetectMIME(path string) string

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

func PrettyJSON(data []byte) (string, error)

PrettyJSON pretty-prints raw JSON bytes with two-space indentation. Used for the --json output mode on every command.

func UnwrapData

func UnwrapData(data []byte) []byte

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

func (e *APIError) DetailLines() []string

DetailLines returns the validation details as sorted "field: message" lines, for friendly multi-line rendering. Non-string detail values are stringified.

func (*APIError) Error

func (e *APIError) Error() string

Error renders a concise single-line description. Richer rendering (bulleted details, dim request id) lives in the cmd display layer.

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

	// OnUnauthorized, when set, is invoked once when a protected request fails
	// 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

func NewClient(baseURL, accessToken string) *Client

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

func (c *Client) AbortImportUpload(kind, jobID string) ([]byte, error)

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

func (c *Client) AppendNote(id string, body map[string]any) ([]byte, error)

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

func (c *Client) ApplyTemplate(id string, body map[string]any) ([]byte, error)

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

func (c *Client) AttachTag(noteID string, body map[string]any) ([]byte, bool, error)

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

func (c *Client) CancelAccountDeletion(currentPassword string) ([]byte, error)

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

func (c *Client) ChangePassword(currentPassword, newPassword string) ([]byte, error)

ChangePassword changes the account password (re-auth via current_password). The server revokes every other session on success.

func (*Client) CheckFile

func (c *Client) CheckFile(hash string, size int64) ([]byte, error)

CheckFile reports whether a blob already exists for the given sha256 hash. A zero size is omitted.

func (*Client) ClearReminder

func (c *Client) ClearReminder(noteID string) ([]byte, error)

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

func (c *Client) CompleteReminder(noteID string, body map[string]any) ([]byte, error)

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

func (c *Client) CompleteTask(id string, body map[string]any) ([]byte, error)

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

func (c *Client) ConfirmEmailChange(token string) ([]byte, error)

ConfirmEmailChange consumes a staged email-change token (public — no bearer).

func (*Client) ConvertNoteToEncrypted added in v0.1.23

func (c *Client) ConvertNoteToEncrypted(id string, body map[string]any) ([]byte, error)

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

func (c *Client) ConvertNoteToPlaintext(id string, body map[string]any) ([]byte, error)

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

func (c *Client) CreateNote(body map[string]any) ([]byte, error)

CreateNote creates a note and returns the {note, usn} mutation envelope.

func (*Client) CreateNotebook

func (c *Client) CreateNotebook(body map[string]any) ([]byte, error)

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

func (c *Client) CreateShortcut(body map[string]any) ([]byte, error)

CreateShortcut creates a shortcut from the given fields and returns the bare created object (201).

func (*Client) CreateTag

func (c *Client) CreateTag(body map[string]any) ([]byte, error)

CreateTag creates a tag and returns the bare created object.

func (*Client) CreateTask added in v0.1.12

func (c *Client) CreateTask(body map[string]any) ([]byte, error)

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

func (c *Client) CreateTemplate(body map[string]any) ([]byte, error)

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

func (c *Client) DeleteAccountExport(id string) ([]byte, error)

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

func (c *Client) DeleteNote(id string, permanent bool) ([]byte, error)

DeleteNote trashes a note (recoverable) by default, or expunges it directly when permanent is true.

func (*Client) DeleteNotebook

func (c *Client) DeleteNotebook(id, notesPolicy string) ([]byte, error)

DeleteNotebook tombstones a notebook. notesPolicy controls its live notes: "move_to_default" (default) reassigns them, "trash" tombstones them.

func (*Client) DeleteShortcut

func (c *Client) DeleteShortcut(id string) ([]byte, error)

DeleteShortcut tombstones a shortcut (204) so the removal propagates via sync.

func (*Client) DeleteTag

func (c *Client) DeleteTag(id, childrenPolicy string) ([]byte, error)

DeleteTag tombstones a tag. childrenPolicy is "reparent_to_grandparent" (default) or "orphan".

func (*Client) DeleteTask added in v0.1.12

func (c *Client) DeleteTask(id string) ([]byte, error)

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

func (c *Client) DeleteTemplate(id string) ([]byte, error)

DeleteTemplate tombstones a user template. System templates are rejected by the server with 403 system_template_readonly.

func (*Client) DetachTag

func (c *Client) DetachTag(noteID, tagID string) ([]byte, error)

DetachTag detaches a tag from a note (idempotent; 204 even if not linked).

func (*Client) EmptyTrash

func (c *Client) EmptyTrash() ([]byte, error)

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

func (c *Client) ExpungeNote(id string) ([]byte, error)

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

func (c *Client) FetchURL(rawURL string) (*http.Response, error)

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

func (c *Client) ForgotPassword(email string) ([]byte, error)

ForgotPassword starts a password reset. Always reports success (anti- enumeration). Public.

func (*Client) GetAccountExport

func (c *Client) GetAccountExport(id string) ([]byte, error)

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

func (c *Client) GetFileDownload(hash string) ([]byte, error)

GetFileDownload returns the presigned download URL and basic metadata for a blob (no bytes).

func (*Client) GetNote

func (c *Client) GetNote(id string, params map[string]string) ([]byte, error)

GetNote fetches one note. params may include deleted=true and format=markdown.

func (*Client) GetNoteHistoryVersion

func (c *Client) GetNoteHistoryVersion(noteID, versionID string) ([]byte, error)

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

func (c *Client) GetNotebook(id string, includeDeleted bool) ([]byte, error)

GetNotebook fetches a single notebook by id. With includeDeleted, tombstoned notebooks are returned instead of 404.

func (*Client) GetProfile

func (c *Client) GetProfile() ([]byte, error)

GetProfile fetches the authenticated user's profile (data-wrapped). The profile id doubles as the sync scope_id.

func (*Client) GetSettings

func (c *Client) GetSettings() ([]byte, error)

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

func (c *Client) GetShortcut(id string, includeDeleted bool) ([]byte, error)

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

func (c *Client) GetSubscription() ([]byte, error)

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

func (c *Client) GetTag(id string, includeDeleted bool) ([]byte, error)

GetTag fetches one tag by id, optionally including a tombstoned one.

func (*Client) GetTask added in v0.1.12

func (c *Client) GetTask(id string) ([]byte, error)

GetTask fetches a single task by id, returning the {task, usn} envelope.

func (*Client) GetTemplate

func (c *Client) GetTemplate(id string, includeDeleted bool) ([]byte, error)

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

func (c *Client) GetUsage() ([]byte, error)

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

func (c *Client) Health() ([]byte, error)

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

func (c *Client) ImportStatus(kind, jobID string) ([]byte, error)

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

func (c *Client) ListAccountExports() ([]byte, error)

ListAccountExports returns what this account's export slots hold right now: the most recent export per format (at most two entries — one ENEX, one HTML), 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

func (c *Client) ListDevices() ([]byte, error)

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

func (c *Client) ListFiles(params map[string]string) ([]byte, error)

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

func (c *Client) ListNoteAudit(noteID string, params map[string]string) ([]byte, error)

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 (c *Client) ListNoteBacklinks(noteID string, params map[string]string) ([]byte, error)

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

func (c *Client) ListNoteHistory(noteID string, params map[string]string) ([]byte, error)

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 (c *Client) ListNoteLinks(noteID string, params map[string]string) ([]byte, error)

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

func (c *Client) ListNoteTags(noteID string, params map[string]string) ([]byte, error)

ListNoteTags lists the live tags attached to a note (collection of tag objects).

func (*Client) ListNoteTasks added in v0.1.12

func (c *Client) ListNoteTasks(noteID string, params map[string]string) ([]byte, error)

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

func (c *Client) ListNotebooks(params map[string]string) ([]byte, error)

ListNotebooks returns the user's notebooks (collection envelope). Accepts the standard list params (limit, offset, order, stack, include_deleted).

func (*Client) ListNotes

func (c *Client) ListNotes(params map[string]string) ([]byte, error)

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

func (c *Client) ListPlans(params map[string]string) ([]byte, error)

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

func (c *Client) ListReminders(params map[string]string) ([]byte, error)

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

func (c *Client) ListSessions(params map[string]string) ([]byte, error)

ListSessions lists the user's active sessions (one per refresh-token family), marking the current one. Standard collection envelope.

func (*Client) ListShortcuts

func (c *Client) ListShortcuts(params map[string]string) ([]byte, error)

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

func (c *Client) ListTagNotes(tagID string, params map[string]string) ([]byte, error)

ListTagNotes lists the live notes carrying a tag (collection of note objects).

func (*Client) ListTags

func (c *Client) ListTags(q url.Values) ([]byte, error)

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

func (c *Client) ListTasks(params map[string]string) ([]byte, error)

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

func (c *Client) ListTemplates(params map[string]string) ([]byte, error)

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

func (c *Client) ListTrash(params map[string]string) ([]byte, error)

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

func (c *Client) Logout(allDevices bool) error

Logout revokes the current session server-side (or every session when allDevices is true). Requires a bearer token.

func (*Client) OpenAPI

func (c *Client) OpenAPI() ([]byte, error)

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

func (c *Client) Origin() string

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

func (c *Client) PresignImportParts(kind, jobID string, partNumbers []int) ([]byte, error)

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

func (c *Client) PublicNote(token string) ([]byte, error)

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

func (c *Client) PublishShare(noteID string, body map[string]any) ([]byte, bool, error)

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

func (c *Client) RawDownload(hash string) (*http.Response, error)

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

func (c *Client) Ready() ([]byte, error)

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

func (c *Client) RegisterDevice(body map[string]any) ([]byte, error)

RegisterDevice upserts a device by its client UUID and returns the bare device object.

func (*Client) RemoveAvatar

func (c *Client) RemoveAvatar() ([]byte, error)

RemoveAvatar clears the avatar reference.

func (*Client) RemoveDevice

func (c *Client) RemoveDevice(deviceID string) ([]byte, error)

RemoveDevice deregisters a device so it stops pinning the tombstone GC floor.

func (*Client) ReorderShortcuts

func (c *Client) ReorderShortcuts(order []string) ([]byte, error)

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

func (c *Client) RequestAccountDeletion(currentPassword, confirm string) ([]byte, error)

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

func (c *Client) ResendVerification(email string) ([]byte, error)

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

func (c *Client) ResetInboundEmail() ([]byte, error)

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

func (c *Client) ResetPassword(token, password string) ([]byte, error)

ResetPassword completes a password reset with a reset token and new password. Revokes all sessions on success. Public.

func (*Client) RestoreNote

func (c *Client) RestoreNote(id string) ([]byte, error)

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

func (c *Client) RevertNoteHistoryVersion(noteID, versionID string) ([]byte, error)

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

func (c *Client) Revoke(token, tokenTypeHint string) error

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

func (c *Client) RevokeSession(id string) ([]byte, error)

RevokeSession revokes a single session (family) by its id.

func (*Client) RevokeSessions

func (c *Client) RevokeSessions(except string) ([]byte, error)

RevokeSessions revokes multiple sessions: every session (except == "") or all but the current one (except == "current").

func (*Client) Search

func (c *Client) Search(params map[string]string) ([]byte, error)

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

func (c *Client) SearchCoordinates(params map[string]string) ([]byte, error)

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

func (c *Client) SetAvatar(hash string) ([]byte, error)

SetAvatar points the avatar at an already-uploaded image blob, by its content sha256 hash. Returns the updated profile.

func (*Client) SetInboundEmailEnabled

func (c *Client) SetInboundEmailEnabled(enabled bool) ([]byte, error)

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

func (c *Client) SetNoteTags(noteID string, tagIDs []string) ([]byte, error)

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

func (c *Client) SetReminder(noteID string, reminderTimeMS int64) ([]byte, error)

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 string) ([]byte, error)

StartAccountExport starts an export job. Both arguments are optional: an empty pair starts a whole-account ENEX export (the original behavior). format selects the archive kind — "enex" (the GDPR ZIP: one ENEX per notebook, the attachment bytes, a manifest) or "html" (a self-contained, browsable offline website) — and notebookID scopes the export to a single notebook, for either 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 third slot. 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

func (c *Client) SubmitSupportRequest(body map[string]any) ([]byte, error)

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

func (c *Client) SyncAck(deviceID string, ackedUSN int64) ([]byte, error)

SyncAck advances a device's last_acked_usn after a fully-applied pull chain.

func (*Client) SyncPull

func (c *Client) SyncPull(body map[string]any) ([]byte, error)

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

func (c *Client) SyncPush(body map[string]any) ([]byte, error)

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

func (c *Client) UncompleteTask(id string) ([]byte, error)

UncompleteTask reopens a completed task (nulls done_at), returning {task, usn}. It is idempotent and does not rewind recurrence.

func (*Client) UnpublishShare

func (c *Client) UnpublishShare(noteID string) ([]byte, error)

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

func (c *Client) UpdateNote(id string, body map[string]any) ([]byte, error)

UpdateNote applies a partial update and returns {note, usn}.

func (*Client) UpdateNotebook

func (c *Client) UpdateNotebook(id string, body map[string]any) ([]byte, error)

UpdateNotebook applies a partial update (only the fields present in body) and returns the bare updated object.

func (*Client) UpdateProfile

func (c *Client) UpdateProfile(body map[string]any) ([]byte, error)

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

func (c *Client) UpdateSettings(body map[string]any) ([]byte, error)

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

func (c *Client) UpdateShortcut(id string, body map[string]any) ([]byte, error)

UpdateShortcut applies a partial update (only the fields present in body) and returns the bare updated object.

func (*Client) UpdateTag

func (c *Client) UpdateTag(id string, body map[string]any) ([]byte, error)

UpdateTag renames and/or re-parents a tag and returns the bare updated object.

func (*Client) UpdateTask added in v0.1.12

func (c *Client) UpdateTask(id string, body map[string]any) ([]byte, error)

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

func (c *Client) UpdateTemplate(id string, body map[string]any) ([]byte, error)

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

func (c *Client) UploadFile(path, mimeType, filename string, isEncrypted bool) ([]byte, error)

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

func (c *Client) VerifyEmail(token string) ([]byte, error)

VerifyEmail consumes an email-verification token. Public.

func (*Client) Version

func (c *Client) Version() ([]byte, error)

Version probes the root /version endpoint and returns the raw body of build metadata (version, commit, build_time, go_version). It lives at the server root and is 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

type ImportUploadPart struct {
	PartNumber int    `json:"part_number"`
	ETag       string `json:"etag"`
}

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

func DecodePaging(data []byte) (Paging, bool)

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.

Jump to

Keyboard shortcuts

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