Documentation
¶
Overview ¶
Package client is the Go client for the Inkless API v1 and a helper for receiving its Standard Webhooks events. Types mirror api/openapi.yaml.
Index ¶
- Constants
- Variables
- func IdempotencyKey() string
- func SignWebhook(secrets []string, id string, ts time.Time, body []byte) (string, error)
- type Assertion
- type Client
- func (c *Client) Artifact(ctx context.Context, id, name string) ([]byte, error)
- func (c *Client) CreateSession(ctx context.Context, id, signerRef string, in CreateSession, idemKey string) (*Session, error)
- func (c *Client) CreateSigningRequest(ctx context.Context, in CreateSigningRequest, idemKey string) (*SigningRequest, error)
- func (c *Client) FailedWebhookDeliveries(ctx context.Context) (*WebhookDeliveryList, error)
- func (c *Client) GetSigningRequest(ctx context.Context, id string) (*SigningRequest, error)
- func (c *Client) Issue(ctx context.Context, id, idemKey string) (*SigningRequest, error)
- func (c *Client) ListSigningRequests(ctx context.Context, since time.Time, cursor string) (*SigningRequestList, error)
- func (c *Client) Revoke(ctx context.Context, id, reason, idemKey string) (*SigningRequest, error)
- func (c *Client) UploadDocument(ctx context.Context, pdf []byte, idemKey string) (*Document, error)
- type CreateSession
- type CreateSigningRequest
- type Document
- type Error
- type Event
- type Revoke
- type Session
- type Signer
- type SignerInput
- type SigningRequest
- type SigningRequestList
- type WebhookDelivery
- type WebhookDeliveryList
Examples ¶
Constants ¶
const ( StateDraft = "draft" StateIssued = "issued" StatePartiallySigned = "partially_signed" StateCompleted = "completed" StateDeclined = "declined" StateExpired = "expired" StateRevoked = "revoked" )
Request states.
const ( // RoutingParallel lets all signers sign at once. RoutingParallel = "parallel" // RoutingSequential makes signers sign in SignerInput.Order. RoutingSequential = "sequential" )
Routing values for CreateSigningRequest.Routing.
const ( SignerWaiting = "waiting" SignerReady = "ready" SignerViewed = "viewed" SignerSigned = "signed" SignerDeclined = "declined" SignerVoided = "voided" )
Signer states.
const ( EventRequestIssued = "request.issued" EventSignerReady = "signer.ready" EventSignerViewed = "signer.viewed" EventSignerSigned = "signer.signed" EventSignerDeclined = "signer.declined" EventRequestCompleted = "request.completed" EventRequestDeclined = "request.declined" EventRequestExpired = "request.expired" EventRequestRevoked = "request.revoked" )
Event types.
const AssuranceEmailCode = "email_code"
AssuranceEmailCode is the signer authentication method that sends a code by email. It is the only assurance value and the default.
const DefaultTimeout = 30 * time.Second
DefaultTimeout is the request timeout of the HTTP client created by New.
const WebhookTolerance = 5 * time.Minute
WebhookTolerance is the accepted clock skew for webhook-timestamp.
Variables ¶
var ErrWebhookSignature = errors.New("inkless: invalid webhook signature")
ErrWebhookSignature is wrapped by every VerifyWebhook failure caused by the request headers or signature, so callers can reject with errors.Is.
Functions ¶
func IdempotencyKey ¶
func IdempotencyKey() string
IdempotencyKey returns a random key. Pass the same key when retrying a POST so the retry returns the first result.
Types ¶
type Assertion ¶
type Assertion struct {
// Subject is the application's identifier of the signer.
Subject string `json:"subject"`
Email string `json:"email"`
// Method names how the application authenticated the signer, for example
// "password" or "sso".
Method string `json:"method"`
AuthenticatedAt time.Time `json:"authenticated_at"`
Assurance string `json:"assurance"`
}
Assertion is the application's statement about the authenticated signer. Inkless stores it as received in the evidence; it does not verify it.
type Client ¶
type Client struct {
// BaseURL is the service root without a trailing slash, for example
// "https://inkless.example.test".
BaseURL string
// APIKey is the application's secret API key, sent as a bearer token.
APIKey string
// HTTP is the client used for requests. If nil, http.DefaultClient is used.
HTTP *http.Client
}
Client calls the Inkless API. The zero value is not usable: set BaseURL and APIKey. A Client is safe for concurrent use as long as its fields are not modified after first use.
Methods that create state take an idempotency key. Pass the same key when retrying a call so the retry returns the first result; an empty key makes the client generate a fresh one, which makes the call non-retryable. API failures are returned as *Error.
Example ¶
ExampleClient creates a client, uploads a PDF, creates and issues a signing request and starts a signing session for one signer.
package main
import (
"context"
"errors"
"fmt"
"log"
"net/http"
"time"
"github.com/edgar4/inkless/client"
)
func main() {
ctx := context.Background()
c := &client.Client{
BaseURL: "https://inkless.example.test",
APIKey: "ik_live_example",
HTTP: &http.Client{Timeout: 30 * time.Second},
}
pdf := []byte("%PDF-1.7 ...")
doc, err := c.UploadDocument(ctx, pdf, client.IdempotencyKey())
if err != nil {
log.Fatal(err)
}
req, err := c.CreateSigningRequest(ctx, client.CreateSigningRequest{
DocumentID: doc.ID,
Signers: []client.SignerInput{{Ref: "signer-1", Name: "Alex Example", Email: "alex@example.test"}},
Routing: "parallel",
ExpiresAt: time.Now().AddDate(0, 0, 14),
}, client.IdempotencyKey())
if err != nil {
log.Fatal(err)
}
if req, err = c.Issue(ctx, req.ID, client.IdempotencyKey()); err != nil {
var apiErr *client.Error
if errors.As(err, &apiErr) {
log.Fatalf("api error %d %s", apiErr.Status, apiErr.Code)
}
log.Fatal(err)
}
sess, err := c.CreateSession(ctx, req.ID, "signer-1", client.CreateSession{
Assertion: client.Assertion{
Subject: "user-42",
Email: "alex@example.test",
Method: "password",
AuthenticatedAt: time.Now(),
},
ReturnURL: "https://app.example.test/signed",
}, client.IdempotencyKey())
if err != nil {
log.Fatal(err)
}
fmt.Println("send the signer to", sess.URL)
}
Output:
func New ¶
New returns a Client for the service at baseURL (without a trailing slash) that authenticates with apiKey and uses an HTTP client with DefaultTimeout.
func (*Client) CreateSession ¶
func (c *Client) CreateSession(ctx context.Context, id, signerRef string, in CreateSession, idemKey string) (*Session, error)
CreateSession starts a signing ceremony for one signer, identified by the ref given at creation, and returns the URL to send the signer to.
func (*Client) CreateSigningRequest ¶
func (c *Client) CreateSigningRequest(ctx context.Context, in CreateSigningRequest, idemKey string) (*SigningRequest, error)
CreateSigningRequest creates a signing request in the draft state for an uploaded document. Call Issue to send it to the signers.
func (*Client) FailedWebhookDeliveries ¶
func (c *Client) FailedWebhookDeliveries(ctx context.Context) (*WebhookDeliveryList, error)
FailedWebhookDeliveries lists webhook deliveries that exhausted their retries, for reconciliation with GetSigningRequest.
func (*Client) GetSigningRequest ¶
GetSigningRequest returns the current state of a signing request.
func (*Client) ListSigningRequests ¶
func (c *Client) ListSigningRequests(ctx context.Context, since time.Time, cursor string) (*SigningRequestList, error)
ListSigningRequests returns requests updated at or after since, oldest first. Pass the returned NextCursor to continue.
type CreateSession ¶
type CreateSession struct {
Assertion Assertion `json:"assertion"`
// ReturnURL is where the signer returns after the ceremony. It must match
// one of the application's allowed origins.
ReturnURL string `json:"return_url"`
}
CreateSession is the body of Client.CreateSession.
type CreateSigningRequest ¶
type CreateSigningRequest struct {
// DocumentID is a document of this application, see Client.UploadDocument.
DocumentID string `json:"document_id"`
Signers []SignerInput `json:"signers"`
// Routing is "parallel" or "sequential".
Routing string `json:"routing"`
// Assurance is the signer authentication method; empty selects
// "email_code".
Assurance string `json:"assurance,omitempty"`
// ConsentVersion selects the consent text; empty selects "v1".
ConsentVersion string `json:"consent_version,omitempty"`
// Locale is the language of the signing pages and consent text, "en" or
// "pt-PT"; empty selects "en".
Locale string `json:"locale,omitempty"`
// ExpiresAt must be in the future and within one year.
ExpiresAt time.Time `json:"expires_at"`
// ExternalRef is the application's own reference, returned as given.
ExternalRef string `json:"external_ref,omitempty"`
// Metadata is a JSON object of at most 8 KiB, returned as given.
Metadata json.RawMessage `json:"metadata,omitempty"`
}
CreateSigningRequest is the body of Client.CreateSigningRequest.
type Document ¶
type Document struct {
ID string `json:"id"`
// SHA256 is the lowercase hexadecimal SHA-256 of the PDF.
SHA256 string `json:"sha256"`
// Size is the PDF size in bytes.
Size int64 `json:"size"`
Pages int `json:"pages"`
}
Document is an uploaded PDF.
type Error ¶
type Error struct {
// Status is the HTTP status code; it is not part of the JSON body.
Status int `json:"-"`
// Code is a stable machine-readable code such as "invalid_state".
Code string `json:"code"`
Message string `json:"message"`
}
Error is the API error body's "error" member. Client methods return it as *Error for any response with status 300 or above; use errors.As to read Status and Code.
type Event ¶
type Event struct {
// ID is unique per event and equals the webhook-id header.
ID string `json:"id"`
// Type is one of the Event* constants.
Type string `json:"type"`
CreatedAt time.Time `json:"created_at"`
RequestID string `json:"request_id"`
// ExternalRef is the request's external reference; empty when not given.
ExternalRef string `json:"external_ref"`
// Sequence increases per request and equals Request.Sequence.
Sequence int64 `json:"sequence"`
// Request is the request as of this event.
Request SigningRequest `json:"request"`
}
Event is the webhook envelope.
func VerifyWebhook ¶
VerifyWebhook checks the Standard Webhooks headers against any of the secrets ("whsec_<base64>"; several during rotation) and returns the event. now is compared with webhook-timestamp using WebhookTolerance. Failures caused by the request wrap ErrWebhookSignature; a malformed secret is a different error. Receivers must still dedupe by Event.ID, ignore events whose Sequence is not above the last one seen for the request, and reconcile with GET /v1/signing-requests/{id} on gaps.
Example ¶
ExampleVerifyWebhook signs a webhook body the way Inkless does and verifies it as a receiver would.
package main
import (
"encoding/base64"
"errors"
"fmt"
"log"
"net/http"
"strconv"
"time"
"github.com/edgar4/inkless/client"
)
func main() {
secrets := []string{"whsec_" + base64.StdEncoding.EncodeToString([]byte("example-only"))}
body := []byte(`{"id":"evt_1","type":"request.issued","sequence":1}`)
sentAt := time.Unix(1_800_000_000, 0)
sig, err := client.SignWebhook(secrets, "evt_1", sentAt, body)
if err != nil {
log.Fatal(err)
}
h := http.Header{}
h.Set("webhook-id", "evt_1")
h.Set("webhook-timestamp", strconv.FormatInt(sentAt.Unix(), 10))
h.Set("webhook-signature", sig)
ev, err := client.VerifyWebhook(secrets, h, body, sentAt.Add(time.Minute))
if err != nil {
log.Fatal(err)
}
fmt.Println(ev.ID, ev.Type, ev.Sequence)
_, err = client.VerifyWebhook(secrets, h, append(body, ' '), sentAt)
fmt.Println(errors.Is(err, client.ErrWebhookSignature))
}
Output: evt_1 request.issued 1 true
type Revoke ¶
type Revoke struct {
Reason string `json:"reason"`
}
Revoke is the body of Client.Revoke.
type Session ¶
type Session struct {
// URL is a one-use signing link.
URL string `json:"url"`
// ExpiresAt is when the link stops working if unopened.
ExpiresAt time.Time `json:"expires_at"`
}
Session is a signing ceremony link for one signer.
type Signer ¶
type Signer struct {
Ref string `json:"ref"`
Name string `json:"name"`
Email string `json:"email"`
Order int `json:"order"`
// State is one of the Signer* constants.
State string `json:"state"`
SignedAt *time.Time `json:"signed_at,omitempty"`
DeclinedAt *time.Time `json:"declined_at,omitempty"`
DeclineReason string `json:"decline_reason,omitempty"`
}
Signer is a signer of a signing request.
type SignerInput ¶
type SignerInput struct {
// Ref is the application's opaque id for the signer, unique within the
// request.
Ref string `json:"ref"`
Name string `json:"name"`
Email string `json:"email"`
// Order is the signing position for sequential routing. If zero, the
// signer's position in the list (1-based) is used.
Order int `json:"order"`
}
SignerInput describes one signer in a CreateSigningRequest.
type SigningRequest ¶
type SigningRequest struct {
ID string `json:"id"`
// State is one of the State* constants.
State string `json:"state"`
// Sequence is the sequence number of the latest event; 0 for drafts.
Sequence int64 `json:"sequence"`
// ExternalRef is the application's reference; empty when not given.
ExternalRef string `json:"external_ref"`
Metadata json.RawMessage `json:"metadata"`
Routing string `json:"routing"`
Assurance string `json:"assurance"`
ConsentVersion string `json:"consent_version"`
Locale string `json:"locale"`
ExpiresAt time.Time `json:"expires_at"`
Document Document `json:"document"`
Signers []Signer `json:"signers"`
RevokeReason string `json:"revoke_reason,omitempty"`
// ArtifactsReady reports whether final.pdf and evidence.zip can be
// downloaded with Client.Artifact.
ArtifactsReady bool `json:"artifacts_ready"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
IssuedAt *time.Time `json:"issued_at,omitempty"`
EndedAt *time.Time `json:"ended_at,omitempty"`
}
SigningRequest is a document sent to one or more signers.
type SigningRequestList ¶
type SigningRequestList struct {
Data []SigningRequest `json:"data"`
// NextCursor is set when more requests follow; pass it to the next call.
NextCursor string `json:"next_cursor,omitempty"`
}
SigningRequestList is one page of Client.ListSigningRequests.
type WebhookDelivery ¶
type WebhookDelivery struct {
EventID string `json:"event_id"`
Type string `json:"type"`
RequestID string `json:"request_id"`
// Attempts is the number of delivery attempts made.
Attempts int `json:"attempts"`
LastError string `json:"last_error,omitempty"`
CreatedAt time.Time `json:"created_at"`
FailedAt *time.Time `json:"failed_at,omitempty"`
}
WebhookDelivery is a webhook event that could not be delivered.
type WebhookDeliveryList ¶
type WebhookDeliveryList struct {
Data []WebhookDelivery `json:"data"`
}
WebhookDeliveryList is the result of Client.FailedWebhookDeliveries.