directory

package
v0.1.0-beta.1 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: Apache-2.0 Imports: 19 Imported by: ? modules, 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.

Documentation

Overview

Package directory stores who exists on a Lagrange instance: people (users, with a human address each), agent addresses, the bearer tokens agents use, and web sessions.

An address is a handle such as "acme-buyer" or "kaan". It is the A2A tenant: the address's agent card lives at /a/<handle>/.well-known/agent-card.json, and every call to /a/<handle> is a task for it. An agent address is reached through a tunnel (no endpoint) or directly at a public endpoint.

Index

Constants

View Source
const (
	LinkVerify = "verify"
	LinkLogin  = "login"
	LinkReset  = "reset"
	LinkInvite = "invite"
)

Purposes of an AuthLink.

View Source
const (
	// AccessPublic lets anyone call, without credentials.
	AccessPublic = "public"
	// AccessWorkspace lets the address's workspaces call.
	AccessWorkspace = "workspace"
	// AccessConnections lets the address's workspaces call, and the workspaces it
	// accepted a connection from.
	AccessConnections = "connections"
)

Who may start a task with an address (Address.Access).

View Source
const (
	ConnPending  = "pending"
	ConnAccepted = "accepted"
	ConnDeclined = "declined"
	ConnBlocked  = "blocked"
)

Statuses of a Connection.

View Source
const (
	KindAgent = "agent"
	KindHuman = "human"
)

Kinds of address.

View Source
const (
	// RoleOwner manages members and roles, and everything an admin does.
	RoleOwner = "owner"
	// RoleAdmin manages agents, tokens, invitations and the waiting rules.
	RoleAdmin = "admin"
	// RoleMember sends, answers, cancels and hides runs.
	RoleMember = "member"
	// RoleViewer only looks.
	RoleViewer = "viewer"
)

Roles in a workspace, from most to least power.

View Source
const APIKeyPrefix = "lgk_"

APIKeyPrefix starts every personal API key, so it can't be mistaken for an address token (lgr_) or a session (lgs_).

View Source
const CLILoginTTL = 5 * time.Minute

CLILoginTTL is how long a `lagrange login` code can be traded for a key.

View Source
const DefaultWorkspace = "default"

DefaultWorkspace is the slug of the workspace that existed before there were workspaces; people an admin creates join it.

View Source
const SessionTTL = 30 * 24 * time.Hour

SessionTTL is how long a web session lasts.

Variables

View Source
var (
	// ErrRoleTooHigh means a key would get more power than its person has.
	ErrRoleTooHigh = errors.New("directory: a key can't have a higher role than yours")
	// ErrBadCode means a login code is unknown, used, expired, or its verifier is wrong.
	ErrBadCode = errors.New("directory: that login code is wrong or expired")
)
View Source
var (
	// ErrNotFound means no such user, address, token or session.
	ErrNotFound = errors.New("directory: not found")
	// ErrTaken means the handle or email is already in use.
	ErrTaken = errors.New("directory: already taken")
	// ErrInvalidHandle means the handle doesn't match HandlePattern.
	ErrInvalidHandle = errors.New("directory: a handle is 2-40 characters: lowercase letters, digits and dashes, starting with a letter or digit")
	// ErrBadCredentials means the email or password is wrong.
	ErrBadCredentials = errors.New("directory: wrong email or password")
	// ErrShortPassword means the password has fewer than 8 characters.
	ErrShortPassword = errors.New("directory: the password needs at least 8 characters")
	// ErrInvalidEmail means the email has no @.
	ErrInvalidEmail = errors.New("directory: that doesn't look like an email address")
)
View Source
var (
	// ErrLastOwner means the change would leave a workspace without an owner.
	ErrLastOwner = errors.New("directory: a workspace needs at least one owner")
	// ErrNotMember means the person isn't a member of the workspace.
	ErrNotMember = errors.New("directory: not a member of that workspace")
)
View Source
var ErrBlocked = errors.New("directory: blocked")

ErrBlocked means the address blocked the workspace.

View Source
var HandlePattern = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{1,39}$`)

HandlePattern is what a handle must look like.

Functions

func NormalizeEmail

func NormalizeEmail(email string) string

NormalizeEmail trims and lowercases an email, so lookups don't depend on case.

func PKCEChallenge

func PKCEChallenge(verifier string) string

PKCEChallenge is the S256 challenge of a verifier (RFC 7636).

func RoleAtLeast

func RoleAtLeast(role, min string) bool

RoleAtLeast reports whether role has at least the power of min.

func ValidAccess

func ValidAccess(access string) bool

ValidAccess reports whether access is one of the three.

func ValidRole

func ValidRole(role string) bool

ValidRole reports whether role is one of the four roles.

Types

type APIKey

type APIKey struct {
	ID        int64      `json:"id"`
	Name      string     `json:"name"`
	Prefix    string     `json:"prefix"`
	Role      string     `json:"role"`
	Workspace string     `json:"workspace"`
	CreatedAt time.Time  `json:"createdAt"`
	LastUsed  *time.Time `json:"lastUsed,omitempty"`
}

APIKey is a personal API key, without its secret.

type Address

type Address struct {
	Handle      string `json:"handle"`
	Kind        string `json:"kind"`
	OwnerID     int64  `json:"ownerId,omitempty"`
	DisplayName string `json:"displayName"`
	Description string `json:"description"`
	// Endpoint is the agent's public base URL. Empty means it connects through a tunnel.
	Endpoint string `json:"endpoint,omitempty"`
	// Access is who may start a task with the address (AccessPublic, AccessWorkspace or
	// AccessConnections).
	Access string `json:"access"`
	// WorkspaceID is the agent's workspace. People's addresses have none: they belong to
	// every workspace the person is a member of.
	WorkspaceID int64 `json:"workspaceId,omitempty"`
	// Card is the agent's own card as last fetched from the agent.
	Card      *a2a.AgentCard `json:"card,omitempty"`
	CreatedAt time.Time      `json:"createdAt"`
}

Address is an agent or a person that can receive tasks.

func (*Address) Name

func (a *Address) Name() string

Name returns the display name, or the handle when there is none.

type AuthLink struct {
	Purpose string
	Email   string
	// UserID is the person it is for; zero for an invitation (they don't exist yet).
	UserID int64
	// InvitedBy is who sent an invitation; zero otherwise.
	InvitedBy int64
	// WorkspaceID and Role are what an invitation joins.
	WorkspaceID int64
	Role        string
	ExpiresAt   time.Time
}

AuthLink is a one-time link sent by email.

type Connection

type Connection struct {
	ID int64 `json:"id"`
	// From is the workspace asking; FromName its name.
	From     int64  `json:"from"`
	FromName string `json:"fromName"`
	To       string `json:"to"`
	Status   string `json:"status"`
	Note     string `json:"note"`
	// RatePerMin caps how many calls a minute the workspace may make to the address.
	RatePerMin  int        `json:"ratePerMin"`
	RequestedBy string     `json:"requestedBy,omitempty"`
	DecidedBy   string     `json:"decidedBy,omitempty"`
	CreatedAt   time.Time  `json:"createdAt"`
	DecidedAt   *time.Time `json:"decidedAt,omitempty"`
}

Connection is a workspace's standing to reach an address of another workspace.

type DecisionLink struct {
	TaskID    string
	Handle    string
	ExpiresAt time.Time
}

DecisionLink lets whoever holds it answer one task as Handle, once.

type Directory

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

Directory is the Postgres-backed directory.

func New

func New(db *pg.DB) *Directory

New returns a directory on db.

func (*Directory) APIKeyUser

func (d *Directory) APIKeyUser(ctx context.Context, secret string) (*User, *KeyGrant, error)

APIKeyUser returns the person a live key acts as and what it may do.

func (*Directory) APIKeys

func (d *Directory) APIKeys(ctx context.Context, userID int64) ([]*APIKey, error)

APIKeys lists a person's live keys, newest first.

func (*Directory) AddMember

func (d *Directory) AddMember(ctx context.Context, workspaceID, userID int64, role string) error

AddMember adds a person to a workspace. Someone already in it is ErrTaken.

func (*Directory) Address

func (d *Directory) Address(ctx context.Context, handle string) (*Address, error)

Address returns the address with handle.

func (*Directory) Addresses

func (d *Directory) Addresses(ctx context.Context) ([]*Address, error)

Addresses lists all addresses, people first, then agents, by handle.

func (*Directory) AddressesIn

func (d *Directory) AddressesIn(ctx context.Context, workspaceID int64) ([]*Address, error)

AddressesIn lists a workspace's addresses, people first, then agents, by handle.

func (d *Directory) AuthLink(ctx context.Context, token, purpose string) (*AuthLink, error)

AuthLink returns an unused, unexpired link for purpose.

func (*Directory) ChangePassword

func (d *Directory) ChangePassword(ctx context.Context, userID int64, current, password string) error

ChangePassword sets a new password after checking the current one. Someone without a password (links or a provider only) sets their first one without it.

func (d *Directory) ClaimAuthLink(ctx context.Context, token, purpose string) (*AuthLink, error)

ClaimAuthLink marks a link used and returns it, unless it was used, expired or is for another purpose. Of two concurrent claims, only one succeeds.

func (*Directory) ClaimCLILogin

func (d *Directory) ClaimCLILogin(ctx context.Context, code, verifier string) (string, *APIKey, error)

ClaimCLILogin trades a login code and its PKCE verifier for a new key, once.

func (d *Directory) ClaimDecisionLink(ctx context.Context, token string) (*DecisionLink, error)

ClaimDecisionLink marks a link used and returns it, unless it was used or expired. Of two concurrent claims, only one succeeds.

func (*Directory) Connection

func (d *Directory) Connection(ctx context.Context, id int64) (*Connection, error)

Connection returns one connection.

func (*Directory) ConnectionsFrom

func (d *Directory) ConnectionsFrom(ctx context.Context, workspaceID int64) ([]*Connection, error)

ConnectionsFrom lists the connections a workspace asked for, newest first.

func (*Directory) ConnectionsTo

func (d *Directory) ConnectionsTo(ctx context.Context, handles []string) ([]*Connection, error)

ConnectionsTo lists the connections asked of the given addresses, pending first.

func (*Directory) CreateAPIKey

func (d *Directory) CreateAPIKey(ctx context.Context, userID, wsID int64, name, role string) (string, *APIKey, error)

CreateAPIKey creates a key for userID in workspace wsID with at most role, and returns its secret, which is visible only now. The role can't exceed the person's own.

func (*Directory) CreateAgent

func (d *Directory) CreateAgent(ctx context.Context, a *Address) error

CreateAgent creates an agent address in a.WorkspaceID (the default workspace when zero), owned by a.OwnerID.

func (*Directory) CreateUser

func (d *Directory) CreateUser(ctx context.Context, email, name, handle, password string, admin bool) (*User, error)

CreateUser creates a person and their human address in the default workspace (admins as owners). An admin vouches for the email, so it counts as verified.

func (*Directory) CreateWorkspace

func (d *Directory) CreateWorkspace(ctx context.Context, name, hint string, ownerID int64) (*Workspace, error)

CreateWorkspace creates a workspace owned by ownerID. The slug comes from hint (made unique); the name is name.

func (*Directory) DecideConnection

func (d *Directory) DecideConnection(ctx context.Context, id int64, status string, ratePerMin int, by int64) error

DecideConnection sets a connection's status (and rate, when above zero).

func (d *Directory) DecisionLink(ctx context.Context, token string) (*DecisionLink, error)

DecisionLink returns an unused, unexpired link.

func (*Directory) Default

func (d *Directory) Default(ctx context.Context) (*Workspace, error)

Default returns the default workspace, creating it if needed.

func (*Directory) DeleteAddress

func (d *Directory) DeleteAddress(ctx context.Context, handle string) error

DeleteAddress removes an agent address and its tokens.

func (*Directory) DeleteConnection

func (d *Directory) DeleteConnection(ctx context.Context, id int64) error

DeleteConnection removes a connection: withdrawn by the asker, or ended by the address.

func (*Directory) EndSessions

func (d *Directory) EndSessions(ctx context.Context, userID int64, keepToken string) error

EndSessions logs a person out everywhere except the session with keepToken (may be empty).

func (*Directory) EnsureAdmin

func (d *Directory) EnsureAdmin(ctx context.Context, email, name, handle, password string) (*User, error)

EnsureAdmin creates the admin user unless a user with that email exists.

func (*Directory) FreeHandle

func (d *Directory) FreeHandle(ctx context.Context, hint string) (string, error)

FreeHandle turns a hint (a provider login, a name, an email) into a valid handle that nobody has yet, adding -2, -3, … when needed.

func (*Directory) HandleWorkspaces

func (d *Directory) HandleWorkspaces(ctx context.Context) (map[string][]int64, error)

HandleWorkspaces maps each address to the workspaces it belongs to: an agent's one workspace, or every workspace a person is a member of (oldest first).

func (*Directory) Identities

func (d *Directory) Identities(ctx context.Context, userID int64) ([]*Identity, error)

Identities lists a person's OAuth accounts.

func (*Directory) LinkIdentity

func (d *Directory) LinkIdentity(ctx context.Context, userID int64, provider, subject, email string) error

LinkIdentity lets an OAuth account log the person in. An account already linked to someone else is ErrTaken.

func (*Directory) Login

func (d *Directory) Login(ctx context.Context, email, password string) (*User, string, error)

Login checks the password and starts a session. It returns the session token.

func (*Directory) Logout

func (d *Directory) Logout(ctx context.Context, token string) error

Logout ends a session.

func (*Directory) MarkVerified

func (d *Directory) MarkVerified(ctx context.Context, userID int64) error

MarkVerified records that the person proved they own their email.

func (*Directory) Members

func (d *Directory) Members(ctx context.Context, workspaceID int64) ([]*Member, error)

Members lists a workspace's members, owners first.

func (*Directory) Membership

func (d *Directory) Membership(ctx context.Context, userID int64, slug string) (*Workspace, error)

Membership returns the workspace with slug and the person's role in it, or ErrNotMember.

func (d *Directory) MintAuthLink(ctx context.Context, l AuthLink, ttl time.Duration) (string, error)

MintAuthLink creates a link token. Only its hash is stored.

func (d *Directory) MintDecisionLink(ctx context.Context, taskID, handle string, ttl time.Duration) (string, error)

MintDecisionLink creates a link token for a task waiting on handle. Only its hash is stored.

func (*Directory) MintToken

func (d *Directory) MintToken(ctx context.Context, handle, label string) (string, error)

MintToken creates a bearer token for an address and returns it. Only its hash is stored, so this is the only time the token is visible.

func (*Directory) NotificationSettings

func (d *Directory) NotificationSettings(ctx context.Context, userID int64) (*NotificationSettings, error)

NotificationSettings returns a person's settings, or the defaults (email on).

func (*Directory) ReachOf

func (d *Directory) ReachOf(ctx context.Context, caller, handle string) (*Reach, error)

ReachOf works out how caller (an address) stands with the address handle: through a shared workspace, an accepted connection, or not at all.

func (*Directory) Register

func (d *Directory) Register(ctx context.Context, r Registration) (*User, error)

Register creates a person, their human address and, with Provider, their identity.

func (d *Directory) ReleaseAuthLink(ctx context.Context, token string) error

ReleaseAuthLink makes a claimed link usable again, after what it was for failed.

func (d *Directory) ReleaseDecisionLink(ctx context.Context, token string) error

ReleaseDecisionLink makes a claimed link usable again, after the answer failed.

func (*Directory) RemoveMember

func (d *Directory) RemoveMember(ctx context.Context, workspaceID, userID int64) error

RemoveMember takes a person out of a workspace, keeping at least one owner.

func (*Directory) RenameWorkspace

func (d *Directory) RenameWorkspace(ctx context.Context, id int64, name string) error

RenameWorkspace changes a workspace's name (its slug stays).

func (*Directory) RequestConnection

func (d *Directory) RequestConnection(ctx context.Context, from int64, handle, note string, by int64) (*Connection, error)

RequestConnection asks for workspace from to reach handle. Asking again after a decline asks anew; a pending or accepted connection is returned as it is; a blocked one is ErrBlocked.

func (*Directory) RevokeAPIKey

func (d *Directory) RevokeAPIKey(ctx context.Context, userID, id int64) error

RevokeAPIKey revokes one of a person's keys.

func (*Directory) Session

func (d *Directory) Session(ctx context.Context, token string) (*User, error)

Session returns the user of a live session token.

func (*Directory) SetAccess

func (d *Directory) SetAccess(ctx context.Context, handle, access string) error

SetAccess changes who may start a task with an address.

func (*Directory) SetCard

func (d *Directory) SetCard(ctx context.Context, handle string, card *a2a.AgentCard) error

SetCard stores the card an agent serves. The display name and description follow the card unless they were set by hand.

func (*Directory) SetNotificationSettings

func (d *Directory) SetNotificationSettings(ctx context.Context, userID int64, s *NotificationSettings) error

SetNotificationSettings stores a person's settings.

func (*Directory) SetPassword

func (d *Directory) SetPassword(ctx context.Context, userID int64, password string) error

SetPassword replaces a person's password.

func (*Directory) SetRole

func (d *Directory) SetRole(ctx context.Context, workspaceID, userID int64, role string) error

SetRole changes a member's role, keeping at least one owner.

func (*Directory) StartCLILogin

func (d *Directory) StartCLILogin(ctx context.Context, userID, wsID int64, name, role, challenge string) (string, error)

StartCLILogin records that userID approved a CLI login for workspace wsID with at most role, and returns the one-time code the CLI trades for a key. challenge is the CLI's PKCE S256 challenge, so only the CLI that started the login can claim the code.

func (*Directory) StartSession

func (d *Directory) StartSession(ctx context.Context, userID int64) (*User, string, error)

StartSession starts a web session for a user and returns the session token.

func (*Directory) TokenHandle

func (d *Directory) TokenHandle(ctx context.Context, token string) (string, error)

TokenHandle returns the address a bearer token belongs to.

func (*Directory) Tokens

func (d *Directory) Tokens(ctx context.Context, handle string) ([]*Token, error)

Tokens lists an address's tokens without their secrets.

func (*Directory) UserByEmail

func (d *Directory) UserByEmail(ctx context.Context, email string) (*User, error)

UserByEmail returns the person with that email.

func (*Directory) UserByHandle

func (d *Directory) UserByHandle(ctx context.Context, handle string) (*User, error)

UserByHandle returns the person whose address is handle.

func (*Directory) UserByID

func (d *Directory) UserByID(ctx context.Context, id int64) (*User, error)

UserByID returns the person with that ID.

func (*Directory) UserByIdentity

func (d *Directory) UserByIdentity(ctx context.Context, provider, subject string) (*User, error)

UserByIdentity returns the person an OAuth account belongs to.

func (*Directory) Users

func (d *Directory) Users(ctx context.Context) ([]*User, error)

Users lists everyone.

func (*Directory) WorkspaceByID

func (d *Directory) WorkspaceByID(ctx context.Context, id int64) (*Workspace, error)

WorkspaceByID returns a workspace (without a role).

func (*Directory) WorkspaceHandles

func (d *Directory) WorkspaceHandles(ctx context.Context, workspaceID int64) ([]string, error)

WorkspaceHandles lists the addresses a workspace sees the traffic of: its agents and its members' own addresses.

func (*Directory) Workspaces

func (d *Directory) Workspaces(ctx context.Context, userID int64) ([]*Workspace, error)

Workspaces lists the workspaces a person is a member of, oldest membership first, with their role.

type Identity

type Identity struct {
	Provider  string    `json:"provider"`
	Email     string    `json:"email"`
	CreatedAt time.Time `json:"createdAt"`
}

Identity is an OAuth account that logs a person in.

type KeyGrant

type KeyGrant struct {
	WorkspaceID int64
	Workspace   string
	Role        string
}

KeyGrant is what a key may do: act as its person in Workspace with at most Role.

type Member

type Member struct {
	User
	Role     string    `json:"role"`
	JoinedAt time.Time `json:"joinedAt"`
}

Member is a person in a workspace.

type NotificationSettings

type NotificationSettings struct {
	Email bool `json:"email"`
	// SlackWebhook is a Slack incoming webhook URL; empty means no Slack.
	SlackWebhook string `json:"slackWebhook"`
}

NotificationSettings is how a person wants to hear that a task waits on them.

type Reach

type Reach struct {
	// SameWorkspace is true when caller and address share a workspace.
	SameWorkspace bool
	// Connection is the accepted connection from one of the caller's workspaces.
	Connection *Connection
	// Blocked is true when the address blocked one of the caller's workspaces.
	Blocked bool
}

Reach is how a caller may reach an address: the connection that lets it, if any.

type Registration

type Registration struct {
	Email, Name, Handle string
	// Password may be empty when the person logs in with a provider (Provider is set).
	Password string
	Admin    bool
	// Verified marks the email as proven: by an admin, an invitation link or a provider.
	Verified bool
	// Provider and Subject link an OAuth account at the same time.
	Provider, Subject string
	// Workspace, with Role, is the workspace the person joins. Zero gives them a
	// workspace of their own, as its owner.
	Workspace int64
	Role      string
}

Registration is a new person.

type Token

type Token struct {
	Handle    string     `json:"handle"`
	Label     string     `json:"label"`
	Prefix    string     `json:"prefix"`
	CreatedAt time.Time  `json:"createdAt"`
	LastUsed  *time.Time `json:"lastUsed,omitempty"`
}

Token is a minted bearer token's public part.

type User

type User struct {
	ID     int64  `json:"id"`
	Email  string `json:"email"`
	Name   string `json:"name"`
	Handle string `json:"handle"`
	Admin  bool   `json:"admin"`
	// Verified means the person proved they own Email (or an admin vouched for them).
	Verified bool `json:"verified"`
	// HasPassword is false for people who log in only with links or a provider.
	HasPassword bool `json:"hasPassword"`
}

User is a person who can log in.

type Workspace

type Workspace struct {
	ID   int64  `json:"id"`
	Slug string `json:"slug"`
	Name string `json:"name"`
	// Role is the reader's role in it, when listed for someone.
	Role string `json:"role,omitempty"`
}

Workspace is a team: its agents and its members.

Jump to

Keyboard shortcuts

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