2. API Reference (fleetmesh_auth)#

Public symbols are re-exported from the top-level fleetmesh_auth package. Each symbol is documented below under its defining module.

2.1. Engine#

Core authentication engine for FleetMesh Auth (fleetmesh_auth.engine).

class fleetmesh_auth.engine.FleetmeshAuthEngine[source]#

Bases: object

Pluggable multi-provider authentication engine for FleetMesh applications.

Coordinates:

  • Sovereign Key / DID / NIP-46 Bunker / NIP-07 Browser Extension / Passkey auth

  • Provider plugins (accounts on other services, e.g. ‘Sign in with Acme’; see plugins.py)

  • Standalone Node Operator Token auth (LocalOperatorProvider)

  • Developer/Operator modular login method & provider selection

  • Unified session storage (fleetmesh_auth_sessions) + automatic session bridging with an attached host application engine (sessions and admin_sessions) when co-hosted.

__init__(*, db_path=None, host=None, directory=None, domain='fleetmesh.local', session_ttl_sec=604800, allow_any_sovereign_key=False, enabled_methods=None, disabled_methods=None, enabled_providers=None, disabled_providers=None, plugins=True, clock=None, token_source=None, store=None)[source]#
Parameters:
Return type:

None

property host: Any#
register_passkey(*, credential_id, pubkey_hex, did, handle, public_key_b64='')[source]#
Parameters:
  • credential_id (str)

  • pubkey_hex (str)

  • did (str)

  • handle (str)

  • public_key_b64 (str)

Return type:

None

get_passkey(credential_id)[source]#
Parameters:

credential_id (str)

Return type:

Dict[str, Any] | None

register_provider(provider)[source]#
Parameters:

provider (AuthProviderPlugin)

Return type:

None

list_providers()[source]#
Return type:

List[Dict[str, Any]]

set_enabled_methods(enabled_methods=None, *, disabled_methods=None)[source]#

Configure which login methods this engine allows.

Parameters:
Return type:

None

set_enabled_providers(enabled_providers=None, *, disabled_providers=None)[source]#

Configure which authentication providers this engine allows.

Parameters:
Return type:

None

list_login_methods(preset='standard')[source]#

Return the modular login options currently enabled on this engine.

Parameters:

preset (str)

Return type:

List[Dict[str, Any]]

get_widget_config(preset='standard', overrides=None)[source]#
Parameters:
Return type:

Dict[str, Any]

now()[source]#
Return type:

int

ping()[source]#

True when the session store answers a trivial query (readiness).

Return type:

bool

count_active_sessions()[source]#

Unexpired sessions in the engine’s own store (one COUNT query).

Return type:

int

sweep_sessions()[source]#

Delete expired sessions (and replay state); returns sessions removed.

Return type:

int

close()[source]#

Release the store’s connections. The engine is unusable afterwards.

Return type:

None

reset_replay_state()[source]#

Forget outstanding challenges, used auth events and sessions (tests).

Return type:

None

issue_challenge(domain=None)[source]#
Parameters:

domain (str | None)

Return type:

Dict[str, Any]

authenticate(payload, *, app_preset='standard', required_role=None)[source]#
Parameters:
Return type:

Dict[str, Any]

register(payload, *, domain=None, app_preset=None)[source]#

Create an account through a provider’s register hook and open a session for it, replying exactly like a successful login.

The provider is payload[“provider”]; when none is named and exactly one registered provider supports registration, that one is used. Refusals: provider_required, unknown_provider, registration_unsupported, provider_not_enabled, method_not_enabled, provider_error, and whatever the provider returns (handle_taken, invalid_handle, weak_password, …).

Parameters:
Return type:

Dict[str, Any]

check_handle(provider_id, handle, *, app_preset=None)[source]#

Ask a provider whether handle could be registered, through its check_handle hook (GET /api/fauth/register/check).

Replies {“ok”: True, “available”: bool, “reason”: None | “handle_taken” | “invalid_handle”} and nothing else. The handle is trimmed, a leading @ dropped, and anything empty, longer than HANDLE_MAX_LEN or outside [A-Za-z0-9._-] is answered invalid_handle before the provider sees it. Refusals: provider_required, unknown_provider, handle_check_unsupported, provider_not_enabled, provider_error, and whatever ok: False the hook returns.

Parameters:
  • provider_id (str | None)

  • handle (str | None)

  • app_preset (str | None)

Return type:

Dict[str, Any]

verify_session(token, *, required_role=None)[source]#

Resolve a bearer credential to its principal.

token may be a session token or the separate admin token issued with an admin session; both are looked up by their sha256, never stored in the clear. The principal reports which one was presented: session_token for a session token, admin_token for an admin token.

Parameters:
  • token (str)

  • required_role (str | None)

Return type:

Dict[str, Any]

revoke_session(token)[source]#

End a session. Either credential works: a session token deletes the session and every admin token that points at it; an admin token deletes that admin credential and the session behind it.

Parameters:

token (str)

Return type:

Dict[str, Any]

2.2. Principals and Roles#

Standardized FleetMesh AuthPrincipal, Role Clearance, Modular Login Options, and White-Label Widget Config.

fleetmesh_auth.principal.normalize_method_id(raw_method)[source]#

Normalize any login method alias to its canonical method_id.

Parameters:

raw_method (str)

Return type:

str

class fleetmesh_auth.principal.AuthPrincipal[source]#

Bases: object

Canonical authenticated identity across FleetMesh applications.

principal_id: str#
did: str#
pubkey: str = ''#
handle: str = ''#
display_name: str = ''#
username: str = ''#
auth_method: str = 'service_login'#
provider_id: str = ''#
roles: list[str]#
scopes: list[str]#
session_token: str = ''#
admin_token: str = ''#
portable_ticket: str = ''#
bunker_relay: str = ''#
issued_at: int = 0#
expires_at: int = 0#
metadata: dict[str, Any]#
pubkey_hex: str = ''#
provider: str = ''#
has_role(required_role)[source]#
Parameters:

required_role (str)

Return type:

bool

to_dict()[source]#
Return type:

dict[str, Any]

__init__(principal_id, did, pubkey='', handle='', display_name='', username='', auth_method='service_login', provider_id='', roles=<factory>, scopes=<factory>, session_token='', admin_token='', portable_ticket='', bunker_relay='', issued_at=0, expires_at=0, metadata=<factory>, pubkey_hex='', provider='')#
Parameters:
Return type:

None

class fleetmesh_auth.principal.AuthWidgetConfig[source]#

Bases: object

White-label FleetMesh Auth Panel configuration for a host application.

app_id: str#
app_title: str#
app_subtitle: str#
mode: str = 'modal'#
brand_name: str = 'fleetmesh'#
brand_badge: str = '.auth'#
accent_primary: str = '#ff2a3c'#
accent_secondary: str = '#ff6b1a'#
logo_variant: str = 'sails'#
required_role: str = 'broadcaster'#
enabled_methods: list[str]#
disabled_methods: list[str]#
primary_methods: list[str]#
enabled_providers: list[str]#
disabled_providers: list[str]#
providers: list[dict[str, Any]]#
primary_actions: list[str]#
more_options_label: str = 'More options'#
signup_provider: str | None = None#
property accent_color: str#
is_method_enabled(method_or_alias)[source]#

Return True if method_or_alias is permitted by this widget config.

Parameters:

method_or_alias (str)

Return type:

bool

get_login_options(providers_detail=None)[source]#

Return resolved modular login button descriptors for primary and expert views.

Parameters:

providers_detail (Sequence[Mapping[str, Any]] | None)

Return type:

list[dict[str, Any]]

to_dict()[source]#
Return type:

dict[str, Any]

__init__(app_id, app_title, app_subtitle, mode='modal', brand_name='fleetmesh', brand_badge='.auth', accent_primary='#ff2a3c', accent_secondary='#ff6b1a', logo_variant='sails', required_role='broadcaster', enabled_methods=<factory>, disabled_methods=<factory>, primary_methods=<factory>, enabled_providers=<factory>, disabled_providers=<factory>, providers=<factory>, primary_actions=<factory>, more_options_label='More options', signup_provider=None)#
Parameters:
Return type:

None

fleetmesh_auth.principal.resolve_login_options(config, providers_detail=None)[source]#

Build the ordered list of modular login options enabled by config.

Parameters:
Return type:

list[dict[str, Any]]

fleetmesh_auth.principal.register_widget_preset(name, overrides, *, base='standard')[source]#

Add (or replace) the panel preset name: base (a built-in or an already registered preset) with overrides applied. Keys that are not AuthWidgetConfig fields are logged and ignored. app_id defaults to name. Raises ValueError for an empty name or an unknown base.

Parameters:
Return type:

None

fleetmesh_auth.principal.unregister_widget_preset(name)[source]#

Forget a registered preset; a built-in of that name shows again. No-op if absent.

Parameters:

name (str)

Return type:

None

fleetmesh_auth.principal.registered_widget_presets()[source]#

The presets registered at runtime, by name (a copy).

Return type:

dict[str, AuthWidgetConfig]

fleetmesh_auth.principal.load_widget_presets_from_env(environ=None)[source]#

Register the presets in FLEETMESH_AUTH_PRESETS_JSON, a JSON object {name: {“base”: str, …overrides}}. Returns the names registered. A value that is not such an object is logged and skipped; so is a preset whose base is unknown.

Parameters:

environ (Mapping[str, str] | None)

Return type:

list[str]

fleetmesh_auth.principal.resolve_widget_config(app_id_or_host, overrides=None)[source]#
Parameters:
Return type:

AuthWidgetConfig

2.3. Refusal Codes#

Refusal codes on the Fleetmesh auth wire.

Every failed reply is {“ok”: false, “error”: <code>, “detail”: <sentence>}. The code is stable and snake_case (a key of ERRORS, which lives in fleetmesh_core.identity.web_auth so the core refusals and the engine’s share one table); the sentence is for people and may change. Providers raise or return either; refusal() builds the wire dict.

exception fleetmesh_auth.errors.AuthRefused[source]#

Bases: FleetmeshError, PermissionError

A login refused for a protocol reason. code is the wire error (a key of ERRORS); detail is the sentence, ERRORS[code] by default. str() is the detail, as it always was for the PermissionError callers caught.

__init__(code, detail=None)[source]#
Parameters:
  • code (str)

  • detail (str | None)

Return type:

None

to_dict()[source]#
Return type:

dict[str, Any]

fleetmesh_auth.errors.refusal(code, detail=None, **extra)[source]#

The wire shape of a refused call. Extra keys (required_role, roles) ride along after detail.

Parameters:
Return type:

Dict[str, Any]

fleetmesh_auth.errors.detail_for(code)[source]#

The default sentence for a code; the code itself if it has none.

Parameters:

code (str)

Return type:

str

2.4. Providers#

The provider plugin standard (API version 1).

A provider proves who someone is by one kind of credential: a key signature, an operator token, an account on some service. fleetmesh_auth ships two (keys and DIDs, and the local node operator); everything else is a plugin, a class that subclasses AuthProviderPlugin and is found by plugins.load_plugins.

A provider declares:

  • provider_id a stable lowercase id ([a-z][a-z0-9_]*); logins name it

    in provider, and principals carry it

  • display_name, description

  • supported_methods the auth_method values it accepts; service_login

    makes it one of the account providers a login that names no provider is tried against, in registration order

  • token_prefixes prefixes of tokens it issues (fmk_): a login carrying

    one in token, api_key or ticket is routed to it

  • login_form the fields the sign-in panel shows for it, or None when

    it needs no form of its own

  • register_form the fields of its sign-up form, when it creates accounts

    (see register); None otherwise

and implements authenticate(payload, context), and optionally register(payload, context) and check_handle(handle). Settings come from the environment through from_settings, as FLEETMESH_AUTH_<PROVIDER_ID>_<NAME>. plugin_testing.check_provider checks a provider against all of this.

class fleetmesh_auth.providers.base.LoginField[source]#

Bases: TypedDict

name: str#
label: str#
type: str#
placeholder: str#
autocomplete: str#
class fleetmesh_auth.providers.base.LoginForm[source]#

Bases: TypedDict

title: str#
submit: str#
hint: str#
fields: List[LoginField]#
class fleetmesh_auth.providers.base.AuthContext[source]#

Bases: TypedDict

What the engine hands authenticate besides the payload.

web_auth: Any#
now: int#
host: Any#
directory: Any#
domain: str#
app_preset: str#
allow_any_sovereign_key: bool#
passkey_store: Any#
class fleetmesh_auth.providers.base.PluginSettings[source]#

Bases: object

A provider’s settings from the environment, namespaced by its id: FLEETMESH_AUTH_ACME_INSTANCE_URL is settings.get(“instance_url”) for the acme provider.

__init__(provider_id, environ=None)[source]#
Parameters:
Return type:

None

env_name(name)[source]#
Parameters:

name (str)

Return type:

str

get(name, default='')[source]#
Parameters:
Return type:

str

raw(env_name, default='')[source]#

A variable outside the namespace, for names a provider kept from before.

Parameters:
  • env_name (str)

  • default (str)

Return type:

str

list(name)[source]#
Parameters:

name (str)

Return type:

List[str]

urls(name)[source]#

http(s) base URLs, without trailing slashes; anything else is logged and skipped.

Parameters:

name (str)

Return type:

FrozenSet[str]

class fleetmesh_auth.providers.base.AuthProviderPlugin[source]#

Bases: ABC

api_version: ClassVar[int] = 1#
provider_id: ClassVar[str] = 'base'#
display_name: ClassVar[str] = 'Base Auth Provider'#
description: ClassVar[str] = ''#
supported_methods: ClassVar[List[str]] = []#
token_prefixes: ClassVar[Tuple[str, ...]] = ()#
login_form: ClassVar[LoginForm | None] = None#
register_form: ClassVar[LoginForm | None] = None#
classmethod from_settings(settings)[source]#

Build the provider from its environment settings. Override to read them.

Parameters:

settings (PluginSettings)

Return type:

AuthProviderPlugin

supports_registration()[source]#

True when this provider creates accounts: it declares a register_form or overrides register.

Return type:

bool

supports_handle_check()[source]#

True when this provider answers check_handle (it overrides the hook).

Return type:

bool

describe()[source]#

Public metadata for the sign-in panel and /api/fauth/providers. Never put secrets here: it is served to anyone.

Return type:

Dict[str, Any]

claims_token(token)[source]#
Parameters:

token (str)

Return type:

bool

abstractmethod authenticate(payload, context)[source]#

Check the credential in payload.

Return {“ok”: True, “principal”: AuthPrincipal} or {“ok”: False, “error”: “<snake_code>”, “detail”: “<sentence>”} (fleetmesh_auth.errors.refusal builds it; detail may be left out and the engine fills in the code’s default sentence). Never raise for a bad credential; the engine tries the next provider on ok: False. Raising AuthRefused(code) is equivalent to returning its dict. The principal’s provider_id should be this provider’s.

Parameters:
Return type:

Dict[str, Any]

register(payload, context)[source]#

Create an account from payload (the register_form fields), for providers that offer sign-up. Same contract as authenticate: return {“ok”: True, “principal”: AuthPrincipal} for the new account (the engine then opens a session for it, as after a login) or {“ok”: False, “error”: “<snake_code>”}; never raise for bad input. Suggested codes: handle_taken, invalid_handle, weak_password, invalid_email. The default refuses with registration_unsupported.

Parameters:
Return type:

Dict[str, Any]

check_handle(handle)[source]#

Say whether handle could be registered, for a sign-up form’s live availability check (GET /api/fauth/register/check). Optional.

The engine has already trimmed handle, dropped a leading @ and refused anything empty, over HANDLE_MAX_LEN characters or outside [A-Za-z0-9._-]; apply the provider’s own stricter rules here. Return {“ok”: True, “available”: bool, “reason”: None | “handle_taken” | “invalid_handle”} (the reason is None when available) or {“ok”: False, “error”: “<snake_code>”} when the answer cannot be given (store down: provider_error). Never raise, and never put anything else in the reply: it is served to anyone. The default raises NotImplementedError; the engine never calls it unless supports_handle_check() is true.

Parameters:

handle (str)

Return type:

Dict[str, Any]

Sovereign Key, DID, Passkey (WebAuthn), and Nostr Bunker (NIP-46 / NIP-07) Auth Provider.

class fleetmesh_auth.providers.key_did.SovereignKeyBunkerProvider[source]#

Bases: AuthProviderPlugin

Authenticates principals via Nostr Bunker (NIP-46), NIP-07 browser extension, direct private key (nsec1… / 64-char hex), DID (did:nostr / did:key), WebAuthn Passkeys (passkey), or FleetMesh portable tickets (fmpass_…).

provider_id: ClassVar[str] = 'sovereign_key'#
display_name: ClassVar[str] = 'Sovereign Key / DID / Passkey'#
description: ClassVar[str] = 'Sign in with a NIP-46 bunker:// URI, NIP-07 browser extension, private key (nsec/hex), DID, or Passkey.'#
supported_methods: ClassVar[List[str]] = ['nip46_bunker', 'nip07_extension', 'private_key', 'did', 'passkey', 'portable_ticket']#
token_prefixes: ClassVar[Tuple[str, ...]] = ('fmpass_',)#
__init__(*, operator_pubkeys=None, admin_pubkeys=None, default_roles=None)[source]#
Parameters:
  • operator_pubkeys (Set[str] | None)

  • admin_pubkeys (Set[str] | None)

  • default_roles (List[str] | None)

Return type:

None

describe()[source]#

Public metadata for the sign-in panel and /api/fauth/providers. Never put secrets here: it is served to anyone.

Return type:

Dict[str, Any]

authenticate(payload, context)[source]#

Check the credential in payload.

Return {“ok”: True, “principal”: AuthPrincipal} or {“ok”: False, “error”: “<snake_code>”, “detail”: “<sentence>”} (fleetmesh_auth.errors.refusal builds it; detail may be left out and the engine fills in the code’s default sentence). Never raise for a bad credential; the engine tries the next provider on ok: False. Raising AuthRefused(code) is equivalent to returning its dict. The principal’s provider_id should be this provider’s.

Parameters:
Return type:

Dict[str, Any]

Local Node Operator / Meshctl Token Provider for standalone FleetMesh services.

class fleetmesh_auth.providers.local_operator.LocalOperatorProvider[source]#

Bases: AuthProviderPlugin

Authenticates node operators via a local operator token, meshctl secret, or configured operator username/password when running without a host database.

provider_id: ClassVar[str] = 'local_operator'#
display_name: ClassVar[str] = 'Node Operator Credentials'#
description: ClassVar[str] = 'Authenticate with local meshnode operator credentials or MESHNODE_OPERATOR_TOKEN.'#
supported_methods: ClassVar[List[str]] = ['operator_token', 'service_login']#
login_form: ClassVar[LoginForm | None] = {'fields': [{'autocomplete': 'username', 'label': 'Operator name', 'name': 'username', 'placeholder': 'admin', 'type': 'text'}, {'autocomplete': 'current-password', 'label': 'Operator token', 'name': 'password', 'type': 'password'}], 'hint': 'The operator name and MESHNODE_OPERATOR_TOKEN set on this node.', 'submit': 'Sign in as operator', 'title': 'Node operator'}#
__init__(*, operator_username=None, operator_token=None)[source]#
Parameters:
  • operator_username (str | None)

  • operator_token (str | None)

Return type:

None

authenticate(payload, context)[source]#

Check the credential in payload.

Return {“ok”: True, “principal”: AuthPrincipal} or {“ok”: False, “error”: “<snake_code>”, “detail”: “<sentence>”} (fleetmesh_auth.errors.refusal builds it; detail may be left out and the engine fills in the code’s default sentence). Never raise for a bad credential; the engine tries the next provider on ok: False. Raising AuthRefused(code) is equivalent to returning its dict. The principal’s provider_id should be this provider’s.

Parameters:
Return type:

Dict[str, Any]

2.5. Plugin Loading and Conformance#

Finding provider plugins.

Two sources, both read once per engine:

  • installed packages that declare an entry point in the group fleetmesh_auth.providers:

    [project.entry-points.”fleetmesh_auth.providers”] acme = “fleetmesh_auth_acme:AcmeAuthProvider”

  • FLEETMESH_AUTH_PLUGINS, a comma or space separated list of module:attribute, for deployments that put code on PYTHONPATH instead of installing it (entry points need installed package metadata).

FLEETMESH_AUTH_DISABLED_PROVIDERS lists provider ids to leave out. The attribute is an AuthProviderPlugin subclass (built with from_settings) or a callable that takes PluginSettings and returns a provider. A plugin that fails to import, declares an API version this release does not speak, or breaks the id rules is logged and skipped: one bad plugin never stops sign-in.

fleetmesh_auth.plugins.build(obj, environ=None)[source]#

A provider from a plugin class or factory, checked against the standard.

Parameters:
Return type:

AuthProviderPlugin

fleetmesh_auth.plugins.load_plugins(environ=None, *, reserved=())[source]#

Every plugin provider that loads, in discovery order, one per id.

Parameters:
Return type:

List[AuthProviderPlugin]

Conformance checks for provider plugins, for a plugin’s own test suite.

from fleetmesh_auth.plugin_testing import check_provider

class Conformance(unittest.TestCase):
def test_standard(self):

check_provider(MyProvider)

check_provider takes the plugin class (or factory) as its entry point names it, builds it the way the engine does, and raises AssertionError naming the first rule it breaks. It checks the declaration, that describe() is public JSON, that bad and empty credentials fail with an error code and do not raise, that register({}) and (when offered) check_handle answer cleanly, and that the engine routes the plugin’s own tokens to it.

fleetmesh_auth.plugin_testing.check_provider(plugin, environ=None)[source]#

Build plugin as the engine would and check it against the standard. Returns the built provider.

Parameters:
Return type:

AuthProviderPlugin

2.6. NIP-46 Bunker and Key Parsing#

NIP-46 Nostr Bunker (bunker://), Bech32 (nsec1/npub1), and DID (did:nostr/did:key) helpers.

fleetmesh_auth.nip46_bunker.is_hex64(value)[source]#
Parameters:

value (str)

Return type:

bool

fleetmesh_auth.nip46_bunker.decode_bech32_hex(bech, expected_hrp=None)[source]#

Decode nsec1… or npub1… Bech32 string into a 64-char lowercase hex string.

Parameters:
  • bech (str)

  • expected_hrp (str | None)

Return type:

str

fleetmesh_auth.nip46_bunker.normalize_secret_key(raw_key)[source]#

Accept 64-char hex or nsec1… Bech32 secret key and return 64-char lowercase hex.

Parameters:

raw_key (str)

Return type:

str

fleetmesh_auth.nip46_bunker.normalize_pubkey_or_did(raw_value)[source]#

Normalize did:nostr:<hex>, did:key:…, npub1…, or 64-char hex into {‘pubkey_hex’: pk, ‘did’: did}.

Parameters:

raw_value (str)

Return type:

dict[str, str]

class fleetmesh_auth.nip46_bunker.BunkerDescriptor[source]#

Bases: object

Parsed NIP-46 bunker:// or nostrconnect:// remote signer connection URI.

scheme: str#
remote_pubkey: str#
did: str#
relays: list[str]#
secret: str = ''#
raw_uri: str = ''#
property remote_pubkey_hex: str#
to_dict()[source]#
Return type:

dict[str, Any]

__init__(scheme, remote_pubkey, did, relays, secret='', raw_uri='')#
Parameters:
Return type:

None

fleetmesh_auth.nip46_bunker.parse_bunker_uri(bunker_uri)[source]#

Parse and validate a NIP-46 bunker://<pubkey>?relay=wss://…&secret=… URI.

Parameters:

bunker_uri (str)

Return type:

BunkerDescriptor

fleetmesh_auth.nip46_bunker.sign_challenge_with_secret_key(sk_input, challenge, origin_url='', *, scheme='fleetmesh-auth-v1')[source]#

Sign a FleetMesh challenge message with a 64-char hex or nsec1… secret key.

Parameters:
  • sk_input (str)

  • challenge (str)

  • origin_url (str)

  • scheme (str)

Return type:

dict[str, str]

2.7. User Directories#

Where an app keeps its users: the one surface fleetmesh_auth needs from it.

fleetmesh_auth proves who someone is; the app hosting it decides who its users are. A UserDirectory finds or creates the app’s record for a proven pubkey, names the keys the app itself runs as, and carries sessions into the app’s own session tables when it has any. HostDirectory (host_directory.py) adapts a co-hosted host application engine; an app without users of its own passes none.

class fleetmesh_auth.directory.UserRecord[source]#

Bases: TypedDict

user_id: str#
handle: str#
display_name: str#
roles: List[str]#
class fleetmesh_auth.directory.UserDirectory[source]#

Bases: Protocol

own_pubkeys()[source]#

Pubkeys the app runs as (operator, node): they sign in as operators.

Return type:

FrozenSet[str]

find_user(pubkey_hex)[source]#

The app’s user for this pubkey, if it has one.

Parameters:

pubkey_hex (str)

Return type:

UserRecord | None

create_user(pubkey_hex, handle_hint)[source]#

Make a user for a pubkey seen for the first time; None if the app declines.

Parameters:
  • pubkey_hex (str)

  • handle_hint (str | None)

Return type:

UserRecord | None

Make token a session in the app’s own tables too (no-op if it keeps none).

Parameters:
Return type:

None

has_session(token)[source]#
Parameters:

token (str)

Return type:

bool

resolve_session(token, now, ttl_sec)[source]#

A session (or API key) the app issued itself, as a principal.

Parameters:
Return type:

Optional[‘AuthPrincipal’]

revoke_session(token)[source]#
Parameters:

token (str)

Return type:

None

default_db_path()[source]#

Where fleetmesh_auth’s own database should live beside the app’s, if anywhere.

Return type:

str | None

__init__(*args, **kwargs)#

HostDirectory: the UserDirectory over a co-hosted host application engine.

Every read of the host application’s internals (_user_conn, _identities, _sessions, its admin and session tables) lives here. Two users schemas exist: the full host engine keyed by identity_id, and a minimal one keyed by user_id.

class fleetmesh_auth.host_directory.HostDirectory[source]#

Bases: object

__init__(host)[source]#
Parameters:

host (Any)

Return type:

None

own_pubkeys()[source]#
Return type:

FrozenSet[str]

find_user(pubkey_hex)[source]#
Parameters:

pubkey_hex (str)

Return type:

UserRecord | None

create_user(pubkey_hex, handle_hint)[source]#
Parameters:
  • pubkey_hex (str)

  • handle_hint (str | None)

Return type:

UserRecord | None

Parameters:
Return type:

None

has_session(token)[source]#
Parameters:

token (str)

Return type:

bool

resolve_session(token, now, ttl_sec)[source]#
Parameters:
Return type:

AuthPrincipal | None

revoke_session(token)[source]#
Parameters:

token (str)

Return type:

None

default_db_path()[source]#
Return type:

str | None

Column sets of the attached host engine’s tables, probed once per connection.

fleetmesh_auth.schema_probe.table_columns(conn, table)[source]#

The column names of table on conn, from PRAGMA table_info on first use.

Parameters:
Return type:

FrozenSet[str]

2.8. Stores#

Store interfaces (fleetmesh_auth.stores.base).

Three concerns, one object: sessions (bearer token → serialised principal), replay state (single-use challenges and used auth event ids) and passkeys. AuthStore is all three plus schema management; the engine takes one. Every now / expires_at is a Unix timestamp in seconds. Methods are thread-safe: the engine’s HTTP server calls them from many threads.

Bearer tokens are never stored: every store keys a session by session_token_key(token) (sha256 hex) and hashes the token on the way in, so a dump of the database holds no usable credential. Admin tokens (the separate credential an admin session gets, see put_admin_token) are hashed the same way and only ever map to a session key.

fleetmesh_auth.stores.base.SessionRecord#

principal_id, did, pubkey_hex, handle, display_name, provider, auth_method, roles, scopes, metadata, issued_at, expires_at (JSON-compatible).

Type:

The serialised session

alias of Dict[str, Any]

fleetmesh_auth.stores.base.session_token_key(token)[source]#

The at-rest key for a bearer token: sha256 hex (the Rust store’s form).

Parameters:

token (str)

Return type:

str

class fleetmesh_auth.stores.base.SessionStore[source]#

Bases: Protocol

put(token, record, expires_at)[source]#

Insert or replace the session under token (only its hash is stored).

Parameters:
Return type:

None

get(token, now, *, include_expired=False)[source]#

The record for token, or None when unknown or expired (an expired row is dropped on the way). include_expired=True returns an expired record untouched so the caller can tell “expired” from “unknown”.

Parameters:
Return type:

Dict[str, Any] | None

delete(token)[source]#
Parameters:

token (str)

Return type:

None

sweep(now)[source]#

Delete sessions with expires_at < now; returns how many.

Parameters:

now (int)

Return type:

int

count_active(now)[source]#
Parameters:

now (int)

Return type:

int

ping()[source]#

True when the backend answers a trivial query (readiness).

Return type:

bool

__init__(*args, **kwargs)#
class fleetmesh_auth.stores.base.ReplayStore[source]#

Bases: Protocol

issue_challenge(challenge, expires_at)[source]#
Parameters:
  • challenge (str)

  • expires_at (int)

Return type:

None

consume_challenge(challenge, now)[source]#

Consume challenge exactly once; False when unknown, expired or already consumed. Concurrent callers: exactly one gets True.

Parameters:
Return type:

bool

consume_event_id(event_id, pubkey, expires_at, now)[source]#

Record event_id as used until max(expires_at, now + 600); False when a live record already exists (a replay). An expired record is taken over.

Parameters:
Return type:

bool

sweep_replay(now)[source]#

Drop expired challenges and used event ids.

Parameters:

now (int)

Return type:

None

__init__(*args, **kwargs)#
class fleetmesh_auth.stores.base.PasskeyStore[source]#

Bases: Protocol

put_passkey(credential_id, record)[source]#

Insert or replace; record has pubkey_hex, did, handle, public_key_b64 and created_at.

Parameters:
Return type:

None

get_passkey(credential_id)[source]#

The record with credential_id added, or None.

Parameters:

credential_id (str)

Return type:

Dict[str, Any] | None

__init__(*args, **kwargs)#
class fleetmesh_auth.stores.base.AuthStore[source]#

Bases: ABC

Sessions + replay + passkeys behind one backend.

abstractmethod ensure_schema()[source]#

Create tables when missing; safe to call repeatedly and concurrently.

Return type:

None

abstractmethod close()[source]#
Return type:

None

abstractmethod clear()[source]#

Forget every session, challenge, used event id and passkey (tests).

Return type:

None

abstractmethod clear_sessions()[source]#
Return type:

None

abstractmethod clear_replay()[source]#
Return type:

None

abstractmethod put(token, record, expires_at)[source]#
Parameters:
Return type:

None

abstractmethod get(token, now, *, include_expired=False)[source]#
Parameters:
Return type:

Dict[str, Any] | None

abstractmethod delete(token)[source]#
Parameters:

token (str)

Return type:

None

abstractmethod get_session_by_key(session_key, now, *, include_expired=False)[source]#

The record for an at-rest session key (a session_token_key value), same expiry rules as get.

Parameters:
  • session_key (str)

  • now (int)

  • include_expired (bool)

Return type:

Dict[str, Any] | None

abstractmethod delete_session_by_key(session_key)[source]#

Delete the session (and its admin tokens) under an at-rest key.

Parameters:

session_key (str)

Return type:

None

abstractmethod put_admin_token(admin_token, session_token, expires_at)[source]#

Record admin_token as a credential for the session of session_token; both are hashed, only the hashes are kept.

Parameters:
  • admin_token (str)

  • session_token (str)

  • expires_at (int)

Return type:

None

abstractmethod resolve_admin_token(admin_token, now)[source]#

The at-rest session key admin_token stands for, or None when unknown or expired.

Parameters:
Return type:

str | None

abstractmethod delete_admin_token(admin_token)[source]#

Forget the admin credential admin_token (the session stays).

Parameters:

admin_token (str)

Return type:

None

abstractmethod migrate_session_tokens()[source]#

Hash any session token still stored in the clear, in place, so sessions created by an older version keep working. Idempotent: returns how many rows it rewrote (0 once everything is hashed).

Return type:

int

abstractmethod sweep(now)[source]#
Parameters:

now (int)

Return type:

int

abstractmethod count_active(now)[source]#
Parameters:

now (int)

Return type:

int

abstractmethod ping()[source]#
Return type:

bool

abstractmethod issue_challenge(challenge, expires_at)[source]#
Parameters:
  • challenge (str)

  • expires_at (int)

Return type:

None

abstractmethod consume_challenge(challenge, now)[source]#
Parameters:
Return type:

bool

abstractmethod consume_event_id(event_id, pubkey, expires_at, now)[source]#
Parameters:
Return type:

bool

abstractmethod sweep_replay(now)[source]#
Parameters:

now (int)

Return type:

None

abstractmethod put_passkey(credential_id, record)[source]#
Parameters:
Return type:

None

abstractmethod get_passkey(credential_id)[source]#
Parameters:

credential_id (str)

Return type:

Dict[str, Any] | None

fleetmesh_auth.stores.base.USED_EVENT_MIN_RETENTION_SEC = 600#

A used event id is remembered at least this long past now (the core’s FederatedWebAuth.consume_auth_event_id rule, and the Rust store’s).

SqliteAuthStore: the engine’s original sqlite persistence behind the AuthStore interface. Same tables and semantics as before the stores existed (fleetmesh_auth_sessions, fleetmesh_auth_passkeys, fleetmesh_auth_meta, and the core’s auth_challenges / used_auth_events DDL), so an existing database file keeps working.

One connection (check_same_thread=False) guarded by one RLock, which is what :memory: needs to be usable from the server’s threads; .conn and .lock are exposed for co-hosted code that shares the database.

Sessions are keyed by sha256(token) and admin tokens by their own sha256, so the database never holds a bearer credential. A database written by an older version (plaintext session_token column) is migrated in place: the tokens are hashed where they stand, which keeps those sessions valid, and migrate_session_tokens() is idempotent.

class fleetmesh_auth.stores.sqlite.SqliteAuthStore[source]#

Bases: AuthStore

SCHEMA_SQL = "\n    CREATE TABLE IF NOT EXISTS fleetmesh_auth_sessions (\n        session_token TEXT PRIMARY KEY,\n        principal_id TEXT NOT NULL,\n        did TEXT NOT NULL,\n        pubkey_hex TEXT NOT NULL,\n        handle TEXT NOT NULL,\n        display_name TEXT NOT NULL,\n        provider TEXT NOT NULL,\n        auth_method TEXT NOT NULL,\n        roles_json TEXT NOT NULL,\n        scopes_json TEXT NOT NULL,\n        metadata_json TEXT NOT NULL,\n        issued_at INTEGER NOT NULL,\n        expires_at INTEGER NOT NULL\n    );\n    CREATE TABLE IF NOT EXISTS fleetmesh_auth_passkeys (\n        credential_id TEXT PRIMARY KEY,\n        pubkey_hex TEXT NOT NULL,\n        did TEXT NOT NULL,\n        handle TEXT NOT NULL,\n        public_key_b64 TEXT NOT NULL DEFAULT '',\n        created_at INTEGER NOT NULL\n    );\n    CREATE TABLE IF NOT EXISTS fleetmesh_auth_admin_tokens (\n        admin_token_hash TEXT PRIMARY KEY,\n        session_token_hash TEXT NOT NULL,\n        expires_at INTEGER NOT NULL\n    );\n    CREATE INDEX IF NOT EXISTS fleetmesh_auth_admin_tokens_expires_at_idx\n        ON fleetmesh_auth_admin_tokens (expires_at);\n    CREATE INDEX IF NOT EXISTS fleetmesh_auth_admin_tokens_session_idx\n        ON fleetmesh_auth_admin_tokens (session_token_hash);\n    CREATE TABLE IF NOT EXISTS fleetmesh_auth_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);\n    CREATE TABLE IF NOT EXISTS auth_challenges (\n        challenge TEXT PRIMARY KEY,\n        created_at INTEGER NOT NULL,\n        expires_at INTEGER NOT NULL\n    );\n    CREATE TABLE IF NOT EXISTS used_auth_events (\n        event_id TEXT PRIMARY KEY,\n        pubkey TEXT NOT NULL,\n        used_at INTEGER NOT NULL,\n        expires_at INTEGER NOT NULL\n    );\n    "#
__init__(db_path=None, *, conn=None, lock=None)[source]#
Parameters:
Return type:

None

ensure_schema()[source]#

Create tables when missing; safe to call repeatedly and concurrently.

Return type:

None

close()[source]#
Return type:

None

clear()[source]#

Forget every session, challenge, used event id and passkey (tests).

Return type:

None

clear_sessions()[source]#
Return type:

None

clear_replay()[source]#
Return type:

None

put(token, record, expires_at)[source]#
Parameters:
Return type:

None

get(token, now, *, include_expired=False)[source]#
Parameters:
Return type:

Dict[str, Any] | None

get_session_by_key(session_key, now, *, include_expired=False)[source]#

The record for an at-rest session key (a session_token_key value), same expiry rules as get.

Parameters:
  • session_key (str)

  • now (int)

  • include_expired (bool)

Return type:

Dict[str, Any] | None

delete(token)[source]#
Parameters:

token (str)

Return type:

None

delete_session_by_key(session_key)[source]#

Delete the session (and its admin tokens) under an at-rest key.

Parameters:

session_key (str)

Return type:

None

put_admin_token(admin_token, session_token, expires_at)[source]#

Record admin_token as a credential for the session of session_token; both are hashed, only the hashes are kept.

Parameters:
  • admin_token (str)

  • session_token (str)

  • expires_at (int)

Return type:

None

resolve_admin_token(admin_token, now)[source]#

The at-rest session key admin_token stands for, or None when unknown or expired.

Parameters:
Return type:

str | None

delete_admin_token(admin_token)[source]#

Forget the admin credential admin_token (the session stays).

Parameters:

admin_token (str)

Return type:

None

migrate_session_tokens()[source]#

Hash every plaintext session token in place; returns the rows rewritten. Idempotent: a hashed row is skipped, so a second run (or a run on a fresh database) returns 0 and changes nothing.

Return type:

int

sweep(now)[source]#
Parameters:

now (int)

Return type:

int

count_active(now)[source]#
Parameters:

now (int)

Return type:

int

ping()[source]#
Return type:

bool

issue_challenge(challenge, expires_at)[source]#
Parameters:
  • challenge (str)

  • expires_at (int)

Return type:

None

consume_challenge(challenge, now)[source]#
Parameters:
Return type:

bool

consume_event_id(event_id, pubkey, expires_at, now)[source]#
Parameters:
Return type:

bool

sweep_replay(now)[source]#
Parameters:

now (int)

Return type:

None

put_passkey(credential_id, record)[source]#
Parameters:
Return type:

None

get_passkey(credential_id)[source]#
Parameters:

credential_id (str)

Return type:

Dict[str, Any] | None

PostgresAuthStore: sessions, replay state and passkeys in Postgres via psycopg 3, in the tables the Rust t6 fauth service uses (fauth_sessions, fauth_challenges, fauth_used_events) plus fauth_passkeys. Several fleetmesh-auth replicas on one database see each other’s sessions and challenges.

Sessions are keyed by sha256(token) (token_key), never the bearer token itself; the record is the session JSON (JSONB). Admin tokens get their own sha256 in fauth_admin_tokens, mapping to the session key. Every statement is parametrised; expired rows are ignored on read and swept opportunistically (roughly every sweep_interval_sec, by whichever call comes first).

psycopg is imported lazily so the sqlite path has no dependency on it. Pooling: psycopg_pool.ConnectionPool when installed, else a small thread-safe pool of plain connections (max_size).

class fleetmesh_auth.stores.postgres.PostgresAuthStore[source]#

Bases: AuthStore

__init__(dsn, *, schema_lock_key=8101803567812444166, max_size=8, sweep_interval_sec=60, ensure_schema=True)[source]#
Parameters:
  • dsn (str)

  • schema_lock_key (int)

  • max_size (int)

  • sweep_interval_sec (int)

  • ensure_schema (bool)

Return type:

None

ensure_schema()[source]#

Create tables when missing; safe to call repeatedly and concurrently.

Return type:

None

close()[source]#
Return type:

None

clear()[source]#

Forget every session, challenge, used event id and passkey (tests).

Return type:

None

clear_sessions()[source]#
Return type:

None

clear_replay()[source]#
Return type:

None

put(token, record, expires_at)[source]#
Parameters:
Return type:

None

get(token, now, *, include_expired=False)[source]#
Parameters:
Return type:

Dict[str, Any] | None

get_session_by_key(session_key, now, *, include_expired=False)[source]#

The record for an at-rest session key (a session_token_key value), same expiry rules as get.

Parameters:
  • session_key (str)

  • now (int)

  • include_expired (bool)

Return type:

Dict[str, Any] | None

delete(token)[source]#
Parameters:

token (str)

Return type:

None

delete_session_by_key(session_key)[source]#

Delete the session (and its admin tokens) under an at-rest key.

Parameters:

session_key (str)

Return type:

None

put_admin_token(admin_token, session_token, expires_at)[source]#

Record admin_token as a credential for the session of session_token; both are hashed, only the hashes are kept.

Parameters:
  • admin_token (str)

  • session_token (str)

  • expires_at (int)

Return type:

None

resolve_admin_token(admin_token, now)[source]#

The at-rest session key admin_token stands for, or None when unknown or expired.

Parameters:
Return type:

str | None

delete_admin_token(admin_token)[source]#

Forget the admin credential admin_token (the session stays).

Parameters:

admin_token (str)

Return type:

None

migrate_session_tokens()[source]#

Nothing to do here: this store has always keyed sessions by sha256(token). Present for the AuthStore contract (the sqlite store has the plaintext rows an older version wrote). Idempotent: 0.

Return type:

int

sweep(now)[source]#
Parameters:

now (int)

Return type:

int

count_active(now)[source]#
Parameters:

now (int)

Return type:

int

ping()[source]#
Return type:

bool

issue_challenge(challenge, expires_at)[source]#
Parameters:
  • challenge (str)

  • expires_at (int)

Return type:

None

consume_challenge(challenge, now)[source]#
Parameters:
Return type:

bool

consume_event_id(event_id, pubkey, expires_at, now)[source]#
Parameters:
Return type:

bool

sweep_replay(now)[source]#
Parameters:

now (int)

Return type:

None

put_passkey(credential_id, record)[source]#
Parameters:
Return type:

None

get_passkey(credential_id)[source]#
Parameters:

credential_id (str)

Return type:

Dict[str, Any] | None

fleetmesh_auth.stores.postgres.session_token_key(token)[source]#

The at-rest key for a bearer token: sha256 hex (the Rust store’s form).

Parameters:

token (str)

Return type:

str

The replay seam: StoreBackedWebAuth is the core’s FederatedWebAuth with its replay state (single-use challenges, used auth event ids) kept in a ReplayStore instead of its own sqlite tables.

Why a subclass, and why these methods. fleetmesh_core is a separate repo and is not modified. In fleetmesh_core/identity/web_auth.py every touch of auth_challenges / used_auth_events goes through four public methods on FederatedWebAuth: issue_challenge, consume_challenge, consume_auth_event_id and reset (plus ensure_tables, which creates them). The verifiers (verify_login_payload, verify_nip98_request) only ever call self.consume_challenge(…) / self.consume_auth_event_id(…), and the key/DID provider calls web_auth.consume_challenge(…) for passkeys; overriding those four is therefore the whole seam. Everything else (signature checks, portable tickets, NIP-98) is inherited unchanged. The base class still gets a private in-memory sqlite connection so its constructor and ensure_tables() are satisfied; nothing is ever written to it.

class fleetmesh_auth.stores.web_auth.StoreBackedWebAuth[source]#

Bases: FederatedWebAuth

__init__(replay, *, origin_url='', node_did='', challenge_ttl_sec=600, clock=None, token_source=None, **kwargs)[source]#
Parameters:
Return type:

None

reset()[source]#

Forget every outstanding challenge and used event id (tests).

Return type:

None

clear()#

Forget every outstanding challenge and used event id (tests).

Return type:

None

issue_challenge(*, now=None, challenge=None)[source]#

Issue and persist a single-use cryptographic login challenge. challenge fixes the id (default: the token source’s 24 random bytes).

Parameters:
  • now (int | None)

  • challenge (str | None)

Return type:

Dict[str, Any]

consume_challenge(challenge, *, now=None)[source]#

Consume challenge once; return False if missing or expired.

Parameters:
  • challenge (str)

  • now (int | None)

Return type:

bool

consume_auth_event_id(event_id, pubkey, expires_at, *, now=None)[source]#

Record event_id in used_auth_events; return False on replay.

Parameters:
  • event_id (str)

  • pubkey (str)

  • expires_at (int)

  • now (int | None)

Return type:

bool

2.9. HTTP Routes and Server#

Mountable HTTP route handlers for /api/fauth/* across FleetMesh web services.

fleetmesh_auth.http_routes.apply_cors_headers(handler)[source]#

Send the handler’s CORS headers, when it has any.

The standalone server’s handler exposes cors_headers(); a host app that mounts these routes with its own handler simply has none, which keeps this a no-op there.

Parameters:

handler (Any)

Return type:

None

fleetmesh_auth.http_routes.extract_request_token(handler, payload=None)[source]#

Extract a session/auth token from HTTP headers, query string, or JSON body.

Parameters:
Return type:

str

fleetmesh_auth.http_routes.handle_fauth_get(handler, engine, path, query_string='')[source]#

Handle GET /api/fauth/* requests on a BaseHTTPRequestHandler-compatible handler.

Returns True if the path matched /api/fauth/* and a response was sent.

Parameters:
Return type:

bool

fleetmesh_auth.http_routes.handle_fauth_post(handler, engine, path, payload)[source]#

Handle POST /api/fauth/* requests on a BaseHTTPRequestHandler-compatible handler.

Returns True if the path matched /api/fauth/* and a response was sent.

Parameters:
Return type:

bool

Standalone HTTP server for FleetMesh Auth (python3 -m fleetmesh_auth).

Two listeners: the public one serves /api/fauth/*, the sign-in portal and /healthz; the optional admin one (–admin-addr / FLEETMESH_AUTH_ADMIN_ADDR) serves /healthz, /readyz and Prometheus /metrics on a port that is not meant to be exposed. Every setting has an environment fallback (FLEETMESH_AUTH_HOST, _PORT, _DB, _DOMAIN, _ADMIN_ADDR); a flag wins.

Both listeners default to 127.0.0.1 and speak plain HTTP. Binding anywhere else is allowed (–host, FLEETMESH_AUTH_HOST) but logs a warning: a TLS-terminating reverse proxy belongs in front of the service, and the listener port itself should stay off the public network.

CORS is an allowlist (FLEETMESH_AUTH_CORS_ORIGINS, comma-separated). The server sends no CORS headers at all unless one is configured, and then echoes only an Origin that is on the list (Vary: Origin on every response).

class fleetmesh_auth.server.RequestMetrics[source]#

Bases: object

Request counters by (method, route, status), rendered as Prometheus text.

__init__()[source]#
Return type:

None

observe(method, path, status)[source]#
Parameters:
Return type:

None

snapshot()[source]#
Return type:

Dict[Tuple[str, str, int], int]

fleetmesh_auth.server.render_metrics(metrics, engine)[source]#

The admin listener’s /metrics body (Prometheus text exposition 0.0.4).

Parameters:
Return type:

str

fleetmesh_auth.server.is_loopback_host(host)[source]#

True for 127.0.0.0/8, ::1 and localhost (what a bind defaults to).

Parameters:

host (str)

Return type:

bool

fleetmesh_auth.server.warn_if_not_loopback(host, port, listener='listener')[source]#

The service speaks plain HTTP: a non-loopback bind needs TLS in front.

Parameters:
Return type:

None

class fleetmesh_auth.server.FleetmeshAuthHTTPHandler[source]#

Bases: BaseHTTPRequestHandler

engine: FleetmeshAuthEngine#
metrics: RequestMetrics | None = None#
cors_origins: Tuple[str, ...] = ()#
log_message(fmt, *args)[source]#

Log an arbitrary message.

This is used by all other logging functions. Override it if you have specific logging wishes.

The first argument, FORMAT, is a format string for the message to be logged. If the format string contains any % escapes requiring parameters, they should be specified as subsequent arguments (it’s just like printf!).

The client ip and current date/time are prefixed to every message.

Unicode control characters are replaced with escaped hex before writing the output to stderr.

Parameters:
Return type:

None

send_response(code, message=None)[source]#

Add the response header to the headers buffer and log the response code.

Also send two standard headers with the server software version and the current date.

Parameters:
  • code (int)

  • message (str | None)

Return type:

None

cors_headers()[source]#

The CORS response headers for this request.

With no allowlist configured: none, so a browser sees a same-origin service. With one: Vary: Origin always (a cache must not hand one origin’s grant to another), and Access-Control-Allow-Origin echoing the request’s Origin only when it is on the list. An origin that is not listed gets no grant, so the browser blocks the cross-origin read even though the request may still be executed.

Return type:

Dict[str, str]

do_OPTIONS()[source]#

A CORS preflight: the grant only when the Origin is on the list.

Return type:

None

do_GET()[source]#
Return type:

None

do_POST()[source]#
Return type:

None

class fleetmesh_auth.server.AdminHTTPHandler[source]#

Bases: BaseHTTPRequestHandler

/healthz, /readyz, /metrics; nothing else, and no public API.

engine: FleetmeshAuthEngine | None = None#
metrics: RequestMetrics | None = None#
log_message(fmt, *args)[source]#

Log an arbitrary message.

This is used by all other logging functions. Override it if you have specific logging wishes.

The first argument, FORMAT, is a format string for the message to be logged. If the format string contains any % escapes requiring parameters, they should be specified as subsequent arguments (it’s just like printf!).

The client ip and current date/time are prefixed to every message.

Unicode control characters are replaced with escaped hex before writing the output to stderr.

Parameters:
Return type:

None

do_GET()[source]#
Return type:

None

class fleetmesh_auth.server.AuthHTTPServer[source]#

Bases: ThreadingHTTPServer

The public listener; .engine and .metrics are what its handler uses.

daemon_threads = True#
engine: FleetmeshAuthEngine#
metrics: RequestMetrics#
class fleetmesh_auth.server.AdminHTTPServer[source]#

Bases: ThreadingHTTPServer

The admin listener (/healthz, /readyz, /metrics).

daemon_threads = True#
engine: FleetmeshAuthEngine | None#
metrics: RequestMetrics | None#
fleetmesh_auth.server.create_auth_http_server(host='127.0.0.1', port=8099, engine=None, metrics=None, cors_origins=None)[source]#

The public listener. cors_origins is the allowlist of origins that may call it cross-origin; None or empty means no CORS headers at all.

Parameters:
Return type:

AuthHTTPServer

fleetmesh_auth.server.create_admin_http_server(host, port, engine, metrics=None)[source]#

A listener for probes and metrics. Pass the public server’s .metrics so /metrics counts its requests; engine may be None (or not yet working), in which case /readyz answers 503.

Parameters:
Return type:

AdminHTTPServer

class fleetmesh_auth.server.ServerSettings[source]#

Bases: object

ServerSettings(host: ‘str’, port: ‘int’, db: ‘str’, domain: ‘str’, admin_addr: ‘Optional[Tuple[str, int]]’, store_url: ‘str’ = ‘’, cors_origins: ‘Tuple[str, …]’ = ())

host: str#
port: int#
db: str#
domain: str#
admin_addr: Tuple[str, int] | None#
store_url: str = ''#
cors_origins: Tuple[str, ...] = ()#
property effective_store_url: str#

store_url when set, else the sqlite db path.

Type:

What make_store() gets

__init__(host, port, db, domain, admin_addr, store_url='', cors_origins=())#
Parameters:
Return type:

None

fleetmesh_auth.server.parse_admin_addr(raw)[source]#

host:port, :port or port → (host, port); empty → None. A missing host is loopback, like the public listener’s default.

Parameters:

raw (str | None)

Return type:

Tuple[str, int] | None

fleetmesh_auth.server.resolve_server_settings(argv=None)[source]#

Flags over environment over defaults.

Parameters:

argv (Sequence[str] | None)

Return type:

ServerSettings

fleetmesh_auth.server.main(argv=None)[source]#
Parameters:

argv (Sequence[str] | None)

Return type:

None

2.10. Login Panel#

White-Labeled FleetMesh Authentication Modal & Modular Login Buttons (HTML/CSS/JS generator).

Provides: - render_method_icon_svg(icon_id) - render_auth_widget_css(config) - render_auth_widget_html(config) - render_auth_widget_js(config) - render_auth_bundle_html(preset, overrides) (single drop-in HTML snippet with CSS + markup + JS)

fleetmesh_auth.ui_widget.render_method_icon_svg(icon_id)[source]#

Return the monochrome white SVG icon markup for icon_id.

Parameters:

icon_id (str)

Return type:

str

fleetmesh_auth.ui_widget.render_auth_widget_css(config)[source]#
Parameters:

config (AuthWidgetConfig)

Return type:

str

fleetmesh_auth.ui_widget.render_auth_widget_html(config)[source]#
Parameters:

config (AuthWidgetConfig)

Return type:

str

fleetmesh_auth.ui_widget.render_auth_widget_js(config)[source]#
Parameters:

config (AuthWidgetConfig)

Return type:

str

fleetmesh_auth.ui_widget.render_auth_bundle_html(preset='standard', overrides=None)[source]#

Return a complete drop-in HTML snippet (<style> + widget HTML + <script>) for embedding the white-labeled FleetMesh Auth panel into any web application.

Parameters:
Return type:

str

2.11. Settings#

Operator settings read from the environment.

Apps build FleetmeshAuthEngine without passing role configuration, so these are how an operator names who is an operator and who is an admin, without changing code (provider plugins read their own, see providers.base.PluginSettings):

  • FLEETMESH_AUTH_OPERATOR_PUBKEYS: keys that sign in as node operators.

  • FLEETMESH_AUTH_ADMIN_PUBKEYS: keys that sign in as admins. In the role model (principal.ROLE_IMPLICATIONS) admin and node_operator imply each other, so both lists grant the same roles today; keep them apart for when they differ.

Each is a list separated by commas or whitespace. Keys are 64-hex x-only pubkeys, npub1… or did:nostr:…. An entry that does not parse is logged and skipped: a typo locks that key out, it never lets anything else in. A value passed to a provider’s constructor replaces the environment’s.

fleetmesh_auth.settings.parse_pubkeys(entries, source='')[source]#

Lowercase hex pubkeys for the secp256k1 keys among entries.

Parameters:
Return type:

FrozenSet[str]

fleetmesh_auth.settings.parse_instances(entries, source='')[source]#

http(s) base URLs among entries, without a trailing slash.

Parameters:
Return type:

FrozenSet[str]

fleetmesh_auth.settings.operator_pubkeys_from_env()[source]#
Return type:

FrozenSet[str]

fleetmesh_auth.settings.admin_pubkeys_from_env()[source]#
Return type:

FrozenSet[str]

fleetmesh_auth.settings.enabled_methods_from_env()[source]#
Return type:

List[str] | None

fleetmesh_auth.settings.disabled_methods_from_env()[source]#
Return type:

FrozenSet[str]

fleetmesh_auth.settings.enabled_providers_from_env()[source]#
Return type:

List[str] | None

fleetmesh_auth.settings.disabled_providers_from_env()[source]#
Return type:

FrozenSet[str]

fleetmesh_auth.settings.parse_origins(entries, source='')[source]#

The bare origins (scheme://host[:port]) among entries, normalised.

A CORS allowlist is a list of origins, not URLs: a path, a query, a wildcard or a scheme other than http/https is logged and skipped, because echoing such a value back would either never match or match everything.

Parameters:
Return type:

tuple[str, …]

fleetmesh_auth.settings.cors_origins_from_env()[source]#

The CORS allowlist from FLEETMESH_AUTH_CORS_ORIGINS (comma separated).

Empty means no cross-origin access at all: the server then sends no CORS headers, so browsers treat it as same-origin only.

Return type:

tuple[str, …]