Source code for fleetmesh_auth.principal

"""Standardized FleetMesh AuthPrincipal, Role Clearance, Modular Login Options, and White-Label Widget Config."""
from __future__ import annotations

import dataclasses
import json
import logging
import os
from typing import Any, Mapping, Sequence

from fleetmesh_core.identity.auth_wire import (
    ROLE_IMPLICATIONS,
    expand_roles,
    has_required_role,
    principal_dict,
)

from fleetmesh_auth.settings import (
    disabled_methods_from_env,
    disabled_providers_from_env,
    enabled_methods_from_env,
    enabled_providers_from_env,
)

log = logging.getLogger('fleetmesh_auth')

VALID_ROLES = frozenset({
    'viewer',
    'creator',
    'broadcaster',
    'moderator',
    'admin',
    'node_operator',
})

# Role implications, their expansion and the principal's wire shape are
# core's (fleetmesh_core.identity.auth_wire) so vectors/web-auth.json can
# pin them; they are re-exported here under the names callers know.

# Modular Login Option Catalog:
# Developers and operators can select any subset of these login methods via
# `AuthWidgetConfig(enabled_methods=[...])`, `FleetmeshAuthEngine(enabled_methods=[...])`,
# or `FLEETMESH_AUTH_ENABLED_METHODS` / `FLEETMESH_AUTH_DISABLED_METHODS`.
LOGIN_METHOD_CATALOG: tuple[dict[str, Any], ...] = (
    {
        'option_id': 'service',
        'method_id': 'service_provider',
        'label': 'Service Account',
        'button_label': 'Continue with a service account',
        'description': 'Sign in with an account on another service',
        'icon_id': 'service',
        'tier': 'primary',
        'provider_id': 'service_provider',
        'aliases': ('service_provider', 'service_login', 'service'),
    },
    {
        'option_id': 'bunker',
        'method_id': 'bunker_nip07',
        'label': 'Bunker / NIP-07',
        'button_label': 'Bunker / NIP-07',
        'description': 'Browser signer extension or remote Nostr Bunker',
        'icon_id': 'bunker',
        'tier': 'expert',
        'provider_id': 'sovereign_key',
        'aliases': ('bunker_nip07', 'bunker', 'nip46_bunker', 'nip07_ext', 'nip07_extension', 'nip07'),
    },
    {
        'option_id': 'key',
        'method_id': 'private_key',
        'label': 'Private Key',
        'button_label': 'Private Key',
        'description': 'Sign locally in your browser with an nsec or hex key',
        'icon_id': 'private_key',
        'tier': 'expert',
        'provider_id': 'sovereign_key',
        'aliases': ('private_key', 'schnorr_key', 'key', 'nsec', 'secret_key'),
    },
    {
        'option_id': 'did',
        'method_id': 'did',
        'label': 'DID',
        'button_label': 'DID',
        'description': 'Decentralized Identifier (did:nostr, did:key, did:web)',
        'icon_id': 'did',
        'tier': 'expert',
        'provider_id': 'sovereign_key',
        'aliases': ('did', 'did_challenge'),
    },
    {
        'option_id': 'api_key',
        'method_id': 'api_key',
        'label': 'API Key',
        'button_label': 'API Key',
        'description': 'Sign in with an API key',
        'icon_id': 'api_key',
        'tier': 'expert',
        'provider_id': 'service_provider',
        'aliases': ('api_key', 'apikey'),
    },
    {
        'option_id': 'passkey',
        'method_id': 'passkey',
        'label': 'Passkey',
        'button_label': 'Passkey',
        'description': 'Hardware security key or device passkey (WebAuthn)',
        'icon_id': 'passkey',
        'tier': 'expert',
        'provider_id': 'sovereign_key',
        'aliases': ('passkey', 'webauthn'),
    },
    {
        'option_id': 'ticket',
        'method_id': 'portable_ticket',
        'label': 'Portable Pass',
        'button_label': 'Portable Pass',
        'description': 'Single-use cross-site pass (fmpass_)',
        'icon_id': 'portable_ticket',
        'tier': 'expert',
        'provider_id': 'sovereign_key',
        'aliases': ('portable_ticket', 'portable_pass', 'ticket', 'pass'),
    },
    {
        'option_id': 'operator',
        'method_id': 'operator_token',
        'label': 'Operator Key',
        'button_label': 'Operator Key',
        'description': 'Standalone node operator credentials',
        'icon_id': 'operator_token',
        'tier': 'expert',
        'provider_id': 'local_operator',
        'aliases': ('operator_token', 'local_operator', 'operator'),
    },
)

# Values AuthWidgetConfig.primary_actions may hold.
PRIMARY_ACTIONS: frozenset[str] = frozenset({'login', 'signup'})

DEFAULT_ENABLED_METHODS: tuple[str, ...] = (
    'service_provider',
    'nip46_bunker',
    'nip07_ext',
    'private_key',
    'schnorr_key',
    'did',
    'did_challenge',
    'api_key',
    'passkey',
    'portable_ticket',
    'operator_token',
)

_ALIAS_TO_CANONICAL_METHOD: dict[str, str] = {}
for _spec in LOGIN_METHOD_CATALOG:
    for _alias in _spec['aliases']:
        _ALIAS_TO_CANONICAL_METHOD[_alias] = _spec['method_id']


[docs]def normalize_method_id(raw_method: str) -> str: """Normalize any login method alias to its canonical method_id.""" clean = str(raw_method or '').strip().lower() return _ALIAS_TO_CANONICAL_METHOD.get(clean, clean)
[docs]@dataclasses.dataclass class AuthPrincipal: """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] = dataclasses.field(default_factory=lambda: ['viewer', 'creator', 'broadcaster']) scopes: list[str] = dataclasses.field(default_factory=lambda: ['read', 'content', 'streams']) session_token: str = '' admin_token: str = '' portable_ticket: str = '' bunker_relay: str = '' issued_at: int = 0 expires_at: int = 0 metadata: dict[str, Any] = dataclasses.field(default_factory=dict) # Optional init aliases pubkey_hex: str = '' provider: str = '' def __post_init__(self) -> None: if not self.pubkey and self.pubkey_hex: self.pubkey = self.pubkey_hex if not self.pubkey_hex and self.pubkey: self.pubkey_hex = self.pubkey if len(self.pubkey) == 64 and all(c in '0123456789abcdefABCDEF' for c in self.pubkey): self.pubkey = self.pubkey.lower() if len(self.pubkey_hex) == 64 and all(c in '0123456789abcdefABCDEF' for c in self.pubkey_hex): self.pubkey_hex = self.pubkey_hex.lower() if self.provider and not self.provider_id: self.provider_id = self.provider if not self.provider: self.provider = self.provider_id self.roles = expand_roles(self.roles)
[docs] def has_role(self, required_role: str) -> bool: return has_required_role(self.roles, required_role)
[docs] def to_dict(self) -> dict[str, Any]: return principal_dict(dataclasses.asdict(self))
[docs]@dataclasses.dataclass class AuthWidgetConfig: """White-label FleetMesh Auth Panel configuration for a host application.""" app_id: str app_title: str app_subtitle: str mode: str = 'modal' # 'gate' | 'modal' brand_name: str = 'fleetmesh' brand_badge: str = '.auth' accent_primary: str = '#ff2a3c' accent_secondary: str = '#ff6b1a' logo_variant: str = 'sails' # 'sails' | 'fleetmesh' | 'ops' required_role: str = 'broadcaster' enabled_methods: list[str] = dataclasses.field( default_factory=lambda: list(DEFAULT_ENABLED_METHODS) ) disabled_methods: list[str] = dataclasses.field(default_factory=list) primary_methods: list[str] = dataclasses.field( default_factory=lambda: ['service_provider'] ) # Provider ids the panel offers; '*' is every provider the engine has, # plugins included. enabled_providers: list[str] = dataclasses.field(default_factory=lambda: ['*']) disabled_providers: list[str] = dataclasses.field(default_factory=list) providers: list[dict[str, Any]] = dataclasses.field(default_factory=list) # Top action bar: any of 'login' | 'signup'. Empty keeps the legacy # rendering (primary buttons + expert gear). Non-empty puts every other # method under one collapsible 'More options' section. primary_actions: list[str] = dataclasses.field(default_factory=list) more_options_label: str = 'More options' # Provider whose register_form backs 'Sign up'; None picks the first # provider in providers_detail with supports_registration. signup_provider: str | None = None def __post_init__(self) -> None: bad = [a for a in (self.primary_actions or []) if a not in PRIMARY_ACTIONS] if bad: raise ValueError(f'primary_actions: unknown action(s) {bad}; allowed: {sorted(PRIMARY_ACTIONS)}') @property def accent_color(self) -> str: return self.accent_primary
[docs] def is_method_enabled(self, method_or_alias: str) -> bool: """Return True if `method_or_alias` is permitted by this widget config.""" raw = str(method_or_alias or '').strip().lower() canonical = normalize_method_id(raw) disabled_raw = {str(m).strip().lower() for m in self.disabled_methods if m} disabled_canon = {normalize_method_id(m) for m in disabled_raw} if raw in disabled_raw or canonical in disabled_canon: return False enabled_raw = {str(m).strip().lower() for m in self.enabled_methods if m} if '*' in enabled_raw: return True enabled_canon = {normalize_method_id(m) for m in enabled_raw} return raw in enabled_raw or canonical in enabled_canon
[docs] def get_login_options( self, providers_detail: Sequence[Mapping[str, Any]] | None = None, ) -> list[dict[str, Any]]: """Return resolved modular login button descriptors for primary and expert views.""" return resolve_login_options(self, providers_detail=providers_detail)
[docs] def to_dict(self) -> dict[str, Any]: data = dataclasses.asdict(self) data['login_options'] = self.get_login_options(self.providers or None) return data
[docs]def resolve_login_options( config: AuthWidgetConfig, providers_detail: Sequence[Mapping[str, Any]] | None = None, ) -> list[dict[str, Any]]: """Build the ordered list of modular login options enabled by `config`.""" enabled_raw = {str(m).strip().lower() for m in config.enabled_methods if m} allow_all_methods = '*' in enabled_raw disabled_raw = {str(m).strip().lower() for m in config.disabled_methods if m} disabled_canon = {normalize_method_id(m) for m in disabled_raw} enabled_prov = {str(p).strip().lower() for p in config.enabled_providers if p} allow_all_prov = '*' in enabled_prov or not enabled_prov disabled_prov = {str(p).strip().lower() for p in config.disabled_providers if p} primary_canon = {normalize_method_id(m) for m in (config.primary_methods or []) if m} options: list[dict[str, Any]] = [] seen_option_ids: set[str] = set() for spec in LOGIN_METHOD_CATALOG: method_id = spec['method_id'] provider_id = spec['provider_id'] aliases = tuple(spec['aliases']) if provider_id in disabled_prov: continue if not allow_all_prov and provider_id not in enabled_prov: continue if method_id in disabled_canon or any(a in disabled_raw for a in aliases): continue is_enabled = allow_all_methods or any(a in enabled_raw for a in aliases) if not is_enabled: continue # For bunker_nip07, track whether NIP-46 bunker and/or NIP-07 extension are individually enabled sub_methods: dict[str, bool] = {} if method_id == 'bunker_nip07': has_explicit_sub = ('nip46_bunker' in enabled_raw) or ('nip07_ext' in enabled_raw) or ('nip07_extension' in enabled_raw) has_umbrella = ('bunker_nip07' in enabled_raw) or ('bunker' in enabled_raw) or allow_all_methods bunker_ok = (has_umbrella or 'nip46_bunker' in enabled_raw) and ('nip46_bunker' not in disabled_raw) nip07_ok = ( has_umbrella or 'nip07_ext' in enabled_raw or 'nip07_extension' in enabled_raw or 'nip07' in enabled_raw ) and ('nip07_ext' not in disabled_raw and 'nip07_extension' not in disabled_raw and 'nip07' not in disabled_raw) if not has_explicit_sub and not has_umbrella: continue if not bunker_ok and not nip07_ok: continue sub_methods = {'nip46_bunker': bunker_ok, 'nip07_extension': nip07_ok} tier = 'primary' if method_id in primary_canon else spec['tier'] entry: dict[str, Any] = { 'option_id': spec['option_id'], 'method_id': method_id, 'label': spec['label'], 'button_label': spec['button_label'], 'description': spec['description'], 'icon_id': spec['icon_id'], 'tier': tier, 'provider_id': provider_id, 'enabled': True, } if sub_methods: entry['sub_methods'] = sub_methods options.append(entry) seen_option_ids.add(spec['option_id']) # Append any custom registered service providers from `providers_detail` builtin_providers = {'service_provider', 'sovereign_key', 'local_operator'} for p in (providers_detail or []): pid = str(p.get('provider_id') or '').strip().lower() if not pid or pid in builtin_providers or pid in seen_option_ids: continue if pid in disabled_prov: continue if not allow_all_prov and pid not in enabled_prov and pid not in enabled_raw: continue if pid in disabled_raw: continue disp = str(p.get('display_name') or pid.replace('_', ' ').title()) btn_label = disp if disp.lower().startswith(('sign in', 'continue')) else f'Continue with {disp}' options.append({ 'option_id': f'provider_{pid}', 'method_id': pid, 'label': disp, 'button_label': btn_label, 'description': str(p.get('description') or f'Sign in with {disp}'), 'icon_id': str(p.get('icon_id') or 'service'), 'tier': str(p.get('tier') or ('primary' if pid in primary_canon or 'service_login' in (p.get('supported_methods') or []) else 'expert')), 'provider_id': pid, 'enabled': True, }) seen_option_ids.add(pid) return options
PRESET_WIDGET_CONFIGS: dict[str, AuthWidgetConfig] = { 'standard': AuthWidgetConfig( app_id='standard', app_title='FleetMesh', app_subtitle='Sign in with your Nostr Bunker, Private Key / DID, or an account.', mode='gate', brand_name='fleetmesh', brand_badge='SIGN IN', accent_primary='#38bdf8', accent_secondary='#0ea5e9', logo_variant='sails', required_role='broadcaster', ), 'admin': AuthWidgetConfig( app_id='admin', app_title='FleetMesh Admin', app_subtitle='Sign in to manage your instance.', mode='gate', brand_name='fleetmesh', brand_badge='ADMIN', accent_primary='#ff6b00', accent_secondary='#38bdf8', logo_variant='fleetmesh', required_role='moderator', ), 'ops': AuthWidgetConfig( app_id='ops', app_title='Fleetmesh Meshnode Ops', app_subtitle='Sign in to manage your node.', mode='gate', brand_name='fleetmesh', brand_badge='OPS', accent_primary='#10b981', accent_secondary='#38bdf8', logo_variant='ops', required_role='node_operator', ), } PRESET_WIDGET_CONFIGS['meshnode-ops'] = PRESET_WIDGET_CONFIGS['ops'] # Presets a host application registered at runtime (or through # FLEETMESH_AUTH_PRESETS_JSON). Consulted before the built-ins, so a host # can add its own `acme` or replace `admin` without forking this package. ENV_PRESETS_JSON = 'FLEETMESH_AUTH_PRESETS_JSON' _REGISTERED_PRESETS: dict[str, AuthWidgetConfig] = {} _WIDGET_CONFIG_FIELDS = frozenset(f.name for f in dataclasses.fields(AuthWidgetConfig)) def _base_widget_config(name: str) -> AuthWidgetConfig | None: raw = (name or '').strip().lower() if raw in _REGISTERED_PRESETS: return _REGISTERED_PRESETS[raw] return PRESET_WIDGET_CONFIGS.get(raw)
[docs]def register_widget_preset(name: str, overrides: Mapping[str, Any], *, base: str = 'standard') -> None: """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.""" key = str(name or '').strip().lower() if not key: raise ValueError('a widget preset needs a name') base_cfg = _base_widget_config(base) if base_cfg is None: raise ValueError(f'unknown widget preset base {base!r}') clean: dict[str, Any] = {} for k, v in dict(overrides or {}).items(): if k not in _WIDGET_CONFIG_FIELDS: log.warning('%s: preset %r: %r is not an AuthWidgetConfig field; ignored', ENV_PRESETS_JSON, key, k) continue if v is None: continue clean[k] = list(v) if isinstance(v, (list, tuple, set, frozenset)) else v clean.setdefault('app_id', key) fresh = { name: list(getattr(base_cfg, name)) for name in ('providers', 'enabled_methods', 'disabled_methods', 'primary_methods', 'enabled_providers', 'disabled_providers') } fresh.update(clean) _REGISTERED_PRESETS[key] = dataclasses.replace(base_cfg, **fresh)
[docs]def unregister_widget_preset(name: str) -> None: """Forget a registered preset; a built-in of that name shows again. No-op if absent.""" _REGISTERED_PRESETS.pop(str(name or '').strip().lower(), None)
[docs]def registered_widget_presets() -> dict[str, AuthWidgetConfig]: """The presets registered at runtime, by name (a copy).""" return dict(_REGISTERED_PRESETS)
[docs]def load_widget_presets_from_env(environ: Mapping[str, str] | None = None) -> list[str]: """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.""" env = os.environ if environ is None else environ raw = str(env.get(ENV_PRESETS_JSON) or '').strip() if not raw: return [] try: data = json.loads(raw) except ValueError as exc: log.warning('%s: not JSON (%s); ignored', ENV_PRESETS_JSON, exc) return [] if not isinstance(data, dict): log.warning('%s: must be a JSON object of presets; ignored', ENV_PRESETS_JSON) return [] loaded: list[str] = [] for name, spec in data.items(): if not isinstance(spec, dict): log.warning('%s: preset %r must be an object; ignored', ENV_PRESETS_JSON, name) continue spec = dict(spec) base = str(spec.pop('base', None) or 'standard') try: register_widget_preset(str(name), spec, base=base) except ValueError as exc: log.warning('%s: preset %r ignored (%s)', ENV_PRESETS_JSON, name, exc) continue loaded.append(str(name).strip().lower()) return loaded
[docs]def resolve_widget_config(app_id_or_host: str, overrides: Mapping[str, Any] | None = None) -> AuthWidgetConfig: raw = (app_id_or_host or '').strip().lower() if raw in _REGISTERED_PRESETS: base = _REGISTERED_PRESETS[raw] elif raw in PRESET_WIDGET_CONFIGS: base = PRESET_WIDGET_CONFIGS[raw] elif 'admin' in raw: base = PRESET_WIDGET_CONFIGS['admin'] elif 'ops' in raw: base = PRESET_WIDGET_CONFIGS['ops'] else: base = PRESET_WIDGET_CONFIGS['standard'] env_enabled_methods = enabled_methods_from_env() env_disabled_methods = disabled_methods_from_env() env_enabled_providers = enabled_providers_from_env() env_disabled_providers = disabled_providers_from_env() cfg = dataclasses.replace( base, providers=list(base.providers), enabled_methods=list(env_enabled_methods if env_enabled_methods is not None else base.enabled_methods), disabled_methods=list(env_disabled_methods if env_disabled_methods else base.disabled_methods), primary_methods=list(base.primary_methods), primary_actions=list(base.primary_actions), enabled_providers=list(env_enabled_providers if env_enabled_providers is not None else base.enabled_providers), disabled_providers=list(env_disabled_providers if env_disabled_providers else base.disabled_providers), ) if overrides: for k, v in overrides.items(): if hasattr(cfg, k) and v is not None: if isinstance(v, (list, tuple, set, frozenset)): setattr(cfg, k, list(v)) else: setattr(cfg, k, v) return cfg
# Presets an operator configured in the environment are there from the start. load_widget_presets_from_env()