smartid

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Jul 20, 2025 License: Apache-2.0, MIT Imports: 23 Imported by: 0

README

Smart-ID Go Client

Project Status

This library provides a modern, developer-friendly Go integration with the official Smart-ID REST API v3 from SK ID Solutions, supporting strong, secure electronic identity authentication and digital signing for users in Estonia, Latvia, and Lithuania.

It is built entirely in Go, leverages well-established cryptographic libraries, and offers a clean, modular design following Go best practices, giving developers full control over request construction, security validation, and interaction flows.

The library abstracts much of the low-level complexity of working with Smart-ID, while strictly following the official specifications and providing the tools necessary to build both cross-device (e.g., browser to mobile) and same-device (e.g., mobile app) authentication flows.

This is a complete Go port of the TypeScript/Node.js Smart-ID client library, maintaining feature parity and API compatibility where possible.

Table of Contents

Overview

Features
  • Complete Smart-ID v3 API Support (June 2025)
  • Strongly Typed Request Builders (Device Link & Notification Authentication)
  • Full Authentication Response Validation with certificate trust checks
  • Smart-ID Scheme Identification (End-Entity Certificate) enforcement
  • Signature Reconstruction and Verification logic
  • Notification Flow Support with VC Type: numeric4
  • Session Secret Digest and User Challenge Verifier validation
  • Clean, Extensible, Minimal Dependencies (standard library + crypto/x509)
  • Comprehensive Test Coverage
  • Concurrent-Safe Design
  • Production Ready
Main Authentication Flows

This library implements the main Smart-ID RP API flows, based on version 3 of the protocol:

Cross-device Use Cases

The RP session is on a separate device from the mobile phone where the Smart-ID app is installed.

  • PC browser to access an RP website
  • Tablet to access an RP application
Same-device Use Cases

The RP frontend resides on the same mobile device as the Smart-ID app.

  • Mobile app authentication
  • Mobile browser detection for same-device flows

Recommended: Use GetAuthenticateAnonymousDeviceLink for same-device use cases unless the user's document-number has already been established. These endpoints provide superior user experience with device-links and callbacks offering the best security protections.

Installation

go get github.com/PaymentSyst/smart-id-client
Before You Start

This library is intended for developers who are already familiar with the Smart-ID system and its technical workflows.

If you are new to Smart-ID, please start by reading the official Smart-ID Demo Documentation:

👉 https://sk-eid.github.io/smart-id-documentation/demo.html

The official documentation explains the Smart-ID concept, registration process, and how to obtain demo credentials required for development and testing.

Quick Start

package main

import (
    "fmt"
    "log"
    
    smartid "github.com/PaymentSyst/smart-id-client"
)

func main() {
    // Create client configuration
    config := &smartid.SmartIdClientConfig{
        RelyingPartyUUID: "00000000-0000-4000-8000-000000000000", // Demo UUID
        RelyingPartyName: "DEMO",
        HostURL:          "https://sid.demo.sk.ee/smart-id-rp",
        Debug:            true,
    }

    // Create Smart-ID client
    client := smartid.NewSmartIdAuthClient(config)
    client.SetSchemeName("smart-id-demo")

    // Build authentication request
    builder := smartid.NewAuthenticationRequestBuilder(
        config.RelyingPartyUUID,
        config.RelyingPartyName,
    )

    request := builder.
        WithInitialCallbackURL("https://example.com/callback").
        WithCertificateLevel(smartid.CertificateLevelQualified).
        WithInteractions(&smartid.DisplayTextAndPINInteraction{
            Type:          "displayTextAndPIN",
            DisplayText60: "Authenticate with Smart-ID",
        }).
        Build()

    // Start authentication session
    response, sessionStartTime, err := client.GetAuthenticateAnonymousDeviceLink(request)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("Session started: %s\n", response.SessionID)

    // Create device link URL
    linkOptions := &smartid.DeviceLinkOptions{
        DeviceLinkType: smartid.DeviceLinkTypeWeb2App,
        Lang:           "eng",
    }

    deviceLinkURL := client.CreateDeviceLinkURL(response, request, sessionStartTime, linkOptions)
    fmt.Printf("Device Link: %s\n", deviceLinkURL)

    // Poll for result
    authResponse, err := client.PollForSessionResult(response.SessionID, nil)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("Authentication completed: %s\n", authResponse.Result.EndResult)
}

Authentication Request Builder

The AuthenticationRequestBuilder provides a fluent interface for constructing Smart-ID authentication requests:

builder := smartid.NewAuthenticationRequestBuilder("your-uuid", "Your RP Name")

// Device Link Authentication
request := builder.
    WithInitialCallbackURL("https://yourapp.com/callback").
    WithCertificateLevel(smartid.CertificateLevelQualified).
    WithHashAlgorithm(smartid.HashAlgorithmSHA512).
    WithInteractions(&smartid.DisplayTextAndPINInteraction{
        Type:          "displayTextAndPIN",
        DisplayText60: "Please authenticate",
    }).
    WithRequestProperties(&smartid.RequestProperties{
        ShareMdClientIPAddress: true,
    }).
    Build()

// Notification Authentication
notificationRequest := builder.
    WithVCType("numeric4").
    Build()
Available Methods
Method Description
WithInitialCallbackURL(url) Sets callback URL for Web2App/App2App flows
WithCertificateLevel(level) Sets certificate level (ADVANCED/QUALIFIED)
WithHashAlgorithm(algorithm) Sets hash algorithm for signatures
WithRequestProperties(props) Adds request properties like IP sharing
WithCapabilities(caps) Adds custom capabilities
WithInteractions(interactions...) Sets user interaction type(s)
WithVCType(vcType) Switches to notification authentication

Smart-ID Authentication Client

The SmartIdAuthClient handles all communication with the Smart-ID API:

// Anonymous device link (recommended for same-device)
response, startTime, err := client.GetAuthenticateAnonymousDeviceLink(request)

// By ETSI identifier
response, startTime, err := client.GetAuthenticateDeviceLinkByEtsi("PNOEE-30303039914", request)

// By document number
response, startTime, err := client.GetAuthenticateDeviceLinkByDocument("PNOEE-30303039914-123", request)
Notification Authentication
// By ETSI identifier
response, err := client.StartAuthenticateNotificationByEtsi("PNOEE-30303039914", notificationRequest)

// By document number  
response, err := client.StartAuthenticateNotificationByDocument("PNOEE-30303039914-123", notificationRequest)
Session Management
// Get session status
status, err := client.GetSessionStatus(sessionID)

// Poll for completion
options := &smartid.PollOptions{
    MaxWaitMs:      60000, // 60 seconds
    PollIntervalMs: 2000,  // 2 seconds
    MaxAttempts:    30,
}
result, err := client.PollForSessionResult(sessionID, options)
// Generate QR code URL
qrOptions := &smartid.DeviceLinkOptions{
    DeviceLinkType: smartid.DeviceLinkTypeQR,
    Lang:           "eng",
    ElapsedSeconds: 10,
}
qrURL := client.CreateDeviceLinkURL(response, request, startTime, qrOptions)

// Generate Web2App URL
web2appOptions := &smartid.DeviceLinkOptions{
    DeviceLinkType: smartid.DeviceLinkTypeWeb2App,
    Lang:           "eng",
}
web2appURL := client.CreateDeviceLinkURL(response, request, startTime, web2appOptions)

Authentication Response Validator

Comprehensive validation of Smart-ID responses:

// Create validator with CA certificate path
validator, err := smartid.NewAuthenticationResponseValidator("/path/to/ca/certs", true)
if err != nil {
    log.Fatal(err)
}

// Validate response
result := validator.
    WithSchemeName("smart-id-demo").
    WithInteractionTypeUsed("displayTextAndPIN").
    WithFlowType("Web2App").
    Validate(authResponse, request).
    GetResult()

if result.HasError() {
    fmt.Printf("Validation errors: %v\n", result.GetErrors())
} else {
    identity := result.GetIdentity()
    fmt.Printf("User: %s %s\n", identity.GetGivenName(), identity.GetSurName())
    
    // Verify signature
    signatureValid := validator.VerifySignature(authResponse, request)
    fmt.Printf("Signature valid: %t\n", signatureValid)
}
Certificate Policy Validation
// Check for specific certificate policies
allowedOIDs := []string{
    "1.3.6.1.4.1.4146.1.1",  // Test OID
    "1.3.6.1.4.1.4146.1.2",  // Production OID
}

pemCert := identity.GetPemCertificate()
hasValidPolicy := validator.CheckIfHasAllowedCertificatePolicies(pemCert, allowedOIDs)

Callback URL Validator

For Web2App and App2App flows:

callbackEntity := &smartid.CallbackValidationEntity{
    SessionSecretDigest:   "digest_from_frontend",
    UserChallengeVerifier: "verifier_from_request",
    SessionSecret:         "base64_session_secret",
    SchemeName:            "smart-id-demo",
    AuthenticationResponse: authResponse,
}

validator := smartid.NewCallbackURLValidator(callbackEntity)
result := validator.Validate().GetResult()

if result.HasError() {
    fmt.Printf("Callback validation failed: %v\n", result.GetErrors())
}

Authentication Identity

Extract user information from certificates:

identity := result.GetIdentity()

// Basic information
fmt.Printf("Given Name: %s\n", identity.GetGivenName())
fmt.Printf("Surname: %s\n", identity.GetSurName())
fmt.Printf("Identity Code: %s\n", identity.GetIdentityCode())
fmt.Printf("Country: %s\n", identity.GetCountry())
fmt.Printf("Document Number: %s\n", identity.GetDocumentNumber())

// Certificate information
fmt.Printf("Valid From: %s\n", identity.GetValidFrom().Format("2006-01-02"))
fmt.Printf("Valid To: %s\n", identity.GetValidTo().Format("2006-01-02"))
fmt.Printf("Date of Birth: %s\n", identity.GetDateOfBirth())

// Certificate access
pemCert := identity.GetPemCertificate()
rawCert := identity.GetRawCertificate()
parsedInfo := identity.GetParsedCertificate()

Examples

Complete Authentication Flow
func authenticateUser() error {
    // Setup
    config := &smartid.SmartIdClientConfig{
        RelyingPartyUUID: "your-uuid",
        RelyingPartyName: "Your App",
        HostURL:          "https://sid.demo.sk.ee/smart-id-rp",
        Debug:            true,
    }
    
    client := smartid.NewSmartIdAuthClient(config)
    
    // Build request
    request := smartid.NewAuthenticationRequestBuilder(
        config.RelyingPartyUUID,
        config.RelyingPartyName,
    ).WithInteractions(&smartid.DisplayTextAndPINInteraction{
        Type:          "displayTextAndPIN",
        DisplayText60: "Login to MyApp",
    }).Build()
    
    // Start session
    response, startTime, err := client.GetAuthenticateAnonymousDeviceLink(request)
    if err != nil {
        return err
    }
    
    // Generate QR code URL
    qrURL := client.CreateDeviceLinkURL(response, request, startTime, &smartid.DeviceLinkOptions{
        DeviceLinkType: smartid.DeviceLinkTypeQR,
    })
    
    // Display QR code to user (implement QR generation)
    fmt.Printf("Scan QR code: %s\n", qrURL)
    
    // Poll for result
    authResponse, err := client.PollForSessionResult(response.SessionID, nil)
    if err != nil {
        return err
    }
    
    // Validate response
    validator, err := smartid.NewAuthenticationResponseValidator("./ca-certs", false)
    if err != nil {
        return err
    }
    
    result := validator.Validate(authResponse, request).GetResult()
    if result.HasError() {
        return fmt.Errorf("validation failed: %v", result.GetErrors())
    }
    
    // Success!
    identity := result.GetIdentity()
    fmt.Printf("Authenticated: %s %s\n", identity.GetGivenName(), identity.GetSurName())
    
    return nil
}
Notification Authentication
func notificationAuth(idCode string) error {
    config := &smartid.SmartIdClientConfig{
        RelyingPartyUUID: "your-uuid",
        RelyingPartyName: "Your App",
        HostURL:          "https://sid.demo.sk.ee/smart-id-rp",
    }
    
    client := smartid.NewSmartIdAuthClient(config)
    
    notificationRequest := smartid.NewAuthenticationRequestBuilder(
        config.RelyingPartyUUID,
        config.RelyingPartyName,
    ).WithInteractions(&smartid.DisplayTextAndPINInteraction{
        Type:          "displayTextAndPIN", 
        DisplayText60: "Confirm login",
    }).WithVCType("numeric4").Build()
    
    response, err := client.StartAuthenticateNotificationByEtsi(idCode, notificationRequest)
    if err != nil {
        return err
    }
    
    fmt.Printf("Verification code: %s\n", response.VerificationCode)
    
    authResponse, err := client.PollForSessionResult(response.SessionID, nil)
    if err != nil {
        return err
    }
    
    fmt.Printf("Authentication result: %s\n", authResponse.Result.EndResult)
    return nil
}

Security

This library implements comprehensive security validations:

✅ Built-in Security Features
  • Session Completion Verification - Ensures proper session state
  • Certificate Chain Validation - Verifies against trusted CA store
  • Certificate Expiry Checks - Validates certificate validity periods
  • Smart-ID Scheme Identification - Enforces proper KeyUsage and EKU
  • Signature Verification - Full ACSP_V2 signature validation
  • Callback Parameter Validation - Prevents tampering in Web2App/App2App
  • TLS Certificate Pinning - Optional public key pinning support
⚠️ Security Responsibilities
  • CA Certificate Management - You must provide valid, up-to-date CA certificates
  • Replay Attack Protection - Implement session token management
  • Secure Backend - Protect session secrets and sensitive data
  • Follow Security Guidelines - Read the Smart-ID Security Guide

API Reference

Core Types
// Client configuration
type SmartIdClientConfig struct {
    RelyingPartyUUID string
    RelyingPartyName string
    HostURL          string
    APIVersion       string
    BrokeredRpName   string
    PinnedCerts      []*x509.Certificate
    PublicSSLKeys    string
    Debug            bool
}

// Certificate levels
const (
    CertificateLevelAdvanced  CertificateLevel = "ADVANCED"
    CertificateLevelQualified CertificateLevel = "QUALIFIED"
)

// Hash algorithms  
const (
    HashAlgorithmSHA256   HashAlgorithm = "SHA-256"
    HashAlgorithmSHA384   HashAlgorithm = "SHA-384"
    HashAlgorithmSHA512   HashAlgorithm = "SHA-512"
    HashAlgorithmSHA3_256 HashAlgorithm = "SHA3-256"
    HashAlgorithmSHA3_384 HashAlgorithm = "SHA3-384"
    HashAlgorithmSHA3_512 HashAlgorithm = "SHA3-512"
)

// Device link types
const (
    DeviceLinkTypeQR      DeviceLinkType = "QR"
    DeviceLinkTypeWeb2App DeviceLinkType = "Web2App"
    DeviceLinkTypeApp2App DeviceLinkType = "App2App"
)
Error Types
// Base Smart-ID error
type SmartIdError struct {
    Message string
}

// User refused operation
type SmartIdUserRefusedError struct {
    SmartIdError
}

// Session timeout
type SmartIdTimeoutError struct {
    SmartIdError
}

// Session failed with specific reason
type SmartIdSessionFailedError struct {
    SmartIdError
    EndResult string
}

Testing

Run the test suite:

# Run all tests
go test ./...

# Run tests with coverage
go test -cover ./...

# Run benchmarks
go test -bench=. ./...

# Run specific test
go test -run TestAuthenticationRequestBuilder ./...
Test Coverage

The library includes comprehensive tests covering:

  • ✅ Request builder functionality
  • ✅ Client configuration and setup
  • ✅ Authentication flows
  • ✅ Response validation
  • ✅ Error handling
  • ✅ Security features
  • ✅ Edge cases and error conditions

Contributing

We welcome contributions! Please:

  1. Fork the repository
  2. Create a feature branch
  3. Add tests for new functionality
  4. Ensure all tests pass
  5. Submit a pull request
Development Setup
git clone https://github.com/PaymentSyst/smart-id-client.git
cd smart-id-client
go mod tidy
go test ./...

License

This project is licensed under the MIT License - see the LICENSE file for details.

Disclaimer

This is an independent, third-party, open-source library developed for convenience in integrating with the official Smart-ID API.

It is not developed, reviewed, endorsed, or certified by SK ID Solutions AS or any official Smart-ID authority.

⚠️ Use at your own risk. Ensure your Smart-ID integration complies with all applicable laws, regulations, and the official Smart-ID Implementation Guidelines.

For production use, thorough independent review and appropriate security measures are strongly recommended.

References

Credits

This Go library is a complete port of the original TypeScript/Node.js Smart-ID client library developed by Joosep Wong.

Go implementation maintains feature parity while leveraging Go's strengths in performance, type safety, and concurrent programming.

Documentation

Overview

Package smartid provides a comprehensive Go client library for integrating with the Smart-ID REST API v3.

This library offers a modern, developer-friendly integration with the official Smart-ID REST API v3 from SK ID Solutions, supporting strong, secure electronic identity authentication and digital signing for users in Estonia, Latvia, and Lithuania.

The library provides:

  • Device Link Authentication (anonymous, by ETSI, by document)
  • Notification Authentication (by ETSI, by document)
  • Comprehensive response validation including certificate trust verification
  • Callback URL validation for Web2App/App2App flows
  • Authentication identity extraction
  • Signature verification
  • Certificate policy validation

Example usage:

import "github.com/PaymentSyst/smart-id-client"

client := smartid.NewSmartIdAuthClient(&smartid.SmartIdClientConfig{
	RelyingPartyUUID: "00000000-0000-4000-8000-000000000000",
	RelyingPartyName: "DEMO",
	HostURL:          "https://sid.demo.sk.ee/smart-id-rp",
	Debug:            true,
})

builder := smartid.NewAuthenticationRequestBuilder(
	"00000000-0000-4000-8000-000000000000",
	"DEMO",
)

request := builder.
	WithInitialCallbackURL("https://example.com/callback").
	WithCertificateLevel(smartid.CertificateLevelQualified).
	WithInteractions(&smartid.DisplayTextAndPINInteraction{
		Type:          "displayTextAndPIN",
		DisplayText60: "Authenticate with Smart-ID",
	}).
	Build()

response, sessionStartTime, err := client.GetAuthenticateAnonymousDeviceLink(request)
if err != nil {
	log.Fatal(err)
}

// Poll for result
authResponse, err := client.PollForSessionResult(response.SessionID, nil)
if err != nil {
	log.Fatal(err)
}

// Validate the response
validator, err := smartid.NewAuthenticationResponseValidator("/path/to/ca/certs", true)
if err != nil {
	log.Fatal(err)
}

result := validator.Validate(authResponse, request).GetResult()
if result.HasError() {
	log.Printf("Validation errors: %v", result.GetErrors())
} else {
	identity := result.GetIdentity()
	log.Printf("Authenticated user: %s %s", identity.GetGivenName(), identity.GetSurName())
}

Index

Constants

This section is empty.

Variables

CertificationLevelOrder maps certificate levels to their priority order

Functions

func GenerateSemanticsIdentifier

func GenerateSemanticsIdentifier(semanticsIdentifierType, countryCode, identityNumber string) string

GenerateSemanticsIdentifier creates a semantics identifier string

func IsSessionSuccessful

func IsSessionSuccessful(status AuthenticationResponse) bool

IsSessionSuccessful checks if an authentication response represents a successful session

Types

type AuthResult

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

AuthResult represents the result of an authentication validation operation

func NewAuthResult

func NewAuthResult() *AuthResult

NewAuthResult creates a new AuthResult instance

func (*AuthResult) AddError

func (r *AuthResult) AddError(error string) *AuthResult

AddError adds an error to the result and marks it as invalid

func (*AuthResult) GetErrors

func (r *AuthResult) GetErrors() []string

GetErrors returns a copy of all errors

func (*AuthResult) GetIdentity

func (r *AuthResult) GetIdentity() *AuthenticationIdentity

GetIdentity returns the authentication identity if available

func (*AuthResult) HasError

func (r *AuthResult) HasError() bool

HasError returns whether there are any errors

func (*AuthResult) IsValid

func (r *AuthResult) IsValid() bool

IsValid returns whether the authentication result is valid

func (*AuthResult) SetIdentity

func (r *AuthResult) SetIdentity(identity *AuthenticationIdentity) *AuthResult

SetIdentity sets the authentication identity

func (*AuthResult) SetValid

func (r *AuthResult) SetValid(valid bool) *AuthResult

SetValid sets the validity of the authentication result

type AuthenticationIdentity

type AuthenticationIdentity struct {
	GivenName       string
	SurName         string
	IdentityCode    string
	IdentityNumber  string
	Country         string
	AuthCertificate string
	DocumentNumber  string
	ValidFrom       time.Time
	ValidTo         time.Time
	DateOfBirth     string
}

AuthenticationIdentity represents an authenticated user's identity extracted from a Smart-ID certificate

func NewAuthenticationIdentity

func NewAuthenticationIdentity() *AuthenticationIdentity

NewAuthenticationIdentity creates a new AuthenticationIdentity instance

func (*AuthenticationIdentity) GetCertificate

func (a *AuthenticationIdentity) GetCertificate() string

GetCertificate returns the raw certificate (Base64)

func (*AuthenticationIdentity) GetCountry

func (a *AuthenticationIdentity) GetCountry() string

GetCountry returns the country

func (*AuthenticationIdentity) GetDateOfBirth

func (a *AuthenticationIdentity) GetDateOfBirth() string

GetDateOfBirth returns the date of birth

func (*AuthenticationIdentity) GetDocumentNumber

func (a *AuthenticationIdentity) GetDocumentNumber() string

GetDocumentNumber returns the document number

func (*AuthenticationIdentity) GetGivenName

func (a *AuthenticationIdentity) GetGivenName() string

GetGivenName returns the given name

func (*AuthenticationIdentity) GetIdentityCode

func (a *AuthenticationIdentity) GetIdentityCode() string

GetIdentityCode returns the identity code

func (*AuthenticationIdentity) GetIdentityNumber

func (a *AuthenticationIdentity) GetIdentityNumber() string

GetIdentityNumber returns the identity number

func (*AuthenticationIdentity) GetParsedCertificate

func (a *AuthenticationIdentity) GetParsedCertificate() map[string]interface{}

GetParsedCertificate returns parsed certificate information

func (*AuthenticationIdentity) GetPemCertificate

func (a *AuthenticationIdentity) GetPemCertificate() string

GetPemCertificate returns the certificate in PEM format

func (*AuthenticationIdentity) GetRawCertificate

func (a *AuthenticationIdentity) GetRawCertificate() *x509.Certificate

GetRawCertificate returns the raw certificate object

func (*AuthenticationIdentity) GetSurName

func (a *AuthenticationIdentity) GetSurName() string

GetSurName returns the surname

func (*AuthenticationIdentity) GetValidFrom

func (a *AuthenticationIdentity) GetValidFrom() time.Time

GetValidFrom returns certificate validity start time

func (*AuthenticationIdentity) GetValidTo

func (a *AuthenticationIdentity) GetValidTo() time.Time

GetValidTo returns certificate validity end time

type AuthenticationRequestBuilder

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

AuthenticationRequestBuilder provides a developer-friendly way to construct Smart-ID authentication requests

func NewAuthenticationRequestBuilder

func NewAuthenticationRequestBuilder(relyingPartyUUID, relyingPartyName string) *AuthenticationRequestBuilder

NewAuthenticationRequestBuilder creates a new AuthenticationRequestBuilder instance

func (*AuthenticationRequestBuilder) Build

Build finalizes and returns the request payload for API consumption

func (*AuthenticationRequestBuilder) WithCapabilities

func (b *AuthenticationRequestBuilder) WithCapabilities(capabilities map[string]interface{}) *AuthenticationRequestBuilder

WithCapabilities adds custom capabilities to the request

func (*AuthenticationRequestBuilder) WithCertificateLevel

WithCertificateLevel sets desired certificate level

func (*AuthenticationRequestBuilder) WithHashAlgorithm

WithHashAlgorithm sets hash algorithm for signature generation

func (*AuthenticationRequestBuilder) WithInitialCallbackURL

func (b *AuthenticationRequestBuilder) WithInitialCallbackURL(url string) *AuthenticationRequestBuilder

WithInitialCallbackURL sets the callback URL for Web2App or App2App flows

func (*AuthenticationRequestBuilder) WithInteractions

func (b *AuthenticationRequestBuilder) WithInteractions(interactions ...Interaction) *AuthenticationRequestBuilder

WithInteractions defines the user-facing interaction shown on the Smart-ID app

func (*AuthenticationRequestBuilder) WithRequestProperties

WithRequestProperties adds request-specific properties

func (*AuthenticationRequestBuilder) WithVCType

WithVCType switches to notification authentication request builder

type AuthenticationResponse

type AuthenticationResponse struct {
	State               string                `json:"state"`
	Result              *AuthenticationResult `json:"result,omitempty"`
	SignatureProtocol   string                `json:"signatureProtocol"`
	Signature           *SignatureInfo        `json:"signature,omitempty"`
	Cert                *CertificateInfo      `json:"cert,omitempty"`
	InteractionTypeUsed string                `json:"interactionTypeUsed,omitempty"`
	FlowType            string                `json:"flowType,omitempty"`
}

AuthenticationResponse represents the final authentication response

type AuthenticationResponseValidator

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

AuthenticationResponseValidator provides comprehensive validation of Smart-ID authentication responses

func NewAuthenticationResponseValidator

func NewAuthenticationResponseValidator(resourcesLocation string, debug bool) (*AuthenticationResponseValidator, error)

NewAuthenticationResponseValidator creates a new validator instance

func (*AuthenticationResponseValidator) BuildACSPV2Payload

func (v *AuthenticationResponseValidator) BuildACSPV2Payload(authenticationResponse *AuthenticationResponse, payload *DeviceLinkAuthRequest) string

BuildACSPV2Payload reconstructs the exact ACSP_V2 payload string required for signature check

func (*AuthenticationResponseValidator) CheckIfHasAllowedCertificatePolicies

func (v *AuthenticationResponseValidator) CheckIfHasAllowedCertificatePolicies(pemCert string, allowedOids []string) bool

CheckIfHasAllowedCertificatePolicies checks if the certificate contains at least one allowed policy OID

func (*AuthenticationResponseValidator) GetResult

GetResult returns the result containing validation errors and extracted identity

func (*AuthenticationResponseValidator) GetTrustedCACertificates

func (v *AuthenticationResponseValidator) GetTrustedCACertificates() []string

GetTrustedCACertificates returns the list of CA certificate file paths loaded for trust validation

func (*AuthenticationResponseValidator) Validate

func (v *AuthenticationResponseValidator) Validate(authenticationResponse *AuthenticationResponse, payload interface{}) *AuthenticationResponseValidator

Validate runs core response and certificate validation logic

func (*AuthenticationResponseValidator) VerifySignature

func (v *AuthenticationResponseValidator) VerifySignature(authenticationResponse *AuthenticationResponse, payload *DeviceLinkAuthRequest) bool

VerifySignature verifies ACSP_V2 signature based on reconstructed payload and certificate

func (*AuthenticationResponseValidator) WithBrokeredRpName

WithBrokeredRpName sets brokered RP name for ACSP_V2 payload reconstruction

func (*AuthenticationResponseValidator) WithCallbackURLValidate

WithCallbackURLValidate runs callback URL validator for Web2App/App2App flows

func (*AuthenticationResponseValidator) WithFlowType

WithFlowType sets flow type for ACSP_V2 payload reconstruction

func (*AuthenticationResponseValidator) WithInteractionTypeUsed

func (v *AuthenticationResponseValidator) WithInteractionTypeUsed(value string) *AuthenticationResponseValidator

WithInteractionTypeUsed sets interaction type used for ACSP_V2 payload reconstruction

func (*AuthenticationResponseValidator) WithSchemeName

WithSchemeName sets scheme name for ACSP_V2 payload reconstruction

type AuthenticationResult

type AuthenticationResult struct {
	EndResult      string `json:"endResult"`
	DocumentNumber string `json:"documentNumber"`
}

AuthenticationResult represents the result portion of an authentication response

type AuthenticationValidationResult

type AuthenticationValidationResult struct {
	HasError bool                    `json:"hasError"`
	Errors   []string                `json:"errors"`
	Identity *AuthenticationIdentity `json:"identity,omitempty"`
}

AuthenticationValidationResult represents the result of authentication validation

type CallbackURLValidator

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

CallbackURLValidator provides utilities for validating callback URL parameters in DeviceLink authentication flows

func NewCallbackURLValidator

func NewCallbackURLValidator(entity *CallbackValidationEntity) *CallbackURLValidator

NewCallbackURLValidator creates a new CallbackURLValidator instance

func (*CallbackURLValidator) GetResult

func (v *CallbackURLValidator) GetResult() *AuthResult

GetResult returns the validation result

func (*CallbackURLValidator) Validate

Validate runs all validation checks on the callback URL parameters

type CallbackValidationEntity

type CallbackValidationEntity struct {
	SessionSecretDigest    string                 `json:"sessionSecretDigest"`
	UserChallengeVerifier  string                 `json:"userChallengeVerifier"`
	SessionSecret          string                 `json:"sessionSecret"`
	SchemeName             string                 `json:"schemeName"`
	AuthenticationResponse AuthenticationResponse `json:"authenticationResponse"`
}

CallbackValidationEntity represents entity for callback validation

type CertificateInfo

type CertificateInfo struct {
	Value            string           `json:"value"`
	CertificateLevel CertificateLevel `json:"certificateLevel"`
}

CertificateInfo represents certificate information in the response

type CertificateLevel

type CertificateLevel string

CertificateLevel represents the certificate levels

const (
	CertificateLevelAdvanced  CertificateLevel = "ADVANCED"
	CertificateLevelQualified CertificateLevel = "QUALIFIED"
)

type ConfirmationMessageAndVerificationCodeChoiceInteraction

type ConfirmationMessageAndVerificationCodeChoiceInteraction struct {
	Type           string `json:"type"`
	DisplayText200 string `json:"displayText200"`
}

ConfirmationMessageAndVerificationCodeChoiceInteraction represents confirmation with VC choice

func (ConfirmationMessageAndVerificationCodeChoiceInteraction) GetType

type ConfirmationMessageInteraction

type ConfirmationMessageInteraction struct {
	Type           string `json:"type"`
	DisplayText200 string `json:"displayText200"`
}

ConfirmationMessageInteraction represents a confirmation message interaction

func (ConfirmationMessageInteraction) GetType

type DeviceLinkAuthRequest

type DeviceLinkAuthRequest struct {
	RelyingPartyUUID            string                  `json:"relyingPartyUUID"`
	RelyingPartyName            string                  `json:"relyingPartyName"`
	InitialCallbackURL          string                  `json:"initialCallbackUrl,omitempty"`
	CertificateLevel            CertificateLevel        `json:"certificateLevel,omitempty"`
	SignatureProtocol           SignatureProtocol       `json:"signatureProtocol"`
	SignatureProtocolParameters SignatureProtocolParams `json:"signatureProtocolParameters"`
	Interactions                string                  `json:"interactions"`
	RequestProperties           *RequestProperties      `json:"requestProperties,omitempty"`
	Capabilities                map[string]interface{}  `json:"capabilities,omitempty"`
}

DeviceLinkAuthRequest represents a device link authentication request

type DeviceLinkAuthResponse

type DeviceLinkAuthResponse struct {
	SessionID      string `json:"sessionID"`
	SessionToken   string `json:"sessionToken"`
	SessionSecret  string `json:"sessionSecret"`
	DeviceLinkBase string `json:"deviceLinkBase"`
}

DeviceLinkAuthResponse represents a device link authentication response

type DeviceLinkOptions

type DeviceLinkOptions struct {
	DeviceLinkType DeviceLinkType `json:"deviceLinkType"`
	Lang           string         `json:"lang,omitempty"`
	ElapsedSeconds int            `json:"elapsedSeconds,omitempty"`
}

DeviceLinkOptions represents options for creating device links

type DeviceLinkType

type DeviceLinkType string

DeviceLinkType represents the type of device link

const (
	DeviceLinkTypeQR      DeviceLinkType = "QR"
	DeviceLinkTypeWeb2App DeviceLinkType = "Web2App"
	DeviceLinkTypeApp2App DeviceLinkType = "App2App"
)

type DisplayTextAndPINInteraction

type DisplayTextAndPINInteraction struct {
	Type          string `json:"type"`
	DisplayText60 string `json:"displayText60"`
}

DisplayTextAndPINInteraction represents a display text and PIN interaction

func (DisplayTextAndPINInteraction) GetType

type HashAlgorithm

type HashAlgorithm string

HashAlgorithm represents the hash algorithms supported by Smart-ID

const (
	HashAlgorithmSHA256   HashAlgorithm = "SHA-256"
	HashAlgorithmSHA384   HashAlgorithm = "SHA-384"
	HashAlgorithmSHA512   HashAlgorithm = "SHA-512"
	HashAlgorithmSHA3_256 HashAlgorithm = "SHA3-256"
	HashAlgorithmSHA3_384 HashAlgorithm = "SHA3-384"
	HashAlgorithmSHA3_512 HashAlgorithm = "SHA3-512"
)

type Interaction

type Interaction interface {
	GetType() string
}

Interaction represents the different types of user interactions

type MaskGenAlgorithm

type MaskGenAlgorithm struct {
	Algorithm  string                  `json:"algorithm"`
	Parameters *MaskGenAlgorithmParams `json:"parameters,omitempty"`
}

MaskGenAlgorithm represents mask generation algorithm parameters

type MaskGenAlgorithmParams

type MaskGenAlgorithmParams struct {
	HashAlgorithm string `json:"hashAlgorithm"`
}

MaskGenAlgorithmParams represents mask generation algorithm parameters

type NotificationAuthRequest

type NotificationAuthRequest struct {
	DeviceLinkAuthRequest
	VCType string `json:"vcType"`
}

NotificationAuthRequest extends DeviceLinkAuthRequest for notification authentication

type NotificationAuthResponse

type NotificationAuthResponse struct {
	SessionID        string `json:"sessionID"`
	VerificationCode string `json:"verificationCode"`
}

NotificationAuthResponse represents a notification authentication response

type NotificationRequestBuilder

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

NotificationRequestBuilder handles notification-specific request building

func NewNotificationRequestBuilder

func NewNotificationRequestBuilder(basePayload *DeviceLinkAuthRequest, vcType string) *NotificationRequestBuilder

NewNotificationRequestBuilder creates a new NotificationRequestBuilder

func (*NotificationRequestBuilder) Build

Build finalizes and returns the notification request payload

type PollOptions

type PollOptions struct {
	MaxWaitMs      int `json:"maxWaitMs,omitempty"`
	PollIntervalMs int `json:"pollIntervalMs,omitempty"`
	MaxAttempts    int `json:"maxAttempts,omitempty"`
}

PollOptions represents options for polling session status

type RequestProperties

type RequestProperties struct {
	ShareMdClientIPAddress bool `json:"shareMdClientIpAddress,omitempty"`
}

RequestProperties represents request properties

type ResponseSignatureAlgorithmParams

type ResponseSignatureAlgorithmParams struct {
	HashAlgorithm    string            `json:"hashAlgorithm"`
	MaskGenAlgorithm *MaskGenAlgorithm `json:"maskGenAlgorithm,omitempty"`
	SaltLength       int               `json:"saltLength,omitempty"`
	TrailerField     string            `json:"trailerField,omitempty"`
}

ResponseSignatureAlgorithmParams represents signature algorithm parameters in response

type SignatureAlgorithm

type SignatureAlgorithm string

SignatureAlgorithm represents the signature algorithms

const (
	SignatureAlgorithmRSASSA_PSS SignatureAlgorithm = "rsassa-pss"
)

type SignatureAlgorithmParameters

type SignatureAlgorithmParameters struct {
	HashAlgorithm HashAlgorithm `json:"hashAlgorithm"`
}

SignatureAlgorithmParameters represents signature algorithm parameters

type SignatureInfo

type SignatureInfo struct {
	Value                        string                            `json:"value"`
	UserChallenge                string                            `json:"userChallenge,omitempty"`
	ServerRandom                 string                            `json:"serverRandom,omitempty"`
	SignatureAlgorithm           string                            `json:"signatureAlgorithm,omitempty"`
	SignatureAlgorithmParameters *ResponseSignatureAlgorithmParams `json:"signatureAlgorithmParameters,omitempty"`
}

SignatureInfo represents signature information in the response

type SignatureProtocol

type SignatureProtocol string

SignatureProtocol represents the signature protocols

const (
	SignatureProtocolACSP_V2 SignatureProtocol = "ACSP_V2"
)

type SignatureProtocolParams

type SignatureProtocolParams struct {
	RPChallenge                  string                       `json:"rpChallenge"`
	SignatureAlgorithm           SignatureAlgorithm           `json:"signatureAlgorithm"`
	SignatureAlgorithmParameters SignatureAlgorithmParameters `json:"signatureAlgorithmParameters"`
}

SignatureProtocolParams represents signature protocol parameters

type SmartIdAuthClient

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

SmartIdAuthClient serves as the primary communication layer between your application and the Smart-ID REST API

func NewSmartIdAuthClient

func NewSmartIdAuthClient(config *SmartIdClientConfig) *SmartIdAuthClient

NewSmartIdAuthClient creates a new SmartIdAuthClient instance

func (*SmartIdAuthClient) CreateDeviceLinkURL

func (c *SmartIdAuthClient) CreateDeviceLinkURL(session *DeviceLinkAuthResponse, payload *DeviceLinkAuthRequest, sessionStartTime int64, opts *DeviceLinkOptions) string

CreateDeviceLinkURL generates a signed DeviceLink URL for QR, Web2App, or App2App flows

func (*SmartIdAuthClient) GenerateCallbackParam

func (c *SmartIdAuthClient) GenerateCallbackParam() string

GenerateCallbackParam generates a random callback parameter

func (c *SmartIdAuthClient) GetAuthenticateAnonymousDeviceLink(requestPayload *DeviceLinkAuthRequest) (*DeviceLinkAuthResponse, int64, error)

GetAuthenticateAnonymousDeviceLink starts anonymous DeviceLink authentication

func (*SmartIdAuthClient) GetAuthenticateDeviceLinkByDocument

func (c *SmartIdAuthClient) GetAuthenticateDeviceLinkByDocument(documentNumber string, requestPayload *DeviceLinkAuthRequest) (*DeviceLinkAuthResponse, int64, error)

GetAuthenticateDeviceLinkByDocument starts DeviceLink authentication by document number

func (*SmartIdAuthClient) GetAuthenticateDeviceLinkByEtsi

func (c *SmartIdAuthClient) GetAuthenticateDeviceLinkByEtsi(idCode string, requestPayload *DeviceLinkAuthRequest) (*DeviceLinkAuthResponse, int64, error)

GetAuthenticateDeviceLinkByEtsi starts DeviceLink authentication by ETSI

func (*SmartIdAuthClient) GetHostURL

func (c *SmartIdAuthClient) GetHostURL() string

GetHostURL returns the current API base URL

func (*SmartIdAuthClient) GetSessionStatus

func (c *SmartIdAuthClient) GetSessionStatus(sessionID string, timeoutMs ...int) (*AuthenticationResponse, error)

GetSessionStatus retrieves the current status of an authentication session

func (*SmartIdAuthClient) PollForSessionResult

func (c *SmartIdAuthClient) PollForSessionResult(sessionID string, options *PollOptions) (*AuthenticationResponse, error)

PollForSessionResult polls session status until success, failure, or timeout occurs

func (*SmartIdAuthClient) SetAPIEndpoint

func (c *SmartIdAuthClient) SetAPIEndpoint(hostURL string, version string) *SmartIdAuthClient

SetAPIEndpoint overrides Smart-ID API endpoint and version

func (*SmartIdAuthClient) SetAPIVersion

func (c *SmartIdAuthClient) SetAPIVersion(version string) *SmartIdAuthClient

SetAPIVersion updates Smart-ID API version

func (*SmartIdAuthClient) SetBrokeredRpName

func (c *SmartIdAuthClient) SetBrokeredRpName(name string) *SmartIdAuthClient

SetBrokeredRpName sets the brokered RP name used in DeviceLink URL generation

func (*SmartIdAuthClient) SetPublicSSLKeys

func (c *SmartIdAuthClient) SetPublicSSLKeys(fingerprints string) *SmartIdAuthClient

SetPublicSSLKeys configures SHA-256 public key pinning for additional security

func (*SmartIdAuthClient) SetSchemeName

func (c *SmartIdAuthClient) SetSchemeName(name string) *SmartIdAuthClient

SetSchemeName sets the scheme name used for signature payloads

func (*SmartIdAuthClient) StartAuthenticateNotificationByDocument

func (c *SmartIdAuthClient) StartAuthenticateNotificationByDocument(documentNumber string, requestPayload *NotificationAuthRequest) (*NotificationAuthResponse, error)

StartAuthenticateNotificationByDocument starts Notification Authentication by document number

func (*SmartIdAuthClient) StartAuthenticateNotificationByEtsi

func (c *SmartIdAuthClient) StartAuthenticateNotificationByEtsi(idCode string, requestPayload *NotificationAuthRequest) (*NotificationAuthResponse, error)

StartAuthenticateNotificationByEtsi starts Notification Authentication by ETSI

type SmartIdClientConfig

type SmartIdClientConfig struct {
	RelyingPartyUUID string
	RelyingPartyName string
	HostURL          string
	APIVersion       string
	BrokeredRpName   string
	PinnedCerts      []*x509.Certificate
	PublicSSLKeys    string
	Debug            bool
}

SmartIdClientConfig represents the configuration for the Smart-ID client

type SmartIdEndResult

type SmartIdEndResult string

SmartIdEndResult represents the possible end results of a Smart-ID session

const (
	SmartIdEndResultOK                                         SmartIdEndResult = "OK"
	SmartIdEndResultUserRefusedInteraction                     SmartIdEndResult = "USER_REFUSED_INTERACTION"
	SmartIdEndResultProtocolFailure                            SmartIdEndResult = "PROTOCOL_FAILURE"
	SmartIdEndResultServerError                                SmartIdEndResult = "SERVER_ERROR"
	SmartIdEndResultTimeout                                    SmartIdEndResult = "TIMEOUT"
	SmartIdEndResultDocumentUnusable                           SmartIdEndResult = "DOCUMENT_UNUSABLE"
	SmartIdEndResultWrongVC                                    SmartIdEndResult = "WRONG_VC"
	SmartIdEndResultRequiredInteractionNotSupportedByApp       SmartIdEndResult = "REQUIRED_INTERACTION_NOT_SUPPORTED_BY_APP"
	SmartIdEndResultUserRefusedDisplayTextAndPIN               SmartIdEndResult = "USER_REFUSED_DISPLAYTEXTANDPIN"
	SmartIdEndResultUserRefusedConfirmationMessage             SmartIdEndResult = "USER_REFUSED_CONFIRMATIONMESSAGE"
	SmartIdEndResultUserRefusedConfirmationMessageWithVCChoice SmartIdEndResult = "USER_REFUSED_CONFIRMATIONMESSAGE_WITH_VC_CHOICE"
	SmartIdEndResultUserRefusedCertChoice                      SmartIdEndResult = "USER_REFUSED_CERT_CHOICE"
)

type SmartIdError

type SmartIdError struct {
	Message string
}

SmartIdError is the base error type for Smart-ID operations

func NewSmartIdError

func NewSmartIdError(message string) *SmartIdError

NewSmartIdError creates a new SmartIdError

func (SmartIdError) Error

func (e SmartIdError) Error() string

type SmartIdSessionFailedError

type SmartIdSessionFailedError struct {
	SmartIdError
	EndResult string
}

SmartIdSessionFailedError represents an error when the Smart-ID session fails

func NewSmartIdSessionFailedError

func NewSmartIdSessionFailedError(endResult string) *SmartIdSessionFailedError

NewSmartIdSessionFailedError creates a new SmartIdSessionFailedError

type SmartIdTimeoutError

type SmartIdTimeoutError struct {
	SmartIdError
}

SmartIdTimeoutError represents an error when the Smart-ID session times out

func NewSmartIdTimeoutError

func NewSmartIdTimeoutError() *SmartIdTimeoutError

NewSmartIdTimeoutError creates a new SmartIdTimeoutError

type SmartIdUserRefusedError

type SmartIdUserRefusedError struct {
	SmartIdError
}

SmartIdUserRefusedError represents an error when the user refuses the Smart-ID operation

func NewSmartIdUserRefusedError

func NewSmartIdUserRefusedError() *SmartIdUserRefusedError

NewSmartIdUserRefusedError creates a new SmartIdUserRefusedError

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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