"""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]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)
# Presets an operator configured in the environment are there from the start.
load_widget_presets_from_env()