grantex

package module
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Mar 1, 2026 License: Apache-2.0 Imports: 17 Imported by: 0

README

Grantex Go SDK

Official Go SDK for the Grantex delegated authorization protocol — OAuth 2.0 for AI agents.

Installation

go get github.com/mishrasanjeev/grantex-go

Quick Start

package main

import (
    "context"
    "fmt"
    "log"

    grantex "github.com/mishrasanjeev/grantex-go"
)

func main() {
    ctx := context.Background()
    client := grantex.NewClient("your-api-key")

    // Register an agent
    agent, err := client.Agents.Register(ctx, grantex.RegisterAgentParams{
        Name:        "Email Assistant",
        Description: "Reads and sends emails on behalf of users",
        Scopes:      []string{"read:email", "send:email"},
    })
    if err != nil {
        log.Fatal(err)
    }

    // Create authorization request
    authReq, err := client.Authorize(ctx, grantex.AuthorizeParams{
        AgentID:     agent.ID,
        PrincipalID: "user-123",
        Scopes:      []string{"read:email", "send:email"},
    })
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Send user to: %s\n", authReq.ConsentURL)

    // Exchange code for token (after user consents)
    tokenResp, err := client.Tokens.Exchange(ctx, grantex.ExchangeTokenParams{
        Code:    "authorization-code",
        AgentID: agent.ID,
    })
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Grant token: %s\n", tokenResp.GrantToken)
}

Configuration

client := grantex.NewClient("api-key",
    grantex.WithBaseURL("https://your-instance.example.com"),
    grantex.WithTimeout(60 * time.Second),
    grantex.WithHTTPClient(customClient),
)

Available Resources

Service Methods
client.Agents Register, Get, List, Update, Delete
client.Tokens Exchange, Refresh, Verify, Revoke
client.Grants Get, List, Revoke, Delegate
client.Audit Log, List, Get
client.Webhooks Create, List, Delete
client.Billing GetSubscription, CreateCheckout, CreatePortal
client.Policies Create, List, Get, Update, Delete
client.Compliance GetSummary, ExportGrants, ExportAudit, EvidencePack
client.Anomalies Detect, List, Acknowledge
client.SCIM CreateToken, ListTokens, RevokeToken, ListUsers, GetUser, CreateUser, ReplaceUser, UpdateUser, DeleteUser
client.SSO CreateConfig, GetConfig, DeleteConfig, GetLoginURL, HandleCallback
client.PrincipalSessions Create

Standalone Functions

// Offline JWT verification
grant, err := grantex.VerifyGrantToken(ctx, token, grantex.VerifyOptions{
    JwksURI:        "https://api.grantex.dev/.well-known/jwks.json",
    RequiredScopes: []string{"read:email"},
})

// PKCE challenge generation
pkce, err := grantex.GeneratePKCE()

// Webhook signature verification
valid := grantex.VerifyWebhookSignature(payload, signature, secret)

// Developer signup (no API key needed)
resp, err := grantex.Signup(ctx, grantex.SignupParams{Name: "My App"})

Error Handling

agent, err := client.Agents.Get(ctx, "id")
if err != nil {
    switch e := err.(type) {
    case *grantex.AuthError:
        // 401/403
    case *grantex.APIError:
        // Other HTTP errors
    case *grantex.NetworkError:
        // Connection/timeout
    case *grantex.TokenError:
        // JWT verification errors
    }
}

Documentation

Full documentation at grantex.dev/docs.

License

Apache 2.0

Documentation

Overview

Package grantex provides a Go SDK for the Grantex delegated authorization protocol.

Create a client with NewClient and use its resource services (Agents, Tokens, Grants, etc.) to interact with the Grantex API.

client := grantex.NewClient("your-api-key")
agent, err := client.Agents.Register(ctx, grantex.RegisterAgentParams{
    Name:        "My Agent",
    Description: "An AI assistant",
    Scopes:      []string{"read:email", "send:email"},
})

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func VerifyWebhookSignature

func VerifyWebhookSignature(payload []byte, signature string, secret string) bool

VerifyWebhookSignature verifies an HMAC-SHA256 webhook signature. The signature should be in "sha256=<hex>" format.

Types

type APIError

type APIError struct {
	StatusCode int
	Body       json.RawMessage
	Code       string
	RequestID  string
	Message    string
	RateLimit  *RateLimit
}

APIError represents a non-2xx HTTP response from the Grantex API.

func (*APIError) Error

func (e *APIError) Error() string

type Agent

type Agent struct {
	ID          string   `json:"id"`
	DID         string   `json:"did"`
	Name        string   `json:"name"`
	Description string   `json:"description"`
	Scopes      []string `json:"scopes"`
	Status      string   `json:"status"`
	DeveloperID string   `json:"developerId"`
	CreatedAt   string   `json:"createdAt"`
	UpdatedAt   string   `json:"updatedAt"`
}

Agent represents a registered agent.

type AgentsService

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

AgentsService handles agent registration and management.

func (*AgentsService) Delete

func (s *AgentsService) Delete(ctx context.Context, agentID string) error

Delete removes an agent.

func (*AgentsService) Get

func (s *AgentsService) Get(ctx context.Context, agentID string) (*Agent, error)

Get retrieves an agent by ID.

func (*AgentsService) List

List retrieves all agents for the current developer.

func (*AgentsService) Register

func (s *AgentsService) Register(ctx context.Context, params RegisterAgentParams) (*Agent, error)

Register creates a new agent.

func (*AgentsService) Update

func (s *AgentsService) Update(ctx context.Context, agentID string, params UpdateAgentParams) (*Agent, error)

Update modifies an existing agent.

type AnomaliesService

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

AnomaliesService handles anomaly detection and management.

func (*AnomaliesService) Acknowledge

func (s *AnomaliesService) Acknowledge(ctx context.Context, anomalyID string) (*Anomaly, error)

Acknowledge marks an anomaly as acknowledged.

func (*AnomaliesService) Detect

Detect triggers anomaly detection and returns results.

func (*AnomaliesService) List

List retrieves anomalies with optional filters.

type Anomaly

type Anomaly struct {
	ID             string                 `json:"id"`
	Type           string                 `json:"type"`
	Severity       string                 `json:"severity"`
	AgentID        *string                `json:"agentId"`
	PrincipalID    *string                `json:"principalId"`
	Description    string                 `json:"description"`
	Metadata       map[string]interface{} `json:"metadata"`
	DetectedAt     string                 `json:"detectedAt"`
	AcknowledgedAt *string                `json:"acknowledgedAt"`
}

Anomaly represents a detected anomaly.

type AuditEntry

type AuditEntry struct {
	EntryID     string                 `json:"entryId"`
	AgentID     string                 `json:"agentId"`
	AgentDID    string                 `json:"agentDid"`
	GrantID     string                 `json:"grantId"`
	PrincipalID string                 `json:"principalId"`
	Action      string                 `json:"action"`
	Metadata    map[string]interface{} `json:"metadata"`
	Hash        string                 `json:"hash"`
	PrevHash    *string                `json:"prevHash"`
	Timestamp   string                 `json:"timestamp"`
	Status      string                 `json:"status"`
}

AuditEntry represents an audit log entry.

type AuditService

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

AuditService handles audit logging and retrieval.

func (*AuditService) Get

func (s *AuditService) Get(ctx context.Context, entryID string) (*AuditEntry, error)

Get retrieves a single audit entry by ID.

func (*AuditService) List

List retrieves audit log entries with optional filters.

func (*AuditService) Log

func (s *AuditService) Log(ctx context.Context, params LogAuditParams) (*AuditEntry, error)

Log creates an audit log entry.

type AuthError

type AuthError struct {
	*APIError
}

AuthError represents a 401 or 403 response.

func (*AuthError) Error

func (e *AuthError) Error() string

type AuthorizationRequest

type AuthorizationRequest struct {
	AuthRequestID string   `json:"authRequestId"`
	ConsentURL    string   `json:"consentUrl"`
	AgentID       string   `json:"agentId"`
	PrincipalID   string   `json:"principalId"`
	Scopes        []string `json:"scopes"`
	ExpiresIn     string   `json:"expiresIn"`
	ExpiresAt     string   `json:"expiresAt"`
	Status        string   `json:"status"`
	CreatedAt     string   `json:"createdAt"`
}

AuthorizationRequest is the response from creating an authorization request.

type AuthorizeParams

type AuthorizeParams struct {
	AgentID             string   `json:"agentId"`
	PrincipalID         string   `json:"principalId"`
	Scopes              []string `json:"scopes"`
	ExpiresIn           string   `json:"expiresIn,omitempty"`
	RedirectURI         string   `json:"redirectUri,omitempty"`
	CodeChallenge       string   `json:"codeChallenge,omitempty"`
	CodeChallengeMethod string   `json:"codeChallengeMethod,omitempty"`
}

AuthorizeParams are the parameters for creating an authorization request.

type BillingService

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

BillingService handles subscription and billing operations.

func (*BillingService) CreateCheckout

func (s *BillingService) CreateCheckout(ctx context.Context, params CreateCheckoutParams) (*CheckoutResponse, error)

CreateCheckout creates a checkout session for upgrading.

func (*BillingService) CreatePortal

func (s *BillingService) CreatePortal(ctx context.Context, params CreatePortalParams) (*PortalResponse, error)

CreatePortal creates a billing portal session.

func (*BillingService) GetSubscription

func (s *BillingService) GetSubscription(ctx context.Context) (*SubscriptionStatus, error)

GetSubscription retrieves the current subscription status.

type ChainIntegrity

type ChainIntegrity struct {
	Valid          bool    `json:"valid"`
	CheckedEntries int     `json:"checkedEntries"`
	FirstBrokenAt  *string `json:"firstBrokenAt"`
}

ChainIntegrity represents audit chain integrity check results.

type CheckoutResponse

type CheckoutResponse struct {
	CheckoutURL string `json:"checkoutUrl"`
}

CheckoutResponse is the response from creating a checkout.

type Client

type Client struct {
	Agents            *AgentsService
	Tokens            *TokensService
	Grants            *GrantsService
	Audit             *AuditService
	Webhooks          *WebhooksService
	Billing           *BillingService
	Policies          *PoliciesService
	Compliance        *ComplianceService
	Anomalies         *AnomaliesService
	SCIM              *SCIMService
	SSO               *SSOService
	PrincipalSessions *PrincipalSessionsService
	// contains filtered or unexported fields
}

Client is the main entry point for the Grantex SDK.

func NewClient

func NewClient(apiKey string, opts ...Option) *Client

NewClient creates a new Grantex API client.

func (*Client) Authorize

func (c *Client) Authorize(ctx context.Context, params AuthorizeParams) (*AuthorizationRequest, error)

Authorize creates an authorization request for a user to grant permissions to an agent.

func (*Client) LastRateLimit added in v0.1.1

func (c *Client) LastRateLimit() *RateLimit

LastRateLimit returns the rate limit metadata from the most recent API response, or nil if unavailable.

func (*Client) RotateKey

func (c *Client) RotateKey(ctx context.Context) (*RotateKeyResponse, error)

RotateKey rotates the developer API key.

type ComplianceAuditExport

type ComplianceAuditExport struct {
	GeneratedAt string       `json:"generatedAt"`
	Total       int          `json:"total"`
	Entries     []AuditEntry `json:"entries"`
}

ComplianceAuditExport is the exported audit data.

type ComplianceExportAuditParams

type ComplianceExportAuditParams struct {
	Since   string `json:"since,omitempty"`
	Until   string `json:"until,omitempty"`
	AgentID string `json:"agentId,omitempty"`
	Status  string `json:"status,omitempty"`
}

ComplianceExportAuditParams are the parameters for exporting audit entries.

type ComplianceExportGrantsParams

type ComplianceExportGrantsParams struct {
	Since  string `json:"since,omitempty"`
	Until  string `json:"until,omitempty"`
	Status string `json:"status,omitempty"`
}

ComplianceExportGrantsParams are the parameters for exporting grants.

type ComplianceGrantsExport

type ComplianceGrantsExport struct {
	GeneratedAt string  `json:"generatedAt"`
	Total       int     `json:"total"`
	Grants      []Grant `json:"grants"`
}

ComplianceGrantsExport is the exported grants data.

type ComplianceService

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

ComplianceService handles compliance reporting and evidence exports.

func (*ComplianceService) EvidencePack

func (s *ComplianceService) EvidencePack(ctx context.Context, params *EvidencePackParams) (*EvidencePack, error)

EvidencePack generates a compliance evidence package.

func (*ComplianceService) ExportAudit

ExportAudit exports audit data for compliance.

func (*ComplianceService) ExportGrants

ExportGrants exports grants data for compliance.

func (*ComplianceService) GetSummary

GetSummary retrieves a compliance summary.

type ComplianceSummary

type ComplianceSummary struct {
	GeneratedAt  string                        `json:"generatedAt"`
	Since        *string                       `json:"since,omitempty"`
	Until        *string                       `json:"until,omitempty"`
	Agents       ComplianceSummaryAgents       `json:"agents"`
	Grants       ComplianceSummaryGrants       `json:"grants"`
	AuditEntries ComplianceSummaryAuditEntries `json:"auditEntries"`
	Policies     ComplianceSummaryPolicies     `json:"policies"`
	Plan         string                        `json:"plan"`
}

ComplianceSummary is the compliance overview.

type ComplianceSummaryAgents

type ComplianceSummaryAgents struct {
	Total     int `json:"total"`
	Active    int `json:"active"`
	Suspended int `json:"suspended"`
	Revoked   int `json:"revoked"`
}

ComplianceSummaryAgents is agent stats in a compliance summary.

type ComplianceSummaryAuditEntries

type ComplianceSummaryAuditEntries struct {
	Total   int `json:"total"`
	Success int `json:"success"`
	Failure int `json:"failure"`
	Blocked int `json:"blocked"`
}

ComplianceSummaryAuditEntries is audit stats in a compliance summary.

type ComplianceSummaryGrants

type ComplianceSummaryGrants struct {
	Total   int `json:"total"`
	Active  int `json:"active"`
	Revoked int `json:"revoked"`
	Expired int `json:"expired"`
}

ComplianceSummaryGrants is grant stats in a compliance summary.

type ComplianceSummaryParams

type ComplianceSummaryParams struct {
	Since string `json:"since,omitempty"`
	Until string `json:"until,omitempty"`
}

ComplianceSummaryParams are the parameters for getting a compliance summary.

type ComplianceSummaryPolicies

type ComplianceSummaryPolicies struct {
	Total int `json:"total"`
}

ComplianceSummaryPolicies is policy stats in a compliance summary.

type CreateCheckoutParams

type CreateCheckoutParams struct {
	Plan       string `json:"plan"`
	SuccessURL string `json:"successUrl"`
	CancelURL  string `json:"cancelUrl"`
}

CreateCheckoutParams are the parameters for creating a checkout session.

type CreatePolicyParams

type CreatePolicyParams struct {
	Name           string   `json:"name"`
	Effect         string   `json:"effect"`
	Priority       *int     `json:"priority,omitempty"`
	AgentID        string   `json:"agentId,omitempty"`
	PrincipalID    string   `json:"principalId,omitempty"`
	Scopes         []string `json:"scopes,omitempty"`
	TimeOfDayStart string   `json:"timeOfDayStart,omitempty"`
	TimeOfDayEnd   string   `json:"timeOfDayEnd,omitempty"`
}

CreatePolicyParams are the parameters for creating a policy.

type CreatePortalParams

type CreatePortalParams struct {
	ReturnURL string `json:"returnUrl"`
}

CreatePortalParams are the parameters for creating a billing portal session.

type CreatePrincipalSessionParams

type CreatePrincipalSessionParams struct {
	PrincipalID string `json:"principalId"`
	ExpiresIn   string `json:"expiresIn,omitempty"`
}

CreatePrincipalSessionParams are the parameters for creating a principal session.

type CreateScimTokenParams

type CreateScimTokenParams struct {
	Label string `json:"label"`
}

CreateScimTokenParams are the parameters for creating a SCIM token.

type CreateScimUserParams

type CreateScimUserParams struct {
	UserName    string      `json:"userName"`
	DisplayName string      `json:"displayName,omitempty"`
	ExternalID  string      `json:"externalId,omitempty"`
	Emails      []ScimEmail `json:"emails,omitempty"`
	Active      *bool       `json:"active,omitempty"`
}

CreateScimUserParams are the parameters for creating a SCIM user.

type CreateSsoConfigParams

type CreateSsoConfigParams struct {
	IssuerURL    string `json:"issuerUrl"`
	ClientID     string `json:"clientId"`
	ClientSecret string `json:"clientSecret"`
	RedirectURI  string `json:"redirectUri"`
}

CreateSsoConfigParams are the parameters for creating an SSO configuration.

type CreateWebhookParams

type CreateWebhookParams struct {
	URL    string   `json:"url"`
	Events []string `json:"events"`
}

CreateWebhookParams are the parameters for creating a webhook.

type DelegateParams

type DelegateParams struct {
	ParentGrantToken string   `json:"parentGrantToken"`
	SubAgentID       string   `json:"subAgentId"`
	Scopes           []string `json:"scopes"`
	ExpiresIn        string   `json:"expiresIn,omitempty"`
}

DelegateParams are the parameters for grant delegation.

type DelegateResponse

type DelegateResponse struct {
	GrantToken string   `json:"grantToken"`
	ExpiresAt  string   `json:"expiresAt"`
	Scopes     []string `json:"scopes"`
	GrantID    string   `json:"grantId"`
}

DelegateResponse is the response from grant delegation.

type DetectAnomaliesResponse

type DetectAnomaliesResponse struct {
	DetectedAt string    `json:"detectedAt"`
	Total      int       `json:"total"`
	Anomalies  []Anomaly `json:"anomalies"`
}

DetectAnomaliesResponse is the response from anomaly detection.

type EvidencePack

type EvidencePack struct {
	Meta           EvidencePackMeta  `json:"meta"`
	Summary        ComplianceSummary `json:"summary"`
	Grants         []Grant           `json:"grants"`
	AuditEntries   []AuditEntry      `json:"auditEntries"`
	Policies       []Policy          `json:"policies"`
	ChainIntegrity ChainIntegrity    `json:"chainIntegrity"`
}

EvidencePack is a compliance evidence package.

type EvidencePackMeta

type EvidencePackMeta struct {
	SchemaVersion string  `json:"schemaVersion"`
	GeneratedAt   string  `json:"generatedAt"`
	Since         *string `json:"since,omitempty"`
	Until         *string `json:"until,omitempty"`
	Framework     string  `json:"framework"`
}

EvidencePackMeta is metadata for an evidence pack.

type EvidencePackParams

type EvidencePackParams struct {
	Since     string `json:"since,omitempty"`
	Until     string `json:"until,omitempty"`
	Framework string `json:"framework,omitempty"`
}

EvidencePackParams are the parameters for generating an evidence pack.

type ExchangeTokenParams

type ExchangeTokenParams struct {
	Code         string `json:"code"`
	AgentID      string `json:"agentId"`
	CodeVerifier string `json:"codeVerifier,omitempty"`
}

ExchangeTokenParams are the parameters for exchanging an authorization code.

type ExchangeTokenResponse

type ExchangeTokenResponse struct {
	GrantToken   string   `json:"grantToken"`
	ExpiresAt    string   `json:"expiresAt"`
	Scopes       []string `json:"scopes"`
	RefreshToken string   `json:"refreshToken"`
	GrantID      string   `json:"grantId"`
}

ExchangeTokenResponse is the response from token exchange or refresh.

type Grant

type Grant struct {
	ID          string   `json:"grantId"`
	AgentID     string   `json:"agentId"`
	AgentDID    string   `json:"agentDid"`
	PrincipalID string   `json:"principalId"`
	DeveloperID string   `json:"developerId"`
	Scopes      []string `json:"scopes"`
	Status      string   `json:"status"`
	IssuedAt    string   `json:"issuedAt"`
	ExpiresAt   string   `json:"expiresAt"`
	RevokedAt   *string  `json:"revokedAt,omitempty"`
}

Grant represents an authorization grant.

type GrantsService

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

GrantsService handles grant management and delegation.

func (*GrantsService) Delegate

func (s *GrantsService) Delegate(ctx context.Context, params DelegateParams) (*DelegateResponse, error)

Delegate creates a delegated grant for a sub-agent.

func (*GrantsService) Get

func (s *GrantsService) Get(ctx context.Context, grantID string) (*Grant, error)

Get retrieves a grant by ID.

func (*GrantsService) List

List retrieves grants with optional filters.

func (*GrantsService) Revoke

func (s *GrantsService) Revoke(ctx context.Context, grantID string) error

Revoke revokes a grant by ID.

type ListAgentsResponse

type ListAgentsResponse struct {
	Agents   []Agent `json:"agents"`
	Total    int     `json:"total"`
	Page     int     `json:"page"`
	PageSize int     `json:"pageSize"`
}

ListAgentsResponse is the response from listing agents.

type ListAnomaliesParams

type ListAnomaliesParams struct {
	Unacknowledged *bool `json:"unacknowledged,omitempty"`
}

ListAnomaliesParams are the parameters for listing anomalies.

type ListAnomaliesResponse

type ListAnomaliesResponse struct {
	Anomalies []Anomaly `json:"anomalies"`
	Total     int       `json:"total"`
}

ListAnomaliesResponse is the response from listing anomalies.

type ListAuditParams

type ListAuditParams struct {
	AgentID     string `json:"agentId,omitempty"`
	GrantID     string `json:"grantId,omitempty"`
	PrincipalID string `json:"principalId,omitempty"`
	Action      string `json:"action,omitempty"`
	Since       string `json:"since,omitempty"`
	Until       string `json:"until,omitempty"`
	Page        int    `json:"page,omitempty"`
	PageSize    int    `json:"pageSize,omitempty"`
}

ListAuditParams are the parameters for listing audit entries.

type ListAuditResponse

type ListAuditResponse struct {
	Entries  []AuditEntry `json:"entries"`
	Total    int          `json:"total"`
	Page     int          `json:"page"`
	PageSize int          `json:"pageSize"`
}

ListAuditResponse is the response from listing audit entries.

type ListGrantsParams

type ListGrantsParams struct {
	AgentID     string `json:"agentId,omitempty"`
	PrincipalID string `json:"principalId,omitempty"`
	Status      string `json:"status,omitempty"`
	Page        int    `json:"page,omitempty"`
	PageSize    int    `json:"pageSize,omitempty"`
}

ListGrantsParams are the parameters for listing grants.

type ListGrantsResponse

type ListGrantsResponse struct {
	Grants   []Grant `json:"grants"`
	Total    int     `json:"total"`
	Page     int     `json:"page"`
	PageSize int     `json:"pageSize"`
}

ListGrantsResponse is the response from listing grants.

type ListPoliciesResponse

type ListPoliciesResponse struct {
	Policies []Policy `json:"policies"`
	Total    int      `json:"total"`
}

ListPoliciesResponse is the response from listing policies.

type ListScimTokensResponse

type ListScimTokensResponse struct {
	Tokens []ScimToken `json:"tokens"`
}

ListScimTokensResponse is the response from listing SCIM tokens.

type ListScimUsersParams

type ListScimUsersParams struct {
	StartIndex int `json:"startIndex,omitempty"`
	Count      int `json:"count,omitempty"`
}

ListScimUsersParams are the parameters for listing SCIM users.

type ListWebhooksResponse

type ListWebhooksResponse struct {
	Webhooks []WebhookEndpoint `json:"webhooks"`
}

ListWebhooksResponse is the response from listing webhooks.

type LogAuditParams

type LogAuditParams struct {
	AgentID  string                 `json:"agentId"`
	GrantID  string                 `json:"grantId"`
	Action   string                 `json:"action"`
	Metadata map[string]interface{} `json:"metadata,omitempty"`
	Status   string                 `json:"status,omitempty"`
}

LogAuditParams are the parameters for logging an audit entry.

type NetworkError

type NetworkError struct {
	Message string
	Cause   error
}

NetworkError represents a network-level failure (DNS, timeout, connection refused).

func (*NetworkError) Error

func (e *NetworkError) Error() string

func (*NetworkError) Unwrap

func (e *NetworkError) Unwrap() error

type Option

type Option func(*clientConfig)

Option configures a Grantex client.

func WithBaseURL

func WithBaseURL(url string) Option

WithBaseURL sets the API base URL. Defaults to "https://api.grantex.dev".

func WithHTTPClient

func WithHTTPClient(client *http.Client) Option

WithHTTPClient sets a custom http.Client for requests.

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout sets the HTTP request timeout. Defaults to 30 seconds.

type PKCEChallenge

type PKCEChallenge struct {
	CodeVerifier        string
	CodeChallenge       string
	CodeChallengeMethod string // Always "S256"
}

PKCEChallenge holds a PKCE code verifier and its S256 challenge.

func GeneratePKCE

func GeneratePKCE() (*PKCEChallenge, error)

GeneratePKCE creates a new PKCE code verifier and S256 challenge pair.

type PoliciesService

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

PoliciesService handles access policy management.

func (*PoliciesService) Create

func (s *PoliciesService) Create(ctx context.Context, params CreatePolicyParams) (*Policy, error)

Create creates a new access policy.

func (*PoliciesService) Delete

func (s *PoliciesService) Delete(ctx context.Context, policyID string) error

Delete removes a policy.

func (*PoliciesService) Get

func (s *PoliciesService) Get(ctx context.Context, policyID string) (*Policy, error)

Get retrieves a policy by ID.

func (*PoliciesService) List

List retrieves all policies.

func (*PoliciesService) Update

func (s *PoliciesService) Update(ctx context.Context, policyID string, params UpdatePolicyParams) (*Policy, error)

Update modifies an existing policy.

type Policy

type Policy struct {
	ID             string   `json:"id"`
	Name           string   `json:"name"`
	Effect         string   `json:"effect"`
	Priority       int      `json:"priority"`
	AgentID        *string  `json:"agentId"`
	PrincipalID    *string  `json:"principalId"`
	Scopes         []string `json:"scopes"`
	TimeOfDayStart *string  `json:"timeOfDayStart"`
	TimeOfDayEnd   *string  `json:"timeOfDayEnd"`
	CreatedAt      string   `json:"createdAt"`
	UpdatedAt      string   `json:"updatedAt"`
}

Policy represents an access policy.

type PortalResponse

type PortalResponse struct {
	PortalURL string `json:"portalUrl"`
}

PortalResponse is the response from creating a portal session.

type PrincipalSessionResponse

type PrincipalSessionResponse struct {
	SessionToken string `json:"sessionToken"`
	DashboardURL string `json:"dashboardUrl"`
	ExpiresAt    string `json:"expiresAt"`
}

PrincipalSessionResponse is the response from creating a principal session.

type PrincipalSessionsService

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

PrincipalSessionsService handles principal session management.

func (*PrincipalSessionsService) Create

Create creates a new principal session for end-user dashboard access.

type RateLimit added in v0.1.1

type RateLimit struct {
	Limit      int
	Remaining  int
	Reset      int64
	RetryAfter int // 0 = not present
}

RateLimit contains rate limit metadata parsed from response headers.

type RefreshTokenParams

type RefreshTokenParams struct {
	RefreshToken string `json:"refreshToken"`
	AgentID      string `json:"agentId"`
}

RefreshTokenParams are the parameters for refreshing a token.

type RegisterAgentParams

type RegisterAgentParams struct {
	Name        string   `json:"name"`
	Description string   `json:"description"`
	Scopes      []string `json:"scopes"`
}

RegisterAgentParams are the parameters for registering an agent.

type RotateKeyResponse

type RotateKeyResponse struct {
	APIKey    string `json:"apiKey"`
	RotatedAt string `json:"rotatedAt"`
}

RotateKeyResponse is returned from RotateKey.

type SCIMService

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

SCIMService handles SCIM 2.0 provisioning operations.

func (*SCIMService) CreateToken

func (s *SCIMService) CreateToken(ctx context.Context, label string) (*ScimTokenWithSecret, error)

CreateToken creates a new SCIM provisioning token.

func (*SCIMService) CreateUser

func (s *SCIMService) CreateUser(ctx context.Context, params CreateScimUserParams) (*ScimUser, error)

CreateUser creates a new SCIM user.

func (*SCIMService) DeleteUser

func (s *SCIMService) DeleteUser(ctx context.Context, userID string) error

DeleteUser removes a SCIM user.

func (*SCIMService) GetUser

func (s *SCIMService) GetUser(ctx context.Context, userID string) (*ScimUser, error)

GetUser retrieves a SCIM user by ID.

func (*SCIMService) ListTokens

func (s *SCIMService) ListTokens(ctx context.Context) (*ListScimTokensResponse, error)

ListTokens retrieves all SCIM provisioning tokens.

func (*SCIMService) ListUsers

func (s *SCIMService) ListUsers(ctx context.Context, params *ListScimUsersParams) (*ScimListResponse, error)

ListUsers retrieves SCIM users with optional pagination.

func (*SCIMService) ReplaceUser

func (s *SCIMService) ReplaceUser(ctx context.Context, userID string, params CreateScimUserParams) (*ScimUser, error)

ReplaceUser replaces a SCIM user (PUT).

func (*SCIMService) RevokeToken

func (s *SCIMService) RevokeToken(ctx context.Context, tokenID string) error

RevokeToken revokes a SCIM provisioning token.

func (*SCIMService) UpdateUser

func (s *SCIMService) UpdateUser(ctx context.Context, userID string, ops []ScimOperation) (*ScimUser, error)

UpdateUser performs a SCIM PATCH operation on a user.

type SSOService

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

SSOService handles SSO configuration and authentication.

func (*SSOService) CreateConfig

func (s *SSOService) CreateConfig(ctx context.Context, params CreateSsoConfigParams) (*SsoConfig, error)

CreateConfig creates an SSO configuration.

func (*SSOService) DeleteConfig

func (s *SSOService) DeleteConfig(ctx context.Context) error

DeleteConfig removes the SSO configuration.

func (*SSOService) GetConfig

func (s *SSOService) GetConfig(ctx context.Context) (*SsoConfig, error)

GetConfig retrieves the current SSO configuration.

func (*SSOService) GetLoginURL

func (s *SSOService) GetLoginURL(ctx context.Context, org string) (*SsoLoginResponse, error)

GetLoginURL gets the SSO login URL for an organization.

func (*SSOService) HandleCallback

func (s *SSOService) HandleCallback(ctx context.Context, code string, state string) (*SsoCallbackResponse, error)

HandleCallback processes an SSO callback.

type ScimEmail

type ScimEmail struct {
	Value   string `json:"value"`
	Primary bool   `json:"primary,omitempty"`
}

ScimEmail represents an email in SCIM format.

type ScimListResponse

type ScimListResponse struct {
	TotalResults int        `json:"totalResults"`
	StartIndex   int        `json:"startIndex"`
	ItemsPerPage int        `json:"itemsPerPage"`
	Resources    []ScimUser `json:"Resources"`
}

ScimListResponse is the SCIM list response.

type ScimOperation

type ScimOperation struct {
	Op    string      `json:"op"`
	Path  string      `json:"path,omitempty"`
	Value interface{} `json:"value,omitempty"`
}

ScimOperation represents a SCIM PATCH operation.

type ScimToken

type ScimToken struct {
	ID         string  `json:"id"`
	Label      string  `json:"label"`
	CreatedAt  string  `json:"createdAt"`
	LastUsedAt *string `json:"lastUsedAt"`
}

ScimToken represents a SCIM provisioning token.

type ScimTokenWithSecret

type ScimTokenWithSecret struct {
	ID         string  `json:"id"`
	Label      string  `json:"label"`
	CreatedAt  string  `json:"createdAt"`
	LastUsedAt *string `json:"lastUsedAt"`
	Token      string  `json:"token"`
}

ScimTokenWithSecret is a SCIM token that includes the secret value.

type ScimUser

type ScimUser struct {
	ID          string       `json:"id"`
	ExternalID  *string      `json:"externalId,omitempty"`
	UserName    string       `json:"userName"`
	DisplayName *string      `json:"displayName,omitempty"`
	Active      bool         `json:"active"`
	Emails      []ScimEmail  `json:"emails"`
	Meta        ScimUserMeta `json:"meta"`
}

ScimUser represents a SCIM-provisioned user.

type ScimUserMeta

type ScimUserMeta struct {
	ResourceType string `json:"resourceType"`
	Created      string `json:"created"`
	LastModified string `json:"lastModified"`
}

ScimUserMeta is SCIM user metadata.

type SignupParams

type SignupParams struct {
	Name  string `json:"name"`
	Email string `json:"email,omitempty"`
}

SignupParams are the parameters for developer registration.

type SignupResponse

type SignupResponse struct {
	DeveloperID string  `json:"developerId"`
	APIKey      string  `json:"apiKey"`
	Name        string  `json:"name"`
	Email       *string `json:"email"`
	Mode        string  `json:"mode"`
	CreatedAt   string  `json:"createdAt"`
}

SignupResponse is returned from Signup.

func Signup

func Signup(ctx context.Context, params SignupParams, opts ...Option) (*SignupResponse, error)

Signup registers a new developer account. This is a static operation that does not require an API key.

type SsoCallbackResponse

type SsoCallbackResponse struct {
	Email       *string `json:"email"`
	Name        *string `json:"name"`
	Sub         *string `json:"sub"`
	DeveloperID string  `json:"developerId"`
}

SsoCallbackResponse is the response from handling an SSO callback.

type SsoConfig

type SsoConfig struct {
	IssuerURL   string `json:"issuerUrl"`
	ClientID    string `json:"clientId"`
	RedirectURI string `json:"redirectUri"`
	CreatedAt   string `json:"createdAt"`
	UpdatedAt   string `json:"updatedAt"`
}

SsoConfig represents an SSO configuration.

type SsoLoginResponse

type SsoLoginResponse struct {
	AuthorizeURL string `json:"authorizeUrl"`
}

SsoLoginResponse is the response from getting an SSO login URL.

type SubscriptionStatus

type SubscriptionStatus struct {
	Plan             string  `json:"plan"`
	Status           string  `json:"status"`
	CurrentPeriodEnd *string `json:"currentPeriodEnd"`
}

SubscriptionStatus represents the current subscription.

type TokenError

type TokenError struct {
	Message string
	Cause   error
}

TokenError represents a token verification or decoding error.

func (*TokenError) Error

func (e *TokenError) Error() string

func (*TokenError) Unwrap

func (e *TokenError) Unwrap() error

type TokensService

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

TokensService handles token exchange, refresh, verification, and revocation.

func (*TokensService) Exchange

Exchange trades an authorization code for a grant token.

func (*TokensService) Refresh

Refresh exchanges a refresh token for a new grant token.

func (*TokensService) Revoke

func (s *TokensService) Revoke(ctx context.Context, tokenID string) error

Revoke revokes a token by its ID.

func (*TokensService) Verify

func (s *TokensService) Verify(ctx context.Context, token string) (*VerifyTokenResponse, error)

Verify performs online token verification.

type UpdateAgentParams

type UpdateAgentParams struct {
	Name        *string  `json:"name,omitempty"`
	Description *string  `json:"description,omitempty"`
	Scopes      []string `json:"scopes,omitempty"`
}

UpdateAgentParams are the parameters for updating an agent.

type UpdatePolicyParams

type UpdatePolicyParams struct {
	Name           *string  `json:"name,omitempty"`
	Effect         *string  `json:"effect,omitempty"`
	Priority       *int     `json:"priority,omitempty"`
	AgentID        *string  `json:"agentId,omitempty"`
	PrincipalID    *string  `json:"principalId,omitempty"`
	Scopes         []string `json:"scopes,omitempty"`
	TimeOfDayStart *string  `json:"timeOfDayStart,omitempty"`
	TimeOfDayEnd   *string  `json:"timeOfDayEnd,omitempty"`
}

UpdatePolicyParams are the parameters for updating a policy.

type VerifiedGrant

type VerifiedGrant struct {
	TokenID         string   `json:"tokenId"`
	GrantID         string   `json:"grantId"`
	PrincipalID     string   `json:"principalId"`
	AgentDID        string   `json:"agentDid"`
	DeveloperID     string   `json:"developerId"`
	Scopes          []string `json:"scopes"`
	IssuedAt        int64    `json:"issuedAt"`
	ExpiresAt       int64    `json:"expiresAt"`
	ParentAgentDID  *string  `json:"parentAgentDid,omitempty"`
	ParentGrantID   *string  `json:"parentGrantId,omitempty"`
	DelegationDepth *int     `json:"delegationDepth,omitempty"`
}

VerifiedGrant represents a verified JWT grant token's claims.

func VerifyGrantToken

func VerifyGrantToken(ctx context.Context, token string, opts VerifyOptions) (*VerifiedGrant, error)

VerifyGrantToken performs offline JWT verification of a grant token using JWKS. It verifies the RS256 signature, expiration, and optionally checks required scopes and audience.

type VerifyOptions

type VerifyOptions struct {
	// JwksURI is the URL to fetch the JSON Web Key Set from.
	JwksURI string

	// RequiredScopes are scopes the token must contain. If empty, scope checking is skipped.
	RequiredScopes []string

	// Audience is the expected audience claim. If empty, audience checking is skipped.
	Audience string

	// ClockTolerance allows for clock skew between servers. Defaults to 0.
	ClockTolerance time.Duration
}

VerifyOptions configures offline grant token verification.

type VerifyTokenResponse

type VerifyTokenResponse struct {
	Valid     bool     `json:"valid"`
	GrantID   *string  `json:"grantId,omitempty"`
	Scopes    []string `json:"scopes,omitempty"`
	Principal *string  `json:"principal,omitempty"`
	Agent     *string  `json:"agent,omitempty"`
	ExpiresAt *string  `json:"expiresAt,omitempty"`
}

VerifyTokenResponse is the response from online token verification.

type WebhookEndpoint

type WebhookEndpoint struct {
	ID        string   `json:"id"`
	URL       string   `json:"url"`
	Events    []string `json:"events"`
	CreatedAt string   `json:"createdAt"`
}

WebhookEndpoint represents a webhook endpoint.

type WebhookEndpointWithSecret

type WebhookEndpointWithSecret struct {
	ID        string   `json:"id"`
	URL       string   `json:"url"`
	Events    []string `json:"events"`
	CreatedAt string   `json:"createdAt"`
	Secret    string   `json:"secret"`
}

WebhookEndpointWithSecret is a webhook endpoint that includes the signing secret.

type WebhooksService

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

WebhooksService handles webhook endpoint management.

func (*WebhooksService) Create

Create registers a new webhook endpoint.

func (*WebhooksService) Delete

func (s *WebhooksService) Delete(ctx context.Context, webhookID string) error

Delete removes a webhook endpoint.

func (*WebhooksService) List

List retrieves all webhook endpoints.

Jump to

Keyboard shortcuts

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