invoance

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Jul 13, 2026 License: MIT Imports: 18 Imported by: 0

README

Invoance Go SDK

Official Go SDK for the Invoance compliance API — cryptographic proof, document anchoring, AI attestation, traces, and audit logs.

Zero non-stdlib dependencies. Synchronous, context.Context-aware, and (T, error) throughout.

Install

go get github.com/Invoance/invoance-go

Requires Go 1.21+.

Quick start

Set your API key:

export INVOANCE_API_KEY=inv_live_...
package main

import (
	"context"
	"crypto/sha256"
	"encoding/hex"
	"fmt"
	"log"

	"github.com/Invoance/invoance-go"
)

func main() {
	ctx := context.Background()

	// Reads INVOANCE_API_KEY and INVOANCE_BASE_URL from the environment.
	client, err := invoance.New()
	if err != nil {
		log.Fatal(err)
	}

	// Ingest a compliance event.
	event, err := client.Events.Ingest(ctx, invoance.IngestEventParams{
		EventType: "policy.approval",
		Payload:   map[string]any{"policy_id": "pol_001", "decision": "approved"},
	})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(event.EventID)

	// Anchor a document by hash.
	docBytes := []byte("...your document bytes...")
	sum := sha256.Sum256(docBytes)
	doc, err := client.Documents.Anchor(ctx, invoance.AnchorDocumentParams{
		DocumentHash: hex.EncodeToString(sum[:]),
		DocumentRef:  "Invoice #1042",
	})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(doc.EventID)

	// Or use the file helper (hashes + uploads in one call).
	anchored, err := client.Documents.AnchorFile(ctx, invoance.AnchorFileParams{
		Path:        "./invoice.pdf",
		DocumentRef: "Invoice #1042",
	})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(anchored.EventID)

	// Ingest an AI attestation.
	att, err := client.Attestations.Ingest(ctx, invoance.IngestAttestationParams{
		Type:          "output",
		Input:         "Summarize this contract",
		Output:        "The contract states...",
		ModelProvider: "openai",
		ModelName:     "gpt-4o",
		ModelVersion:  "2025-01-01",
		Subject:       &invoance.AttestationSubject{UserID: "u_42", SessionID: "sess_4f9a"},
	})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(att.AttestationID)
}

Quick validation

Sanity-check that your API key works before wiring the SDK into a larger app:

client, _ := invoance.New()
res := client.Validate(context.Background())
if !res.Valid {
	log.Fatalf("Invoance: %s (base: %s)", res.Reason, res.BaseURL)
}

Validate probes GET /v1/me (which requires no scopes, so any live key passes), never returns an error, and returns a ValidationResult{Valid, Reason, BaseURL} — use it in health checks, startup scripts, or CI guards.

To inspect what the key actually is (organization, tenant, scopes, limits), call Me:

me, err := client.Me(context.Background())
if err != nil {
	log.Fatal(err)
}
fmt.Println(me["organization"], me["api_key"], me["limits"])

One-liner for a terminal sanity check, no SDK required:

curl -sS -o /dev/null -w "%{http_code}\n" \
  -H "Authorization: Bearer $INVOANCE_API_KEY" \
  "${INVOANCE_BASE_URL:-https://api.invoance.com}/v1/me"
# 200 = key valid · 401 = bad key · anything else = investigate

Configuration

The client reads from environment variables automatically:

Variable Required Default
INVOANCE_API_KEY Yes
INVOANCE_BASE_URL No https://api.invoance.com

You can also pass options explicitly:

client, err := invoance.New(
	invoance.WithAPIKey("inv_live_..."),
	invoance.WithTimeout(60*time.Second),
	invoance.WithExtraHeaders(map[string]string{"X-Trace": "abc"}),
)

Available options: WithAPIKey, WithBaseURL, WithAPIVersion, WithTimeout, WithHTTPClient, WithIdempotencyKey, WithExtraHeaders.

Error handling

Every method returns an error that is always a *invoance.Error. Branch on its Kind, or use the Is* predicate helpers (they walk the error chain via errors.As):

resp, err := client.Events.Ingest(ctx, params)
if err != nil {
	switch {
	case invoance.IsAuthentication(err):
		// 401 — bad API key
	case invoance.IsQuotaExceeded(err):
		var e *invoance.Error
		errors.As(err, &e)
		if e.RetryAfterSeconds != nil {
			log.Printf("rate limited, retry in %.0fs", *e.RetryAfterSeconds)
		}
	case invoance.IsValidation(err):
		// 400 or client-side validation
	case invoance.IsTimeout(err) || invoance.IsNetwork(err):
		// transport failure
	default:
		log.Printf("invoance error: %v", err)
	}
}

Kind values: KindAuthentication, KindForbidden, KindNotFound, KindValidation, KindConflict, KindQuotaExceeded, KindServer, KindNetwork, KindTimeout, KindUnknown.

Resources

Every network method takes ctx context.Context as its first argument and returns (T, error). Optional scalar params are plain zero-omittable fields (empty string / nil pointer = "omit"); flexible JSON blobs are map[string]any.

Events
// Ingest a compliance event (POST /events). EventType + Payload required;
// EventTime, TraceID, IdempotencyKey optional.
res, _ := client.Events.Ingest(ctx, invoance.IngestEventParams{
	EventType: "policy.approval",
	Payload:   map[string]any{"policy_id": "pol_001", "decision": "approved"},
	EventTime: "2026-07-06T12:00:00Z", // optional RFC3339
	TraceID:   "trc_123",              // optional
})
fmt.Println(res.EventID, res.IngestedAt)

// List events (GET /events). All fields optional; Page/Limit are *int.
page, limit := 1, 50
list, _ := client.Events.List(ctx, invoance.ListEventsParams{
	Page:      &page,
	Limit:     &limit,
	DateFrom:  "2026-01-01",
	DateTo:    "2026-07-01",
	EventType: "policy.approval",
})
fmt.Println(list.Total, list.HasMore)

// Get one event (GET /events/{id}).
event, _ := client.Events.Get(ctx, "evt_123")
fmt.Println(event.PayloadHash)

// Verify a hash or payload against the anchored event
// (POST /events/{id}/verify). Provide exactly one of PayloadHash or Payload.
v, _ := client.Events.Verify(ctx, "evt_123", invoance.VerifyEventParams{
	PayloadHash: "e3b0c44298fc1c149afbf4c8996fb924...", // 64-char hex SHA-256
})
// ...or let the server canonicalize + hash a raw payload:
v, _ = client.Events.Verify(ctx, "evt_123", invoance.VerifyEventParams{
	Payload: map[string]any{"policy_id": "pol_001", "decision": "approved"},
})
fmt.Println(v.MatchResult)
Documents
// Anchor a document by hash (POST /document/anchor). DocumentHash required
// (validated client-side); the rest optional.
doc, _ := client.Documents.Anchor(ctx, invoance.AnchorDocumentParams{
	DocumentHash:     hash, // 64-char hex SHA-256
	DocumentRef:      "Invoice #1042",
	EventType:        "invoice.issued",
	OriginalBytesB64: b64Bytes,                     // optional: upload the original
	Metadata:         map[string]any{"amount": 1200},
	TraceID:          "trc_123",
})
fmt.Println(doc.EventID, doc.Status)

// Convenience: hash + base64 + anchor in one call. Provide exactly one of
// Path or Bytes. DocumentRef defaults to the file's basename when Path is set.
anchored, _ := client.Documents.AnchorFile(ctx, invoance.AnchorFileParams{
	Path:        "./invoice.pdf",
	DocumentRef: "Invoice #1042",
})
// Raw bytes instead of a path; SkipOriginal to anchor the hash only:
anchored, _ = client.Documents.AnchorFile(ctx, invoance.AnchorFileParams{
	Bytes:        blob,
	DocumentRef:  "blob",
	SkipOriginal: true,
})
fmt.Println(anchored.EventID)

// List documents (GET /document).
docs, _ := client.Documents.List(ctx, invoance.ListDocumentsParams{
	DocumentRef: "Invoice #1042",
})
fmt.Println(docs.Total)

// Get one document's metadata (GET /document/{id}).
d, _ := client.Documents.Get(ctx, "evt_123")
fmt.Println(d.DocumentHash, d.HasOriginal)

// Download the original bytes (GET /document/{id}/original) => []byte.
raw, _ := client.Documents.GetOriginal(ctx, "evt_123")
_ = os.WriteFile("out.pdf", raw, 0o644)

// Verify a hash against the anchored document (POST /document/{id}/verify).
vd, _ := client.Documents.Verify(ctx, "evt_123", invoance.VerifyDocumentParams{
	DocumentHash: hash,
})
fmt.Println(vd.MatchResult)
AI Attestations
// Ingest an attestation (POST /ai/attestations). Type, Input, Output,
// ModelProvider, ModelName, ModelVersion required; Subject/TraceID optional.
att, _ := client.Attestations.Ingest(ctx, invoance.IngestAttestationParams{
	Type:          "output",
	Input:         "Summarize this contract",
	Output:        "The contract states...",
	ModelProvider: "openai",
	ModelName:     "gpt-4o",
	ModelVersion:  "2025-01-01",
	Subject: &invoance.AttestationSubject{
		UserID:    "u_42",
		SessionID: "sess_4f9a",
		Extra:     map[string]any{"tenant": "acme"}, // merged verbatim
	},
})
fmt.Println(att.AttestationID, att.PayloadHash)

// List attestations (GET /ai/attestations).
alist, _ := client.Attestations.List(ctx, invoance.ListAttestationsParams{
	AttestationType: "output",
	ModelProvider:   "openai",
})
fmt.Println(alist.Total)

// Get one attestation (GET /ai/attestations/{id}).
a, _ := client.Attestations.Get(ctx, "att_123")
fmt.Println(a.AttestationHash)

// Get the original canonical JSON as an untyped map
// (GET /ai/attestations/{id}/raw).
rawMap, _ := client.Attestations.GetRaw(ctx, "att_123")
fmt.Println(rawMap["type"])

// Server-side verify by content hash (POST /ai/attestations/{id}/verify).
va, _ := client.Attestations.Verify(ctx, "att_123", invoance.VerifyAttestationParams{
	ContentHash: "e3b0c44298fc1c149afbf4c8996fb924...", // 64-char hex
})
fmt.Println(va.MatchResult)

// Hash a raw payload client-side then verify. Pass the canonical JSON exactly
// as stored (see the note below) — []byte or string, key order preserved.
vp, _ := client.Attestations.VerifyPayload(ctx, "att_123",
	[]byte(`{"type":"output","payload":{...},"context":{...}}`))
vp, _ = client.Attestations.VerifyPayloadString(ctx, "att_123", rawJSON)
fmt.Println(vp.MatchResult)

// Verify the Ed25519 signature fully offline (fetches the record, verifies
// against its embedded 32-byte public key).
sig, _ := client.Attestations.VerifySignature(ctx, "att_123")
fmt.Println(sig.Valid, sig.Reason)

Note: for VerifyPayload / VerifyPayloadString, pass the raw JSON string or bytes exactly as shown in the dashboard's "Raw immutable record" viewer. Key order is preserved (not sorted) because the backend hashes with serde struct field order (type, payload, context, subject). Do not unmarshal into a map first — that would lose order.

Traces
// Create a trace (POST /traces). Label required; Metadata optional.
trace, _ := client.Traces.Create(ctx, invoance.CreateTraceParams{
	Label:    "Batch 2026-07",
	Metadata: map[string]any{"customer": "acme"},
})
fmt.Println(trace.TraceID, trace.Status)

// List traces (GET /traces). Status filters "open" / "sealed".
tlist, _ := client.Traces.List(ctx, invoance.ListTracesParams{Status: "open"})
fmt.Println(tlist.Total)

// Get trace detail with paginated event summaries (GET /traces/{id}).
page, lim := 1, 50
detail, _ := client.Traces.Get(ctx, "trc_123", invoance.GetTraceParams{
	EventPage:  &page,
	EventLimit: &lim,
})
fmt.Println(detail.EventTotal, detail.CompositeHash)

// Seal a trace asynchronously (POST /traces/{id}/seal); server responds 202.
sealed, _ := client.Traces.Seal(ctx, "trc_123")
fmt.Println(sealed.Status, sealed.Message)

// Export the proof bundle as JSON, sealed traces only (GET /traces/{id}/proof).
proof, _ := client.Traces.Proof(ctx, "trc_123")
fmt.Println(proof.CompositeHash, proof.Verification.AllSignaturesValid)

// Download the proof bundle as a PDF (GET /traces/{id}/proof/pdf) => []byte.
pdf, _ := client.Traces.ProofPDF(ctx, "trc_123")
_ = os.WriteFile("proof.pdf", pdf, 0o644)

// Delete an empty, open trace (DELETE /traces/{id}).
del, _ := client.Traces.Delete(ctx, "trc_123")
fmt.Println(del.Deleted)
Audit logs

The audit resource has five sub-resources: Events, Orgs, Streams, PortalSessions, and Exports. The audit ledger requires an Idempotency-Key; if you don't supply one on Events.Ingest, the SDK derives a content-stable key from the request body for safe retries.

client.Audit.Events — the signed audit-event ledger:

// Append one signed event (POST /audit/events). OrganizationID, Action, Actor
// required; OccurredAt defaults to now, Targets to []. IdempotencyKey overrides
// the derived content key.
ev, _ := client.Audit.Events.Ingest(ctx, invoance.IngestAuditEventParams{
	OrganizationID: "org_acme",
	Action:         "invoice.approved",
	Actor:          map[string]any{"type": "user", "id": "u_1"},
	Targets:        []map[string]any{{"type": "invoice", "id": "inv_42"}},
	Context:        map[string]any{"ip": "1.2.3.4"},
	Metadata:       map[string]any{"amount": 1200},
})

// Keyset-paginated listing (GET /audit/events).
limit := 100
alist, _ := client.Audit.Events.List(ctx, invoance.ListAuditEventsParams{
	OrganizationID: "org_acme",
	Actions:        "invoice.approved",
	ActorID:        "u_1",
	RangeStart:     "2026-01-01T00:00:00Z",
	RangeEnd:       "2026-07-01T00:00:00Z",
	Limit:          &limit,
	Cursor:         "", // pass NextCursor from the prior page
})
fmt.Println(len(alist.Events), alist.NextCursor)

// Get one audit event (GET /audit/events/{id}) => typed AuditEvent.
one, _ := client.Audit.Events.Get(ctx, "aevt_1")

// Server-side verify with the pinned key (GET /audit/events/{id}/verify).
sv, _ := client.Audit.Events.Verify(ctx, "aevt_1")
fmt.Println(sv["valid"])

client.Audit.Orgs — end-customer orgs:

_, _ = client.Audit.Orgs.Create(ctx, invoance.CreateAuditOrgParams{
	OrganizationID: "org_acme",
	Name:           "Acme Inc.", // optional
})
orgs, _ := client.Audit.Orgs.List(ctx, invoance.ListAuditOrgsParams{
	IncludeArchived: true, // archived orgs are excluded by default
})
rep, _ := client.Audit.Orgs.Integrity(ctx, "org_acme")     // integrity report
_, _ = client.Audit.Orgs.SetRetention(ctx, "org_acme", 365) // retention days

// Rename (PATCH /audit/orgs/{id}); a nil Name clears the stored name.
name := "Acme Incorporated"
_, _ = client.Audit.Orgs.Update(ctx, "org_acme", invoance.UpdateAuditOrgParams{Name: &name})

// Archive/unarchive (idempotent). Archiving freezes new activity — ingest,
// streams, portal, and exports return 409 org_archived — history stays
// verifiable.
_, _ = client.Audit.Orgs.Archive(ctx, "org_acme")
_, _ = client.Audit.Orgs.Unarchive(ctx, "org_acme")

// Hard delete, allowed only when nothing signed would be destroyed
// (never-ingested, or archived + retention fully purged); otherwise 409
// org_not_deletable.
_, _ = client.Audit.Orgs.Delete(ctx, "org_acme")
_ = orgs
_ = rep

client.Audit.Streams — SIEM/webhook delivery (org-scoped; the signing secret is returned once on create):

s, _ := client.Audit.Streams.Create(ctx, "org_acme", invoance.CreateAuditStreamParams{
	URL:  "https://siem.example/hook",
	Type: "webhook", // default; v1 supports webhook only
})
streams, _ := client.Audit.Streams.List(ctx, "org_acme")
_, _ = client.Audit.Streams.Test(ctx, "org_acme", "stream_1")   // test delivery
_, _ = client.Audit.Streams.Delete(ctx, "org_acme", "stream_1")
_ = s
_ = streams

client.Audit.PortalSessions — one-time hosted-viewer links:

sessDur, linkDur := 3600, 600
portal, _ := client.Audit.PortalSessions.Create(ctx, invoance.CreatePortalSessionParams{
	OrganizationID:         "org_acme",
	Intent:                 "audit_logs", // "audit_logs" or "log_streams"
	SessionDurationSeconds: &sessDur,     // optional
	LinkDurationSeconds:    &linkDur,     // optional
})
fmt.Println(portal["url"])

client.Audit.Exports — async export jobs:

job, _ := client.Audit.Exports.Create(ctx, invoance.CreateAuditExportParams{
	OrganizationID: "org_acme",
	Format:         "csv", // "csv" or "ndjson"
	Filters:        map[string]any{"action": "invoice.approved"}, // optional
})
// Poll until ready; a "ready" response carries a download_url.
status, _ := client.Audit.Exports.Get(ctx, job["export_id"].(string))
fmt.Println(status["status"], status["download_url"])

Offline verification

The SDK can verify signatures and hashes entirely client-side — no trust in the server required. See the per-resource sections above for Attestations. VerifySignature / VerifyPayload; the audit-ledger equivalents are top-level package functions.

// Verify an attestation's Ed25519 signature.
res, _ := client.Attestations.VerifySignature(ctx, "att_123")
fmt.Println(res.Valid, res.Reason)

// Verify a typed audit event offline. Pass nil opts to trust the event's
// embedded key, or pin the tenant's registered key for a real tamper guarantee.
event, _ := client.Audit.Events.Get(ctx, "aevt_1")
result := invoance.VerifyAuditEventStruct(event, nil)
fmt.Println(result.Valid, result.PayloadHash, result.KeySource)

// Pin the registered key (hex string or []byte):
result = invoance.VerifyAuditEventStruct(event, &invoance.AuditVerifyOptions{
	PublicKey: registeredHexKey,
})

// VerifyAuditEvent takes a raw map[string]any (e.g. from a map-returning audit
// method) for full fidelity when you have unknown fields.
raw, _ := client.Audit.Events.Verify(ctx, "aevt_1")
_ = invoance.VerifyAuditEvent(raw, nil)

For attestation payload verification, pass the raw JSON string or bytes exactly as stored (the dashboard's "Raw immutable record"). Key order is preserved — do not decode into a map first:

raw := []byte(`{"type":"output","payload":{...},"context":{...}}`)
v, _ := client.Attestations.VerifyPayload(ctx, "att_123", raw)
fmt.Println(v.MatchResult)

License

MIT © 2026 Invoance, Inc.

Documentation

Overview

Package invoance is the official Go SDK for the Invoance compliance API — cryptographic proof, document anchoring, AI attestation, traces, and audit logs.

Create a client with New, reading INVOANCE_API_KEY (and optionally INVOANCE_BASE_URL) from the environment, or pass options explicitly:

client, err := invoance.New(invoance.WithAPIKey("inv_live_..."))
if err != nil {
    log.Fatal(err)
}
resp, err := client.Events.Ingest(ctx, invoance.IngestEventParams{
    EventType: "user.login",
    Payload:   map[string]any{"user_id": "u_42"},
})

Every network method takes a context.Context as its first argument and returns (T, error). All errors are *Error; branch on Kind or use the Is* predicate helpers.

Index

Constants

View Source
const AuditSchemaID = "invoance.audit/1"

AuditSchemaID is the frozen canonicalization schema identifier.

View Source
const SDKVersion = "0.2.0"

SDKVersion is the released version of this SDK. It is embedded in the User-Agent header sent on every request.

Variables

This section is empty.

Functions

func CanonicalAuditBytes

func CanonicalAuditBytes(event map[string]any) ([]byte, error)

CanonicalAuditBytes returns the canonical signed bytes for an audit event: build the signed object, strip nulls recursively, sort every object's keys deeply (alphabetical), emit compact UTF-8 JSON.

encoding/json marshals map[string]any with keys sorted alphabetically and produces compact output, so a plain Marshal of the null-stripped signed object yields the canonical form.

func ContentIdempotencyKey

func ContentIdempotencyKey(body map[string]any) string

ContentIdempotencyKey derives a stable Idempotency-Key from an event body: "idem_" + sha256hex(stableStringify(body)), where stableStringify is compact JSON with all object keys sorted deeply (NO null stripping). Because encoding/json already marshals map keys in sorted order and produces compact output, marshaling a map[string]any body yields the stable form.

func IsAuthentication

func IsAuthentication(err error) bool

IsAuthentication reports whether err is an authentication (401) error.

func IsConflict

func IsConflict(err error) bool

IsConflict reports whether err is a conflict (409) error.

func IsForbidden

func IsForbidden(err error) bool

IsForbidden reports whether err is a forbidden (403) error.

func IsNetwork

func IsNetwork(err error) bool

IsNetwork reports whether err is a transport/network error.

func IsNotFound

func IsNotFound(err error) bool

IsNotFound reports whether err is a not-found (404) error.

func IsQuotaExceeded

func IsQuotaExceeded(err error) bool

IsQuotaExceeded reports whether err is a quota/rate-limit (429) error.

func IsServer

func IsServer(err error) bool

IsServer reports whether err is a server (5xx) error.

func IsTimeout

func IsTimeout(err error) bool

IsTimeout reports whether err is a timeout error.

func IsValidation

func IsValidation(err error) bool

IsValidation reports whether err is a validation error (400 or client-side).

func NormalizeTS

func NormalizeTS(value string) (string, error)

NormalizeTS converts an RFC3339 timestamp to the one canonical form (§4.4): UTC, exactly 3 fractional digits (TRUNCATED, not rounded), suffix "Z".

func PayloadHashHex

func PayloadHashHex(canonical []byte) string

PayloadHashHex returns the lowercase hex SHA-256 of the canonical bytes.

Types

type AiAttestation

type AiAttestation struct {
	AttestationID   string              `json:"attestation_id"`
	TenantID        string              `json:"tenant_id"`
	AttestationType string              `json:"attestation_type"`
	AttestationHash string              `json:"attestation_hash"`
	InputHash       *string             `json:"input_hash,omitempty"`
	OutputHash      *string             `json:"output_hash,omitempty"`
	SignedPayload   string              `json:"signed_payload"`
	Signature       string              `json:"signature"`
	PublicKey       string              `json:"public_key"`
	SignatureAlg    string              `json:"signature_alg"`
	ModelProvider   *string             `json:"model_provider,omitempty"`
	ModelName       *string             `json:"model_name,omitempty"`
	ModelVersion    *string             `json:"model_version,omitempty"`
	RetentionPolicy string              `json:"retention_policy"`
	CreatedAt       string              `json:"created_at"`
	Organization    *OrganizationPublic `json:"organization,omitempty"`
}

AiAttestation is a single AI attestation record.

type AnchorDocumentParams

type AnchorDocumentParams struct {
	// DocumentHash is the required 64-char lowercase hex SHA-256 digest.
	DocumentHash string
	// DocumentRef is an optional human-readable reference.
	DocumentRef string
	// EventType is an optional classification string.
	EventType string
	// OriginalBytesB64 optionally uploads the original bytes (base64).
	OriginalBytesB64 string
	// Metadata is optional arbitrary JSON metadata.
	Metadata map[string]any
	// IdempotencyKey is an optional per-call idempotency key.
	IdempotencyKey string
	// TraceID optionally associates the document with a trace.
	TraceID string
}

AnchorDocumentParams are the parameters for Documents.Anchor.

type AnchorDocumentResponse

type AnchorDocumentResponse struct {
	EventID      string `json:"event_id"`
	CreatedAt    string `json:"created_at"`
	DocumentHash string `json:"document_hash"`
	Status       string `json:"status"`
}

AnchorDocumentResponse is returned by Documents.Anchor / AnchorFile.

type AnchorFileParams

type AnchorFileParams struct {
	// Path is a file path on disk. DocumentRef defaults to its basename.
	Path string
	// Bytes is the file content as raw bytes.
	Bytes []byte
	// DocumentRef is an optional human-readable reference.
	DocumentRef string
	// EventType is an optional classification string.
	EventType string
	// Metadata is optional arbitrary JSON metadata.
	Metadata map[string]any
	// IdempotencyKey is an optional per-call idempotency key.
	IdempotencyKey string
	// SkipOriginal skips uploading the original file bytes when true.
	SkipOriginal bool
	// TraceID optionally associates the document with a trace.
	TraceID string
}

AnchorFileParams are the parameters for Documents.AnchorFile. Provide exactly one of Path or Bytes.

type AttestationListItem

type AttestationListItem struct {
	AttestationID   string  `json:"attestation_id"`
	AttestationType string  `json:"attestation_type"`
	AttestationHash string  `json:"attestation_hash"`
	ModelProvider   *string `json:"model_provider,omitempty"`
	ModelName       *string `json:"model_name,omitempty"`
	RetentionPolicy string  `json:"retention_policy"`
	CreatedAt       string  `json:"created_at"`
}

AttestationListItem is one entry in a ListAttestationsResponse.

type AttestationSubject

type AttestationSubject struct {
	// UserID maps to the "user_id" wire key.
	UserID string
	// SessionID maps to the "session_id" wire key.
	SessionID string
	// Extra holds additional tenant-specific keys, merged as-is.
	Extra map[string]any
}

AttestationSubject is the optional subject context for an attestation.

type AttestationsResource

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

AttestationsResource is the AI-attestations resource (client.Attestations).

func (*AttestationsResource) Get

func (r *AttestationsResource) Get(ctx context.Context, attestationID string) (AiAttestation, error)

Get retrieves a single attestation (GET /ai/attestations/{id}).

func (*AttestationsResource) GetRaw

func (r *AttestationsResource) GetRaw(ctx context.Context, attestationID string) (map[string]any, error)

GetRaw retrieves the original canonical JSON payload as an untyped map (GET /ai/attestations/{id}/raw).

func (*AttestationsResource) Ingest

Ingest anchors an AI attestation (POST /ai/attestations).

func (*AttestationsResource) List

List returns a paginated attestation listing (GET /ai/attestations).

func (*AttestationsResource) Verify

Verify checks a submitted content hash against the anchored attestation (POST /ai/attestations/{id}/verify).

func (*AttestationsResource) VerifyPayload

func (r *AttestationsResource) VerifyPayload(ctx context.Context, attestationID string, payload []byte) (VerifyAttestationResponse, error)

VerifyPayload hashes a raw payload client-side and calls Verify.

The payload must be the canonical JSON stored in Invoance (the "Raw immutable record"). Pass it as a JSON string or []byte to PRESERVE KEY ORDER — the backend hashes with serde_json struct field order (type, payload, context, subject), NOT alphabetical order. The bytes are compacted (whitespace stripped) with encoding/json.Compact, which preserves order; they are NOT re-sorted. Do not unmarshal into a map first, as that would lose order.

func (*AttestationsResource) VerifyPayloadString

func (r *AttestationsResource) VerifyPayloadString(ctx context.Context, attestationID string, payload string) (VerifyAttestationResponse, error)

VerifyPayloadString is a convenience wrapper over VerifyPayload for string input. String input is the safest choice for key-order fidelity.

func (*AttestationsResource) VerifySignature

func (r *AttestationsResource) VerifySignature(ctx context.Context, attestationID string) (SignatureVerificationResult, error)

VerifySignature fetches the attestation and verifies its Ed25519 signature fully client-side, using the raw 32-byte public key embedded in the record.

type AuditEvent

type AuditEvent struct {
	ID               string         `json:"id"`
	OrgID            string         `json:"org_id"`
	Seq              int64          `json:"seq"`
	OccurredAt       string         `json:"occurred_at"`
	IngestedAt       string         `json:"ingested_at"`
	Action           string         `json:"action"`
	Actor            map[string]any `json:"actor"`
	Targets          []any          `json:"targets"`
	Context          map[string]any `json:"context,omitempty"`
	Metadata         map[string]any `json:"metadata,omitempty"`
	PayloadHash      string         `json:"payload_hash"`
	Signature        string         `json:"signature"`
	SigningPublicKey string         `json:"signing_public_key"`
}

AuditEvent is a single signed audit-ledger event. Unknown fields are not captured; use the map-returning audit methods for full fidelity.

type AuditEventsResource

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

AuditEventsResource is the audit-event ledger sub-resource (client.Audit.Events).

func (*AuditEventsResource) Get

func (r *AuditEventsResource) Get(ctx context.Context, eventID string) (AuditEvent, error)

Get retrieves a single audit event (GET /audit/events/{id}).

func (*AuditEventsResource) Ingest

Ingest appends one signed audit event (POST /audit/events). The ledger requires an Idempotency-Key; if none is supplied, a content-stable one is derived from the request body.

func (*AuditEventsResource) List

List returns a keyset-paginated audit listing (GET /audit/events).

func (*AuditEventsResource) Verify

func (r *AuditEventsResource) Verify(ctx context.Context, eventID string) (map[string]any, error)

Verify runs the server-side verify (pinned key) for one event (GET /audit/events/{id}/verify), returning the raw server response.

type AuditExportsResource

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

AuditExportsResource is the async export-jobs sub-resource (client.Audit.Exports).

func (*AuditExportsResource) Create

Create queues an async export job (POST /audit/exports).

func (*AuditExportsResource) Get

func (r *AuditExportsResource) Get(ctx context.Context, exportID string) (map[string]any, error)

Get polls an export job (GET /audit/exports/{id}). When status is "ready" the response carries a download_url.

type AuditKeySource

type AuditKeySource string

AuditKeySource indicates which key was used to verify an audit event.

const (
	// KeySourcePinned means a caller-supplied public key was used.
	KeySourcePinned AuditKeySource = "pinned"
	// KeySourceEvent means the key embedded in the event was used.
	KeySourceEvent AuditKeySource = "event"
)

type AuditOrgsResource

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

AuditOrgsResource is the audit end-customer orgs sub-resource (client.Audit.Orgs).

func (*AuditOrgsResource) Archive added in v0.2.0

func (r *AuditOrgsResource) Archive(ctx context.Context, organizationID string) (map[string]any, error)

Archive freezes an org (POST /audit/orgs/{orgID}/archive). Idempotent. While archived, ingest, streams, portal, and exports return 409 org_archived; history stays verifiable. The response carries archived_at.

func (*AuditOrgsResource) Create

func (r *AuditOrgsResource) Create(ctx context.Context, params CreateAuditOrgParams) (map[string]any, error)

Create registers an end-customer org (POST /audit/orgs).

func (*AuditOrgsResource) Delete added in v0.2.0

func (r *AuditOrgsResource) Delete(ctx context.Context, organizationID string) (map[string]any, error)

Delete hard-deletes an org (DELETE /audit/orgs/{orgID}). Allowed only when nothing signed would be destroyed (a never-ingested org, or an archived org whose retention has fully purged); otherwise the server returns 409 org_not_deletable.

func (*AuditOrgsResource) Integrity

func (r *AuditOrgsResource) Integrity(ctx context.Context, organizationID string) (map[string]any, error)

Integrity returns the integrity report for an org (GET /audit/orgs/{orgID}/integrity).

func (*AuditOrgsResource) List

func (r *AuditOrgsResource) List(ctx context.Context, params ListAuditOrgsParams) (map[string]any, error)

List lists orgs (GET /audit/orgs). Archived orgs are excluded unless params.IncludeArchived is set.

func (*AuditOrgsResource) SetRetention

func (r *AuditOrgsResource) SetRetention(ctx context.Context, organizationID string, days int) (map[string]any, error)

SetRetention updates the retention window for an org (PUT /audit/orgs/{orgID}/retention).

func (*AuditOrgsResource) Unarchive added in v0.2.0

func (r *AuditOrgsResource) Unarchive(ctx context.Context, organizationID string) (map[string]any, error)

Unarchive reactivates an archived org (POST /audit/orgs/{orgID}/unarchive). Idempotent. The response carries archived_at set to null.

func (*AuditOrgsResource) Update added in v0.2.0

func (r *AuditOrgsResource) Update(ctx context.Context, organizationID string, params UpdateAuditOrgParams) (map[string]any, error)

Update renames an org (PATCH /audit/orgs/{orgID}). organizationID accepts the aorg_ id or your external organization_id. A nil params.Name clears the stored name.

type AuditPortalSessionsResource

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

AuditPortalSessionsResource is the hosted-viewer portal sub-resource (client.Audit.PortalSessions).

func (*AuditPortalSessionsResource) Create

Create mints a one-time hosted-viewer link (POST /audit/portal_sessions).

type AuditResource

type AuditResource struct {
	// Events is the audit-event ledger sub-resource.
	Events *AuditEventsResource
	// Orgs is the end-customer orgs sub-resource.
	Orgs *AuditOrgsResource
	// Streams is the SIEM/webhook streams sub-resource.
	Streams *AuditStreamsResource
	// PortalSessions is the hosted-viewer portal-link sub-resource.
	PortalSessions *AuditPortalSessionsResource
	// Exports is the async export-jobs sub-resource.
	Exports *AuditExportsResource
}

AuditResource is the audit-logs resource (client.Audit), with five sub-resources.

type AuditStreamsResource

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

AuditStreamsResource is the audit streams sub-resource (client.Audit.Streams).

func (*AuditStreamsResource) Create

func (r *AuditStreamsResource) Create(ctx context.Context, organizationID string, params CreateAuditStreamParams) (map[string]any, error)

Create creates a stream (POST /audit/orgs/{orgID}/streams). The signing secret is returned once.

func (*AuditStreamsResource) Delete

func (r *AuditStreamsResource) Delete(ctx context.Context, organizationID, streamID string) (map[string]any, error)

Delete deletes a stream (DELETE /audit/orgs/{orgID}/streams/{streamID}).

func (*AuditStreamsResource) List

func (r *AuditStreamsResource) List(ctx context.Context, organizationID string) (map[string]any, error)

List lists streams for an org (GET /audit/orgs/{orgID}/streams).

func (*AuditStreamsResource) Test

func (r *AuditStreamsResource) Test(ctx context.Context, organizationID, streamID string) (map[string]any, error)

Test sends a test delivery to a stream (POST /audit/orgs/{orgID}/streams/{streamID}/test).

type AuditVerifyOptions

type AuditVerifyOptions struct {
	// PublicKey optionally pins a trusted key (hex or raw bytes). When set,
	// the event's embedded key is ignored and KeySource is "pinned".
	PublicKey any
}

AuditVerifyOptions configures VerifyAuditEvent.

type AuditVerifyResult

type AuditVerifyResult struct {
	// Valid reports whether the signature verified.
	Valid bool
	// Reason is a machine reason when invalid; empty when valid.
	Reason string
	// PayloadHash is the recomputed canonical payload hash (hex).
	PayloadHash string
	// KeySource indicates whether a pinned or embedded key was used.
	KeySource AuditKeySource
}

AuditVerifyResult is the outcome of VerifyAuditEvent.

func VerifyAuditEvent

func VerifyAuditEvent(event map[string]any, opts *AuditVerifyOptions) AuditVerifyResult

VerifyAuditEvent verifies one audit event's Ed25519 signature offline, against either a pinned public key or the key embedded in the event.

The event is a decoded JSON object (map[string]any) — pass the raw map from audit list/get responses for full fidelity, since it reads event["id"] or event["event_id"]. See VerifyAuditEventStruct for verifying an AuditEvent.

Trust note: verifying against the event-embedded key only proves internal consistency. For a real tamper guarantee, pin the tenant's registered key via AuditVerifyOptions.PublicKey.

func VerifyAuditEventStruct

func VerifyAuditEventStruct(event AuditEvent, opts *AuditVerifyOptions) AuditVerifyResult

VerifyAuditEventStruct is a typed convenience wrapper over VerifyAuditEvent for an AuditEvent value.

type Client

type Client struct {
	// Events is the compliance-events resource.
	Events *EventsResource
	// Documents is the document-anchoring resource.
	Documents *DocumentsResource
	// Attestations is the AI-attestations resource.
	Attestations *AttestationsResource
	// Traces is the traces resource.
	Traces *TracesResource
	// Audit is the audit-logs resource (with sub-resources).
	Audit *AuditResource
	// contains filtered or unexported fields
}

Client is the top-level SDK entry point. Construct it with New. Resource accessors are exposed as fields.

func New

func New(opts ...Option) (*Client, error)

New constructs a Client from functional options and the environment. INVOANCE_API_KEY is required unless WithAPIKey is passed; New returns an error (of kind Validation) when no API key is available.

func (*Client) Me added in v0.2.0

func (c *Client) Me(ctx context.Context) (map[string]any, error)

Me retrieves the authenticated caller's introspection document as an untyped map (GET /me). The response describes the organization, tenant, API key (id, prefix, scopes, ...), and effective limits. The endpoint requires API-key authentication but no scopes.

func (*Client) Validate

func (c *Client) Validate(ctx context.Context) ValidationResult

Validate probes GET /v1/me to confirm the API key works. The endpoint requires no scopes, so keys restricted to e.g. audit:* validate correctly. Validate never returns an error for expected outcomes — every failure mode is folded into the ValidationResult.

type ComplianceEvent

type ComplianceEvent struct {
	EventID         string         `json:"event_id"`
	TenantID        string         `json:"tenant_id"`
	EventType       string         `json:"event_type"`
	Payload         map[string]any `json:"payload"`
	EventTime       *string        `json:"event_time,omitempty"`
	RetentionPolicy string         `json:"retention_policy"`
	// AccessTier is not returned by every endpoint (e.g. the single-event GET omits it).
	AccessTier     *string             `json:"access_tier,omitempty"`
	ExpiresAt      *string             `json:"expires_at,omitempty"`
	APIKeyID       *string             `json:"api_key_id,omitempty"`
	UserID         *string             `json:"user_id,omitempty"`
	IngestedAt     string              `json:"ingested_at"`
	PayloadHash    string              `json:"payload_hash"`
	RequestHash    string              `json:"request_hash"`
	EventHash      string              `json:"event_hash"`
	IdempotencyKey *string             `json:"idempotency_key,omitempty"`
	Organization   *OrganizationPublic `json:"organization,omitempty"`
}

ComplianceEvent is a single compliance event.

type CreateAuditExportParams

type CreateAuditExportParams struct {
	// OrganizationID is the required org id.
	OrganizationID string
	// Format is required: "csv" or "ndjson".
	Format string
	// Filters is an optional filter object.
	Filters map[string]any
}

CreateAuditExportParams are the parameters for Audit.Exports.Create.

type CreateAuditOrgParams

type CreateAuditOrgParams struct {
	// OrganizationID is your external org id (required).
	OrganizationID string
	// Name is an optional display name.
	Name string
}

CreateAuditOrgParams are the parameters for Audit.Orgs.Create.

type CreateAuditStreamParams

type CreateAuditStreamParams struct {
	// URL is the required delivery endpoint.
	URL string
	// Type defaults to "webhook" (v1 supports webhook only).
	Type string
}

CreateAuditStreamParams are the parameters for Audit.Streams.Create.

type CreatePortalSessionParams

type CreatePortalSessionParams struct {
	// OrganizationID is the required org id.
	OrganizationID string
	// Intent is required: "audit_logs" or "log_streams".
	Intent string
	// SessionDurationSeconds is the viewer session length (optional).
	SessionDurationSeconds *int
	// LinkDurationSeconds is the one-time link open window (optional).
	LinkDurationSeconds *int
}

CreatePortalSessionParams are the parameters for Audit.PortalSessions.Create.

type CreateTraceParams

type CreateTraceParams struct {
	// Label is the required human-readable trace label.
	Label string
	// Metadata is optional arbitrary JSON metadata.
	Metadata map[string]any
}

CreateTraceParams are the parameters for Traces.Create.

type CreateTraceResponse

type CreateTraceResponse struct {
	TraceID   string `json:"trace_id"`
	Status    string `json:"status"`
	CreatedAt string `json:"created_at"`
	Label     string `json:"label"`
}

CreateTraceResponse is returned by Traces.Create.

type DeleteTraceResponse

type DeleteTraceResponse struct {
	TraceID string `json:"trace_id"`
	Deleted bool   `json:"deleted"`
}

DeleteTraceResponse is returned by Traces.Delete.

type DocumentEvent

type DocumentEvent struct {
	EventID          string              `json:"event_id"`
	TenantID         string              `json:"tenant_id"`
	DocumentRef      string              `json:"document_ref"`
	DocumentHash     string              `json:"document_hash"`
	SignatureB64     string              `json:"signature_b64"`
	SignedPayloadB64 string              `json:"signed_payload_b64"`
	PublicKeyB64     string              `json:"public_key_b64"`
	HasOriginal      bool                `json:"has_original"`
	Metadata         map[string]any      `json:"metadata,omitempty"`
	CreatedAt        string              `json:"created_at"`
	Organization     *OrganizationPublic `json:"organization,omitempty"`
}

DocumentEvent is a single anchored document.

type DocumentListItem

type DocumentListItem struct {
	EventID      string `json:"event_id"`
	DocumentRef  string `json:"document_ref"`
	DocumentHash string `json:"document_hash"`
	EventType    string `json:"event_type"`
	HasOriginal  bool   `json:"has_original"`
	CreatedAt    string `json:"created_at"`
}

DocumentListItem is one entry in a ListDocumentsResponse.

type DocumentsResource

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

DocumentsResource is the document-anchoring resource (client.Documents).

func (*DocumentsResource) Anchor

Anchor anchors a document hash (POST /document/anchor).

func (*DocumentsResource) AnchorFile

AnchorFile reads a file (Path or Bytes), computes its SHA-256 hash, base64-encodes the bytes (unless SkipOriginal), and calls Anchor.

func (*DocumentsResource) Get

func (r *DocumentsResource) Get(ctx context.Context, eventID string) (DocumentEvent, error)

Get retrieves a single document (GET /document/{eventID}).

func (*DocumentsResource) GetOriginal

func (r *DocumentsResource) GetOriginal(ctx context.Context, eventID string) ([]byte, error)

GetOriginal downloads the original document bytes (GET /document/{eventID}/original).

func (*DocumentsResource) List

List returns a paginated document listing (GET /document).

func (*DocumentsResource) Verify

Verify checks a submitted hash against the anchored document (POST /document/{eventID}/verify).

type Error

type Error struct {
	// Kind classifies the error.
	Kind ErrorKind
	// Message is a human-readable description.
	Message string
	// StatusCode is the HTTP status code, or 0 for client-side / transport
	// errors that never received a response.
	StatusCode int
	// ErrorCode is the server-provided machine code (body["error"]), or "".
	ErrorCode string
	// Body is the parsed JSON error body, when the server returned one.
	Body map[string]any
	// RetryAfterSeconds is populated on 429 responses that carry a
	// Retry-After header.
	RetryAfterSeconds *float64
	// Request identifies the originating request, when known.
	Request *RequestContext
	// contains filtered or unexported fields
}

Error is the single error type returned by every SDK method. Inspect Kind (or use the Is* predicates) to branch on the failure category.

func (*Error) Error

func (e *Error) Error() string

Error implements the error interface.

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap returns the underlying cause, if any, so errors.Is/As can traverse to transport errors.

type ErrorKind

type ErrorKind string

ErrorKind classifies an *Error. Use the Is* predicate helpers to test a returned error's kind through the error chain.

const (
	// KindAuthentication maps to HTTP 401 — bad or missing API key.
	KindAuthentication ErrorKind = "authentication"
	// KindForbidden maps to HTTP 403 — authenticated but not permitted.
	KindForbidden ErrorKind = "forbidden"
	// KindNotFound maps to HTTP 404.
	KindNotFound ErrorKind = "not_found"
	// KindValidation maps to HTTP 400, and is also used for client-side
	// input validation failures raised before a request is sent.
	KindValidation ErrorKind = "validation"
	// KindConflict maps to HTTP 409.
	KindConflict ErrorKind = "conflict"
	// KindQuotaExceeded maps to HTTP 429 — rate limited / quota exceeded.
	KindQuotaExceeded ErrorKind = "quota_exceeded"
	// KindServer maps to any 5xx response.
	KindServer ErrorKind = "server"
	// KindNetwork is a transport failure before a response was received
	// (DNS, connection refused, TLS handshake, etc.).
	KindNetwork ErrorKind = "network"
	// KindTimeout means the request exceeded the configured timeout.
	KindTimeout ErrorKind = "timeout"
	// KindUnknown is any non-2xx status that does not map to a more
	// specific kind (and is below 500).
	KindUnknown ErrorKind = "unknown"
)

type EventListItem

type EventListItem struct {
	EventID         string  `json:"event_id"`
	EventType       string  `json:"event_type"`
	PayloadHash     string  `json:"payload_hash"`
	EventHash       string  `json:"event_hash"`
	RetentionPolicy string  `json:"retention_policy"`
	IngestedAt      string  `json:"ingested_at"`
	EventTime       *string `json:"event_time,omitempty"`
	IdempotencyKey  *string `json:"idempotency_key,omitempty"`
}

EventListItem is one entry in a ListEventsResponse.

type EventsResource

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

EventsResource is the compliance-events resource (client.Events).

func (*EventsResource) Get

func (r *EventsResource) Get(ctx context.Context, eventID string) (ComplianceEvent, error)

Get retrieves a single event (GET /events/{eventID}).

func (*EventsResource) Ingest

Ingest anchors a compliance event (POST /events).

func (*EventsResource) List

List returns a paginated event listing (GET /events).

func (*EventsResource) Verify

func (r *EventsResource) Verify(ctx context.Context, eventID string, params VerifyEventParams) (VerifyEventResponse, error)

Verify checks a submitted hash or payload against the anchored event (POST /events/{eventID}/verify). Passing neither PayloadHash nor Payload returns a client-side validation error.

type GetTraceParams

type GetTraceParams struct {
	// EventPage is the 1-based event page (default 1).
	EventPage *int
	// EventLimit is the max events per page (default 50, max 200).
	EventLimit *int
}

GetTraceParams are the event-pagination parameters for Traces.Get.

type IngestAttestationParams

type IngestAttestationParams struct {
	// Type is the required attestation type (e.g. "output").
	Type string
	// Input is the required model input string.
	Input string
	// Output is the required model output string.
	Output string
	// ModelProvider is the required provider (e.g. "openai").
	ModelProvider string
	// ModelName is the required model name (e.g. "gpt-4o").
	ModelName string
	// ModelVersion is the required model version.
	ModelVersion string
	// Subject optionally identifies who/what triggered the attestation.
	// UserID maps to user_id, SessionID to session_id; Extra keys pass
	// through verbatim. Omitted entirely when empty.
	Subject *AttestationSubject
	// IdempotencyKey is an optional per-call idempotency key.
	IdempotencyKey string
	// TraceID optionally associates the attestation with a trace.
	TraceID string
}

IngestAttestationParams are the parameters for Attestations.Ingest.

type IngestAttestationResponse

type IngestAttestationResponse struct {
	AttestationID string `json:"attestation_id"`
	CreatedAt     string `json:"created_at"`
	InputHash     string `json:"input_hash"`
	OutputHash    string `json:"output_hash"`
	PayloadHash   string `json:"payload_hash"`
	Status        string `json:"status"`
}

IngestAttestationResponse is returned by Attestations.Ingest.

type IngestAuditEventParams

type IngestAuditEventParams struct {
	// OrganizationID is your external org id (required).
	OrganizationID string
	// Action is the required action string.
	Action string
	// Actor is the required actor object.
	Actor map[string]any
	// OccurredAt is an optional RFC3339 UTC timestamp; defaults to now.
	OccurredAt string
	// Targets is the optional list of target objects; defaults to [].
	Targets []map[string]any
	// Context is optional additional context.
	Context map[string]any
	// Metadata is optional metadata.
	Metadata map[string]any
	// IdempotencyKey overrides the derived content idempotency key.
	IdempotencyKey string
}

IngestAuditEventParams are the parameters for Audit.Events.Ingest.

type IngestEventParams

type IngestEventParams struct {
	// EventType is the required event classifier.
	EventType string
	// Payload is the required JSON object payload.
	Payload map[string]any
	// EventTime is an optional caller-supplied timestamp (RFC3339). Omitted
	// when empty.
	EventTime string
	// IdempotencyKey is an optional per-call idempotency key.
	IdempotencyKey string
	// TraceID optionally associates the event with a trace. Omitted when empty.
	TraceID string
}

IngestEventParams are the parameters for Events.Ingest.

type IngestEventResponse

type IngestEventResponse struct {
	EventID    string `json:"event_id"`
	IngestedAt string `json:"ingested_at"`
}

IngestEventResponse is returned by Events.Ingest.

type ListAttestationsParams

type ListAttestationsParams struct {
	Page            *int
	Limit           *int
	DateFrom        string
	DateTo          string
	AttestationType string
	ModelProvider   string
}

ListAttestationsParams are the query parameters for Attestations.List.

type ListAttestationsResponse

type ListAttestationsResponse struct {
	Attestations []AttestationListItem `json:"attestations"`
	Page         int                   `json:"page"`
	Limit        int                   `json:"limit"`
	Total        int                   `json:"total"`
	HasMore      bool                  `json:"has_more"`
}

ListAttestationsResponse is a paginated attestation listing.

type ListAuditEventsParams

type ListAuditEventsParams struct {
	OrganizationID string
	Actions        string
	ActorID        string
	TargetID       string
	// RangeStart and RangeEnd are inclusive RFC3339 bounds on occurred_at.
	RangeStart string
	RangeEnd   string
	Limit      *int
	Cursor     string
}

ListAuditEventsParams are the query parameters for Audit.Events.List.

type ListAuditEventsResponse

type ListAuditEventsResponse struct {
	Events     []AuditEvent `json:"events"`
	NextCursor *string      `json:"next_cursor"`
}

ListAuditEventsResponse is a keyset-paginated audit listing.

type ListAuditOrgsParams added in v0.2.0

type ListAuditOrgsParams struct {
	// IncludeArchived includes archived orgs in the listing; archived orgs
	// are excluded by default.
	IncludeArchived bool
}

ListAuditOrgsParams are the query parameters for Audit.Orgs.List.

type ListDocumentsParams

type ListDocumentsParams struct {
	Page        *int
	Limit       *int
	DateFrom    string
	DateTo      string
	DocumentRef string
}

ListDocumentsParams are the query parameters for Documents.List.

type ListDocumentsResponse

type ListDocumentsResponse struct {
	Documents []DocumentListItem `json:"documents"`
	Page      int                `json:"page"`
	Limit     int                `json:"limit"`
	Total     int                `json:"total"`
	HasMore   bool               `json:"has_more"`
}

ListDocumentsResponse is a paginated document listing.

type ListEventsParams

type ListEventsParams struct {
	Page      *int
	Limit     *int
	DateFrom  string
	DateTo    string
	EventType string
}

ListEventsParams are the query parameters for Events.List.

type ListEventsResponse

type ListEventsResponse struct {
	Events  []EventListItem `json:"events"`
	Page    int             `json:"page"`
	Limit   int             `json:"limit"`
	Total   int             `json:"total"`
	HasMore bool            `json:"has_more"`
}

ListEventsResponse is a paginated event listing.

type ListTracesParams

type ListTracesParams struct {
	Page  *int
	Limit *int
	// Status filters by "open" or "sealed"; empty means no filter.
	Status string
}

ListTracesParams are the query parameters for Traces.List.

type ListTracesResponse

type ListTracesResponse struct {
	Traces  []TraceListItem `json:"traces"`
	Page    int             `json:"page"`
	Limit   int             `json:"limit"`
	Total   int             `json:"total"`
	HasMore bool            `json:"has_more"`
}

ListTracesResponse is a paginated trace listing.

type Option

type Option func(*config)

Option configures a Client. Options are applied in order by New.

func WithAPIKey

func WithAPIKey(key string) Option

WithAPIKey sets the API key explicitly, overriding INVOANCE_API_KEY.

func WithAPIVersion

func WithAPIVersion(version string) Option

WithAPIVersion sets the API version prefix (default "v1"). Surrounding slashes are stripped. The prefix is prepended to every request path.

func WithBaseURL

func WithBaseURL(url string) Option

WithBaseURL overrides the API host (default https://api.invoance.com, or the INVOANCE_BASE_URL environment variable). Trailing slashes are stripped.

func WithExtraHeaders

func WithExtraHeaders(headers map[string]string) Option

WithExtraHeaders merges additional headers into every request.

func WithHTTPClient

func WithHTTPClient(client *http.Client) Option

WithHTTPClient supplies a custom *http.Client. When set, its Timeout is used as-is and WithTimeout is ignored for that client.

func WithIdempotencyKey

func WithIdempotencyKey(key string) Option

WithIdempotencyKey sets a default Idempotency-Key sent with every mutating request. A per-call idempotency key overrides this default.

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout sets the per-request timeout (default 30s).

type OrganizationPublic

type OrganizationPublic struct {
	Name             string  `json:"name"`
	IssuerName       string  `json:"issuer_name"`
	PrimaryDomain    string  `json:"primary_domain"`
	DomainVerified   bool    `json:"domain_verified"`
	DomainVerifiedAt *string `json:"domain_verified_at,omitempty"`
	LogoURL          *string `json:"logo_url,omitempty"`
}

OrganizationPublic is the tenant-org descriptor embedded in some responses.

type RequestContext

type RequestContext struct {
	Method string
	Path   string
}

RequestContext identifies the request that produced an error.

type SealTraceResponse

type SealTraceResponse struct {
	TraceID string `json:"trace_id"`
	Status  string `json:"status"`
	Message string `json:"message"`
}

SealTraceResponse is returned by Traces.Seal.

type SignatureVerificationResult

type SignatureVerificationResult struct {
	// Valid reports whether the signature is valid.
	Valid bool
	// Reason is a human-readable reason when invalid; empty when valid.
	Reason string
	// Attestation is the record that was verified.
	Attestation AiAttestation
	// SignedData is the parsed JSON covered by the signature, or nil.
	SignedData map[string]any
}

SignatureVerificationResult is the result of client-side Ed25519 signature verification via Attestations.VerifySignature.

type TraceDetail

type TraceDetail struct {
	TraceID       string              `json:"trace_id"`
	Label         string              `json:"label"`
	Status        string              `json:"status"`
	EventCount    *int                `json:"event_count"`
	CreatedAt     string              `json:"created_at"`
	SealedAt      *string             `json:"sealed_at"`
	CompositeHash *string             `json:"composite_hash"`
	SealEventID   *string             `json:"seal_event_id"`
	Metadata      map[string]any      `json:"metadata,omitempty"`
	Events        []TraceEventSummary `json:"events"`
	EventPage     int                 `json:"event_page"`
	EventLimit    int                 `json:"event_limit"`
	EventTotal    int                 `json:"event_total"`
	EventHasMore  bool                `json:"event_has_more"`
}

TraceDetail is a trace with paginated event summaries.

type TraceEventSummary

type TraceEventSummary struct {
	EventID     string `json:"event_id"`
	EventType   string `json:"event_type"`
	PayloadHash string `json:"payload_hash"`
	IngestedAt  string `json:"ingested_at"`
}

TraceEventSummary is a summary of an event in a trace.

type TraceListItem

type TraceListItem struct {
	TraceID       string  `json:"trace_id"`
	Label         string  `json:"label"`
	Status        string  `json:"status"`
	EventCount    *int    `json:"event_count"`
	CreatedAt     string  `json:"created_at"`
	SealedAt      *string `json:"sealed_at"`
	CompositeHash *string `json:"composite_hash"`
}

TraceListItem is one entry in a ListTracesResponse.

type TraceProofBundle

type TraceProofBundle struct {
	Version       string                 `json:"version"`
	TraceID       string                 `json:"trace_id"`
	Label         string                 `json:"label"`
	TenantDomain  string                 `json:"tenant_domain"`
	Status        string                 `json:"status"`
	CreatedAt     string                 `json:"created_at"`
	SealedAt      string                 `json:"sealed_at"`
	CompositeHash string                 `json:"composite_hash"`
	EventCount    int                    `json:"event_count"`
	Events        []TraceProofEvent      `json:"events"`
	SealEvent     TraceProofSealEvent    `json:"seal_event"`
	Verification  TraceProofVerification `json:"verification"`
}

TraceProofBundle is an exported proof bundle for a sealed trace.

type TraceProofEvent

type TraceProofEvent struct {
	EventID     string         `json:"event_id"`
	EventType   string         `json:"event_type"`
	Payload     map[string]any `json:"payload"`
	ContentHash string         `json:"content_hash"`
	Timestamp   string         `json:"timestamp"`
	Signature   string         `json:"signature"`
	PublicKey   string         `json:"public_key"`
}

TraceProofEvent is a full event within a proof bundle.

type TraceProofSealEvent

type TraceProofSealEvent struct {
	EventID     string `json:"event_id"`
	EventType   string `json:"event_type"`
	ContentHash string `json:"content_hash"`
	Timestamp   string `json:"timestamp"`
	Signature   string `json:"signature"`
	PublicKey   string `json:"public_key"`
}

TraceProofSealEvent is the seal event within a proof bundle.

type TraceProofVerification

type TraceProofVerification struct {
	CompositeHashValid bool `json:"composite_hash_valid"`
	AllSignaturesValid bool `json:"all_signatures_valid"`
}

TraceProofVerification carries the server's verification summary.

type TracesResource

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

TracesResource is the traces resource (client.Traces).

func (*TracesResource) Create

Create creates a new trace (POST /traces).

func (*TracesResource) Delete

func (r *TracesResource) Delete(ctx context.Context, traceID string) (DeleteTraceResponse, error)

Delete deletes an empty open trace (DELETE /traces/{traceID}).

func (*TracesResource) Get

func (r *TracesResource) Get(ctx context.Context, traceID string, params GetTraceParams) (TraceDetail, error)

Get retrieves trace detail with paginated events (GET /traces/{traceID}).

func (*TracesResource) List

List returns a paginated trace listing (GET /traces).

func (*TracesResource) Proof

func (r *TracesResource) Proof(ctx context.Context, traceID string) (TraceProofBundle, error)

Proof exports the proof bundle as JSON, for sealed traces only (GET /traces/{traceID}/proof).

func (*TracesResource) ProofPDF

func (r *TracesResource) ProofPDF(ctx context.Context, traceID string) ([]byte, error)

ProofPDF downloads the proof bundle as a PDF, for sealed traces only (GET /traces/{traceID}/proof/pdf).

func (*TracesResource) Seal

func (r *TracesResource) Seal(ctx context.Context, traceID string) (SealTraceResponse, error)

Seal seals a trace asynchronously (POST /traces/{traceID}/seal). The server responds with 202.

type UpdateAuditOrgParams added in v0.2.0

type UpdateAuditOrgParams struct {
	// Name is the new display name. A nil Name sends JSON null, which clears
	// the stored name.
	Name *string
}

UpdateAuditOrgParams are the parameters for Audit.Orgs.Update.

type ValidationResult

type ValidationResult struct {
	Valid   bool
	Reason  string
	BaseURL string
}

ValidationResult is the outcome of Client.Validate.

Valid == true means the API key was accepted by the server (2xx, 403, or 429 — 403 and 429 still prove the key authenticated). Valid == false means the key was rejected, or the request never reached the server.

type VerifyAttestationParams

type VerifyAttestationParams struct {
	// ContentHash is the 64-char lowercase hex SHA-256 digest to check.
	ContentHash string
}

VerifyAttestationParams are the parameters for Attestations.Verify.

type VerifyAttestationResponse

type VerifyAttestationResponse struct {
	AttestationID string              `json:"attestation_id"`
	MatchResult   bool                `json:"match_result"`
	MatchedField  *string             `json:"matched_field,omitempty"`
	AnchoredHash  string              `json:"anchored_hash"`
	SubmittedHash string              `json:"submitted_hash"`
	AnchoredAt    string              `json:"anchored_at"`
	Organization  *OrganizationPublic `json:"organization,omitempty"`
}

VerifyAttestationResponse is returned by Attestations.Verify.

type VerifyDocumentParams

type VerifyDocumentParams struct {
	// DocumentHash is the 64-char lowercase hex SHA-256 digest to check.
	DocumentHash string
}

VerifyDocumentParams are the parameters for Documents.Verify.

type VerifyDocumentResponse

type VerifyDocumentResponse struct {
	EventID       string              `json:"event_id"`
	MatchResult   bool                `json:"match_result"`
	DocumentRef   string              `json:"document_ref"`
	AnchoredHash  string              `json:"anchored_hash"`
	SubmittedHash string              `json:"submitted_hash"`
	AnchoredAt    string              `json:"anchored_at"`
	Organization  *OrganizationPublic `json:"organization,omitempty"`
}

VerifyDocumentResponse is returned by Documents.Verify.

type VerifyEventParams

type VerifyEventParams struct {
	// PayloadHash is a 64-char lowercase hex SHA-256 digest.
	PayloadHash string
	// Payload is a raw JSON object the server canonicalizes and hashes.
	Payload map[string]any
}

VerifyEventParams are the parameters for Events.Verify. Provide exactly one of PayloadHash (hex SHA-256) or Payload.

type VerifyEventResponse

type VerifyEventResponse struct {
	EventID       string              `json:"event_id"`
	MatchResult   bool                `json:"match_result"`
	MatchedField  *string             `json:"matched_field,omitempty"`
	AnchoredHash  string              `json:"anchored_hash"`
	SubmittedHash string              `json:"submitted_hash"`
	AnchoredAt    string              `json:"anchored_at"`
	Method        string              `json:"method"`
	Organization  *OrganizationPublic `json:"organization,omitempty"`
}

VerifyEventResponse is returned by Events.Verify.

Directories

Path Synopsis
examples
attestations command
Command attestations ingests an AI attestation and verifies its signature offline.
Command attestations ingests an AI attestation and verifies its signature offline.
audit command
Command audit registers an org, appends a signed audit event, and verifies the returned event offline.
Command audit registers an org, appends a signed audit event, and verifies the returned event offline.
documents command
Command documents anchors a document by its hash and verifies it.
Command documents anchors a document by its hash and verifies it.
quickstart command
Command quickstart shows the core Invoance SDK flow: validate the key, ingest an event, and read it back.
Command quickstart shows the core Invoance SDK flow: validate the key, ingest an event, and read it back.
traces command
Command traces creates a trace, attaches an event, seals it, and exports the proof bundle.
Command traces creates a trace, attaches an event, seals it, and exports the proof bundle.

Jump to

Keyboard shortcuts

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