[GH-ISSUE #5573] [Bug]: Public keys created via the API do not appear in the panel. #3892

Closed
opened 2026-10-31 20:35:42 +07:00 by bsakaguchi · 1 comment
Owner

Originally created by @tanmoumou252 on GitHub (Jun 25, 2026).
Original GitHub issue: https://github.com/MHSanaei/3x-ui/issues/5573

Describe the bug

The public key created via the API does not appear in the input panel, but it can be seen in the panel’s JSON.

And the private key is always displayed.

However, when copying inbound links such as VLESS from the panel, they are copied directly from the panel. In other words, the VLESS pbk field is empty.

How to reproduce the problem

python3 << 'PYEOF'
import urllib.request, json, time, subprocess, hashlib, uuid, sqlite3

# ==================== 配置 ====================
API_TOKEN = ""
BASE_URL = "http://127.0.0.1:2082/ui/panel/api"
HEADERS = {
    "Accept": "application/json",
    "Content-Type": "application/json",
    "Authorization": f"Bearer {API_TOKEN}"
}
CLIENT_UUID = ""
CLIENT_EMAIL = "user@example.com"
SUB_ID = str(uuid.uuid4())
PORT = 50508
REMARK = "VLESS-Reality-IPv6"

def api_get(path):
    req = urllib.request.Request(f"{BASE_URL}{path}", headers=HEADERS, method='GET')
    with urllib.request.urlopen(req, timeout=10) as r:
        return json.loads(r.read().decode('utf-8'))

def api_post(path, data=None):
    if data is None:
        data = b'{}'
    elif isinstance(data, dict):
        data = json.dumps(data).encode('utf-8')
    req = urllib.request.Request(f"{BASE_URL}{path}", data=data, headers=HEADERS, method='POST')
    with urllib.request.urlopen(req, timeout=10) as r:
        return json.loads(r.read().decode('utf-8'))

# ===========================================================

conn = sqlite3.connect('/etc/x-ui/x-ui.db')
tables = [t[0] for t in conn.execute("SELECT name FROM sqlite_master WHERE type='table'").fetchall()]
token_hash = hashlib.sha256(API_TOKEN.encode()).hexdigest()
if 'api_tokens' in tables:
    conn.execute("DELETE FROM api_tokens")
    conn.execute("INSERT INTO api_tokens (name, token, enabled, created_at) VALUES (?, ?, 1, ?)",
                 ("default", token_hash, int(time.time())))
    conn.commit()
else:
    cols = [c[1] for c in conn.execute("PRAGMA table_info(users)").fetchall()]
    if 'api_token' in cols:
        conn.execute("UPDATE users SET api_token=? WHERE id=1", (token_hash,))
        conn.commit()
    else:
        print(" Token unset")
conn.close()
time.sleep(2)

# ===========================================================

try:
    list_result = api_get("/inbounds/list")
    for inbound in list_result.get('obj', []):
        if inbound.get('port') == PORT or inbound.get('remark') == REMARK:
            old_id = inbound['id']
            api_post(f"/inbounds/del/{old_id}")
            time.sleep(1)
except Exception as e:
    print(f"  check error {e}")
time.sleep(2)

# ===========================================================

try:
    kp_result = api_get("/server/getNewX25519Cert")
    private_key = kp_result['obj']['privateKey']
    public_key = kp_result['obj']['publicKey']
except Exception as e:

    kp = subprocess.run(['/opt/3xui/bin/xray-linux-amd64', 'x25519'], capture_output=True, text=True)
    lines = kp.stdout.strip().splitlines()
    private_key = ""
    public_key = ""
    for line in lines:
        lower = line.lower()
        if 'private' in lower: private_key = line.split()[-1]
        elif 'public' in lower: public_key = line.split()[-1]
print(f"  Private Key: {private_key}")
print(f"  Public Key:  {public_key}")

# ===========================================================

payload = {
    "remark": REMARK,
    "listen": "",
    "port": PORT,
    "protocol": "vless",
    "settings": {
        "clients": [{
            "id": CLIENT_UUID,
            "email": CLIENT_EMAIL,
            "flow": "",
            "limitIp": 0,
            "totalGB": 0,
            "expiryTime": 0,
            "enable": True,
            "tgId": 0,
            "subId": SUB_ID,
            "comment": "",
            "reset": 0
        }],
        "decryption": "none",
        "encryption": "none"
    },
    "streamSettings": {
        "network": "tcp",
        "tcpSettings": {
            "acceptProxyProtocol": False,
            "header": {"type": "none"}
        },
        "security": "reality",
        "realitySettings": {
            "show": False,
            "xver": 0,
            "target": "www.intel.com:443",
            "serverNames": ["www.intel.com"],
            "privateKey": private_key,
            "publicKey": public_key,
            "minClientVer": "",
            "maxClientVer": "",
            "maxTimediff": 0,
            "shortIds": ["8094e338"]
        }
    },
    "sniffing": {"enabled": False},
    "enable": True,
    "expiryTime": 0,
    "total": 0,
    "subSortIndex": 1
}
result = api_post("/inbounds/add", payload)
if result.get("success"):
    inbound_id = result['obj']['id']

else:
    print(f"  error: {result}")
    exit(1)

# ===========================================================

try:
    s = api_post("/setting/all")
    settings = s.get('obj', {})
    settings['subEnable'] = False
    api_post("/setting/update", settings)

except Exception as e:
    print(f"  update: {e}")

api_post("/server/restartXrayService")

time.sleep(5)

# ===========================================================

with open('/tmp/install_info.txt', 'w') as f:
    f.write(f"PUBLIC_KEY={public_key}\n")
    f.write(f"SUB_ID={SUB_ID}\n")
    f.write(f"INBOUND_ID={inbound_id}\n")

print(f"\n  pbk: {public_key}")
print(f"  subId: {SUB_ID}")
PYEOF



echo "vless://uuid@[${IPV6}]:50508?type=tcp&encryption=none&security=reality&pbk=${PUBLIC_KEY}"

Expected behavior

.

Actual behavior

.

Relevant logs

.

Screenshots

Image Image Image

3x-ui version

3.4.0

Xray-core version

v26.6.22

How did you install 3x-ui?

Other (please describe in the bug body)

Operating system

Alpine

Which parts of the panel are affected?

No response

Browser (only if it is a UI bug)

Firefox

Is the panel behind a reverse proxy or CDN?

Yes — other

Before submitting

  • I searched existing issues and this bug has not been reported.
  • I am running the latest released version of 3x-ui (or have verified the bug still exists on it).
  • This bug report is written in English.
  • I have redacted any sensitive data (tokens, real domains, client UUIDs).
Originally created by @tanmoumou252 on GitHub (Jun 25, 2026). Original GitHub issue: https://github.com/MHSanaei/3x-ui/issues/5573 ### Describe the bug The public key created via the API does not appear in the input panel, but it can be seen in the panel’s JSON. And the private key is always displayed. However, when copying inbound links such as VLESS from the panel, they are copied directly from the panel. In other words, the VLESS pbk field is empty. ### How to reproduce the problem ```bash python3 << 'PYEOF' import urllib.request, json, time, subprocess, hashlib, uuid, sqlite3 # ==================== 配置 ==================== API_TOKEN = "" BASE_URL = "http://127.0.0.1:2082/ui/panel/api" HEADERS = { "Accept": "application/json", "Content-Type": "application/json", "Authorization": f"Bearer {API_TOKEN}" } CLIENT_UUID = "" CLIENT_EMAIL = "user@example.com" SUB_ID = str(uuid.uuid4()) PORT = 50508 REMARK = "VLESS-Reality-IPv6" def api_get(path): req = urllib.request.Request(f"{BASE_URL}{path}", headers=HEADERS, method='GET') with urllib.request.urlopen(req, timeout=10) as r: return json.loads(r.read().decode('utf-8')) def api_post(path, data=None): if data is None: data = b'{}' elif isinstance(data, dict): data = json.dumps(data).encode('utf-8') req = urllib.request.Request(f"{BASE_URL}{path}", data=data, headers=HEADERS, method='POST') with urllib.request.urlopen(req, timeout=10) as r: return json.loads(r.read().decode('utf-8')) # =========================================================== conn = sqlite3.connect('/etc/x-ui/x-ui.db') tables = [t[0] for t in conn.execute("SELECT name FROM sqlite_master WHERE type='table'").fetchall()] token_hash = hashlib.sha256(API_TOKEN.encode()).hexdigest() if 'api_tokens' in tables: conn.execute("DELETE FROM api_tokens") conn.execute("INSERT INTO api_tokens (name, token, enabled, created_at) VALUES (?, ?, 1, ?)", ("default", token_hash, int(time.time()))) conn.commit() else: cols = [c[1] for c in conn.execute("PRAGMA table_info(users)").fetchall()] if 'api_token' in cols: conn.execute("UPDATE users SET api_token=? WHERE id=1", (token_hash,)) conn.commit() else: print(" Token unset") conn.close() time.sleep(2) # =========================================================== try: list_result = api_get("/inbounds/list") for inbound in list_result.get('obj', []): if inbound.get('port') == PORT or inbound.get('remark') == REMARK: old_id = inbound['id'] api_post(f"/inbounds/del/{old_id}") time.sleep(1) except Exception as e: print(f" check error {e}") time.sleep(2) # =========================================================== try: kp_result = api_get("/server/getNewX25519Cert") private_key = kp_result['obj']['privateKey'] public_key = kp_result['obj']['publicKey'] except Exception as e: kp = subprocess.run(['/opt/3xui/bin/xray-linux-amd64', 'x25519'], capture_output=True, text=True) lines = kp.stdout.strip().splitlines() private_key = "" public_key = "" for line in lines: lower = line.lower() if 'private' in lower: private_key = line.split()[-1] elif 'public' in lower: public_key = line.split()[-1] print(f" Private Key: {private_key}") print(f" Public Key: {public_key}") # =========================================================== payload = { "remark": REMARK, "listen": "", "port": PORT, "protocol": "vless", "settings": { "clients": [{ "id": CLIENT_UUID, "email": CLIENT_EMAIL, "flow": "", "limitIp": 0, "totalGB": 0, "expiryTime": 0, "enable": True, "tgId": 0, "subId": SUB_ID, "comment": "", "reset": 0 }], "decryption": "none", "encryption": "none" }, "streamSettings": { "network": "tcp", "tcpSettings": { "acceptProxyProtocol": False, "header": {"type": "none"} }, "security": "reality", "realitySettings": { "show": False, "xver": 0, "target": "www.intel.com:443", "serverNames": ["www.intel.com"], "privateKey": private_key, "publicKey": public_key, "minClientVer": "", "maxClientVer": "", "maxTimediff": 0, "shortIds": ["8094e338"] } }, "sniffing": {"enabled": False}, "enable": True, "expiryTime": 0, "total": 0, "subSortIndex": 1 } result = api_post("/inbounds/add", payload) if result.get("success"): inbound_id = result['obj']['id'] else: print(f" error: {result}") exit(1) # =========================================================== try: s = api_post("/setting/all") settings = s.get('obj', {}) settings['subEnable'] = False api_post("/setting/update", settings) except Exception as e: print(f" update: {e}") api_post("/server/restartXrayService") time.sleep(5) # =========================================================== with open('/tmp/install_info.txt', 'w') as f: f.write(f"PUBLIC_KEY={public_key}\n") f.write(f"SUB_ID={SUB_ID}\n") f.write(f"INBOUND_ID={inbound_id}\n") print(f"\n pbk: {public_key}") print(f" subId: {SUB_ID}") PYEOF echo "vless://uuid@[${IPV6}]:50508?type=tcp&encryption=none&security=reality&pbk=${PUBLIC_KEY}" ``` ### Expected behavior . ### Actual behavior . ### Relevant logs ```shell . ``` ### Screenshots <img width="740" height="299" alt="Image" src="https://github.com/user-attachments/assets/6aa87d4b-45a0-4689-8289-3b5beac8c0e9" /> <img width="630" height="427" alt="Image" src="https://github.com/user-attachments/assets/5c66f2f9-c1c9-48bc-9800-2bd33c8acdf1" /> <img width="891" height="434" alt="Image" src="https://github.com/user-attachments/assets/ac276eb4-e0ca-4de1-95a9-9c4671b70ca3" /> ### 3x-ui version 3.4.0 ### Xray-core version v26.6.22 ### How did you install 3x-ui? Other (please describe in the bug body) ### Operating system Alpine ### Which parts of the panel are affected? _No response_ ### Browser (only if it is a UI bug) Firefox ### Is the panel behind a reverse proxy or CDN? Yes — other ### Before submitting - [x] I searched [existing issues](../issues?q=is%3Aissue) and this bug has not been reported. - [x] I am running the latest released version of 3x-ui (or have verified the bug still exists on it). - [x] This bug report is written in English. - [x] I have redacted any sensitive data (tokens, real domains, client UUIDs).
bsakaguchi 2026-10-31 20:35:42 +07:00
  • closed this issue
  • added the
    bug
    label
Author
Owner

@github-actions[bot] commented on GitHub (Jun 25, 2026):

The root cause is a mismatch between the JSON structure your script submits and the structure the panel expects for REALITY settings. Specifically, publicKey is being placed at the top level of realitySettings, but the panel schema requires it to be nested inside a settings sub-object one level deeper.

What your script sends:

"realitySettings": {
  "privateKey": "<server_private_key>",
  "publicKey": "<server_public_key>",   ← wrong level
  ...
}

What the panel expects (confirmed in frontend/src/schemas/protocols/security/reality.ts and the canonical test fixture frontend/src/test/golden/fixtures/inbound-full/vless-tcp-reality.json):

"realitySettings": {
  "privateKey": "<server_private_key>",   ← server private key stays at top level
  ...
  "settings": {
    "publicKey": "<server_public_key>",   ← public key goes inside settings{}
    "fingerprint": "chrome",
    "serverName": "",
    "spiderX": "/"
  }
}

Why the behaviour looks inconsistent:

  • The backend API (internal/web/service/inbound.go) stores streamSettings as a raw JSON blob without transforming the realitySettings sub-tree, so whatever the caller submits is persisted verbatim. The "JSON view" in the panel therefore shows your publicKey at the top level because that is exactly what was stored.
  • The panel's form and link-copy logic parse the stored JSON through a Zod schema (RealityStreamSettingsSchema), which reads the public key from realitySettings.settings.publicKey. Because that path is absent in your stored blob, the form renders the public key field as empty and the VLESS link generator emits pbk= with no value (inbound-link.ts line 410: params.set('pbk', reality.settings.publicKey)).
  • The private key works because it is defined at the top level of realitySettings in both the schema and your payload, so it lands in the right place.

Fix for your script — update the realitySettings section of the payload:

"realitySettings": {
    "show": False,
    "xver": 0,
    "target": "www.intel.com:443",
    "serverNames": ["www.intel.com"],
    "privateKey": private_key,        # stays at top level
    "minClientVer": "",
    "maxClientVer": "",
    "maxTimediff": 0,
    "shortIds": ["8094e338"],
    "settings": {                     # publicKey goes here
        "publicKey": public_key,
        "fingerprint": "chrome",
        "serverName": "",
        "spiderX": "/"
    }
}

Delete and re-create the inbound (or use the update endpoint) with this corrected payload. After that the panel form will display the public key, and copied VLESS links will carry the correct pbk value.

This reply was generated automatically; a maintainer may follow up.

<!-- gh-comment-id:4803158980 --> @github-actions[bot] commented on GitHub (Jun 25, 2026): The root cause is a mismatch between the JSON structure your script submits and the structure the panel expects for REALITY settings. Specifically, `publicKey` is being placed at the **top level** of `realitySettings`, but the panel schema requires it to be nested inside a `settings` sub-object one level deeper. **What your script sends:** ```json "realitySettings": { "privateKey": "<server_private_key>", "publicKey": "<server_public_key>", ← wrong level ... } ``` **What the panel expects** (confirmed in `frontend/src/schemas/protocols/security/reality.ts` and the canonical test fixture `frontend/src/test/golden/fixtures/inbound-full/vless-tcp-reality.json`): ```json "realitySettings": { "privateKey": "<server_private_key>", ← server private key stays at top level ... "settings": { "publicKey": "<server_public_key>", ← public key goes inside settings{} "fingerprint": "chrome", "serverName": "", "spiderX": "/" } } ``` **Why the behaviour looks inconsistent:** - The backend API (`internal/web/service/inbound.go`) stores `streamSettings` as a raw JSON blob without transforming the `realitySettings` sub-tree, so whatever the caller submits is persisted verbatim. The "JSON view" in the panel therefore shows your `publicKey` at the top level because that is exactly what was stored. - The panel's form and link-copy logic parse the stored JSON through a Zod schema (`RealityStreamSettingsSchema`), which reads the public key from `realitySettings.settings.publicKey`. Because that path is absent in your stored blob, the form renders the public key field as empty and the VLESS link generator emits `pbk=` with no value (`inbound-link.ts` line 410: `params.set('pbk', reality.settings.publicKey)`). - The private key works because it is defined at the top level of `realitySettings` in both the schema and your payload, so it lands in the right place. **Fix for your script** — update the `realitySettings` section of the payload: ```python "realitySettings": { "show": False, "xver": 0, "target": "www.intel.com:443", "serverNames": ["www.intel.com"], "privateKey": private_key, # stays at top level "minClientVer": "", "maxClientVer": "", "maxTimediff": 0, "shortIds": ["8094e338"], "settings": { # publicKey goes here "publicKey": public_key, "fingerprint": "chrome", "serverName": "", "spiderX": "/" } } ``` Delete and re-create the inbound (or use the update endpoint) with this corrected payload. After that the panel form will display the public key, and copied VLESS links will carry the correct `pbk` value. *This reply was generated automatically; a maintainer may follow up.*
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
MHSanaei/3x-ui#3892
No description provided.