celerisserver

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Oct 8, 2026 License: Apache-2.0 Imports: 13 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Celeris Go server

Go Reference License

Mints Celeris credentials on a trusted server. Your server authenticates its user, decides what they may do, and signs those claims; clients connect with the result through sdk-go-client or any other Celeris SDK.

How it fits

  1. Your application asks your credential endpoint for credentials.
  2. The endpoint authenticates the user, decides the claims, and signs them with this module.
  3. The application connects with what came back. It never sees the signing secret.

A trusted backend that consumes realtime itself skips the endpoint and signs its own credentials; see A backend that consumes realtime.

Install

go get github.com/useceleris/sdk-go-server

Go 1.27 or newer. The package name is celerisserver. It requires the client module for the credential types and errors, never the other way round, and signs with the standard library only.

Sign credentials

// From trusted configuration, never from code.
signer, err := celerisserver.NewSigner(celerisserver.SignerOptions{
	ClientID:      os.Getenv("CELERIS_CLIENT_ID"),
	SigningSecret: os.Getenv("CELERIS_SIGNING_SECRET"),
})

if err != nil {
	log.Fatal(err)
}

// Claims your server decided for a user it authenticated.
credentials, err := signer.Sign(celerisserver.Claims{
	Channels: celerisserver.RestrictedChannels("room-42"),
	Permissions: celerisserver.RestrictedSegments(
		celerisserver.SegmentClaim{SegmentID: "chat", Read: true, Write: true},
	),
	Reference: "user-8317",
	Replay:    celerisserver.ReplayLookback(30 * time.Second),
})

Sign is synchronous and stamps the current time. Sign afresh for every request: credentials are never cached, reused or backdated. celeris.Credentials encodes as JSON, {"payload": "...", "signature": "..."}, ready to return from your endpoint. A Signer is safe for concurrent use and holds no resources.

Claims

Authenticate and authorize the user before choosing their claims, and never sign permissions a client asked for. The zero Claims is invalid, so unrestricted access is always explicit:

Field Values Default
Channels AllChannels() or RestrictedChannels(references...): 1–255 ASCII letters, digits, -, _ required
Permissions AllSegments(read, write) or RestrictedSegments(claims...); none listed denies all required
Reference the identity peers see in deliveries and presence: nonempty, no colon, CR or LF omitted
Replay ReplayBacklog() for all the server retains, or ReplayLookback(d) in whole milliseconds, 0–4294967295 ms no replay
AllowEcho whether a connection receives its own publishes false

Replay applies each time the connection joins a segment. ReplayLookback(0) and no replay differ: the first replays nothing older than the join.

A credential endpoint

Every browser or mobile application needs one. This handler, from examples/credential-endpoint, authenticates the user, reads a bounded request, authorizes the channel and signs fresh:

http.HandleFunc("POST /realtime-credentials", func(writer http.ResponseWriter, request *http.Request) {
	account, ok := authenticate(request)

	if !ok {
		http.Error(writer, "unauthenticated", http.StatusUnauthorized)

		return
	}

	var body struct {
		ChannelReference string `json:"channelReference"`
		ReplayLookbackMS int64  `json:"replayLookbackMs"`
	}

	if err := json.NewDecoder(http.MaxBytesReader(writer, request.Body, 4096)).Decode(&body); err != nil {
		http.Error(writer, "invalid request", http.StatusBadRequest)

		return
	}

	// Authorize the requested channel against what the user may access.
	if !slices.Contains(account.rooms, body.ChannelReference) {
		http.Error(writer, "forbidden", http.StatusForbidden)

		return
	}

	// Sign fresh per request; never cache or backdate credentials.
	credentials, err := signer.Sign(claimsFor(account, body.ChannelReference, body.ReplayLookbackMS))

	if err != nil {
		http.Error(writer, "signing failed", http.StatusInternalServerError)

		return
	}

	writer.Header().Set("Content-Type", "application/json")
	_ = json.NewEncoder(writer).Encode(credentials)
})

authenticate and claimsFor are yours: your session check, and your policy for what the user may do, including how much replay a reconnecting client may have. Serve the endpoint from an http.Server with ReadHeaderTimeout set.

A backend that consumes realtime

NewCredentialProvider turns a signer into the client's CredentialProvider, for a trusted server that connects itself. Every attempt calls your claims function afresh and signs with a fresh timestamp; nothing in the request widens what it returns.

provider, err := celerisserver.NewCredentialProvider(signer, func(_ context.Context, request celeris.CredentialRequest) (celerisserver.Claims, error) {
	claims := celerisserver.Claims{
		Channels:    celerisserver.RestrictedChannels(request.ChannelReference),
		Permissions: celerisserver.AllSegments(true, true),
	}

	// On reconnect, catch up on what the outage missed.
	if request.Reconnect {
		claims.Replay = celerisserver.ReplayLookback(request.ReplayLookback)
	}

	return claims, nil
})

Pass provider as celeris.ClientOptions.CredentialProvider. examples/quickstart is the whole flow as a program. If the claims function fails or returns invalid claims, the client's Connect reports a generic ErrTransport; sign the claims directly with Sign to see which rule failed.

Errors

Invalid options or claims fail with celeris.ErrConfiguration, naming every field and rule that failed but never the value:

_, err = signer.Sign(celerisserver.Claims{
	Channels:    celerisserver.RestrictedChannels("room-42", "room-42"),
	Permissions: celerisserver.AllSegments(true, false),
	Reference:   "user:8317",
})

fmt.Println(err)
// Output: Invalid claims. Channels.References: Must not repeat a channel reference. Reference: Must not contain a colon, CR or LF.

Every string that is signed must be valid UTF-8. The signed bytes equal the JavaScript reference signer's for the same claims, proven by shared signing vectors.

Keeping the secret

The signing secret is the trust boundary: keep it on trusted servers, and never ship it, or this module, in an application. A Signer keeps the secret only inside the digest it computes, so printing it never shows the secret. SignerOptions print as redacted through fmt and slog, but fmt prints a struct's unexported fields one by one, so pass the options to NewSigner rather than keeping them in a struct of your own. The package prints and logs nothing.

Versioning

Releases follow semantic versioning. Before v1.0.0, a minor release may change the API.

More documentation

Development

make check runs formatting, go vet, golangci-lint, govulncheck, module tidiness and the unit suites under the race detector, including the signing vectors and the package checks, which also compile every snippet in this README. make live runs the acceptance suites against a real Celeris stack; they read CELERIS_WS_URL, CELERIS_CLIENT_ID and CELERIS_SIGNING_SECRET from a gitignored .env or the environment.

Read CONVENTIONS.md before contributing, and SECURITY.md before reporting a vulnerability.

License

Apache 2.0.

Documentation

Overview

Package celerisserver mints Celeris credentials on a trusted server.

A Signer holds your application's signing secret and signs Claims your server decides for a user it has authenticated. Hand the resulting credentials to clients from your own credential endpoint, or let a server that consumes realtime itself sign per attempt with NewCredentialProvider.

Never ship the signing secret, or this package, to a client.

Example
package main

import (
	"log"
	"os"
	"time"

	celerisserver "github.com/useceleris/sdk-go-server"
)

func main() {
	// From trusted configuration, never from code.
	signer, err := celerisserver.NewSigner(celerisserver.SignerOptions{
		ClientID:      os.Getenv("CELERIS_CLIENT_ID"),
		SigningSecret: os.Getenv("CELERIS_SIGNING_SECRET"),
	})

	if err != nil {
		log.Fatal(err)
	}

	// Claims your server decided for a user it authenticated.
	credentials, err := signer.Sign(celerisserver.Claims{
		Channels: celerisserver.RestrictedChannels("room-42"),
		Permissions: celerisserver.RestrictedSegments(
			celerisserver.SegmentClaim{SegmentID: "chat", Read: true, Write: true},
		),
		Reference: "user-8317",
		Replay:    celerisserver.ReplayLookback(30 * time.Second),
	})

	if err != nil {
		log.Fatal(err)
	}

	// Return them from your credential endpoint as JSON:
	// {"payload": "...", "signature": "..."}.
	_ = credentials
}

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewCredentialProvider

func NewCredentialProvider(signer *Signer, claims ClaimsFunc) (celeris.CredentialProvider, error)

NewCredentialProvider returns a celeris.CredentialProvider for a trusted server that consumes realtime itself. Every attempt calls claims afresh and signs with a fresh timestamp. A context already done, before claims runs or after it returns, fails without signing; claims' own errors are returned unchanged, and the client reports them as a transport failure.

It fails with celeris.ErrConfiguration when signer or claims is nil.

Example

A backend that consumes realtime itself signs fresh claims for every connection attempt.

package main

import (
	"context"
	"log"

	celeris "github.com/useceleris/sdk-go-client"
	celerisserver "github.com/useceleris/sdk-go-server"
)

func main() {
	var signer *celerisserver.Signer // from celerisserver.NewSigner

	provider, err := celerisserver.NewCredentialProvider(signer, func(_ context.Context, request celeris.CredentialRequest) (celerisserver.Claims, error) {
		claims := celerisserver.Claims{
			Channels:    celerisserver.RestrictedChannels(request.ChannelReference),
			Permissions: celerisserver.AllSegments(true, true),
		}

		// On reconnect, catch up on what the outage missed.
		if request.Reconnect {
			claims.Replay = celerisserver.ReplayLookback(request.ReplayLookback)
		}

		return claims, nil
	})

	if err != nil {
		log.Fatal(err)
	}

	client, err := celeris.NewClient(celeris.ClientOptions{CredentialProvider: provider})

	if err != nil {
		log.Fatal(err)
	}

	_ = client
}

Types

type ChannelScope

type ChannelScope struct {
	// contains filtered or unexported fields

} // end struct ChannelScope

ChannelScope is the set of channels credentials may connect to. Make one with AllChannels or RestrictedChannels.

func AllChannels

func AllChannels() ChannelScope

AllChannels grants every channel of the application.

func RestrictedChannels

func RestrictedChannels(references ...string) ChannelScope

RestrictedChannels grants only the listed channels: at least one, each listed once.

type Claims

type Claims struct {
	// Channels the credentials may connect to.
	Channels ChannelScope

	// Permissions on the segments of those channels.
	Permissions SegmentPermissions

	// Reference identifies the token, such as a user id, in presence and
	// deliveries. Empty leaves it out.
	Reference string

	// Replay is the history replayed on each segment join. The zero value
	// replays nothing.
	Replay Replay

	// AllowEcho lets a connection receive its own publishes.
	AllowEcho bool

} // end struct Claims

Claims are what one set of credentials grants. Your server decides them for a user it has authenticated; nothing from the client widens them.

The zero value is invalid: Channels and Permissions must be chosen explicitly, so unrestricted access is never granted by omission (AUTH-02).

type ClaimsFunc

type ClaimsFunc func(ctx context.Context, request celeris.CredentialRequest) (Claims, error)

ClaimsFunc decides the claims for one connection attempt. It is authoritative: nothing in the request, which comes from the connecting client, widens scope beyond what it returns.

type Replay

type Replay struct {
	// contains filtered or unexported fields

} // end struct Replay

Replay is the history replayed when a connection joins a segment. Make one with ReplayBacklog or ReplayLookback; the zero value replays nothing.

func ReplayBacklog

func ReplayBacklog() Replay

ReplayBacklog replays everything the server still retains for a segment.

func ReplayLookback

func ReplayLookback(lookback time.Duration) Replay

ReplayLookback replays what a segment received within lookback before the join: whole milliseconds, from 0 to 4294967295. Zero replays nothing older than the join.

type SegmentClaim

type SegmentClaim struct {
	SegmentID string
	Read      bool
	Write     bool

} // end struct SegmentClaim

SegmentClaim grants access to one segment.

type SegmentPermissions

type SegmentPermissions struct {
	// contains filtered or unexported fields

} // end struct SegmentPermissions

SegmentPermissions grant read and write access to segments. Make one with AllSegments or RestrictedSegments.

func AllSegments

func AllSegments(read, write bool) SegmentPermissions

AllSegments grants the same access to every segment.

func RestrictedSegments

func RestrictedSegments(segments ...SegmentClaim) SegmentPermissions

RestrictedSegments grants access to the listed segments only, each listed once. With none listed, the credentials can connect but neither read nor write.

type Signer

type Signer struct {
	// contains filtered or unexported fields

} // end struct Signer

Signer mints credentials on a trusted server. It keeps the signing secret only inside the digest it computes, so printing a Signer, even field by field, never shows the secret. It is safe for concurrent use.

func NewSigner

func NewSigner(options SignerOptions) (*Signer, error)

NewSigner validates options and returns a signer. It fails with celeris.ErrConfiguration, naming the field and rule but never the value.

func (*Signer) Sign

func (signer *Signer) Sign(claims Claims) (celeris.Credentials, error)

Sign mints credentials for claims, timestamped now. Sign fresh for every connection attempt; never cache or reuse credentials (D-001). It fails with celeris.ErrConfiguration for invalid claims, naming each field and rule.

Example

Invalid claims name each field and rule, never the value.

package main

import (
	"fmt"
	"log"

	celerisserver "github.com/useceleris/sdk-go-server"
)

func main() {
	signer, err := celerisserver.NewSigner(celerisserver.SignerOptions{ClientID: "client", SigningSecret: "secret"})

	if err != nil {
		log.Fatal(err)
	}

	_, err = signer.Sign(celerisserver.Claims{
		Channels:    celerisserver.RestrictedChannels("room-42", "room-42"),
		Permissions: celerisserver.AllSegments(true, false),
		Reference:   "user:8317",
	})

	fmt.Println(err)
}
Output:
Invalid claims. Channels.References: Must not repeat a channel reference. Reference: Must not contain a colon, CR or LF.

type SignerOptions

type SignerOptions struct {
	// ClientID is your application's client id: nonempty, with no colon, CR
	// or LF.
	ClientID string

	// SigningSecret is your application's signing secret. Keep it on trusted
	// servers only.
	SigningSecret string

	// Clock returns the time credentials are signed at. Nil means time.Now.
	Clock func() time.Time

} // end struct SignerOptions

SignerOptions configures a Signer. They hold the signing secret, so fmt verbs and slog show them as redacted. fmt prints an unexported struct field field by field, which redaction cannot reach: pass the options to NewSigner rather than keeping them in a struct of your own.

func (SignerOptions) Format

func (SignerOptions) Format(state fmt.State, _ rune)

Format redacts the options for every fmt verb.

func (SignerOptions) LogValue

func (SignerOptions) LogValue() slog.Value

LogValue redacts the options in slog output.

func (SignerOptions) String

func (SignerOptions) String() string

Directories

Path Synopsis
examples
credential-endpoint command
Command credential-endpoint is the endpoint every browser or mobile application needs.
Command credential-endpoint is the endpoint every browser or mobile application needs.
quickstart command
Command quickstart is a trusted backend process that signs its own credentials and consumes realtime through the client: the pattern for a backend worker, not a browser.
Command quickstart is a trusted backend process that signs its own credentials and consumes realtime through the client: the pattern for a backend worker, not a browser.

Jump to

Keyboard shortcuts

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