Template
Allow re-copying invite configs and end-user server choice (v3.0.1).
Invite pages keep created configs for repeat copy; guest/invite can pick a server when enabled. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -103,7 +103,7 @@ else:
|
||||
application_path = os.path.dirname(__file__)
|
||||
|
||||
DATA_FILE = os.path.join(application_path, 'data.json') # legacy JSON; used only for one-shot import / export
|
||||
CURRENT_VERSION = "v3.0.0"
|
||||
CURRENT_VERSION = "v3.0.1"
|
||||
RELEASES_REPO_URL = repo_url()
|
||||
RELEASES_API_LATEST = api_latest_url()
|
||||
BIN_DIR = os.environ.get('TUNNEL_BIN_DIR', os.path.join(application_path, 'bin'))
|
||||
@@ -2401,6 +2401,7 @@ class GuestSettings(BaseModel):
|
||||
create_server_id: int = 0
|
||||
create_inbound_id: int = 0
|
||||
create_xui_panel_id: str = ''
|
||||
create_allow_server_choice: bool = True
|
||||
|
||||
|
||||
class DonateMethodSettings(BaseModel):
|
||||
@@ -2474,6 +2475,7 @@ class ShareAuthRequest(BaseModel):
|
||||
|
||||
class GuestCreateRequest(BaseModel):
|
||||
name: str = 'Guest VPN'
|
||||
server_id: Optional[int] = None
|
||||
|
||||
|
||||
class InviteCreateRequest(BaseModel):
|
||||
@@ -2488,6 +2490,7 @@ class InviteCreateRequest(BaseModel):
|
||||
duration_days: int = 0 # client lifetime after redeem; 0 = no expiry
|
||||
note: str = ''
|
||||
enabled: bool = True
|
||||
allow_server_choice: bool = True
|
||||
|
||||
|
||||
class InviteUpdateRequest(BaseModel):
|
||||
@@ -2504,10 +2507,12 @@ class InviteUpdateRequest(BaseModel):
|
||||
note: Optional[str] = None
|
||||
enabled: Optional[bool] = None
|
||||
reset_used: bool = False
|
||||
allow_server_choice: Optional[bool] = None
|
||||
|
||||
|
||||
class InviteRedeemRequest(BaseModel):
|
||||
name: str = 'Invite VPN'
|
||||
server_id: Optional[int] = None
|
||||
|
||||
|
||||
class TunnelStartRequest(BaseModel):
|
||||
@@ -5705,6 +5710,7 @@ def _guest_settings(data: Optional[dict] = None) -> dict:
|
||||
'create_server_id': 0,
|
||||
'create_inbound_id': 0,
|
||||
'create_xui_panel_id': '',
|
||||
'create_allow_server_choice': True,
|
||||
}
|
||||
defaults.update(guest)
|
||||
return defaults
|
||||
@@ -5780,22 +5786,26 @@ async def api_guest_connections(token: str, request: Request):
|
||||
data, guest, holder, err = _resolve_guest(token, request)
|
||||
if err:
|
||||
return err
|
||||
allow_choice = bool(guest.get('create_allow_server_choice', True))
|
||||
protocol = guest.get('create_protocol') or 'xui'
|
||||
servers = _pickable_servers_for_protocol(data, protocol) if (
|
||||
guest.get('allow_create') and allow_choice and protocol_base(protocol) != 'xui'
|
||||
) else []
|
||||
meta = {
|
||||
'allow_create': bool(guest.get('allow_create')),
|
||||
'create_protocol': protocol,
|
||||
'allow_server_choice': bool(servers),
|
||||
'default_server_id': int(guest.get('create_server_id') or 0),
|
||||
'servers': servers,
|
||||
}
|
||||
if not holder:
|
||||
return {
|
||||
'connections': [],
|
||||
'allow_create': bool(guest.get('allow_create')),
|
||||
'create_protocol': guest.get('create_protocol') or 'xui',
|
||||
}
|
||||
return {'connections': [], **meta}
|
||||
conns = [
|
||||
_enrich_guest_conn(c, data)
|
||||
for c in data.get('user_connections', [])
|
||||
if c['user_id'] == holder['id']
|
||||
]
|
||||
return {
|
||||
'connections': conns,
|
||||
'allow_create': bool(guest.get('allow_create')),
|
||||
'create_protocol': guest.get('create_protocol') or 'xui',
|
||||
}
|
||||
return {'connections': conns, **meta}
|
||||
|
||||
|
||||
@app.post('/api/guest/{token}/config/{connection_id}', tags=["Guest"])
|
||||
@@ -5817,33 +5827,7 @@ async def api_guest_config(token: str, connection_id: str, request: Request):
|
||||
return JSONResponse({'error': 'Subscription expired'}, status_code=403)
|
||||
if maybe_start_user_expiration(data, holder['id']):
|
||||
save_data(data)
|
||||
|
||||
if protocol_base(conn.get('protocol', '')) == 'xui':
|
||||
from managers.xui_api import xui_get_config
|
||||
config = await xui_get_config(
|
||||
data.get('settings', {}),
|
||||
conn['client_id'],
|
||||
panel_id=conn.get('xui_panel_id') or None,
|
||||
)
|
||||
vpn_link = config if str(config).startswith('http') else (generate_vpn_link(config) if config else '')
|
||||
return {
|
||||
'config': config,
|
||||
'vpn_link': vpn_link,
|
||||
'subscription_url': config if str(config).startswith('http') else '',
|
||||
'expires_at': holder.get('expiration_date'),
|
||||
}
|
||||
|
||||
sid = conn['server_id']
|
||||
server = data['servers'][sid]
|
||||
proto_info = server.get('protocols', {}).get(conn['protocol'], {})
|
||||
port = proto_info.get('port', '55424')
|
||||
ssh = get_ssh(server)
|
||||
ssh.connect()
|
||||
manager = get_protocol_manager(ssh, conn['protocol'])
|
||||
config = _manager_call(manager, 'get_client_config', conn['protocol'], conn['client_id'], get_server_connect_host(server, conn['protocol']), port)
|
||||
ssh.disconnect()
|
||||
vpn_link = generate_vpn_link(config) if config else ''
|
||||
return {'config': config, 'vpn_link': vpn_link, 'expires_at': holder.get('expiration_date')}
|
||||
return await _fetch_connection_config_payload(data, conn, expires_at=holder.get('expiration_date'))
|
||||
except Exception as e:
|
||||
logger.exception("Error getting guest config")
|
||||
return JSONResponse({'error': str(e)}, status_code=500)
|
||||
@@ -5864,18 +5848,32 @@ async def api_guest_create(token: str, req: GuestCreateRequest, request: Request
|
||||
name = (req.name or 'Guest VPN').strip() or 'Guest VPN'
|
||||
# Unique-ish name to avoid collisions
|
||||
name = f"{name}_{secrets.token_hex(3)}"
|
||||
allow_choice = bool(guest.get('create_allow_server_choice', True))
|
||||
|
||||
try:
|
||||
from managers.user_expiration import maybe_start_user_expiration, user_is_expired
|
||||
if user_is_expired(holder):
|
||||
return JSONResponse({'error': 'Subscription expired'}, status_code=403)
|
||||
|
||||
if protocol_base(protocol) == 'xui':
|
||||
sid = 0
|
||||
else:
|
||||
try:
|
||||
sid = _resolve_chosen_server_id(
|
||||
data,
|
||||
protocol=protocol,
|
||||
default_server_id=int(guest.get('create_server_id') or 0),
|
||||
requested_server_id=req.server_id,
|
||||
allow_choice=allow_choice,
|
||||
)
|
||||
except ValueError as ve:
|
||||
return JSONResponse({'error': str(ve)}, status_code=400)
|
||||
|
||||
if protocol_base(protocol) == 'aivpn':
|
||||
from managers.aivpn_manager import resolve_provision_protocol
|
||||
sid = int(guest.get('create_server_id') or 0)
|
||||
if sid >= len(data['servers']):
|
||||
return JSONResponse({'error': 'Guest server not found'}, status_code=400)
|
||||
protocol = resolve_provision_protocol(data['servers'][sid], 'aivpn')
|
||||
elif protocol_base(protocol) != 'xui':
|
||||
protocol = _match_protocol_on_server(data['servers'][sid], protocol)
|
||||
|
||||
if protocol_base(protocol) == 'xui':
|
||||
from managers.xui_api import xui_create_vless_config
|
||||
@@ -5900,9 +5898,6 @@ async def api_guest_create(token: str, req: GuestCreateRequest, request: Request
|
||||
sid = 0
|
||||
protocol = 'xui'
|
||||
else:
|
||||
sid = int(guest.get('create_server_id') or 0)
|
||||
if sid >= len(data['servers']):
|
||||
return JSONResponse({'error': 'Guest server not found'}, status_code=400)
|
||||
server = data['servers'][sid]
|
||||
proto_info = server.get('protocols', {}).get(protocol, {})
|
||||
port = proto_info.get('port', '55424')
|
||||
@@ -5970,12 +5965,90 @@ async def api_guest_regenerate_token(request: Request):
|
||||
|
||||
# ======================== Invite links (limited config creation) ========================
|
||||
|
||||
def _invite_public_view(link: dict) -> dict:
|
||||
def _server_supports_protocol(server: dict, protocol: str) -> bool:
|
||||
"""True if server has an installed client VPN matching protocol (or any for aivpn)."""
|
||||
base = protocol_base(protocol)
|
||||
if base == 'xui':
|
||||
return False
|
||||
protocols = server.get('protocols') or {}
|
||||
for key, info in protocols.items():
|
||||
if not isinstance(info, dict) or not info.get('installed'):
|
||||
continue
|
||||
kb = protocol_base(key)
|
||||
if kb not in CLIENT_VPN_BASES or kb == 'xui':
|
||||
continue
|
||||
if base == 'aivpn' or kb == base or key == protocol:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _match_protocol_on_server(server: dict, protocol: str) -> str:
|
||||
"""Map requested protocol to an installed key on this server (prefer exact)."""
|
||||
protocols = server.get('protocols') or {}
|
||||
if protocol in protocols and isinstance(protocols.get(protocol), dict) and protocols[protocol].get('installed'):
|
||||
return protocol
|
||||
base = protocol_base(protocol)
|
||||
if base == 'aivpn':
|
||||
return protocol
|
||||
candidates = [
|
||||
key for key, info in protocols.items()
|
||||
if isinstance(info, dict) and info.get('installed') and protocol_base(key) == base
|
||||
]
|
||||
if not candidates:
|
||||
return protocol
|
||||
candidates.sort()
|
||||
return candidates[0]
|
||||
|
||||
|
||||
def _pickable_servers_for_protocol(data: dict, protocol: str) -> list:
|
||||
"""Safe server list for end-user pickers (name/host/id only)."""
|
||||
out = []
|
||||
for idx, server in enumerate(data.get('servers') or []):
|
||||
if not isinstance(server, dict):
|
||||
continue
|
||||
if not _server_supports_protocol(server, protocol):
|
||||
continue
|
||||
out.append({
|
||||
'id': idx,
|
||||
'name': server.get('name') or server.get('host') or f'Server {idx + 1}',
|
||||
'host': server.get('host') or '',
|
||||
})
|
||||
return out
|
||||
|
||||
|
||||
def _resolve_chosen_server_id(
|
||||
data: dict,
|
||||
*,
|
||||
protocol: str,
|
||||
default_server_id: int,
|
||||
requested_server_id: Optional[int],
|
||||
allow_choice: bool,
|
||||
) -> int:
|
||||
"""Pick server_id for guest/invite create; validate against installed protocols."""
|
||||
servers = data.get('servers') or []
|
||||
default_sid = int(default_server_id or 0)
|
||||
if not allow_choice or requested_server_id is None:
|
||||
sid = default_sid
|
||||
else:
|
||||
sid = int(requested_server_id)
|
||||
if sid < 0 or sid >= len(servers):
|
||||
raise ValueError('Server not found')
|
||||
if protocol_base(protocol) != 'xui' and not _server_supports_protocol(servers[sid], protocol):
|
||||
raise ValueError('Selected server does not have the required protocol')
|
||||
return sid
|
||||
|
||||
|
||||
def _invite_public_view(link: dict, data: Optional[dict] = None) -> dict:
|
||||
max_uses = int(link.get('max_uses') or 0)
|
||||
used = int(link.get('used_count') or 0)
|
||||
remaining = None if max_uses <= 0 else max(0, max_uses - used)
|
||||
exhausted = remaining is not None and remaining <= 0
|
||||
duration_days = int(link.get('duration_days') or 0)
|
||||
protocol = link.get('protocol') or 'awg'
|
||||
allow_server_choice = bool(link.get('allow_server_choice', True)) and protocol_base(protocol) != 'xui'
|
||||
servers = []
|
||||
if data is not None and allow_server_choice:
|
||||
servers = _pickable_servers_for_protocol(data, protocol)
|
||||
return {
|
||||
'id': link.get('id'),
|
||||
'name': link.get('name') or 'Invite',
|
||||
@@ -5988,8 +6061,10 @@ def _invite_public_view(link: dict) -> dict:
|
||||
'expired': False,
|
||||
'exhausted': exhausted,
|
||||
'has_password': bool(link.get('password_hash')),
|
||||
'protocol': link.get('protocol') or 'awg',
|
||||
'protocol': protocol,
|
||||
'server_id': int(link.get('server_id') or 0),
|
||||
'allow_server_choice': allow_server_choice,
|
||||
'servers': servers,
|
||||
'duration_days': duration_days,
|
||||
'user_id': link.get('user_id') or '',
|
||||
'note': link.get('note') or '',
|
||||
@@ -6008,6 +6083,58 @@ def _invite_auth_ok(link: dict, request: Request) -> bool:
|
||||
return bool(request.session.get(f"invite_auth_{link.get('token')}"))
|
||||
|
||||
|
||||
def _enrich_invite_conn(c: dict, data: dict) -> dict:
|
||||
out = dict(c)
|
||||
if protocol_base(out.get('protocol', '')) == 'xui':
|
||||
out['server_name'] = '3x-ui'
|
||||
else:
|
||||
sid = int(out.get('server_id') or 0)
|
||||
if sid < len(data.get('servers') or []):
|
||||
srv = data['servers'][sid]
|
||||
out['server_name'] = srv.get('name') or srv.get('host') or ''
|
||||
else:
|
||||
out['server_name'] = 'Unknown'
|
||||
return out
|
||||
|
||||
|
||||
async def _fetch_connection_config_payload(data: dict, conn: dict, expires_at: Optional[str] = None) -> dict:
|
||||
"""Shared config fetch for guest/invite/share self-service surfaces."""
|
||||
if protocol_base(conn.get('protocol', '')) == 'xui':
|
||||
from managers.xui_api import xui_get_config
|
||||
config = await xui_get_config(
|
||||
data.get('settings', {}),
|
||||
conn['client_id'],
|
||||
panel_id=conn.get('xui_panel_id') or None,
|
||||
)
|
||||
vpn_link = config if str(config).startswith('http') else (generate_vpn_link(config) if config else '')
|
||||
return {
|
||||
'config': config,
|
||||
'vpn_link': vpn_link,
|
||||
'subscription_url': config if str(config).startswith('http') else '',
|
||||
'expires_at': expires_at,
|
||||
}
|
||||
|
||||
sid = int(conn.get('server_id') or 0)
|
||||
if sid >= len(data.get('servers') or []):
|
||||
raise RuntimeError('Server not found')
|
||||
server = data['servers'][sid]
|
||||
protocol = conn['protocol']
|
||||
proto_info = server.get('protocols', {}).get(protocol, {})
|
||||
port = proto_info.get('port', '55424')
|
||||
ssh = get_ssh(server)
|
||||
await asyncio.to_thread(ssh.connect)
|
||||
try:
|
||||
manager = get_protocol_manager(ssh, protocol)
|
||||
config = await asyncio.to_thread(
|
||||
_manager_call, manager, 'get_client_config',
|
||||
protocol, conn['client_id'], get_server_connect_host(server, protocol), port,
|
||||
)
|
||||
finally:
|
||||
await asyncio.to_thread(ssh.disconnect)
|
||||
vpn_link = generate_vpn_link(config) if config else ''
|
||||
return {'config': config, 'vpn_link': vpn_link, 'expires_at': expires_at}
|
||||
|
||||
|
||||
def _expiry_ms_from_duration_days(duration_days: int) -> int:
|
||||
"""3x-ui expiryTime is unix ms; 0 means no expiry. Starts now (on redeem)."""
|
||||
days = int(duration_days or 0)
|
||||
@@ -6176,11 +6303,12 @@ async def api_create_invite(request: Request, req: InviteCreateRequest):
|
||||
'expires_at': None,
|
||||
'duration_days': int(req.duration_days or 0),
|
||||
'note': req.note or '',
|
||||
'allow_server_choice': bool(req.allow_server_choice),
|
||||
'created_at': datetime.now().isoformat(),
|
||||
}
|
||||
data.setdefault('invite_links', []).append(link)
|
||||
save_data(data)
|
||||
view = _invite_public_view(link)
|
||||
view = _invite_public_view(link, data)
|
||||
return {'status': 'success', 'invite': view, 'url': f"/invite/{link['token']}"}
|
||||
|
||||
|
||||
@@ -6222,6 +6350,8 @@ async def api_update_invite(request: Request, invite_id: str, req: InviteUpdateR
|
||||
link['note'] = req.note
|
||||
if req.enabled is not None:
|
||||
link['enabled'] = bool(req.enabled)
|
||||
if req.allow_server_choice is not None:
|
||||
link['allow_server_choice'] = bool(req.allow_server_choice)
|
||||
if req.reset_used:
|
||||
link['used_count'] = 0
|
||||
if protocol_base(link.get('protocol') or 'xui') == 'xui':
|
||||
@@ -6237,7 +6367,7 @@ async def api_update_invite(request: Request, invite_id: str, req: InviteUpdateR
|
||||
if not int(link.get('xui_inbound_id') or 0):
|
||||
return JSONResponse({'error': 'Select a VLESS inbound from 3x-ui'}, status_code=400)
|
||||
save_data(data)
|
||||
return {'status': 'success', 'invite': _invite_public_view(link)}
|
||||
return {'status': 'success', 'invite': _invite_public_view(link, data)}
|
||||
|
||||
|
||||
@app.delete('/api/invites/{invite_id}', tags=["Invites"])
|
||||
@@ -6263,7 +6393,7 @@ async def invite_public_page(token: str, request: Request):
|
||||
f"<h1>{_t('invite_not_found', lang)}</h1><p>{_t('invite_not_found_desc', lang)}</p>",
|
||||
status_code=404,
|
||||
)
|
||||
view = _invite_public_view(link)
|
||||
view = _invite_public_view(link, data)
|
||||
need_password = bool(link.get('password_hash')) and not _invite_auth_ok(link, request)
|
||||
return tpl(
|
||||
request,
|
||||
@@ -6298,7 +6428,7 @@ async def api_invite_info(token: str, request: Request):
|
||||
return JSONResponse({'error': 'Not found'}, status_code=404)
|
||||
if not _invite_auth_ok(link, request):
|
||||
return JSONResponse({'error': 'Unauthorized'}, status_code=401)
|
||||
view = _invite_public_view(link)
|
||||
view = _invite_public_view(link, data)
|
||||
# Don't leak admin note / ids beyond what's needed
|
||||
return {
|
||||
'name': view['name'],
|
||||
@@ -6311,9 +6441,64 @@ async def api_invite_info(token: str, request: Request):
|
||||
'max_uses': view['max_uses'],
|
||||
'used_count': view['used_count'],
|
||||
'protocol': view['protocol'],
|
||||
'allow_server_choice': view['allow_server_choice'],
|
||||
'server_id': view['server_id'],
|
||||
'servers': view.get('servers') or [],
|
||||
'duration_days': view['duration_days'],
|
||||
}
|
||||
|
||||
|
||||
@app.get('/api/invite/{token}/connections', tags=["Invites"])
|
||||
async def api_invite_connections(token: str, request: Request):
|
||||
"""List configs created via this invite (re-copy without consuming another use)."""
|
||||
data = load_data()
|
||||
link = _find_invite(data, token)
|
||||
if not link:
|
||||
return JSONResponse({'error': 'Not found'}, status_code=404)
|
||||
if not _invite_auth_ok(link, request):
|
||||
return JSONResponse({'error': 'Unauthorized'}, status_code=401)
|
||||
invite_id = link.get('id')
|
||||
holder_id = link.get('user_id') or ''
|
||||
conns = [
|
||||
_enrich_invite_conn(c, data)
|
||||
for c in data.get('user_connections', [])
|
||||
if c.get('invite_id') == invite_id and (not holder_id or c.get('user_id') == holder_id)
|
||||
]
|
||||
conns.sort(key=lambda c: c.get('created_at') or '', reverse=True)
|
||||
return {
|
||||
'connections': conns,
|
||||
'invite': _invite_public_view(link, data),
|
||||
}
|
||||
|
||||
|
||||
@app.post('/api/invite/{token}/config/{connection_id}', tags=["Invites"])
|
||||
async def api_invite_config(token: str, connection_id: str, request: Request):
|
||||
data = load_data()
|
||||
link = _find_invite(data, token)
|
||||
if not link:
|
||||
return JSONResponse({'error': 'Not found'}, status_code=404)
|
||||
if not _invite_auth_ok(link, request):
|
||||
return JSONResponse({'error': 'Unauthorized'}, status_code=401)
|
||||
invite_id = link.get('id')
|
||||
holder_id = link.get('user_id') or ''
|
||||
conn = next(
|
||||
(
|
||||
c for c in data.get('user_connections', [])
|
||||
if c.get('id') == connection_id
|
||||
and c.get('invite_id') == invite_id
|
||||
and (not holder_id or c.get('user_id') == holder_id)
|
||||
),
|
||||
None,
|
||||
)
|
||||
if not conn:
|
||||
return JSONResponse({'error': 'Not found'}, status_code=404)
|
||||
try:
|
||||
return await _fetch_connection_config_payload(data, conn, expires_at=conn.get('expires_at'))
|
||||
except Exception as e:
|
||||
logger.exception('Error getting invite config')
|
||||
return JSONResponse({'error': str(e)}, status_code=500)
|
||||
|
||||
|
||||
@app.post('/api/invite/{token}/create', tags=["Invites"])
|
||||
async def api_invite_create_config(token: str, req: InviteRedeemRequest, request: Request):
|
||||
data = load_data()
|
||||
@@ -6323,7 +6508,7 @@ async def api_invite_create_config(token: str, req: InviteRedeemRequest, request
|
||||
if not _invite_auth_ok(link, request):
|
||||
return JSONResponse({'error': 'Unauthorized'}, status_code=401)
|
||||
|
||||
view = _invite_public_view(link)
|
||||
view = _invite_public_view(link, data)
|
||||
if not view['available']:
|
||||
if view['expired']:
|
||||
return JSONResponse({'error': 'Invite link expired'}, status_code=403)
|
||||
@@ -6335,13 +6520,29 @@ async def api_invite_create_config(token: str, req: InviteRedeemRequest, request
|
||||
if not holder_id or not any(u['id'] == holder_id for u in data['users']):
|
||||
return JSONResponse({'error': 'Invite holder user is not configured'}, status_code=400)
|
||||
|
||||
protocol = link.get('protocol') or 'xui'
|
||||
allow_choice = bool(link.get('allow_server_choice', True))
|
||||
try:
|
||||
if protocol_base(protocol) == 'xui':
|
||||
sid = int(link.get('server_id') or 0)
|
||||
else:
|
||||
sid = _resolve_chosen_server_id(
|
||||
data,
|
||||
protocol=protocol,
|
||||
default_server_id=int(link.get('server_id') or 0),
|
||||
requested_server_id=req.server_id,
|
||||
allow_choice=allow_choice,
|
||||
)
|
||||
except ValueError as ve:
|
||||
return JSONResponse({'error': str(ve)}, status_code=400)
|
||||
|
||||
# Reserve a use slot under lock
|
||||
async with DATA_LOCK:
|
||||
data = load_data()
|
||||
link = _find_invite(data, token)
|
||||
if not link:
|
||||
return JSONResponse({'error': 'Not found'}, status_code=404)
|
||||
view = _invite_public_view(link)
|
||||
view = _invite_public_view(link, data)
|
||||
if not view['available']:
|
||||
return JSONResponse({'error': 'Invite link is no longer available'}, status_code=403)
|
||||
link['used_count'] = int(link.get('used_count') or 0) + 1
|
||||
@@ -6352,10 +6553,11 @@ async def api_invite_create_config(token: str, req: InviteRedeemRequest, request
|
||||
try:
|
||||
data = load_data()
|
||||
protocol = link.get('protocol') or 'xui'
|
||||
sid = int(link.get('server_id') or 0)
|
||||
if protocol_base(protocol) == 'aivpn' and sid < len(data.get('servers') or []):
|
||||
from managers.aivpn_manager import resolve_provision_protocol
|
||||
protocol = resolve_provision_protocol(data['servers'][sid], 'aivpn')
|
||||
elif protocol_base(protocol) != 'xui' and sid < len(data.get('servers') or []):
|
||||
protocol = _match_protocol_on_server(data['servers'][sid], protocol)
|
||||
created = await _create_config_for_protocol(
|
||||
data,
|
||||
protocol=protocol,
|
||||
@@ -6372,16 +6574,18 @@ async def api_invite_create_config(token: str, req: InviteRedeemRequest, request
|
||||
'protocol': created['protocol'],
|
||||
'client_id': created['client_id'],
|
||||
'name': name,
|
||||
'invite_id': link.get('id'),
|
||||
'xui_panel_id': created.get('xui_panel_id') or link.get('xui_panel_id') or '',
|
||||
'created_at': datetime.now().isoformat(),
|
||||
}
|
||||
if created.get('expires_at'):
|
||||
conn['expires_at'] = created['expires_at']
|
||||
async with DATA_LOCK:
|
||||
data = load_data()
|
||||
data.setdefault('user_connections', []).append(conn)
|
||||
save_data(data)
|
||||
config = created.get('config') or ''
|
||||
subscription_url = created.get('subscription_url') or ''
|
||||
# For subscription URLs, vpn_link is the same shareable string
|
||||
vpn_link = subscription_url or (generate_vpn_link(config) if config else '')
|
||||
data = load_data()
|
||||
link = _find_invite(data, token) or link
|
||||
@@ -6391,8 +6595,8 @@ async def api_invite_create_config(token: str, req: InviteRedeemRequest, request
|
||||
'subscription_url': subscription_url,
|
||||
'vpn_link': vpn_link,
|
||||
'expires_at': created.get('expires_at'),
|
||||
'connection': conn,
|
||||
'invite': _invite_public_view(link),
|
||||
'connection': _enrich_invite_conn(conn, data),
|
||||
'invite': _invite_public_view(link, data),
|
||||
}
|
||||
except Exception as e:
|
||||
# Roll back reserved use
|
||||
|
||||
+28
-1
@@ -29,6 +29,10 @@
|
||||
<div id="connectionsList">
|
||||
{% if allow_create %}
|
||||
<div class="share-create">
|
||||
<div id="guestServerPickWrap" class="form-group" style="text-align:left; margin-bottom:var(--space-sm); display:none;">
|
||||
<label class="form-label">{{ _('choose_server') }}</label>
|
||||
<select class="form-select" id="guestServerPick"></select>
|
||||
</div>
|
||||
<button class="btn btn-secondary share-btn-lg" type="button" onclick="createGuestConfig()" id="createBtn">
|
||||
<span id="createBtnText">{{ _('guest_get_config') }}</span>
|
||||
<div class="spinner hidden" id="createSpinner"></div>
|
||||
@@ -178,6 +182,23 @@
|
||||
const data = await res.json();
|
||||
document.getElementById('loadingState').classList.add('hidden');
|
||||
|
||||
const wrap = document.getElementById('guestServerPickWrap');
|
||||
const sel = document.getElementById('guestServerPick');
|
||||
if (wrap && sel && data.allow_server_choice && (data.servers || []).length) {
|
||||
const prev = sel.value;
|
||||
sel.innerHTML = '';
|
||||
(data.servers || []).forEach(s => {
|
||||
const opt = document.createElement('option');
|
||||
opt.value = String(s.id);
|
||||
opt.textContent = s.host ? `${s.name} (${s.host})` : s.name;
|
||||
if (String(s.id) === String(prev) || String(s.id) === String(data.default_server_id)) opt.selected = true;
|
||||
sel.appendChild(opt);
|
||||
});
|
||||
wrap.style.display = '';
|
||||
} else if (wrap) {
|
||||
wrap.style.display = 'none';
|
||||
}
|
||||
|
||||
if (!data.connections || data.connections.length === 0) {
|
||||
document.getElementById('emptyState').classList.remove('hidden');
|
||||
document.getElementById('connectionsGrid').classList.add('hidden');
|
||||
@@ -221,10 +242,16 @@
|
||||
text.classList.add('hidden');
|
||||
spinner.classList.remove('hidden');
|
||||
try {
|
||||
const body = { name: 'Guest VPN' };
|
||||
const wrap = document.getElementById('guestServerPickWrap');
|
||||
const sel = document.getElementById('guestServerPick');
|
||||
if (wrap && wrap.style.display !== 'none' && sel && sel.value !== '') {
|
||||
body.server_id = parseInt(sel.value, 10);
|
||||
}
|
||||
const res = await fetch(`/api/guest/${TOKEN}/create`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: 'Guest VPN' })
|
||||
body: JSON.stringify(body)
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok || data.error) throw new Error(data.error || _('error'));
|
||||
|
||||
+283
-106
@@ -1,102 +1,104 @@
|
||||
{% extends "base.html" %}
|
||||
{% from "macros/icons.html" import icon %}
|
||||
|
||||
{% block title_extra %} — {{ _('invite_public_title') }}{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="card" style="max-width: 520px; margin: 2.5rem auto; overflow:hidden;">
|
||||
<div style="padding: var(--space-xl) var(--space-lg) var(--space-md); text-align:center; background: linear-gradient(180deg, rgba(59,130,246,0.12), transparent);">
|
||||
<div style="width:56px;height:56px;border-radius:16px;margin:0 auto var(--space-md);display:flex;align-items:center;justify-content:center;background:var(--bg-primary);font-size:1.6rem;">🔗</div>
|
||||
<h2 class="card-title" style="margin-bottom:6px;">{{ invite.name }}</h2>
|
||||
<p style="color: var(--text-muted); font-size: 0.92rem; margin:0;">{{ _('invite_public_subtitle') }}</p>
|
||||
</div>
|
||||
<div class="share-page">
|
||||
<header class="share-hero">
|
||||
<h1 class="share-title">{{ invite.name }}</h1>
|
||||
<p class="share-user">{{ _('invite_public_subtitle') }}</p>
|
||||
{% if not need_password %}
|
||||
<p class="share-hint">{{ _('share_copy_hint') }}</p>
|
||||
{% endif %}
|
||||
</header>
|
||||
|
||||
{% if need_password %}
|
||||
<div style="padding: var(--space-lg); text-align: center;">
|
||||
<p style="margin-bottom: var(--space-md);">{{ _('invite_protected_desc') }}</p>
|
||||
<form id="authForm" onsubmit="authInvite(event)"
|
||||
style="display: flex; flex-direction: column; gap: var(--space-md); max-width: 300px; margin: 0 auto;">
|
||||
<div class="form-group">
|
||||
<input type="password" id="invitePassword" class="form-input" placeholder="{{ _('password') }}" required autofocus>
|
||||
</div>
|
||||
<button type="submit" class="btn btn-primary" id="authBtn">
|
||||
<div class="share-auth card">
|
||||
<div class="share-auth-icon">{{ icon('lock') }}</div>
|
||||
<p>{{ _('invite_protected_desc') }}</p>
|
||||
<form id="authForm" onsubmit="authInvite(event)" class="share-auth-form">
|
||||
<input type="password" id="invitePassword" class="form-input" placeholder="{{ _('password') }}" required autofocus>
|
||||
<button type="submit" class="btn btn-primary share-btn-lg" id="authBtn">
|
||||
<span id="authBtnText">{{ _('login') }}</span>
|
||||
<div class="spinner hidden" id="authSpinner"></div>
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
{% else %}
|
||||
<div style="padding: var(--space-lg);">
|
||||
<div style="display:grid; grid-template-columns:1fr 1fr; gap:var(--space-sm); margin-bottom:var(--space-lg);">
|
||||
<div style="background:var(--bg-primary); border-radius:var(--radius-md); padding:var(--space-md); text-align:center;">
|
||||
<div style="font-size:0.72rem; color:var(--text-muted); text-transform:uppercase;">{{ _('invite_uses') }}</div>
|
||||
<div id="usesValue" style="font-weight:700; font-size:1.15rem; margin-top:4px;">
|
||||
{% if invite.unlimited %}∞{% else %}{{ invite.remaining }}{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
<div style="background:var(--bg-primary); border-radius:var(--radius-md); padding:var(--space-md); text-align:center;">
|
||||
<div style="font-size:0.72rem; color:var(--text-muted); text-transform:uppercase;">{{ _('invite_duration_short') }}</div>
|
||||
<div style="font-weight:700; font-size:1.15rem; margin-top:4px;">
|
||||
{% if invite.duration_days %}{{ invite.duration_days }} {{ _('days_short') }}{% else %}∞{% endif %}
|
||||
</div>
|
||||
<div style="display:grid; grid-template-columns:1fr 1fr; gap:var(--space-sm); margin-bottom:var(--space-md);">
|
||||
<div style="background:var(--bg-card); border-radius:var(--radius-md); padding:var(--space-md); text-align:center;">
|
||||
<div style="font-size:0.72rem; color:var(--text-muted); text-transform:uppercase;">{{ _('invite_uses') }}</div>
|
||||
<div id="usesValue" style="font-weight:700; font-size:1.15rem; margin-top:4px;">
|
||||
{% if invite.unlimited %}∞{% else %}{{ invite.remaining }}{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
<div style="background:var(--bg-card); border-radius:var(--radius-md); padding:var(--space-md); text-align:center;">
|
||||
<div style="font-size:0.72rem; color:var(--text-muted); text-transform:uppercase;">{{ _('invite_duration_short') }}</div>
|
||||
<div style="font-weight:700; font-size:1.15rem; margin-top:4px;">
|
||||
{% if invite.duration_days %}{{ invite.duration_days }} {{ _('days_short') }}{% else %}∞{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p id="statusHint" style="text-align:center; color:var(--text-muted); font-size:0.88rem; margin:0 0 var(--space-md);">
|
||||
{% if invite.duration_days %}
|
||||
{{ _('invite_duration_starts_hint').replace('{}', invite.duration_days|string) }}
|
||||
{% else %}
|
||||
{{ _('invite_get_config_hint') }}
|
||||
{% endif %}
|
||||
</p>
|
||||
<p id="statusHint" style="text-align:center; color:var(--text-muted); font-size:0.88rem; margin:0 0 var(--space-md);">
|
||||
{% if invite.duration_days %}
|
||||
{{ _('invite_duration_starts_hint').replace('{}', invite.duration_days|string) }}
|
||||
{% else %}
|
||||
{{ _('invite_get_config_hint') }}
|
||||
{% endif %}
|
||||
</p>
|
||||
|
||||
{% if invite.available %}
|
||||
<button class="btn btn-primary" style="width:100%;" onclick="createInviteConfig()" id="createBtn">
|
||||
<div id="createBlock" {% if not invite.available %}style="display:none;"{% endif %}>
|
||||
<div id="serverPickWrap" class="form-group" style="margin-bottom:var(--space-md); {% if not invite.allow_server_choice or not invite.servers %}display:none;{% endif %}">
|
||||
<label class="form-label">{{ _('choose_server') }}</label>
|
||||
<select class="form-select" id="inviteServerPick">
|
||||
{% for s in invite.servers or [] %}
|
||||
<option value="{{ s.id }}" {% if s.id == invite.server_id %}selected{% endif %}>{{ s.name }}{% if s.host %} ({{ s.host }}){% endif %}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</div>
|
||||
<button class="btn btn-primary share-btn-lg" style="width:100%;" onclick="createInviteConfig()" id="createBtn">
|
||||
<span id="createBtnText">{{ _('guest_get_config') }}</span>
|
||||
<div class="spinner hidden" id="createSpinner" style="width:14px;height:14px;"></div>
|
||||
</button>
|
||||
{% elif invite.exhausted %}
|
||||
<p style="text-align:center; color:#ef4444; margin:0;">{{ _('invite_exhausted') }}</p>
|
||||
{% else %}
|
||||
<p style="text-align:center; color:#ef4444; margin:0;">{{ _('disabled') }}</p>
|
||||
{% endif %}
|
||||
</div>
|
||||
<p id="exhaustedMsg" style="text-align:center; color:#ef4444; margin:0 0 var(--space-md); {% if invite.available or not invite.exhausted %}display:none;{% endif %}">{{ _('invite_exhausted') }}</p>
|
||||
<p id="disabledMsg" style="text-align:center; color:#ef4444; margin:0 0 var(--space-md); {% if invite.available or invite.exhausted %}display:none;{% endif %}">{{ _('disabled') }}</p>
|
||||
|
||||
<div class="share-loading" id="loadingState" style="margin-top:var(--space-lg);">
|
||||
<div class="spinner share-spinner"></div>
|
||||
<p>{{ _('loading_share_conns') }}</p>
|
||||
</div>
|
||||
<div id="connectionsGrid" class="share-grid hidden"></div>
|
||||
<div id="emptyState" class="share-empty hidden">
|
||||
<p>{{ _('invite_no_saved_configs') }}</p>
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
<div class="modal-backdrop" id="configModal">
|
||||
<div class="modal" style="max-width: 600px;">
|
||||
<div class="modal share-modal">
|
||||
<div class="modal-header">
|
||||
<h2 class="modal-title" id="configModalTitle">{{ _('config') }}</h2>
|
||||
<button class="modal-close" onclick="closeModal('configModal')">×</button>
|
||||
<button class="modal-close" onclick="closeModal('configModal')" type="button">×</button>
|
||||
</div>
|
||||
<div id="expiresBanner" class="hidden" style="margin:0 var(--space-md) var(--space-sm); padding:var(--space-sm) var(--space-md); border-radius:var(--radius-md); background:rgba(59,130,246,0.1); color:var(--text-muted); font-size:0.85rem;"></div>
|
||||
<div class="config-tabs">
|
||||
<button class="config-tab active" onclick="switchConfigTab('conf')">{{ _('invite_sub_tab') }}</button>
|
||||
<button class="config-tab" onclick="switchConfigTab('vpn')">{{ _('vpn_key_tab') }}</button>
|
||||
<button class="config-tab" onclick="switchConfigTab('qr')">{{ _('qr_code_tab') }}</button>
|
||||
</div>
|
||||
<div class="config-panel active" id="panel-conf">
|
||||
<div class="config-display">
|
||||
<textarea class="config-text" id="configText" readonly rows="8"
|
||||
style="width:100%; border:none; background:transparent; color:inherit; font-family:monospace; resize:none; outline:none;"></textarea>
|
||||
<div class="config-actions">
|
||||
<button class="btn btn-secondary btn-sm" onclick="copyConfig()" style="flex:1">{{ _('copy_config') }}</button>
|
||||
<a id="downloadBtn" class="btn btn-primary btn-sm"
|
||||
style="flex:1; text-decoration:none; display:flex; align-items:center; justify-content:center;">
|
||||
{{ _('download_conf') }}
|
||||
</a>
|
||||
</div>
|
||||
<div class="share-modal-body">
|
||||
<button type="button" class="btn btn-primary share-btn-lg" id="modalCopyBtn" onclick="copyCurrentKey()">
|
||||
{{ icon('copy') }}
|
||||
<span>{{ _('copy_key_big') }}</span>
|
||||
</button>
|
||||
<div class="share-qr-wrap">
|
||||
<div id="qrcode"></div>
|
||||
<p class="share-qr-caption">{{ _('qr_code_tab') }}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="config-panel" id="panel-vpn">
|
||||
<div class="vpn-link-box" id="vpnLinkText" style="min-height: 100px;"></div>
|
||||
<div class="config-actions" style="margin-top:var(--space-sm);">
|
||||
<button class="btn btn-secondary btn-sm" onclick="copyVpnLink()" style="flex:1">{{ _('copy_key') }}</button>
|
||||
<div class="share-extra">
|
||||
<button type="button" class="btn btn-secondary w-full" id="downloadBtn">{{ _('download_config_file') }}</button>
|
||||
<button type="button" class="share-link-btn" onclick="toggleConfigText()">{{ _('show_config_text') }}</button>
|
||||
<textarea class="config-text share-config-text hidden" id="configText" readonly rows="8"></textarea>
|
||||
</div>
|
||||
</div>
|
||||
<div class="config-panel" id="panel-qr">
|
||||
<div class="qr-container"><div id="qrcode"></div></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -105,6 +107,41 @@
|
||||
let currentConfig = '';
|
||||
let currentVpnLink = '';
|
||||
|
||||
function escAttr(s) {
|
||||
return String(s || '').replace(/\\/g, '\\\\').replace(/'/g, "\\'");
|
||||
}
|
||||
function escHtml(s) {
|
||||
return String(s || '')
|
||||
.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
||||
}
|
||||
function protoLabel(p) {
|
||||
const base = String(p || '').split('__')[0];
|
||||
const map = {
|
||||
awg: 'AmneziaWG', awg2: 'AmneziaWG 2.0', awg_legacy: 'AWG Legacy',
|
||||
xray: 'Xray', xui: '3x-ui VLESS', hysteria: 'Hysteria 2',
|
||||
naiveproxy: 'NaiveProxy', mieru: 'Mieru', telemt: 'Telemt', wireguard: 'WireGuard',
|
||||
};
|
||||
return map[base] || (base || '').toUpperCase();
|
||||
}
|
||||
function pickKey(config, vpnLink) {
|
||||
const link = (vpnLink || '').trim();
|
||||
return link || (config || '').trim();
|
||||
}
|
||||
async function copyKeyText(text) {
|
||||
if (!text) throw new Error(_('error'));
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
} catch {
|
||||
const ta = document.createElement('textarea');
|
||||
ta.value = text;
|
||||
document.body.appendChild(ta);
|
||||
ta.select();
|
||||
document.execCommand('copy');
|
||||
ta.remove();
|
||||
}
|
||||
showToast(_('key_copied'), 'success');
|
||||
}
|
||||
|
||||
async function authInvite(e) {
|
||||
e.preventDefault();
|
||||
const password = document.getElementById('invitePassword').value;
|
||||
@@ -132,22 +169,12 @@
|
||||
}
|
||||
}
|
||||
|
||||
function switchConfigTab(tab) {
|
||||
document.querySelectorAll('.config-tab').forEach(t => t.classList.remove('active'));
|
||||
document.querySelectorAll('.config-panel').forEach(p => p.classList.remove('active'));
|
||||
const tabs = document.querySelectorAll('.config-tab');
|
||||
const panels = { conf: 'panel-conf', vpn: 'panel-vpn', qr: 'panel-qr' };
|
||||
const tabIdx = { conf: 0, vpn: 1, qr: 2 };
|
||||
tabs[tabIdx[tab]].classList.add('active');
|
||||
document.getElementById(panels[tab]).classList.add('active');
|
||||
}
|
||||
|
||||
function openConfigModal(name, config, vpnLink, expiresAt) {
|
||||
currentConfig = config;
|
||||
currentVpnLink = vpnLink || config || '';
|
||||
document.getElementById('configText').value = config;
|
||||
document.getElementById('vpnLinkText').textContent = currentVpnLink;
|
||||
function fillModal(name, config, vpnLink, expiresAt) {
|
||||
currentConfig = config || '';
|
||||
currentVpnLink = vpnLink || '';
|
||||
document.getElementById('configModalTitle').textContent = name;
|
||||
document.getElementById('configText').value = currentConfig;
|
||||
document.getElementById('configText').classList.add('hidden');
|
||||
const banner = document.getElementById('expiresBanner');
|
||||
if (expiresAt) {
|
||||
banner.textContent = _('invite_config_expires_at').replace('{}', new Date(expiresAt).toLocaleString());
|
||||
@@ -155,29 +182,142 @@
|
||||
} else {
|
||||
banner.classList.add('hidden');
|
||||
}
|
||||
document.getElementById('downloadBtn').onclick = () => downloadFile(config, `${name}.txt`);
|
||||
document.getElementById('downloadBtn').onclick = () => downloadFile(currentConfig, `${name || 'vpn'}.conf`);
|
||||
const qrContainer = document.getElementById('qrcode');
|
||||
qrContainer.innerHTML = '';
|
||||
new QRCode(qrContainer, {
|
||||
text: currentVpnLink || config, width: 256, height: 256,
|
||||
colorDark: '#000000', colorLight: '#ffffff',
|
||||
correctLevel: QRCode.CorrectLevel.L
|
||||
});
|
||||
switchConfigTab('conf');
|
||||
openModal('configModal');
|
||||
const qrPayload = pickKey(currentConfig, currentVpnLink) || currentConfig;
|
||||
if (qrPayload && typeof QRCode !== 'undefined') {
|
||||
new QRCode(qrContainer, {
|
||||
text: qrPayload, width: 220, height: 220,
|
||||
colorDark: '#000000', colorLight: '#ffffff',
|
||||
correctLevel: QRCode.CorrectLevel.L
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function copyConfig() { copyToClipboard(currentConfig); }
|
||||
function copyVpnLink() { copyToClipboard(currentVpnLink); }
|
||||
async function copyCurrentKey() {
|
||||
try { await copyKeyText(pickKey(currentConfig, currentVpnLink)); }
|
||||
catch (err) { alert(`${_('error')}: ` + err.message); }
|
||||
}
|
||||
function toggleConfigText() {
|
||||
document.getElementById('configText').classList.toggle('hidden');
|
||||
}
|
||||
|
||||
function updateStatus(invite) {
|
||||
if (!invite) return;
|
||||
const uses = document.getElementById('usesValue');
|
||||
if (uses && invite) {
|
||||
uses.textContent = invite.unlimited ? '∞' : String(invite.remaining ?? 0);
|
||||
if (uses) uses.textContent = invite.unlimited ? '∞' : String(invite.remaining ?? 0);
|
||||
const createBlock = document.getElementById('createBlock');
|
||||
const exhaustedMsg = document.getElementById('exhaustedMsg');
|
||||
const disabledMsg = document.getElementById('disabledMsg');
|
||||
if (invite.available) {
|
||||
if (createBlock) createBlock.style.display = '';
|
||||
if (exhaustedMsg) exhaustedMsg.style.display = 'none';
|
||||
if (disabledMsg) disabledMsg.style.display = 'none';
|
||||
} else {
|
||||
if (createBlock) createBlock.style.display = 'none';
|
||||
if (invite.exhausted) {
|
||||
if (exhaustedMsg) exhaustedMsg.style.display = '';
|
||||
if (disabledMsg) disabledMsg.style.display = 'none';
|
||||
} else {
|
||||
if (exhaustedMsg) exhaustedMsg.style.display = 'none';
|
||||
if (disabledMsg) disabledMsg.style.display = '';
|
||||
}
|
||||
}
|
||||
if (invite && !invite.available) {
|
||||
const btn = document.getElementById('createBtn');
|
||||
if (btn) btn.style.display = 'none';
|
||||
const wrap = document.getElementById('serverPickWrap');
|
||||
const sel = document.getElementById('inviteServerPick');
|
||||
if (wrap && sel && invite.allow_server_choice && (invite.servers || []).length) {
|
||||
const prev = sel.value;
|
||||
sel.innerHTML = '';
|
||||
(invite.servers || []).forEach(s => {
|
||||
const opt = document.createElement('option');
|
||||
opt.value = String(s.id);
|
||||
opt.textContent = s.host ? `${s.name} (${s.host})` : s.name;
|
||||
if (String(s.id) === String(prev) || String(s.id) === String(invite.server_id)) opt.selected = true;
|
||||
sel.appendChild(opt);
|
||||
});
|
||||
wrap.style.display = '';
|
||||
} else if (wrap) {
|
||||
wrap.style.display = 'none';
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchInviteConfig(connId) {
|
||||
const res = await fetch(`/api/invite/${TOKEN}/config/${connId}`, { method: 'POST' });
|
||||
const data = await res.json();
|
||||
if (!res.ok || data.error) throw new Error(data.error || _('error'));
|
||||
return data;
|
||||
}
|
||||
|
||||
async function loadConnections() {
|
||||
const loading = document.getElementById('loadingState');
|
||||
if (!loading) return;
|
||||
try {
|
||||
const res = await fetch(`/api/invite/${TOKEN}/connections`);
|
||||
if (res.status === 401) return;
|
||||
const data = await res.json();
|
||||
loading.classList.add('hidden');
|
||||
if (data.invite) updateStatus(data.invite);
|
||||
|
||||
const grid = document.getElementById('connectionsGrid');
|
||||
const empty = document.getElementById('emptyState');
|
||||
if (!data.connections || !data.connections.length) {
|
||||
empty.classList.remove('hidden');
|
||||
grid.classList.add('hidden');
|
||||
grid.innerHTML = '';
|
||||
return;
|
||||
}
|
||||
empty.classList.add('hidden');
|
||||
grid.classList.remove('hidden');
|
||||
grid.innerHTML = data.connections.map(c => `
|
||||
<article class="share-card" data-conn-id="${escHtml(c.id)}">
|
||||
<div class="share-card-top">
|
||||
<div>
|
||||
<div class="share-card-name">${escHtml(c.name)}</div>
|
||||
<div class="share-card-meta">${escHtml(protoLabel(c.protocol))} · ${escHtml(c.server_name || '')}</div>
|
||||
</div>
|
||||
<span class="badge badge-success share-badge">${_('active')}</span>
|
||||
</div>
|
||||
<button type="button" class="btn btn-primary share-btn-lg share-copy-btn"
|
||||
onclick="copyKeyFromCard(this, '${escAttr(c.id)}')">
|
||||
${typeof uiIcon === 'function' ? uiIcon('copy') : '📋'}
|
||||
<span class="share-copy-label">${_('copy_key_big')}</span>
|
||||
</button>
|
||||
<button type="button" class="share-link-btn"
|
||||
onclick="showDetails('${escAttr(c.id)}', '${escAttr(c.name)}')">
|
||||
${_('more_qr_download')}
|
||||
</button>
|
||||
</article>
|
||||
`).join('');
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
loading.classList.add('hidden');
|
||||
}
|
||||
}
|
||||
|
||||
async function copyKeyFromCard(btn, connId) {
|
||||
const label = btn.querySelector('.share-copy-label');
|
||||
const prev = label ? label.textContent : '';
|
||||
btn.disabled = true;
|
||||
if (label) label.textContent = _('copying_key');
|
||||
try {
|
||||
const data = await fetchInviteConfig(connId);
|
||||
await copyKeyText(pickKey(data.config, data.vpn_link));
|
||||
} catch (err) {
|
||||
alert(`${_('error')}: ` + err.message);
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
if (label) label.textContent = prev || _('copy_key_big');
|
||||
}
|
||||
}
|
||||
|
||||
async function showDetails(connId, name) {
|
||||
try {
|
||||
const data = await fetchInviteConfig(connId);
|
||||
fillModal(name, data.config, data.vpn_link || '', data.expires_at);
|
||||
openModal('configModal');
|
||||
} catch (err) {
|
||||
alert(`${_('error')}: ` + err.message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -189,16 +329,27 @@
|
||||
text.classList.add('hidden');
|
||||
spinner.classList.remove('hidden');
|
||||
try {
|
||||
const body = { name: 'Invite VPN' };
|
||||
const wrap = document.getElementById('serverPickWrap');
|
||||
const sel = document.getElementById('inviteServerPick');
|
||||
if (wrap && wrap.style.display !== 'none' && sel && sel.value !== '') {
|
||||
body.server_id = parseInt(sel.value, 10);
|
||||
}
|
||||
const res = await fetch(`/api/invite/${TOKEN}/create`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: 'Invite VPN' })
|
||||
body: JSON.stringify(body)
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok || data.error) throw new Error(data.error || _('error'));
|
||||
const share = data.subscription_url || data.config || '';
|
||||
if (share) openConfigModal(data.connection?.name || 'VPN', share, data.vpn_link || share, data.expires_at);
|
||||
if (share || data.vpn_link) {
|
||||
fillModal(data.connection?.name || 'VPN', share || data.config || '', data.vpn_link || share, data.expires_at);
|
||||
await copyKeyText(pickKey(share || data.config || '', data.vpn_link || share));
|
||||
openModal('configModal');
|
||||
}
|
||||
updateStatus(data.invite);
|
||||
await loadConnections();
|
||||
} catch (err) {
|
||||
alert(`${_('error')}: ` + err.message);
|
||||
} finally {
|
||||
@@ -207,17 +358,43 @@
|
||||
spinner.classList.add('hidden');
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener('DOMContentLoaded', loadConnections);
|
||||
</script>
|
||||
|
||||
<style>
|
||||
.share-page { max-width: 440px; margin: 1.25rem auto 2.5rem; padding: 0 var(--space-md); }
|
||||
.share-hero { text-align: center; margin-bottom: var(--space-lg); }
|
||||
.share-title { font-size: 1.75rem; font-weight: 700; letter-spacing: -0.02em; margin: 0 0 var(--space-xs); }
|
||||
.share-user { color: var(--text-muted); font-size: 0.95rem; margin: 0 0 var(--space-sm); }
|
||||
.share-hint {
|
||||
margin: 0 auto; max-width: 22rem; padding: 0.75rem 1rem; border-radius: 12px;
|
||||
background: var(--accent-glow); color: var(--text-primary); font-size: 0.95rem; line-height: 1.4;
|
||||
border: 1px solid color-mix(in srgb, var(--accent) 35%, transparent);
|
||||
}
|
||||
.share-grid { display: flex; flex-direction: column; gap: var(--space-md); margin-top: var(--space-lg); }
|
||||
.share-card {
|
||||
background: var(--bg-card); border: 1px solid var(--border); border-radius: var(--radius-lg);
|
||||
padding: var(--space-md); display: flex; flex-direction: column; gap: var(--space-sm);
|
||||
}
|
||||
.share-card-top { display: flex; justify-content: space-between; gap: var(--space-sm); align-items: flex-start; }
|
||||
.share-card-name { font-weight: 600; }
|
||||
.share-card-meta { font-size: 0.8rem; color: var(--text-muted); margin-top: 2px; }
|
||||
.share-btn-lg { width: 100%; justify-content: center; min-height: 48px; }
|
||||
.share-link-btn {
|
||||
background: none; border: none; color: var(--accent); cursor: pointer; font-size: 0.85rem; padding: 4px 0;
|
||||
}
|
||||
.share-loading, .share-empty { text-align: center; color: var(--text-muted); padding: var(--space-lg) 0; }
|
||||
.share-modal { max-width: 420px; }
|
||||
.share-modal-body { padding: var(--space-md) var(--space-lg) var(--space-lg); display: flex; flex-direction: column; gap: var(--space-md); }
|
||||
.share-qr-wrap { text-align: center; }
|
||||
.share-qr-caption { font-size: 0.8rem; color: var(--text-muted); margin-top: var(--space-xs); }
|
||||
.share-config-text { width: 100%; font-family: monospace; font-size: 0.75rem; }
|
||||
.share-auth { max-width: 360px; margin: 0 auto; text-align: center; padding: var(--space-xl); }
|
||||
.share-auth-form { display: flex; flex-direction: column; gap: var(--space-md); margin-top: var(--space-md); }
|
||||
.spinner {
|
||||
border: 3px solid rgba(255, 255, 255, 0.1);
|
||||
border-top: 3px solid var(--accent-color);
|
||||
border-radius: 50%;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
animation: spin 1s linear infinite;
|
||||
display: inline-block;
|
||||
border: 3px solid rgba(255,255,255,0.1); border-top: 3px solid var(--accent-color);
|
||||
border-radius: 50%; width: 20px; height: 20px; animation: spin 1s linear infinite; display: inline-block;
|
||||
}
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
</style>
|
||||
|
||||
@@ -174,6 +174,14 @@
|
||||
<input class="form-input" type="text" id="inviteNote" placeholder="{{ _('invite_note_placeholder') }}">
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label style="display:flex; align-items:center; gap:var(--space-sm); cursor:pointer;">
|
||||
<input type="checkbox" id="inviteAllowServerChoice" checked>
|
||||
{{ _('allow_server_choice') }}
|
||||
</label>
|
||||
<div class="form-hint">{{ _('allow_server_choice_hint') }}</div>
|
||||
</div>
|
||||
|
||||
<div class="form-group" id="inviteResetUsedWrap" style="display:none;">
|
||||
<label style="display:flex; align-items:center; gap:var(--space-sm); cursor:pointer;">
|
||||
<input type="checkbox" id="inviteResetUsed"> {{ _('invite_reset_used') }}
|
||||
@@ -355,6 +363,7 @@
|
||||
document.getElementById('inviteNote').value = '';
|
||||
document.getElementById('inviteClearPwdWrap').style.display = 'none';
|
||||
document.getElementById('inviteResetUsedWrap').style.display = 'none';
|
||||
document.getElementById('inviteAllowServerChoice').checked = true;
|
||||
const serverSel = document.getElementById('inviteServer');
|
||||
if (xuiConfigured && [...serverSel.options].some(o => o.value === 'xui')) serverSel.value = 'xui';
|
||||
else if (serverSel.options.length) serverSel.selectedIndex = 0;
|
||||
@@ -384,6 +393,7 @@
|
||||
document.getElementById('inviteClearPassword').checked = false;
|
||||
document.getElementById('inviteResetUsedWrap').style.display = 'block';
|
||||
document.getElementById('inviteResetUsed').checked = false;
|
||||
document.getElementById('inviteAllowServerChoice').checked = inv.allow_server_choice !== false;
|
||||
setInviteSelection(inv.protocol || 'xui', inv.server_id || 0);
|
||||
const panelSel = document.getElementById('inviteXuiPanel');
|
||||
if (panelSel && inv.xui_panel_id && [...panelSel.options].some(o => o.value === inv.xui_panel_id)) {
|
||||
@@ -417,6 +427,7 @@
|
||||
xui_inbound_id: inbound,
|
||||
xui_panel_id: document.getElementById('inviteXuiPanel')?.value || '',
|
||||
note: document.getElementById('inviteNote').value || '',
|
||||
allow_server_choice: document.getElementById('inviteAllowServerChoice').checked,
|
||||
};
|
||||
const pwd = document.getElementById('invitePassword').value;
|
||||
if (pwd) body.password = pwd;
|
||||
|
||||
@@ -131,6 +131,13 @@
|
||||
</select>
|
||||
<input type="hidden" id="guest_create_protocol_pref" value="{{ settings.guest.create_protocol or '' }}">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label style="display: flex; align-items: center; gap: var(--space-sm); cursor: pointer;">
|
||||
<input type="checkbox" id="guest_allow_server_choice" {% if settings.guest.create_allow_server_choice is not defined or settings.guest.create_allow_server_choice %}checked{% endif %}>
|
||||
{{ _('allow_server_choice') }}
|
||||
</label>
|
||||
<div class="form-hint">{{ _('allow_server_choice_hint') }}</div>
|
||||
</div>
|
||||
<div class="form-group" id="guestInboundGroup" style="{% if settings.guest.create_protocol != 'xui' %}display:none;{% endif %}">
|
||||
<label class="form-label">{{ _('xui_server_select_label') }}</label>
|
||||
<select class="form-select" id="guest_create_xui_panel" onchange="loadGuestInbounds()">
|
||||
@@ -1516,6 +1523,7 @@
|
||||
create_server_id: createServerId,
|
||||
create_inbound_id: parseInt(document.getElementById('guest_create_inbound_id').value || '0'),
|
||||
create_xui_panel_id: document.getElementById('guest_create_xui_panel')?.value || '',
|
||||
create_allow_server_choice: !!(document.getElementById('guest_allow_server_choice') && document.getElementById('guest_allow_server_choice').checked),
|
||||
};
|
||||
|
||||
const donateMethod = (key) => ({
|
||||
|
||||
@@ -537,6 +537,10 @@
|
||||
"aivpn_picking": "Scoring protocols…",
|
||||
"aivpn_on": "On",
|
||||
"aivpn_protocol_option": "AIVPN (auto)",
|
||||
"choose_server": "Choose server",
|
||||
"allow_server_choice": "Allow user to choose server",
|
||||
"allow_server_choice_hint": "End users pick a server when creating a config. Default server is used as fallback.",
|
||||
"invite_no_saved_configs": "No configs yet. Create one above — you can copy it again anytime.",
|
||||
"revproxy_title": "Reverse Proxy",
|
||||
"revproxy_subtitle": "High-performance traffic obfuscation: hide your VPN endpoint behind a polished public-facing site, drop the DPI footprint.",
|
||||
"management": "Management",
|
||||
|
||||
@@ -491,6 +491,10 @@
|
||||
"aivpn_picking": "Scoring protocols…",
|
||||
"aivpn_on": "On",
|
||||
"aivpn_protocol_option": "AIVPN (auto)",
|
||||
"choose_server": "Choose server",
|
||||
"allow_server_choice": "Allow user to choose server",
|
||||
"allow_server_choice_hint": "End users pick a server when creating a config. Default server is used as fallback.",
|
||||
"invite_no_saved_configs": "No configs yet. Create one above — you can copy it again anytime.",
|
||||
"revproxy_title": "Reverse Proxy",
|
||||
"revproxy_subtitle": "High-performance traffic obfuscation: hide your VPN endpoint behind a polished public-facing site, drop the DPI footprint.",
|
||||
"warp_hint": "WARP routes this host outbound through Cloudflare. It does not create a public panel URL like Quick Tunnel or ngrok.",
|
||||
|
||||
@@ -491,6 +491,10 @@
|
||||
"aivpn_picking": "Scoring protocols…",
|
||||
"aivpn_on": "On",
|
||||
"aivpn_protocol_option": "AIVPN (auto)",
|
||||
"choose_server": "Choose server",
|
||||
"allow_server_choice": "Allow user to choose server",
|
||||
"allow_server_choice_hint": "End users pick a server when creating a config. Default server is used as fallback.",
|
||||
"invite_no_saved_configs": "No configs yet. Create one above — you can copy it again anytime.",
|
||||
"revproxy_title": "Reverse Proxy",
|
||||
"revproxy_subtitle": "High-performance traffic obfuscation: hide your VPN endpoint behind a polished public-facing site, drop the DPI footprint.",
|
||||
"warp_hint": "WARP routes this host outbound through Cloudflare. It does not create a public panel URL like Quick Tunnel or ngrok.",
|
||||
|
||||
@@ -537,6 +537,10 @@
|
||||
"aivpn_picking": "Оценка протоколов…",
|
||||
"aivpn_on": "Вкл",
|
||||
"aivpn_protocol_option": "AIVPN (авто)",
|
||||
"choose_server": "Выберите сервер",
|
||||
"allow_server_choice": "Разрешить пользователю выбрать сервер",
|
||||
"allow_server_choice_hint": "Пользователь сам выбирает сервер при создании конфига. Сервер по умолчанию — запасной вариант.",
|
||||
"invite_no_saved_configs": "Пока нет конфигов. Создайте выше — копировать можно повторно в любой момент.",
|
||||
"revproxy_title": "Reverse Proxy",
|
||||
"revproxy_subtitle": "Высокопроизводительная маскировка трафика: прячем VPN за обычным сайтом, снижаем заметность для DPI.",
|
||||
"management": "Управление",
|
||||
|
||||
@@ -491,6 +491,10 @@
|
||||
"aivpn_picking": "Scoring protocols…",
|
||||
"aivpn_on": "On",
|
||||
"aivpn_protocol_option": "AIVPN (auto)",
|
||||
"choose_server": "Choose server",
|
||||
"allow_server_choice": "Allow user to choose server",
|
||||
"allow_server_choice_hint": "End users pick a server when creating a config. Default server is used as fallback.",
|
||||
"invite_no_saved_configs": "No configs yet. Create one above — you can copy it again anytime.",
|
||||
"revproxy_title": "Reverse Proxy",
|
||||
"revproxy_subtitle": "High-performance traffic obfuscation: hide your VPN endpoint behind a polished public-facing site, drop the DPI footprint.",
|
||||
"warp_hint": "WARP routes this host outbound through Cloudflare. It does not create a public panel URL like Quick Tunnel or ngrok.",
|
||||
|
||||
Reference in New Issue
Block a user