scalekit

package module
v2.0.4 Latest Latest
Warning

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

Go to latest
Published: Sep 22, 2025 License: MIT Imports: 31 Imported by: 0

README


Official Go SDK

Go Reference Go Report Card

Scalekit is the auth stack for AI apps - from human authentication to agent authorization. Build secure AI products faster with authentication for humans (SSO, passwordless, full-stack auth) and agents (MCP/APIs, delegated actions), all unified on one platform. This Go SDK enables both traditional B2B authentication and cutting-edge agentic workflows.

🤖 Agent-First Features

  • 🔐 Agent Identity: Agents as first-class actors with human ownership and org context
  • 🎯 MCP-Native OAuth 2.1: Purpose-built for Model Context Protocol with DCR/PKCE support
  • ⏰ Ephemeral Credentials: Time-bound, task-based authorization (minutes, not days)
  • 🔒 Token Vault: Per-user, per-tool token storage with rotation and progressive consent
  • 👥 Human-in-the-Loop: Step-up authentication when risk crosses thresholds
  • 📊 Immutable Audit: Track which user initiated, which agent acted, what resource was accessed

👨‍💼 Human Authentication

  • 🔐 Enterprise SSO: Support for SAML and OIDC protocols
  • 👥 SCIM Provisioning: Automated user provisioning and deprovisioning
  • 🚀 Passwordless Authentication: Magic links, OTP, and modern auth flows
  • 🏢 Multi-tenant Architecture: Organization-level authentication policies
  • 📱 Social Logins: Support for popular social identity providers
  • 🛡️ Full-Stack Auth: Complete IdP-of-record solution for B2B SaaS
📚 Documentation • 🚀 SSO Quickstart • 💻 API Reference

Pre-requisites

  1. Sign up for a Scalekit account.
  2. Get your env_url, client_id and client_secret from the Scalekit dashboard.

Installation

go get -u github.com/scalekit-inc/scalekit-sdk-go/v2

Usage

Initialize the Scalekit client using the appropriate credentials. Refer code sample below.

import "github.com/scalekit-inc/scalekit-sdk-go/v2"

func main() {
  scalekitClient := scalekit.NewScalekitClient(
    "<SCALEKIT_ENV_URL>",
    "<SCALEKIT_CLIENT_ID>",
    "<SCALEKIT_CLIENT_SECRET>",
  )

  // Use the sc object to interact with the Scalekit API
  authUrl, _ := scalekitClient.GetAuthorizationUrl(
    "https://acme-corp.com/redirect-uri",
    scalekit.AuthorizationUrlOptions{
      State: "state",
      ConnectionId: "con_123456789",
    },
  )
}

Minimum Requirements

Before integrating the Scalekit Go SDK, ensure your development environment meets these requirements:

Component Version
Go 1.22+

Note: Go 1.22+ provides the essential features required by this SDK. For optimal performance and security, consider using the latest stable release.

Examples - SSO with Go HTTP Server

Below is a simple code sample that showcases how to implement Single Sign-on using Scalekit SDK

package main

import (
  "fmt"
  "net/http"

  "github.com/scalekit-inc/scalekit-sdk-go/v2"
)

func main() {
  sc := scalekit.NewScalekit(
    "<SCALEKIT_ENV_URL>",
    "<SCALEKIT_CLIENT_ID>",
    "<SCALEKIT_CLIENT_SECRET>",
  )

  redirectUri := "http://localhost:8080/auth/callback"

  // Get the authorization URL and redirect the user to the IdP login page
  http.HandleFunc("/auth/login", func(w http.ResponseWriter, r *http.Request) {
    authUrl, _ := scalekitClient.GetAuthorizationUrl(
      redirectUri,
      scalekit.AuthorizationUrlOptions{
        State: "state",
        ConnectionId: "con_123456789",
      },
    )
    http.Redirect(w, r, authUrl, http.StatusSeeOther)
  })

  // Handle the callback from the Scalekit
  http.HandleFunc("/auth/callback", func(w http.ResponseWriter, r *http.Request) {
    code := r.URL.Query().Get("code")
    state := r.URL.Query().Get("state")

    authResp, _ := scalekitClient.AuthenticateWithCode(code, redirectUri)

    http.SetCookie(w, &http.Cookie{
      Name: "access_token",
      Value: authResp.AccessToken,
    })

    fmt.Fprintf(w, "Access token: %s", authResp.AccessToken)
  })

  fmt.Println("Server started at http://localhost:8080")
  http.ListenAndServe(":8080", nil)
}

📱 Example Apps

Explore fully functional sample applications built with popular Go frameworks and the Scalekit SDK:

Framework Repository Description
Go HTTP Server scalekit-go-example Basic HTTP server implementation
📖 Quickstart Guides
📚 Documentation & Reference
🛠️ Additional Resources

License

This project is licensed under the MIT license. See the LICENSE file for more information.

Documentation

Index

Constants

View Source
const (
	TemplateTypeUnspecified = authv1.TemplateType_UNSPECIFIED
	TemplateTypeSignin      = authv1.TemplateType_SIGNIN
	TemplateTypeSignup      = authv1.TemplateType_SIGNUP
)

Enum constants for TemplateType

View Source
const (
	PasswordlessTypeUnspecified = authv1.PasswordlessType_PASSWORDLESS_TYPE_UNSPECIFIED
	PasswordlessTypeOtp         = authv1.PasswordlessType_OTP
	PasswordlessTypeLink        = authv1.PasswordlessType_LINK
	PasswordlessTypeLinkOtp     = authv1.PasswordlessType_LINK_OTP
)

Enum constants for PasswordlessType

Variables

View Source
var (
	ErrRefreshTokenRequired  = errors.New("refresh token is required")
	ErrTokenExpired          = errors.New("token has expired")
	ErrInvalidExpClaimFormat = errors.New("invalid exp claim format")
	ErrAuthRequestIdRequired = errors.New("authRequestId is required")
)

Error types

Functions

func ValidateToken

func ValidateToken[T interface{}](token string, jwksFn func() (*jose.JSONWebKeySet, error)) (*T, error)

Types

type AccessTokenClaims

type AccessTokenClaims struct {
	Sub      string   `json:"sub"`
	Iss      string   `json:"iss"`
	Audience Audience `json:"aud,omitempty"`
	Iat      int      `json:"iat"`
	Exp      int      `json:"exp"`
	Claims   Claims   `json:"-"`
}

func (*AccessTokenClaims) UnmarshalJSON

func (a *AccessTokenClaims) UnmarshalJSON(data []byte) error

type AddPermissionsToRoleResponse added in v2.0.4

type AddPermissionsToRoleResponse = rolesv1.AddPermissionsToRoleResponse

type Audience

type Audience []string

type AuthenticationOptions

type AuthenticationOptions struct {
	CodeVerifier string
}

type AuthenticationResponse

type AuthenticationResponse struct {
	User        User
	IdToken     string
	AccessToken string
	ExpiresIn   int
}

type AuthorizationUrlOptions

type AuthorizationUrlOptions struct {
	ConnectionId        string
	OrganizationId      string
	Scopes              []string
	State               string
	Nonce               string
	DomainHint          string
	LoginHint           string
	CodeChallenge       string
	CodeChallengeMethod string
	Provider            string
	Prompt              string
}

type Claims

type Claims map[string]interface{}

type Connection

type Connection interface {
	GetConnection(ctx context.Context, organizationId string, id string) (*GetConnectionResponse, error)
	ListConnectionsByDomain(ctx context.Context, domain string) (*ListConnectionsResponse, error)
	ListConnections(ctx context.Context, organizationId string) (*ListConnectionsResponse, error)
	EnableConnection(ctx context.Context, organizationId string, id string) (*ToggleConnectionResponse, error)
	DisableConnection(ctx context.Context, organizationId string, id string) (*ToggleConnectionResponse, error)
}

type CreateDomainOptions added in v2.0.4

type CreateDomainOptions struct {
	DomainType DomainType
}

CreateDomainOptions represents optional parameters for creating a domain

type CreateDomainResponse

type CreateDomainResponse = domainsv1.CreateDomainResponse

type CreateMembershipResponse

type CreateMembershipResponse = usersv1.CreateMembershipResponse

type CreateOrganizationOptions

type CreateOrganizationOptions struct {
	ExternalId string
	Metadata   map[string]string
}

type CreateOrganizationRoleResponse added in v2.0.4

type CreateOrganizationRoleResponse = rolesv1.CreateOrganizationRoleResponse

type CreatePermissionResponse added in v2.0.4

type CreatePermissionResponse = rolesv1.CreatePermissionResponse

Type aliases for permission-related responses

type CreateRoleResponse added in v2.0.4

type CreateRoleResponse = rolesv1.CreateRoleResponse

Type aliases for role-related responses

type CreateUserAndMembershipResponse

type CreateUserAndMembershipResponse = usersv1.CreateUserAndMembershipResponse

Type aliases for response types

type Directory

type Directory interface {
	ListDirectories(ctx context.Context, organizationId string) (*ListDirectoriesResponse, error)
	ListDirectoryUsers(ctx context.Context, organizationId string, directoryId string, options *ListDirectoryUsersOptions) (*ListDirectoryUsersResponse, error)
	ListDirectoryGroups(ctx context.Context, organizationId string, directoryId string, options *ListDirectoryGroupsOptions) (*ListDirectoryGroupsResponse, error)
	GetPrimaryDirectoryByOrganizationId(ctx context.Context, organizationId string) (*GetDirectoryResponse, error)
	EnableDirectory(ctx context.Context, organizationId string, directoryId string) (*ToggleDirectoryResponse, error)
	DisableDirectory(ctx context.Context, organizationId string, directoryId string) (*ToggleDirectoryResponse, error)
	GetDirectory(ctx context.Context, organizationId string, directoryId string) (*GetDirectoryResponse, error)
}

type Domain

type Domain interface {
	CreateDomain(ctx context.Context, organizationId, name string, options ...*CreateDomainOptions) (*CreateDomainResponse, error)
	GetDomain(ctx context.Context, id string, organizationId string) (*GetDomainResponse, error)
	ListDomains(ctx context.Context, organizationId string) (*ListDomainResponse, error)
	DeleteDomain(ctx context.Context, id string, organizationId string) error
}

type DomainType added in v2.0.4

type DomainType = string

DomainType is defined as a string type alias

const (
	DomainTypeUnspecified  DomainType = "DOMAIN_TYPE_UNSPECIFIED"
	DomainTypeAllowedEmail DomainType = "ALLOWED_EMAIL_DOMAIN"
	DomainTypeOrganization DomainType = "ORGANIZATION_DOMAIN"
)

Domain type constants

type Feature

type Feature struct {
	Name    string
	Enabled bool
}

type GetConnectionResponse

type GetConnectionResponse = connectionsv1.GetConnectionResponse

type GetDirectoryResponse

type GetDirectoryResponse = directoriesv1.GetDirectoryResponse

type GetDomainResponse

type GetDomainResponse = domainsv1.GetDomainResponse

type GetOrganizationRoleResponse added in v2.0.4

type GetOrganizationRoleResponse = rolesv1.GetOrganizationRoleResponse

type GetOrganizationRoleUsersCountResponse added in v2.0.4

type GetOrganizationRoleUsersCountResponse = rolesv1.GetOrganizationRoleUsersCountResponse

type GetPermissionResponse added in v2.0.4

type GetPermissionResponse = rolesv1.GetPermissionResponse

type GetRoleResponse added in v2.0.4

type GetRoleResponse = rolesv1.GetRoleResponse

type GetRoleUsersCountResponse added in v2.0.4

type GetRoleUsersCountResponse = rolesv1.GetRoleUsersCountResponse

type GetUserResponse

type GetUserResponse = usersv1.GetUserResponse

type GrantType

type GrantType = string
const (
	GrantTypeAuthorizationCode GrantType = "authorization_code"
	GrantTypeRefreshToken      GrantType = "refresh_token"
	GrantTypeClientCredentials GrantType = "client_credentials"
)

type IdTokenClaims

type IdTokenClaims struct {
	Id                  string     `json:"sub"`
	Username            string     `json:"preferred_username"`
	Name                string     `json:"name"`
	GivenName           string     `json:"given_name"`
	FamilyName          string     `json:"family_name"`
	Email               string     `json:"email"`
	EmailVerified       bool       `json:"email_verified"`
	PhoneNumber         string     `json:"phone_number"`
	PhoneNumberVerified bool       `json:"phone_number_verified"`
	Profile             string     `json:"profile"`
	Picture             string     `json:"picture"`
	Gender              string     `json:"gender"`
	BirthDate           string     `json:"birthdate"`
	ZoneInfo            string     `json:"zoneinfo"`
	Locale              string     `json:"locale"`
	UpdatedAt           string     `json:"updated_at"`
	Identities          []Identity `json:"identities"`
	Metadata            string     `json:"metadata"`
	Claims              Claims     `json:"-"`
}

func (*IdTokenClaims) UnmarshalJSON

func (i *IdTokenClaims) UnmarshalJSON(data []byte) error

type Identity

type Identity struct {
	ConnectionId          string `json:"connection_id"`
	OrganizationId        string `json:"organization_id"`
	ConnectionType        string `json:"connection_type"`
	ProviderName          string `json:"provider_name"`
	Social                bool   `json:"social"`
	ProviderRawAttributes string `json:"provider_raw_attributes"`
}

type IdpInitiatedLoginClaims

type IdpInitiatedLoginClaims struct {
	ConnectionID   string  `json:"connection_id"`
	OrganizationID string  `json:"organization_id"`
	LoginHint      string  `json:"login_hint"`
	RelayState     *string `json:"relay_state"`
}
type Link = organizationsv1.Link

type ListConnectionsResponse

type ListConnectionsResponse = connectionsv1.ListConnectionsResponse

type ListDirectoriesResponse

type ListDirectoriesResponse = directoriesv1.ListDirectoriesResponse

type ListDirectoryGroupsOptions

type ListDirectoryGroupsOptions struct {
	PageSize      uint32
	PageToken     string
	IncludeDetail *bool
	UpdatedAfter  *time.Time
}

type ListDirectoryUsersOptions

type ListDirectoryUsersOptions struct {
	PageSize         uint32
	PageToken        string
	IncludeDetail    *bool
	DirectoryGroupId *string
	UpdatedAfter     *time.Time
}

type ListDomainResponse

type ListDomainResponse = domainsv1.ListDomainResponse

type ListEffectiveRolePermissionsResponse added in v2.0.4

type ListEffectiveRolePermissionsResponse = rolesv1.ListEffectiveRolePermissionsResponse

type ListOrganizationRolesResponse added in v2.0.4

type ListOrganizationRolesResponse = rolesv1.ListOrganizationRolesResponse

type ListOrganizationUsersResponse

type ListOrganizationUsersResponse = usersv1.ListOrganizationUsersResponse

type ListPermissionsResponse added in v2.0.4

type ListPermissionsResponse = rolesv1.ListPermissionsResponse

type ListRolePermissionsResponse added in v2.0.4

type ListRolePermissionsResponse = rolesv1.ListRolePermissionsResponse

type ListRolesResponse added in v2.0.4

type ListRolesResponse = rolesv1.ListRolesResponse

type ListUsersOptions

type ListUsersOptions struct {
	PageSize  uint32
	PageToken string
}

ListUsersOptions represents optional parameters for listing users

type LogoutUrlOptions

type LogoutUrlOptions struct {
	IdTokenHint           string
	PostLogoutRedirectUri string
	State                 string
}

type Organization

type Organization interface {
	CreateOrganization(ctx context.Context, name string, options CreateOrganizationOptions) (*CreateOrganizationResponse, error)
	ListOrganization(ctx context.Context, options *ListOrganizationOptions) (*ListOrganizationsResponse, error)
	GetOrganization(ctx context.Context, id string) (*GetOrganizationResponse, error)
	GetOrganizationByExternalId(ctx context.Context, externalId string) (*GetOrganizationResponse, error)
	UpdateOrganization(ctx context.Context, id string, organization *UpdateOrganization) (*UpdateOrganizationResponse, error)
	UpdateOrganizationByExternalId(ctx context.Context, externalId string, organization *UpdateOrganization) (*UpdateOrganizationResponse, error)
	DeleteOrganization(ctx context.Context, id string) error
	GeneratePortalLink(ctx context.Context, organizationId string) (*Link, error)
	UpdateOrganizationSettings(ctx context.Context, id string, settings OrganizationSettings) (*GetOrganizationResponse, error)
}

type OrganizationSettings

type OrganizationSettings struct {
	Features []Feature
}

type PasswordlessService

type PasswordlessService interface {
	SendPasswordlessEmail(ctx context.Context, email string, options *SendPasswordlessOptions) (*SendPasswordlessResponse, error)
	VerifyPasswordlessEmail(ctx context.Context, options *VerifyPasswordlessOptions) (*VerifyPasswordLessResponse, error)
	ResendPasswordlessEmail(ctx context.Context, authRequestId string) (*SendPasswordlessResponse, error)
}

PasswordlessService interface defines the methods for passwordless authentication

type PasswordlessType

type PasswordlessType = authv1.PasswordlessType

type PermissionService added in v2.0.4

type PermissionService interface {
	// Permission management
	CreatePermission(ctx context.Context, permission *rolesv1.CreatePermission) (*CreatePermissionResponse, error)
	GetPermission(ctx context.Context, permissionName string) (*GetPermissionResponse, error)
	ListPermissions(ctx context.Context, pageToken ...string) (*ListPermissionsResponse, error)
	UpdatePermission(ctx context.Context, permissionName string, permission *rolesv1.CreatePermission) (*UpdatePermissionResponse, error)
	DeletePermission(ctx context.Context, permissionName string) error

	// Role-Permission relationships
	ListRolePermissions(ctx context.Context, roleName string) (*ListRolePermissionsResponse, error)
	AddPermissionsToRole(ctx context.Context, roleName string, permissionNames []string) (*AddPermissionsToRoleResponse, error)
	RemovePermissionFromRole(ctx context.Context, roleName, permissionName string) error
	ListEffectiveRolePermissions(ctx context.Context, roleName string) (*ListEffectiveRolePermissionsResponse, error)
}

PermissionService defines the interface for permission management operations

type RoleService added in v2.0.4

type RoleService interface {
	// Environment-level role management
	CreateRole(ctx context.Context, role *rolesv1.CreateRole) (*CreateRoleResponse, error)
	GetRole(ctx context.Context, roleName string) (*GetRoleResponse, error)
	ListRoles(ctx context.Context) (*ListRolesResponse, error)
	UpdateRole(ctx context.Context, roleName string, role *rolesv1.UpdateRole) (*UpdateRoleResponse, error)
	DeleteRole(ctx context.Context, roleName string, reassignRoleName ...string) error
	GetRoleUsersCount(ctx context.Context, roleName string) (*GetRoleUsersCountResponse, error)

	// Organization-level role management
	CreateOrganizationRole(ctx context.Context, orgId string, role *rolesv1.CreateOrganizationRole) (*CreateOrganizationRoleResponse, error)
	GetOrganizationRole(ctx context.Context, orgId, roleName string) (*GetOrganizationRoleResponse, error)
	ListOrganizationRoles(ctx context.Context, orgId string) (*ListOrganizationRolesResponse, error)
	UpdateOrganizationRole(ctx context.Context, orgId, roleName string, role *rolesv1.UpdateRole) (*UpdateOrganizationRoleResponse, error)
	DeleteOrganizationRole(ctx context.Context, orgId, roleName string, reassignRoleName ...string) error
	GetOrganizationRoleUsersCount(ctx context.Context, orgId, roleName string) (*GetOrganizationRoleUsersCountResponse, error)
	UpdateDefaultOrganizationRoles(ctx context.Context, orgId, defaultMemberRole string) (*UpdateDefaultOrganizationRolesResponse, error)
	DeleteOrganizationRoleBase(ctx context.Context, orgId, roleName string) error
}

RoleService defines the interface for role management operations

type Scalekit

type Scalekit interface {
	Connection() Connection
	Directory() Directory
	Domain() Domain
	Organization() Organization
	User() UserService
	Passwordless() PasswordlessService
	Role() RoleService
	Permission() PermissionService
	GetAuthorizationUrl(redirectUri string, options AuthorizationUrlOptions) (*url.URL, error)
	AuthenticateWithCode(
		code string,
		redirectUri string,
		options AuthenticationOptions,
	) (*AuthenticationResponse, error)
	GetIdpInitiatedLoginClaims(idpInitiateLoginToken string) (*IdpInitiatedLoginClaims, error)
	ValidateAccessToken(accessToken string) (bool, error)
	VerifyWebhookPayload(secret string, headers map[string]string, payload []byte) (bool, error)
	RefreshAccessToken(refreshToken string) (*TokenResponse, error)
	GetLogoutUrl(options LogoutUrlOptions) (*url.URL, error)
	GetAccessTokenClaims(accessToken string) (*AccessTokenClaims, error)
}

func NewScalekitClient

func NewScalekitClient(envUrl, clientId, clientSecret string) Scalekit

type SendPasswordlessOptions

type SendPasswordlessOptions struct {
	Template          *TemplateType
	MagiclinkAuthUri  string // Use empty string for no magic link URI, or specify the authentication URI
	State             string // Use empty string for no state, or specify a custom state value
	ExpiresIn         uint32 // Use 0 for server default, or specify seconds (e.g., 3600 for 1 hour)
	TemplateVariables map[string]string
}

SendPasswordlessOptions represents optional parameters for sending passwordless authentication

type SendPasswordlessResponse

type SendPasswordlessResponse = authv1.SendPasswordlessResponse

Type aliases for response types

type TemplateType

type TemplateType = authv1.TemplateType

Type aliases for enum types

type ToggleConnectionResponse

type ToggleConnectionResponse = connectionsv1.ToggleConnectionResponse

type ToggleDirectoryResponse

type ToggleDirectoryResponse = directoriesv1.ToggleDirectoryResponse

type TokenResponse

type TokenResponse struct {
	AccessToken  string
	RefreshToken string
	ExpiresIn    int
}

type UpdateDefaultOrganizationRolesResponse added in v2.0.4

type UpdateDefaultOrganizationRolesResponse = rolesv1.UpdateDefaultOrganizationRolesResponse

type UpdateMembershipResponse

type UpdateMembershipResponse = usersv1.UpdateMembershipResponse

type UpdateOrganization

type UpdateOrganization = organizationsv1.UpdateOrganization

type UpdateOrganizationRoleResponse added in v2.0.4

type UpdateOrganizationRoleResponse = rolesv1.UpdateOrganizationRoleResponse

type UpdatePermissionResponse added in v2.0.4

type UpdatePermissionResponse = rolesv1.UpdatePermissionResponse

type UpdateRoleResponse added in v2.0.4

type UpdateRoleResponse = rolesv1.UpdateRoleResponse

type UpdateUserResponse

type UpdateUserResponse = usersv1.UpdateUserResponse

type User

type User = IdTokenClaims

type UserService

type UserService interface {
	CreateUserAndMembership(ctx context.Context, organizationId string, user *usersv1.CreateUser, sendInvitationEmail bool) (*CreateUserAndMembershipResponse, error)
	UpdateUser(ctx context.Context, userId string, updateUser *usersv1.UpdateUser) (*UpdateUserResponse, error)
	GetUser(ctx context.Context, userId string) (*GetUserResponse, error)
	ListOrganizationUsers(ctx context.Context, organizationId string, options *ListUsersOptions) (*ListOrganizationUsersResponse, error)
	DeleteUser(ctx context.Context, userId string) error
	CreateMembership(ctx context.Context, organizationId string, userId string, membership *usersv1.CreateMembership, sendInvitationEmail bool) (*CreateMembershipResponse, error)
	UpdateMembership(ctx context.Context, organizationId string, userId string, membership *usersv1.UpdateMembership) (*UpdateMembershipResponse, error)
	DeleteMembership(ctx context.Context, organizationId string, userId string, cascade bool) error
	ResendInvite(ctx context.Context, organizationId string, userId string) (*usersv1.ResendInviteResponse, error)
}

type VerifyPasswordLessResponse

type VerifyPasswordLessResponse = authv1.VerifyPasswordLessResponse

type VerifyPasswordlessOptions

type VerifyPasswordlessOptions struct {
	Code          string // Use empty string for no code, or specify the OTP code
	LinkToken     string // Use empty string for no link token, or specify the link token
	AuthRequestId string // Use empty string for no auth request id, or specify the id
}

VerifyPasswordlessOptions represents options for verifying passwordless authentication

Jump to

Keyboard shortcuts

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