Add OIDC browser approval and PKCE session handoff for pages CLI
Build and publish container images / images (push) Successful in 14m39s
Release container images / release (push) Successful in 25s

This commit is contained in:
Anya Tokugawa committed 2026-11-01 20:26:45 +09:00
1 parent 2af87b4f58
commit 60f5fb1881
18 files changed
+1397 -23

No files matched your search

+75 -8
View File
@@ -1,6 +1,7 @@
#!/usr/bin/env python3
"""pages — navigate and edit PagesWiki from your terminal (pages-cli)."""
import argparse
import base64
import contextlib
import difflib
import fcntl
@@ -11,6 +12,7 @@ import os
from pathlib import Path
import posixpath
import re
import secrets
import shlex
import stat
import subprocess
@@ -130,11 +132,69 @@ class Client:
raise
result = self.json('/_/auth/totp', method='POST', form={
'challenge_token': e.payload['challenge_token'], 'code': otp('TOTP: ')})
return self.accept_session(result)
def accept_session(self, result):
token = result.get('access_token')
if not isinstance(token, str) or not re.fullmatch(r'[A-Za-z0-9_.~-]{16,1024}', token) or result.get('token_type') != 'Bearer':
raise Failure('Server did not issue a Bearer session.')
duration = result.get('expires_in')
if not isinstance(duration, int) or isinstance(duration, bool) or not 1 <= duration <= 30*24*60*60:
raise Failure('Invalid session lifetime.')
self.token = token
return time.time() + int(result['expires_in'])
return time.time() + duration
def login_oidc(self, no_browser=False, expected_username='', *, sleep=time.sleep, clock=time.monotonic):
verifier = secrets.token_urlsafe(32)
challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).decode().rstrip('=')
try:
started = self.json('/_/auth/cli/start', method='POST', form={
'code_challenge': challenge, 'code_challenge_method': 'S256'})
except Failure as e:
if e.status in (404, 405, 501):
raise Failure('CLI OIDC login is unavailable on this server. Check the configured server URL and deploy a server version supporting /_/auth/cli/start.', e.status) from None
if e.status == 403 and e.payload.get('error') == 'oidc_disabled':
raise Failure('OIDC login is not enabled for this domain. Ask your administrator to enable it.', e.status) from None
raise
device, route, code = (started.get(k) for k in ('device_code', 'verification_uri', 'user_code'))
if (not isinstance(device, str) or not re.fullmatch(r'[A-Za-z0-9_-]{43}', device)
or not isinstance(route, str) or not re.fullmatch(r'/_/auth/cli/verify\?request=[A-Za-z0-9_-]{43}', route)
or not isinstance(code, str) or not re.fullmatch(r'[A-F0-9]{4}-[A-F0-9]{4}', code)):
raise Failure('Invalid browser login response; no browser was opened.')
lifetime, interval = int(started.get('expires_in', 0)), int(started.get('interval', 0))
if not 1 <= lifetime <= 300 or not 5 <= interval <= 30:
raise Failure('Invalid browser login lifetime or polling interval.')
deadline = clock() + lifetime
print('Open this URL and approve only the request you started:')
print(self.base + route)
print('Confirmation code:', code)
print('Waiting for approval (up to 5 minutes). Ctrl+C cancels locally.', flush=True)
if not no_browser:
try: webbrowser.open(self.base + route, new=2)
except (webbrowser.Error, OSError): pass # URL remains usable on another device.
while clock() + interval < deadline:
sleep(interval)
try:
result = self.json('/_/auth/cli/token', method='POST', form={
'device_code': device, 'code_verifier': verifier})
except Failure as e:
reason = e.payload.get('error')
if e.status == 400 and reason == 'authorization_pending': continue
if e.status == 400 and reason == 'slow_down':
interval = min(30, interval + 5); continue
if reason in ('access_denied', 'expired_token', 'oidc_disabled'):
raise Failure('Browser login denied, expired or disabled. Restart pages login --oidc.') from None
raise # Never retry an ambiguous token exchange or a network failure.
name = result.get('username')
expires = self.accept_session(result)
if (not isinstance(name, str) or not name or any(unicodedata.category(c).startswith('C') for c in name)
or (expected_username and name.lower() != expected_username.lower())):
try: self.json('/_/auth/logout', method='POST')
except Failure: pass
self.token = ''
raise Failure('The browser account differs from the configured username; attempted to revoke the new session.')
return expires, name
raise Failure('Browser login expired. Restart pages login --oidc.')
def listing(self, path, prefix=''):
return self.json('/_/api/v1/path-picker?' + url.urlencode({'path': path, 'mode': 'children', 'prefix': prefix}))
@@ -304,7 +364,7 @@ def configure(words, root=None):
# Configuration and session locks use this order. Never retarget an
# active credential to a different Domain or account.
with Profile(name, root).locked() as session:
if session.data.get('token') and (spec['origin'] != session.data.get('origin') or spec.get('username', '') != session.data.get('username')):
if session.data.get('token') and (spec['origin'] != session.data.get('origin') or spec.get('username', '') != session.data.get('configured_username', session.data.get('username'))):
raise Failure('Log out this profile before changing its origin or username.')
data['profiles'][name] = spec
if len(data['profiles']) == 1: data['default_profile'] = name
@@ -480,7 +540,10 @@ def main(argv=None):
parser.print_help(); return
if args.command == 'login':
login = argparse.ArgumentParser(prog='pages login', description='Log into the configured connection. Password and TOTP are prompted privately.')
login.parse_args(args.args)
login.add_argument('--oidc', action='store_true', help='Authenticate and approve in a browser; no local password required')
login.add_argument('--no-browser', action='store_true', help='Print the browser login URL without opening it (requires --oidc)')
login_args = login.parse_args(args.args)
if login_args.no_browser and not login_args.oidc: login.error('--no-browser requires --oidc')
elif '--help' in args.args:
execute(None, None, [args.command] + args.args); return
with contextlib.ExitStack() as stack:
@@ -494,13 +557,17 @@ def main(argv=None):
# Hold the profile lock before releasing the configuration lock.
profile = stack.enter_context(Profile(name).locked())
if args.command == 'login':
if not spec.get('username'): raise Failure('Set your account with pages configure --username NAME.')
if not login_args.oidc and not spec.get('username'): raise Failure('Set your account with pages configure --username NAME, or use pages login --oidc.')
if profile.data.get('token'): raise Failure('Log out this profile before replacing its session.')
client = Client(spec['origin'], lang=lang)
expires = client.login(spec['username'], getpass.getpass('Password: '))
same_identity = profile.data.get('origin') == client.base and profile.data.get('username') == spec['username']
if login_args.oidc:
expires, username = client.login_oidc(login_args.no_browser, spec.get('username', ''))
else:
username = spec['username']
expires = client.login(username, getpass.getpass('Password: '))
same_identity = profile.data.get('origin') == client.base and profile.data.get('username') == username
cwd = profile.data.get('cwd', '/') if same_identity else '/'
profile.data = {'origin': client.base, 'username': spec['username'], 'token': client.token, 'expires': expires, 'cwd': cwd}
profile.data = {'origin': client.base, 'username': username, 'configured_username': spec.get('username', ''), 'token': client.token, 'expires': expires, 'cwd': cwd}
try:
profile.save()
except OSError:
@@ -512,7 +579,7 @@ def main(argv=None):
raise Failure('Could not save credentials; attempted to revoke the new session.') from None
print('Logged in. Session saved privately.'); return
if not profile.data.get('token'): raise Failure('Log in first.')
if args.command != 'logout' and (profile.data.get('origin') != spec['origin'] or profile.data.get('username') != spec.get('username')):
if args.command != 'logout' and (profile.data.get('origin') != spec['origin'] or profile.data.get('configured_username', profile.data.get('username')) != spec.get('username', '')):
raise Failure('Session and configured identity differ. Log out before reconnecting.')
if args.command not in ('logout', 'status') and profile.data.get('expires', 0) <= time.time(): raise Failure('Session expired; log out and log in again.')
client = Client(profile.data['origin'], profile.data['token'], lang)