hcbapi

package
v0.1.12 Latest Latest
Warning

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

Go to latest
Published: Jul 31, 2026 License: MIT Imports: 24 Imported by: 0 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

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CompactTransactions added in v0.1.10

func CompactTransactions(data json.RawMessage) (json.RawMessage, error)

CompactTransactions rewrites a transactions array (the data field of a paged ledger response) into one small summary object per transaction: the scalars that matter for scanning (id, date, amount_cents, memo, code), tag labels, the transaction type, and a best-effort counterparty/actor pulled from the type-specific sub-object. False booleans and empty fields are omitted. Full detail for any single transaction is available from GetTransaction.

func CredentialsFileEncrypted added in v0.1.8

func CredentialsFileEncrypted(path string) (bool, error)

CredentialsFileEncrypted reports whether path is an encrypted credentials envelope. It does not decrypt the file.

func CredentialsJSONEncrypted added in v0.1.8

func CredentialsJSONEncrypted(b []byte) bool

CredentialsJSONEncrypted reports whether b looks like an encrypted credentials envelope. It does not decrypt the payload.

func DefaultCredentialsPath

func DefaultCredentialsPath() (string, error)

DefaultCredentialsPath is ~/.config/hcb/credentials.json.

func RequireCredentialsEncryptionKey added in v0.1.8

func RequireCredentialsEncryptionKey() error

RequireCredentialsEncryptionKey returns an error unless server-side credential encryption is configured.

func WriteCredentialsBytes added in v0.1.8

func WriteCredentialsBytes(path string, b []byte) error

WriteCredentialsBytes writes an already-encoded credentials document atomically with 0600 permissions.

Types

type APIError

type APIError struct {
	StatusCode int
	Code       string
	Messages   []string
	Body       string
}

APIError is a non-2xx response from the v4 API, decoded from the standard {"error": "...", "messages": [...]} envelope.

func (*APIError) Error

func (e *APIError) Error() string

type Client

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

Client is a read-only HCB v4 API client with automatic token refresh. Safe for concurrent use.

func NewClient

func NewClient(credsPath string) (*Client, error)

NewClient loads credentials from path and returns a client.

func NewClientFromDefaultPath

func NewClientFromDefaultPath() (*Client, error)

NewClientFromDefaultPath loads ~/.config/hcb/credentials.json.

func NewClientWithToken

func NewClientWithToken(baseURL, accessToken string) *Client

NewClientWithToken returns a client that authenticates with a fixed access token supplied by the caller (e.g. per-request tokens on a multi-user HTTP server). It never refreshes and never persists anything.

func (*Client) AvailableIcons

func (c *Client) AvailableIcons(ctx context.Context) (json.RawMessage, error)

AvailableIcons returns the mobile-app icon flags the user has unlocked.

func (*Client) BalanceByDate

func (c *Client) BalanceByDate(ctx context.Context, org string) (json.RawMessage, error)

BalanceByDate returns the org's daily running balance series (past year).

func (*Client) BaseURL

func (c *Client) BaseURL() string

BaseURL returns the API host (e.g. https://hcb.hackclub.com).

func (*Client) CredentialsPath

func (c *Client) CredentialsPath() string

func (*Client) DownloadFile

func (c *Client) DownloadFile(ctx context.Context, fileURL, destDir, name string) (string, error)

DownloadFile fetches a signed file URL (receipt url/preview_url, check deposit images, comment attachments, org logos) and writes it into destDir. If name is empty, it uses the Content-Disposition filename, falling back to the URL's path basename. Signed URLs are self-authorizing, so no Authorization header is sent — deliberately, to avoid leaking the bearer token to blob/CDN hosts. Returns the saved file's path.

func (*Client) Get

func (c *Client) Get(ctx context.Context, path string, query url.Values) (json.RawMessage, error)

Get performs an authenticated GET and returns the raw JSON body. On 401 it refreshes once and retries with the fresh token.

func (*Client) GetCard

func (c *Client) GetCard(ctx context.Context, id string, expand []string) (json.RawMessage, error)

GetCard returns one card (crd_…). expand: organization, user, last_frozen_by, total_spent_cents, balance_available.

func (*Client) GetCardGrant

func (c *Client) GetCardGrant(ctx context.Context, id string, expand []string) (json.RawMessage, error)

GetCardGrant returns one grant (cdg_…). expand: user, organization, balance_cents, disbursements.

func (*Client) GetCheck

func (c *Client) GetCheck(ctx context.Context, id string) (json.RawMessage, error)

GetCheck returns one mailed check (chk_…). NOTE: upstream bug — the server's policy has no show? so this currently returns 403 for everyone.

func (*Client) GetCheckDeposit

func (c *Client) GetCheckDeposit(ctx context.Context, id string) (json.RawMessage, error)

GetCheckDeposit returns one check deposit (ckd_…).

func (*Client) GetCurrentUser

func (c *Client) GetCurrentUser(ctx context.Context, expand []string, avatarSize int) (json.RawMessage, error)

GetCurrentUser returns the authenticated user's profile. expand: shipping_address, billing_address. avatarSize (px) sizes the avatar URL; 0 = default.

func (*Client) GetDonation added in v0.1.10

func (c *Client) GetDonation(ctx context.Context, id string) (json.RawMessage, error)

GetDonation returns one donation (don_…).

func (*Client) GetInvitation

func (c *Client) GetInvitation(ctx context.Context, id string) (json.RawMessage, error)

GetInvitation returns one of the user's invitations (ivt_…).

func (*Client) GetInvoice

func (c *Client) GetInvoice(ctx context.Context, id string) (json.RawMessage, error)

GetInvoice returns one invoice (inv_…).

func (*Client) GetOrganization

func (c *Client) GetOrganization(ctx context.Context, id string, expand []string) (json.RawMessage, error)

GetOrganization returns one org by public id (org_…) or slug. expand: balance_cents, users, account_number, reporting.

func (*Client) GetPage

func (c *Client) GetPage(ctx context.Context, path string, query url.Values) (*Page, error)

GetPage performs Get and decodes the pagination envelope.

func (*Client) GetSponsor

func (c *Client) GetSponsor(ctx context.Context, id string) (json.RawMessage, error)

GetSponsor returns one sponsor (spo_…).

func (*Client) GetTag

func (c *Client) GetTag(ctx context.Context, id string) (json.RawMessage, error)

GetTag returns one tag by id (tag_…).

func (*Client) GetTransaction

func (c *Client) GetTransaction(ctx context.Context, id, org string) (json.RawMessage, error)

GetTransaction returns one transaction (HcbCode). If org is non-empty the org-scoped route is used (amounts/memos are rendered from that org's view); otherwise the top-level route auto-expands the organization.

func (*Client) GetUser

func (c *Client) GetUser(ctx context.Context, id string) (json.RawMessage, error)

GetUser looks up any user by public id (requires admin:read + auditor role).

func (*Client) GetUserByEmail

func (c *Client) GetUserByEmail(ctx context.Context, email string) (json.RawMessage, error)

GetUserByEmail looks up any user by email (requires admin:read + auditor role).

func (*Client) GetWire added in v0.1.10

func (c *Client) GetWire(ctx context.Context, id string) (json.RawMessage, error)

GetWire returns one wire transfer by public id.

func (*Client) ListCardDesigns

func (c *Client) ListCardDesigns(ctx context.Context, org string) (json.RawMessage, error)

ListCardDesigns lists card personalization designs; org ("" = common only) adds that org's designs.

func (*Client) ListCardGrantTransactions

func (c *Client) ListCardGrantTransactions(ctx context.Context, id string, page PageOpts) (*Page, error)

ListCardGrantTransactions returns a page of spending on the grant's card.

func (*Client) ListCardTransactions

func (c *Client) ListCardTransactions(ctx context.Context, cardID string, missingReceipts bool, page PageOpts) (*Page, error)

ListCardTransactions returns a page of a card's charges.

func (*Client) ListCheckDeposits

func (c *Client) ListCheckDeposits(ctx context.Context, org string) (json.RawMessage, error)

ListCheckDeposits lists an org's check deposits.

func (*Client) ListChecks

func (c *Client) ListChecks(ctx context.Context, org string) (json.RawMessage, error)

ListChecks lists an org's mailed checks.

func (*Client) ListComments

func (c *Client) ListComments(ctx context.Context, transactionID string) (json.RawMessage, error)

ListComments lists a transaction's comments (oldest first).

func (*Client) ListDonations added in v0.1.10

func (c *Client) ListDonations(ctx context.Context, org, status string, expand []string, page PageOpts) (json.RawMessage, error)

ListDonations lists an org's donations (newest first), paginated. status filters by visible state (e.g. deposited, in_transit). expand: stats (adds a stats object with total_cents successfully raised). Returned raw so the optional stats key survives alongside the pagination envelope.

func (*Client) ListFollowers

func (c *Client) ListFollowers(ctx context.Context, org string) (json.RawMessage, error)

ListFollowers returns the org's followers.

func (*Client) ListInvoices

func (c *Client) ListInvoices(ctx context.Context, org string) (json.RawMessage, error)

ListInvoices lists an org's invoices.

func (*Client) ListMissingReceiptTransactions

func (c *Client) ListMissingReceiptTransactions(ctx context.Context, page PageOpts) (*Page, error)

ListMissingReceiptTransactions returns the user's own card charges still missing a receipt.

func (*Client) ListMyCardGrants

func (c *Client) ListMyCardGrants(ctx context.Context, expand []string) (json.RawMessage, error)

ListMyCardGrants lists grants the user has received.

func (*Client) ListMyCards

func (c *Client) ListMyCards(ctx context.Context, expand []string) (json.RawMessage, error)

ListMyCards lists the user's cards across all orgs. expand: organization, user, total_spent_cents.

func (*Client) ListMyInvitations

func (c *Client) ListMyInvitations(ctx context.Context) (json.RawMessage, error)

ListMyInvitations lists the user's pending org invitations.

func (*Client) ListMyOrganizations

func (c *Client) ListMyOrganizations(ctx context.Context, expand []string) (json.RawMessage, error)

ListMyOrganizations returns the orgs the user belongs to. expand: balance_cents, users, account_number, reporting.

func (*Client) ListOrgCardGrants

func (c *Client) ListOrgCardGrants(ctx context.Context, org string, expand []string) (json.RawMessage, error)

ListOrgCardGrants lists an org's card grants.

func (*Client) ListOrgCards

func (c *Client) ListOrgCards(ctx context.Context, org string, expand []string) (json.RawMessage, error)

ListOrgCards lists an org's cards.

func (*Client) ListOrgInvitations

func (c *Client) ListOrgInvitations(ctx context.Context, org string) (json.RawMessage, error)

ListOrgInvitations lists an org's pending invitations.

func (*Client) ListOrgTransactions

func (c *Client) ListOrgTransactions(ctx context.Context, org string, filters TransactionFilters, page PageOpts) (*Page, error)

ListOrgTransactions returns a page of the org's ledger (pending + settled).

func (*Client) ListOrganizerPositions added in v0.1.10

func (c *Client) ListOrganizerPositions(ctx context.Context, org string, expand []string, page PageOpts) (*Page, error)

ListOrganizerPositions lists an org's team members (organizer positions): each with role and signee status. expand: user (the member's full user record; without it only user_id is returned).

func (*Client) ListReceipts

func (c *Client) ListReceipts(ctx context.Context, transactionID string) (json.RawMessage, error)

ListReceipts lists receipts on a transaction, or the user's Receipt Bin if transactionID is empty. Each receipt carries signed url/preview_url fields.

func (*Client) ListSponsors

func (c *Client) ListSponsors(ctx context.Context, org string) (json.RawMessage, error)

ListSponsors lists an org's sponsors.

func (*Client) ListSubOrganizations

func (c *Client) ListSubOrganizations(ctx context.Context, org string) (json.RawMessage, error)

ListSubOrganizations returns the org's sub-organizations.

func (*Client) ListTags

func (c *Client) ListTags(ctx context.Context, org string) (json.RawMessage, error)

ListTags lists an org's transaction tags.

func (*Client) ListWires added in v0.1.10

func (c *Client) ListWires(ctx context.Context, org string, page PageOpts) (*Page, error)

ListWires lists an org's outgoing international wire transfers (newest first).

func (*Client) MemoSuggestions

func (c *Client) MemoSuggestions(ctx context.Context, org, txn string) (json.RawMessage, error)

MemoSuggestions returns up to 4 suggested memos for a transaction.

func (*Client) Refresh

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

Refresh forces a token refresh (used by `hcb auth refresh`).

func (*Client) TokenInfo

func (c *Client) TokenInfo(ctx context.Context) (json.RawMessage, error)

TokenInfo returns Doorkeeper's introspection of the current token.

type Credentials

type Credentials struct {
	BaseURL      string `json:"base_url"`
	ClientID     string `json:"client_id"`
	ClientSecret string `json:"client_secret"`
	// TokenURL overrides BaseURL+/api/v4/oauth/token for refresh grants.
	// Set by AuthServer logins, where the hosted bridge holds the client
	// secret and proxies the exchange to HCB.
	TokenURL     string `json:"token_url,omitempty"`
	AccessToken  string `json:"access_token"`
	RefreshToken string `json:"refresh_token"`
	Scope        string `json:"scope,omitempty"`
	CreatedAt    int64  `json:"created_at"`
	ExpiresIn    int64  `json:"expires_in"`
}

Credentials is the on-disk auth state at ~/.config/hcb/credentials.json.

func LoadCredentials

func LoadCredentials(path string) (*Credentials, error)

func LoadCredentialsBytes added in v0.1.8

func LoadCredentialsBytes(b []byte) (*Credentials, error)

LoadCredentialsBytes decodes a plaintext credentials JSON object or an encrypted credentials envelope.

func Login

func Login(ctx context.Context, cfg LoginConfig, out io.Writer) (*Credentials, error)

Login runs the OAuth authorization-code flow: starts a localhost callback listener, sends the user to the authorize page, exchanges the returned code, and returns credentials ready to Save. Progress is written to out.

func (*Credentials) Expired

func (c *Credentials) Expired(now time.Time) bool

Expired reports whether the access token is expired (or within a 120s safety margin of expiring). ExpiresIn == 0 means a non-expiring token.

func (*Credentials) Save

func (c *Credentials) Save(path string) error

Save writes the credentials atomically with 0600 permissions.

type LoginConfig

type LoginConfig struct {
	BaseURL      string
	ClientID     string
	ClientSecret string
	Scope        string
	// AuthServer, when set, brokers the flow through the hosted bridge's
	// sub-authorization-server (<AuthServer>/oauth/authorize + /oauth/token)
	// instead of talking to HCB directly. The bridge holds the client secret
	// and accepts any localhost callback port, so no local client config is
	// needed; token refreshes route through the bridge too (via
	// Credentials.TokenURL). PKCE (S256) binds the code to this process.
	AuthServer string
	// ListenAddr for the local callback server. Direct flow default is
	// 127.0.0.1:8910 (the port registered on the OAuth app); the AuthServer
	// flow defaults to an ephemeral port since any port is accepted.
	ListenAddr string
	// OpenBrowser opens the authorize URL; nil uses the OS default browser.
	OpenBrowser func(url string) error
}

LoginConfig configures the authorization-code login flow. (HCB's device-flow endpoint 500s in production, so a localhost callback — the gh-style flow — is the supported way to log in.)

type Page

type Page struct {
	TotalCount int             `json:"total_count"`
	HasMore    bool            `json:"has_more"`
	Data       json.RawMessage `json:"data"`
}

Page is the cursor-pagination envelope used by v4 list endpoints.

func CompactPage added in v0.1.10

func CompactPage(p *Page) (*Page, error)

CompactPage returns a copy of p with its data array compacted.

type PageOpts

type PageOpts struct {
	Limit int    // default 25, max 100
	After string // cursor: public id of the last item of the previous page
}

PageOpts are cursor-pagination options for paginated list endpoints.

type TransactionFilters

type TransactionFilters struct {
	Search          string
	Type            string // ach_transfer, mailed_check, hcb_transfer, card_charge, check_deposit, donation, invoice, refund, fiscal_sponsorship_fee, reimbursement, wire, paypal_transfer, wise_transfer
	TagID           string
	Expenses        bool
	Revenue         bool
	MinimumAmount   string // dollars, e.g. "1.50"
	MaximumAmount   string
	StartDate       string // YYYY-MM-DD
	EndDate         string
	UserID          string
	MissingReceipts bool
	Category        string
	Merchant        string
	OrderBy         string
}

TransactionFilters mirror the v4 ledger's filters[…] and type params.

Jump to

Keyboard shortcuts

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