"""GitHub资源地址与凭据选择;普通发布者不能借用服务器全局PAT。""" import os import re from urllib.parse import urlsplit from skill_archive_source import item_source, source_key def repository_parts(url): if not isinstance(url, str): raise ValueError('invalid repository') parsed = urlsplit(url.strip()) if (parsed.scheme != 'https' or parsed.hostname != 'github.com' or parsed.username or parsed.password or parsed.port not in (None, 443) or parsed.query or parsed.fragment): raise ValueError('invalid repository origin') parts = parsed.path.strip('/').split('/') if len(parts) != 2: raise ValueError('invalid repository path') owner, repo = parts if repo.endswith('.git'): repo = repo[:-4] if (not re.fullmatch(r'[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?', owner) or not re.fullmatch(r'[A-Za-z0-9_.-]{1,100}', repo) or repo in {'.', '..'}): raise ValueError('invalid repository identity') return owner, repo def canonical_repository(url): owner, repo = repository_parts(url) return f'https://github.com/{owner}/{repo}' def github_item_source(item): return item_source(item, repository_parts) def canonical_resource_source(item): return source_key(github_item_source(item)) def _token(value): if value is None or value == '': return None if not isinstance(value, str) or not re.fullmatch(r'[\x21-\x7e]+', value): raise ValueError('invalid github credential') return value def select_github_token(item, *, admin_check=None): github_item_source(item) author = item.get('author') if not isinstance(author, str) or not author.strip(): raise ValueError('invalid resource author') creator = _token(item.get('github_token')) if creator is not None: return creator if admin_check is None: from 安全认证 import is_admin admin_check = is_admin # 权限来自服务端管理员配置与已保存作者,不信任请求账号或前端管理员标记。 if admin_check(author) is True: return _token(os.environ.get('GITHUB_PAT')) return None