Compare commits

..
14 Commits
Author SHA1 Message Date
LeoVasanko 4d48c0720a README 2026-02-06 01:07:00 +00:00
LeoVasanko 083d20c8c9 README 2026-02-06 01:00:58 +00:00
LeoVasanko c662fbd39c README 2026-02-06 00:29:16 +00:00
LeoVasanko edf80aef52 README 2026-02-06 00:27:01 +00:00
LeoVasanko 8d5c53ab72 README 2026-02-06 00:25:38 +00:00
LeoVasanko f8a760ddfd README 2026-02-06 00:23:44 +00:00
LeoVasanko 430394a1e5 README 2026-02-06 00:22:03 +00:00
LeoVasanko 4c54ad5d1f Docs, screenshot of permissions view. 2026-02-06 00:16:29 +00:00
LeoVasanko 0b2be18b44 Docs 2026-02-06 00:08:27 +00:00
LeoVasanko 1c8be68811 README 2026-02-05 22:58:42 +00:00
LeoVasanko 116bc3c4ef README 2026-02-05 22:44:26 +00:00
LeoVasanko c641c721c7 README 2026-02-05 21:54:14 +00:00
LeoVasanko 8fc03ade04 Remove the reset subcommand that was broken and unnecessary. 2026-02-05 21:53:30 +00:00
LeoVasanko 6ad3aa7d8c Screenshots, README. 2026-02-05 21:38:57 +00:00
9 changed files with 383 additions and 292 deletions
+153 -12
View File
@@ -1,28 +1,35 @@
# Paskia # Paskia
![Screenshot](https://git.zi.fi/leovasanko/paskia/raw/main/docs/screenshots/forbidden-light.webp) ![Login dialog screenshot](https://git.zi.fi/leovasanko/paskia/raw/main/docs/screenshots/login-light.webp)
An easy to install passkey-based authentication service that protects any web application with strong passwordless login. An easy to install passkey-based authentication service that protects any web application with strong passwordless login.
## What is Paskia? ## What is Paskia?
- Easy to use fully featured auth&auth system (login and permissions) - Easy to use fully featured auth&auth system (login and permissions)
- Organization and role-based access control (optional) - Organization and role-based access control
* Org admins control their users and roles * Org admins control their users and roles
* Master admin can create multiple independent orgs * Multiple independent orgs
* Master admin makes permissions available for orgs to assign * Master admin can do everything or delegate to org admins
- User Profile and Administration by API and web interface. - User Profile and Admin by API and web interface
under `/auth/` or `auth.example.com` - Implements login/reauth/forbidden flows for you
- Reset tokens and additional device linking via QR code or codewords. - Single Sign-On (SSO): Users register once and authenticate across your services
- Pure Python, FastAPI, packaged with prebuilt Vue frontend - Remote autentication by entering random keywords from another device (like 2fa)
- No CORS, NodeJS or anything extra needed.
## Authenticate to get to your app, or in your app
Two interfaces:
- API fetch: auth checks and login without leaving your app - API fetch: auth checks and login without leaving your app
- Forward-auth proxy: protect any unprotected site or service (Caddy, Nginx) - Forward-auth proxy: protect any unprotected site or service (Caddy, Nginx)
The API mode is useful for applications that can be customized to run with Paskia. Forward auth can also protect your javascript and other assets. Each provides fine-grained permission control and reauthentication requests where needed, and both can be mixed where needed. The API mode is useful for applications that can be customized to run with Paskia. Forward auth can also protect your javascript and other assets. Each provides fine-grained permission control and reauthentication requests where needed, and both can be mixed where needed.
Single Sign-On (SSO): Users register once and authenticate across all applications under your domain name (configured rp-id). ## Authentication flows already done
![Forbidden dialog, dark mode](https://git.zi.fi/leovasanko/paskia/raw/main/docs/screenshots/forbidden-dark.webp)
**Automatic light/dark mode switching with overrides by user profile and protected app's theme.**
Paskia includes set of login, reauthentication and forbidden dialogs that it can use to perform the needed flows. We never leave the URL, no redirections, and if you make use of API mode, we won't even interrupt whatever your app was doing but retry the blocked API fetch after login like nothing happened.
## Quick Start ## Quick Start
@@ -44,11 +51,10 @@ uv tool install paskia
## Configuration ## Configuration
There is no config file. All settings are passed as CLI options: All configuration is passed by CLI arguments, of which there are just a few.
```text ```text
paskia [options] paskia [options]
paskia reset [user] # Generate passkey reset link
``` ```
| Option | Description | Default | | Option | Description | Default |
@@ -59,6 +65,141 @@ paskia reset [user] # Generate passkey reset link
| --origin *url* | Restrict allowed origins for WebSocket auth (repeatable) | All under rp-id | | --origin *url* | Restrict allowed origins for WebSocket auth (repeatable) | All under rp-id |
| --auth-host *url* | Dedicated authentication site, e.g. **auth.example.com** | Use **/auth/** path on each site | | --auth-host *url* | Dedicated authentication site, e.g. **auth.example.com** | Use **/auth/** path on each site |
## Tutorial: From Local Testing to Production
This section walks you through a complete example, from running Paskia locally to protecting a real site in production.
### Step 1: Local Testing
For development and testing, run Paskia without any arguments:
```fish
paskia
```
This starts the server on [localhost:4401](http://localhost:4401) with passkeys bound to `localhost`. On first run, Paskia prints a registration link for the Master Admin—click it to register your first passkey.
### Step 2: Production Configuration
For a real deployment, configure Paskia with your domain name (rp-id). This enables SSO setup for that domain and any subdomains.
```fish
paskia --rp-id example.com --rp-name "Example Corp"
```
This binds passkeys to `*.example.com`. The `--rp-name` is shown to users during passkey registration.
### Step 3: Set Up Caddy
Install [Caddy](https://caddyserver.com/) and copy the [auth folder](caddy/auth) to `/etc/caddy/auth`. Say your current unprotected Caddyfile looks like this:
```caddyfile
app.example.com {
reverse_proxy :3000
}
```
Add Paskia full site protection:
```caddyfile
app.example.com {
import auth/setup
handle {
import auth/require perm=myapp:login
reverse_proxy :3000
}
}
```
Run `systemctl reload caddy`. Now `app.example.com` requires the `myapp:login` permission. Try accessing it and you'll land on a login dialog.
### Step 4: Assign Permissions via Admin Panel
![Admin panel permissions](https://git.zi.fi/leovasanko/paskia/raw/main/docs/screenshots/master-permissions.webp)
1. Go to `app.example.com/auth/admin/`
2. Create a permission, give it a name and scope `myapp:login`
3. Assign it to Organization
4. In that organization, assign it to the Administration role
Now you have granted yourself the new permission.
Permission scopes are text identifiers with colons as separators that we can use for permission checks. The `myapp:` prefix is a convention to namespace permissions per application—you but you can use other forms as you see fit (urlsafe characters, no spaces allowed).
### Step 5: Add API Authentication to Your App
Your backend already receives `Remote-*` headers from Caddy's forward-auth. For frontend API calls, we provide a [JS paskia module](https://www.npmjs.com/package/paskia):
```js
import { apiJson } from 'https://cdn.jsdelivr.net/npm/paskia@latest/dist/paskia.js'
const data = await apiJson('/api/sensitive', { method: 'POST' })
```
When a 401/403 occurs, the auth dialog appears automatically, and the request retries after authentication.
To protect the API path with a different permission, update your Caddyfile:
```caddyfile
app.example.com {
import auth/setup
@api path /api/*
handle @api {
import auth/require perm=myapp:api
reverse_proxy :3000
}
handle {
import auth/require perm=myapp:login
reverse_proxy :3000
}
}
```
Create the `myapp:api` permission in the admin panel, that will be required for all API access. Link to `/auth/` for the built-in profile page.
You may also remove the `myapp:login` protection from the rest of your site paths, unless you wish to keep all your assets behind a login page. Having this as the last entry in your config allows free access to everything not matched by other sections.
```Caddyfile
handle {
reverse_proxy :3000
}
```
### Step 6: Run Paskia as a Service
Create a system user paskia, install UV on the system, and create a systemd unit:
```fish
sudo useradd --system --home-dir /srv/paskia --create-home paskia
curl -LsSf https://astral.sh/uv/install.sh | sudo env UV_INSTALL_DIR=/usr/local/bin sh
sudo systemctl edit --force --full paskia.service
```
Paste the following and save:
```ini
[Unit]
Description=Paskia Authentication Server
[Service]
Type=simple
User=paskia
WorkingDirectory=/srv/paskia
ExecStart=uvx paskia --rp-id example.com --rp-name "Example Corp"
[Install]
WantedBy=multi-user.target
```
Then enable and start, view output for registration link:
```fish
sudo systemctl enable --now paskia && sudo journalctl -u paskia -f -n 20 -o cat
```
## Further Documentation ## Further Documentation
- [Caddy configuration](https://git.zi.fi/LeoVasanko/paskia/src/branch/main/docs/Caddy.md) - [Caddy configuration](https://git.zi.fi/LeoVasanko/paskia/src/branch/main/docs/Caddy.md)
+188 -33
View File
@@ -1,43 +1,198 @@
# Integrating Paskia with your App # Integrating Paskia with your App
Protect API routes with forward-auth (see [Caddy configuration](Caddy.md)). Optionally protect your app assets and not just the API. This guide covers frontend and backend integration with Paskia. For Caddy forward-auth setup, see [Caddy configuration](Caddy.md).
Catch response status 401/403 in fetch calls to protected endpoints and implement authentication flow in this case. The response is JSON and contains `detail` (an error message describing what is needed) and `auth.iframe` (a URL). Render that URL in an iframe and retry the request after authentication (see below). ## Frontend Integration
While the app is in (active) use, call `/auth/api/validate` occasionally to keep the session alive (session lifetime is 24h), otherwise the user will have to login every day. Max-age limits are unaffected by this and can be used on endpoints needing to reauthenticate with passkey more frequently. ### Using the paskia-js Module
Fetch `/auth/api/user-info` to display user/session details, or link to `/auth/` if you prefer using the built-in profile UI and not having to do anything more. The [paskia](https://www.npmjs.com/package/paskia) JavaScript module provides utilities for API calls, session validation, and authentication overlays. Works with any framework or vanilla JS.
## Authentication Flow (iframe) ```html
<script type="module">
```js import { apiJson, apiFetch, SessionValidator } from 'https://cdn.jsdelivr.net/npm/paskia@latest/dist/paskia.js'
// Show an authentication dialog </script>
const iframe = document.createElement('iframe')
iframe.src = auth.url // from 401/403 response JSON
iframe.style.cssText = `
position: fixed;
inset: 0;
width: 100%;
height: 100%;
border: 0;
z-index: 9999;
background: transparent;
backdrop-filter: blur(0.1rem) brightness(0.7);
`
document.body.appendChild(iframe)
// Wait until user is finished with the dialog
const handler = ev => {
if (ev.origin !== location.origin) return
iframe.remove()
removeEventListener('message', handler)
if (ev.data?.type === 'auth-success') retry_original_fetch()
}
addEventListener('message', handler)
``` ```
This describes the frontend flow for handling 401/403 responses from endpoints protected by Paskia forward-auth, without ever exiting your app. Or install to your project:
When a protected request fails, the backend returns 401 (needs auth / reauth) or 403 (missing permission). For API requests, the response is JSON that includes an iframe URL. Your app should render that URL in a full-screen iframe overlay, and retry the request after the iframe reports success. If it reports `auth-cancel`, don't try again. The backdrop for the dialog is a stylistic choice, and you can style the background shown with the dialog any way you wish, and consider using CSS file with the iframe rather than inline styles as used in the example. ```sh
npm install paskia
```
Following this flow the user gets authenticated properly and after that your app keeps running as if nothing ever happened. ### API Fetch with Automatic Auth
Use `apiJson` or `apiFetch` for API calls. When a 401/403 response includes an auth URL, the authentication dialog appears automatically, then the request retries. The JSON variant is purely for convenience, doing JSON headers and conversions for you.
```js
import { apiJson, apiFetch, AuthCancelledError } from 'paskia'
// JSON API call (sets Content-Type, parses response)
try {
const data = await apiJson('/api/endpoint', { method: 'POST', body: { key: 'value' } })
} catch (e) {
if (e instanceof AuthCancelledError) {
// User cancelled auth dialog
}
}
// Raw fetch with auth handling (returns Response object)
const response = await apiFetch('/api/endpoint')
```
For requests that shouldn't trigger auth dialogs, use standard `fetch` or our `fetchJson`.
### Session Validation Polling
Keep sessions alive and detect when the user logs out or switches accounts:
```js
import { SessionValidator } from 'paskia'
const validator = new SessionValidator(
() => currentUser?.uuid, // getter for current user ID
(error) => handleSessionLost(error) // callback when session is lost or user changes
)
validator.start() // start polling (pauses on idle)
validator.stop() // stop polling
```
The validator calls `/auth/api/validate` periodically to:
- Renew the session cookie (24h lifetime)
- Detect if the user logged out or switched accounts
- Pause polling when the page is idle, allowing sessions to expire when not used
### Manual Auth Flow
If you need custom control, handle 401/403 responses manually:
```js
import { showAuthIframe, AuthCancelledError } from 'paskia'
const response = await fetch('/api/protected')
if (response.status === 401 || response.status === 403) {
const data = await response.json()
if (data.auth?.iframe) {
try {
await showAuthIframe(data.auth.iframe)
// Retry the original request
} catch (e) {
if (e instanceof AuthCancelledError) {
// User clicked Back
}
}
}
}
```
### User Info and Profile
Get current user details:
```js
const user = await apiJson('/auth/api/user-info', { method: 'POST' })
// Returns: { uuid, display_name, credentials, sessions, permissions, ... }
```
Or link to the built-in profile page: `/auth/`
## Backend Integration
### Using Forward-Auth Headers
When using Caddy forward-auth, your backend receives `Remote-*` headers on authenticated requests. See [Headers](Headers.md) for the full list.
```python
# Example: Python/FastAPI
@app.get("/api/data")
def get_data(request: Request):
user_id = request.headers.get("Remote-User")
org_id = request.headers.get("Remote-Org")
permissions = request.headers.get("Remote-Groups", "").split(",")
# ...
```
### Direct Validation from Backend
Your backend can validate sessions directly by calling Paskia's validate endpoint:
```python
import httpx
async def validate_session(request) -> dict:
"""Validate a session cookie and check permissions."""
authcookie = request.get("__Host-paskia")
response = await httpx.post(
"http://localhost:4401/auth/api/validate?perm=myapp:login+myapp:api",
headers={
"Host": request.headers["host"]
"X-Forwarded-For": request.client.host,
"Cookie": f"__Host-paskia={}",
},
)
if response.status_code != 200:
return response.json() # Return to client
# User authenticated... We are good to go!
ctx = response.json() # User and session information
```
This is useful for:
- WebSocket connections where headers aren't available after handshake
- Background jobs that need to verify a stored session
- APIs not behind forward-auth (auth/restrict)
### Validate Endpoint Parameters
`POST /auth/api/validate` accepts query parameters:
| Parameter | Description |
|-----------|-------------|
| `perm=scope:name` | Require this permission (repeatable) |
| `max_age=5min` | Require recent passkey use |
Returns 200 with user info on success, 401/403 on failure.
## Proxying /auth/ to Paskia
Your app server needs to proxy `/auth/` paths to Paskia. This can be done by your application but is much easier done by Caddy or Nginx.
### Caddy
This handles both HTTP and WebSocket connections. Caddy's `reverse_proxy` handles HTTP and WebSocket transparently. This is essentially what our Caddy [auth/setup](../caddy/auth/setup) snippet does: `reverse_proxy :4401`.
```caddyfile
app.example.com {
import auth/setup
# ... your routes in handle blocks
}
```
### Nginx
Certain headers need to be configured for correct host and WS support:
```nginx
location /auth/ {
proxy_pass http://localhost:4401;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
}
```
### Node.js / Express
Using `http-proxy-middleware`:
```js
import { createProxyMiddleware } from 'http-proxy-middleware'
app.use('/auth', createProxyMiddleware({ target: 'http://localhost:4401', ws: true, changeOrigin: false }))
```
### Python / FastAPI
You will need to process and handle `/auth/` for HTTP requests and `/auth/ws/` for WebSockets manually, which is beyond the scope of this documentation.
We highly recommend Caddy instead as the simpler and more production-worthy solution that Just Works.
Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

+37 -106
View File
@@ -8,26 +8,6 @@
:root { :root {
color-scheme: light dark; /* Automatic themes by browser */ color-scheme: light dark; /* Automatic themes by browser */
} }
/* Login/reauth/forbidden dialog will appear in this iframe */
#auth-iframe {
/* Full viewport overlay */
border: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 9999;
/* Optional transparent background with optional blur backdrop */
color-scheme: auto;
background: transparent;
backdrop-filter: blur(.1rem) brightness(0.7);
-webkit-backdrop-filter: blur(.1rem) brightness(0.7);
}
/* Prevent background scroll when auth-iframe is shown */
body:has(#auth-iframe) {
overflow: hidden;
}
</style> </style>
</head> </head>
<body> <body>
@@ -65,99 +45,50 @@
</div> </div>
</div> </div>
<script> <script type="module">
import { apiFetch, apiJson, AuthCancelledError } from '/paskia-js/dist/paskia.js'
const output = document.getElementById('output'); const output = document.getElementById('output');
let pendingCall = null; // Stores the API call to retry after auth
// The auth iframe posts messages when authentication completes or is cancelled.
// Message types: 'auth-success' (proceed), 'auth-back' (user cancelled)
// Errors during auth stay in the dialog allowing retry, no message is sent.
window.addEventListener('message', (event) => {
const { type, message } = event.data || {};
if (type === 'auth-success') {
log('✓ Authentication successful, retrying...');
hideAuthIframe();
// Retry the original API call that triggered authentication
if (pendingCall) {
const { url, method } = pendingCall;
pendingCall = null;
apiCall(url, method);
}
} else if (type === 'auth-back') {
log(message || 'Authentication cancelled');
hideAuthIframe();
pendingCall = null;
}
});
// Make an API call, handling 401/403 by showing the auth iframe.
// The server returns JSON with auth.iframe URL when authentication is needed.
async function apiCall(url, method = 'GET') {
log(`${method} ${url}...`);
const response = await fetch(url, { method });
// Server returns 401 (login/reauth) or 403 (missing permissions)
// with a JSON body containing the iframe URL for authentication
if (response.status === 401 || response.status === 403) {
const data = await response.json();
if (data.auth?.iframe) {
const mode = data.auth.mode; // 'login' or 'reauth'
log(`${mode === 'reauth' ? 'Re-authentication' : 'Authentication'} required...`);
pendingCall = { url, method };
showAuthIframe(data.auth.iframe);
return;
}
log(`Error: ${response.status} - ${data.detail}`);
return;
}
// Forward endpoint returns 204 on success (Caddy then adds Remote-* headers)
if (response.status === 204) {
log('✓ Success (204 No Content)\nHeaders:\n' +
[...response.headers].filter(([k]) => k.startsWith('remote-'))
.map(([k, v]) => ` ${k}: ${v}`).join('\n'));
return;
}
if (!response.ok) {
log(`Error: ${response.status} ${response.statusText}`);
return;
}
const data = await response.json();
log('✓ Response:\n' + JSON.stringify(data, null, 2));
}
async function logout() {
await fetch('/auth/api/logout', { method: 'POST' });
log('Logged out');
}
// Create fullscreen iframe for authentication.
// The 'allow' attribute enables WebAuthn (passkey) API inside the iframe.
function showAuthIframe(url) {
hideAuthIframe();
const iframe = document.createElement('iframe');
iframe.id = 'auth-iframe';
iframe.src = url;
document.body.appendChild(iframe);
log("Authentication dialog open...")
}
function hideAuthIframe() {
document.getElementById('auth-iframe')?.remove();
}
function log(msg) { function log(msg) {
output.textContent = msg; output.textContent = msg;
} }
// Make an API call using paskia module (handles 401/403 automatically)
window.apiCall = async function(url, method = 'GET') {
log(`${method} ${url}...`);
try {
const response = await apiFetch(url, { method });
// Forward endpoint returns 204 on success
if (response.status === 204) {
log('✓ Success (204 No Content)');
return;
}
if (!response.ok) {
log(`Error: ${response.status} ${response.statusText}`);
return;
}
const data = await response.json();
log('✓ Response:\n' + JSON.stringify(data, null, 2));
} catch (e) {
if (e instanceof AuthCancelledError) {
log('Authentication cancelled');
} else {
log(`Error: ${e.message}`);
}
}
}
window.logout = async function() {
await fetch('/auth/api/logout', { method: 'POST' });
log('Logged out');
}
// Browser mode: open the forward endpoint directly in a new window. // Browser mode: open the forward endpoint directly in a new window.
// When Accept: text/html, the server redirects to the login page if needed, window.browserNav = function(url) {
// then back to the original URL after authentication.
function browserNav(url) {
log('Opening in new window...\nIf not authenticated, you\'ll see the login page.\nAfter auth, you\'ll see a 204 response (blank page = success).'); log('Opening in new window...\nIf not authenticated, you\'ll see the login page.\nAfter auth, you\'ll see a 204 response (blank page = success).');
window.open(url, '_blank'); window.open(url, '_blank');
} }
+5 -35
View File
@@ -13,18 +13,14 @@ from paskia import globals as _globals
from paskia.bootstrap import bootstrap_if_needed from paskia.bootstrap import bootstrap_if_needed
from paskia.config import PaskiaConfig from paskia.config import PaskiaConfig
from paskia.db.background import flush from paskia.db.background import flush
from paskia.fastapi import reset as reset_cmd
from paskia.util import startupbox from paskia.util import startupbox
from paskia.util.hostutil import normalize_origin from paskia.util.hostutil import normalize_origin
DEFAULT_PORT = 4401 DEFAULT_PORT = 4401
EPILOG = """\ EPILOG = """\
Examples: Example:
paskia # localhost:4401 paskia --rp-id example.com --rp-name "Example Corporation" --auth-host auth.example.com
paskia -l :8080 # All interfaces, port 8080
paskia -l /tmp/paskia.sock # Unix socket
paskia reset [user] # Generate passkey reset link
""" """
@@ -63,10 +59,7 @@ def add_common_options(p: argparse.ArgumentParser) -> None:
) )
p.add_argument( p.add_argument(
"--auth-host", "--auth-host",
help=( help=("Dedicated authentication site (optionally with scheme/port)"),
"Dedicated host (optionally with scheme/port) to serve the auth UI at the root,"
" e.g. auth.example.com or https://auth.example.com"
),
) )
@@ -81,17 +74,6 @@ def main():
epilog=EPILOG, epilog=EPILOG,
) )
# Subcommand for reset
parser.add_argument(
"command",
nargs="?",
help="Command: 'reset' for credential reset, or omit to run server",
)
parser.add_argument(
"reset_query",
nargs="?",
help="For 'reset' command: user UUID or substring of display name",
)
parser.add_argument( parser.add_argument(
"-l", "-l",
"--listen", "--listen",
@@ -105,16 +87,8 @@ def main():
args = parser.parse_args() args = parser.parse_args()
# Detect "reset" subcommand # Parse endpoint using fastapi_vue.hostutil
is_reset = args.command == "reset" endpoints = parse_endpoint(args.listen, DEFAULT_PORT)
if is_reset:
endpoints = []
else:
if args.command is not None:
raise SystemExit(f"Unknown command: {args.command}")
# Parse endpoint using fastapi_vue.hostutil
endpoints = parse_endpoint(args.listen, DEFAULT_PORT)
# Extract host/port/uds from first endpoint for config display and site_url # Extract host/port/uds from first endpoint for config display and site_url
ep = endpoints[0] if endpoints else {} ep = endpoints[0] if endpoints else {}
@@ -218,10 +192,6 @@ def main():
await bootstrap_if_needed() await bootstrap_if_needed()
await flush() await flush()
if is_reset:
exit_code = reset_cmd.run(args.reset_query)
raise SystemExit(exit_code)
if len(endpoints) > 1: if len(endpoints) > 1:
async with asyncio.TaskGroup() as tg: async with asyncio.TaskGroup() as tg:
for ep in endpoints: for ep in endpoints:
-106
View File
@@ -1,106 +0,0 @@
"""CLI support for creating user credential reset links.
Usage (via main CLI):
paskia reset [query]
If query is omitted, the master admin (first Administration role user in
an organization granting auth:admin) is targeted. Otherwise query is
matched as either an exact UUID or a case-insensitive substring of the
display name. If multiple users match, they are listed and the command
aborts. A new one-time reset link is always created.
"""
import asyncio
from uuid import UUID
from paskia import authsession as _authsession
from paskia import db
from paskia.util import hostutil
async def _resolve_targets(query: str | None):
if query:
# Try UUID
targets: list[tuple] = []
try:
q_uuid = UUID(query)
p = next(
(p for p in db.data().permissions.values() if p.scope == "auth:admin"),
None,
)
if p:
for org_uuid in p.orgs:
users = db.get_organization_users(org_uuid)
for u, role_name in users:
if u.uuid == q_uuid:
return [(u, role_name)]
# UUID not found among admin orgs -> fall back to substring search (rare case)
except ValueError:
pass
# Substring search
needle = query.lower()
p = next(
(p for p in db.data().permissions.values() if p.scope == "auth:admin"), None
)
if p:
for org_uuid in p.orgs:
users = db.get_organization_users(org_uuid)
for u, role_name in users:
if needle in (u.display_name or "").lower():
targets.append((u, role_name))
# De-duplicate
seen = set()
deduped = []
for u, role_name in targets:
if u.uuid not in seen:
seen.add(u.uuid)
deduped.append((u, role_name))
return deduped
# No query -> master admin
p = next(
(p for p in db.data().permissions.values() if p.scope == "auth:admin"), None
)
if not p or not p.orgs:
return []
first_org_uuid = next(iter(p.orgs))
users = db.get_organization_users(first_org_uuid)
admin_users = [pair for pair in users if pair[1] == "Administration"]
return admin_users[:1]
async def _create_reset(user, role_name: str):
expiry = _authsession.reset_expires()
token = db.create_reset_token(
user_uuid=user.uuid,
expiry=expiry,
token_type="manual reset",
)
return hostutil.reset_link_url(token), token
async def _main(query: str | None) -> int:
try:
candidates = await _resolve_targets(query)
if not candidates:
print("No matching users found")
return 1
if len(candidates) > 1:
print("Multiple matches. Refine your query:")
for u, role_name in candidates:
print(f" - {u.display_name} ({u.uuid}) role={role_name}")
return 2
user, role_name = candidates[0]
link, token = await _create_reset(user, role_name)
print(f"Reset link for {user.display_name} ({user.uuid}):\n{link}\n")
return 0
except Exception as e: # pragma: no cover
print("Failed to create reset link:", e)
return 1
def run(query: str | None) -> int:
"""Synchronous wrapper for CLI entrypoint."""
return asyncio.run(_main(query))
__all__ = ["run"]