> ## Documentation Index
> Fetch the complete documentation index at: https://veniceai-docs-revamp.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# نماذج TEE وE2EE

> ذكاء اصطناعي معزّز للخصوصية مع بيئات التنفيذ الموثوقة والتشفير الكامل من طرف إلى طرف

يقدّم Venice نماذج معزّزة للخصوصية تعمل داخل بيئات تنفيذ موثوقة (TEE) وتدعم التشفير الكامل من طرف إلى طرف (E2EE). توفّر هذه النماذج ضمانات تشفيرية تكفل أن تبقى بياناتك خاصة — حتى عن Venice نفسها.

## فهم مستويات الخصوصية

| النوع    | البادئة  | ما يعنيه                                                                                                                   |
| -------- | -------- | -------------------------------------------------------------------------------------------------------------------------- |
| **TEE**  | `tee-*`  | يعمل النموذج داخل جيب مؤمَّن عتاديًا. لا يستطيع Venice الوصول إلى الحسابات. يمكنك التحقق من ذلك عبر التصديق (attestation). |
| **E2EE** | `e2ee-*` | تشفير كامل من طرف إلى طرف. تُشفَّر مطالباتك على جانب العميل قبل إرسالها. فقط TEE يمكنه فك تشفيرها.                         |

<Info>
  تشمل نماذج E2EE حماية TEE بالإضافة إلى تشفير من جانب العميل. أما نماذج TEE فتوفر أمان الجيب دون اشتراط تشفير من جانب العميل.
</Info>

## النماذج المتاحة

<div id="tee-e2ee-models-placeholder">جارٍ التحميل...</div>

راجع [صفحة النماذج](/models/overview) للاطلاع على القائمة الكاملة مع التسعير وحدود السياق.

## نماذج TEE

تعمل نماذج TEE داخل جيوب مؤمَّنة عتاديًا (Intel TDX، NVIDIA Confidential Computing). تكون أوزان النموذج وبياناتك محمية من النظام المضيف — بما في ذلك البنية التحتية لـ Venice.

### الاستخدام الأساسي

تعمل نماذج TEE تمامًا مثل النماذج العادية:

<CodeGroup>
  ```python Python theme={"dark"}
  from openai import OpenAI

  client = OpenAI(
      api_key="your-venice-api-key",
      base_url="https://api.venice.ai/api/v1"
  )

  response = client.chat.completions.create(
      model="tee-qwen3-5-122b-a10b",
      messages=[{"role": "user", "content": "Explain quantum computing"}]
  )

  print(response.choices[0].message.content)
  ```

  ```javascript Node.js theme={"dark"}
  import OpenAI from 'openai';

  const client = new OpenAI({
      apiKey: 'your-venice-api-key',
      baseURL: 'https://api.venice.ai/api/v1'
  });

  const response = await client.chat.completions.create({
      model: 'tee-qwen3-5-122b-a10b',
      messages: [{ role: 'user', content: 'Explain quantum computing' }]
  });

  console.log(response.choices[0].message.content);
  ```

  ```bash cURL theme={"dark"}
  curl https://api.venice.ai/api/v1/chat/completions \
    -H "Authorization: Bearer $API_KEY_VENICE" \
    -H "Content-Type: application/json" \
    -d '{
      "model": "tee-qwen3-5-122b-a10b",
      "messages": [{"role": "user", "content": "Explain quantum computing"}]
    }'
  ```
</CodeGroup>

### التحقق من تصديق TEE

يمكنك التحقق تشفيريًا من أن النموذج يعمل داخل TEE حقيقي عبر جلب تقرير التصديق الخاص به:

<CodeGroup>
  ```bash cURL theme={"dark"}
  # توليد nonce عشوائي (يمنع هجمات إعادة التشغيل)
  NONCE=$(openssl rand -hex 16)

  # جلب التصديق
  curl "https://api.venice.ai/api/v1/tee/attestation?model=tee-qwen3-5-122b-a10b&nonce=$NONCE" \
    -H "Authorization: Bearer $API_KEY_VENICE"
  ```

  ```python Python theme={"dark"}
  import secrets
  import requests

  nonce = secrets.token_hex(16)

  response = requests.get(
      f"https://api.venice.ai/api/v1/tee/attestation",
      params={"model": "tee-qwen3-5-122b-a10b", "nonce": nonce},
      headers={"Authorization": f"Bearer {api_key}"}
  )

  attestation = response.json()
  print(f"Verified: {attestation['verified']}")
  print(f"TEE Provider: {attestation['tee_provider']}")
  print(f"Model: {attestation['model']}")
  ```
</CodeGroup>

تتضمن استجابة التصديق:

| الحقل             | الوصف                                                                                                |
| ----------------- | ---------------------------------------------------------------------------------------------------- |
| `verified`        | ما إذا نجح التصديق في التحقق من جانب الخادم                                                          |
| `nonce`           | الـ nonce الخاص بك، يؤكد حداثة الاستجابة                                                             |
| `model`           | معرّف النموذج المُصدَّق عليه                                                                         |
| `tee_provider`    | معرّف مزوّد TEE                                                                                      |
| `intel_quote`     | اقتباس Intel TDX الخام (base64) للتحقق من جانب العميل                                                |
| `nvidia_payload`  | بيانات تصديق GPU من NVIDIA (إن وُجدت)                                                                |
| `signing_key`     | المفتاح العام للتحقق من توقيع الاستجابة (يُطلب عادةً لتدفقات E2EE؛ وقد يُحذف لبعض نماذج TEE العادية) |
| `signing_address` | عنوان Ethereum المشتق من مفتاح التوقيع                                                               |

<Tip>
  للاستخدام في الإنتاج، تحقق من التصديق من جانب العميل عبر تحليل اقتباس Intel TDX والتحقق من تصديق NVIDIA.
</Tip>

<Note>
  بالنسبة للتحقق من نموذج TEE العادي، يكفي `signing_address` وحقول التحقق من جانب الخادم لإجراء فحوصات التصديق الأساسية. ويُطلب `signing_key` عندما تحتاج إلى اتفاق مفاتيح E2EE من جانب العميل وفحوصات ربط مفاتيح صارمة.
</Note>

### توقيعات الاستجابة

يمكن لنماذج TEE توقيع استجاباتها، ما يُثبت أن المخرجات صدرت من الجيب المُصدَّق عليه:

<CodeGroup>
  ```bash cURL theme={"dark"}
  # بعد الحصول على إكمال، تحقق من التوقيع
  curl "https://api.venice.ai/api/v1/tee/signature?model=tee-qwen3-5-122b-a10b&request_id=chatcmpl-abc123" \
    -H "Authorization: Bearer $API_KEY_VENICE"
  ```

  ```python Python theme={"dark"}
  response = requests.get(
      f"https://api.venice.ai/api/v1/tee/signature",
      params={"model": "tee-qwen3-5-122b-a10b", "request_id": completion_id},
      headers={"Authorization": f"Bearer {api_key}"}
  )

  signature = response.json()
  # تحقق من أن التوقيع يطابق signing_address من التصديق
  ```
</CodeGroup>

## نماذج E2EE

تضيف نماذج E2EE تشفيرًا من جانب العميل فوق حماية TEE. تُشفَّر مطالباتك قبل مغادرة جهازك، ولا يستطيع فك تشفيرها سوى TEE.

يستخدم Venice E2EE:

* **ECDH (Elliptic Curve Diffie-Hellman)** على secp256k1 لتبادل المفاتيح
* **HKDF-SHA256** لاشتقاق المفاتيح
* **AES-256-GCM** للتشفير المتماثل
* **تصديق TEE** للتحقق من أن النموذج يعمل في جيب آمن

<Warning>
  يتطلب E2EE تنفيذًا من جانب العميل. توضّح الأمثلة أدناه البروتوكول الكامل.
</Warning>

### كيف يعمل E2EE

<Steps>
  <Step title="توليد زوج مفاتيح مؤقت">
    يولّد العميل زوج مفاتيح secp256k1 لهذه الجلسة.
  </Step>

  <Step title="جلب تصديق TEE">
    يطلب العميل `/api/v1/tee/attestation` ويتلقّى المفتاح العام للنموذج، ودليل التصديق، والـ nonce.
  </Step>

  <Step title="التحقق من التصديق">
    يتحقق العميل من تطابق الـ nonce، وتعطيل وضع التصحيح، وصلاحية التصديق.
  </Step>

  <Step title="تشفير الرسائل">
    يُشفّر العميل المطالبات باستخدام السر المشترك ECDH → HKDF → AES-GCM.
  </Step>

  <Step title="إرسال الطلب">
    يرسل العميل الطلب مع رؤوس E2EE (`X-Venice-TEE-Client-Pub-Key`، `X-Venice-TEE-Model-Pub-Key`، `X-Venice-TEE-Signing-Algo`).
  </Step>

  <Step title="معالجة TEE">
    يفك TEE تشفير الطلب، ويعالجه، ويُشفّر الاستجابة.
  </Step>

  <Step title="فك تشفير الاستجابة">
    يتلقى العميل أجزاءً مشفّرة ويفك تشفيرها باستخدام المفتاح الخاص.
  </Step>
</Steps>

### المتطلبات المسبقة

**JavaScript (Node.js ESM):**

```bash theme={"dark"}
npm install elliptic @noble/ciphers @noble/hashes
```

**Python:**

```bash theme={"dark"}
pip install cryptography ecdsa requests
```

### الخطوة 1: التحقق من دعم النموذج لـ E2EE

أولًا، تحقق من أن النموذج يدعم E2EE عبر فحص نقطة النهاية `/models`.

<CodeGroup>
  ```javascript JavaScript theme={"dark"}
  async function getE2EEModels(apiKey) {
    const response = await fetch('https://api.venice.ai/api/v1/models', {
      headers: { Authorization: `Bearer ${apiKey}` },
    })
    const { data } = await response.json()

    return data.filter(model => model.model_spec?.capabilities?.supportsE2EE === true)
  }

  // مثال على الاستخدام
  const models = await getE2EEModels('your-api-key')
  console.log('E2EE Models:', models.map(m => m.id))
  // المخرجات: ['e2ee-qwen3-5-122b-a10b', 'e2ee-glm-5', ...]
  ```

  ```python Python theme={"dark"}
  import requests

  def get_e2ee_models(api_key: str) -> list:
      """Get list of models that support E2EE."""
      response = requests.get(
          'https://api.venice.ai/api/v1/models',
          headers={'Authorization': f'Bearer {api_key}'}
      )
      models = response.json()['data']

      return [
          model for model in models
          if model.get('model_spec', {}).get('capabilities', {}).get('supportsE2EE')
      ]

  # مثال على الاستخدام
  models = get_e2ee_models('your-api-key')
  print('E2EE Models:', [m['id'] for m in models])
  ```
</CodeGroup>

### الخطوة 2: توليد زوج مفاتيح مؤقت

ولّد زوج مفاتيح جديدًا لكل جلسة. يجب الإبقاء على المفتاح الخاص في الذاكرة فقط وتصفيره بأمان بعد الاستخدام.

<CodeGroup>
  ```javascript JavaScript theme={"dark"}
  import { ec as EC } from 'elliptic'

  function generateEphemeralKeyPair() {
    const ec = new EC('secp256k1')
    const keyPair = ec.genKeyPair()

    return {
      privateKey: new Uint8Array(keyPair.getPrivate().toArray('be', 32)),
      publicKeyHex: keyPair.getPublic('hex'), // التنسيق غير المضغوط (65 بايت hex)
    }
  }

  // أمان: قم بملء المفتاح الخاص بالأصفار عند الانتهاء
  function zeroFill(arr) {
    arr.fill(0)
  }
  ```

  ```python Python theme={"dark"}
  from ecdsa import SECP256k1, SigningKey
  import secrets

  def generate_ephemeral_key_pair():
      """Generate ephemeral secp256k1 key pair for E2EE session."""
      private_key = SigningKey.generate(curve=SECP256k1)
      public_key = private_key.get_verifying_key()

      # احصل على المفتاح العام غير المضغوط (04 || x || y)
      public_key_bytes = b'\x04' + public_key.to_string()

      return {
          'private_key': private_key.to_string(),  # 32 بايت
          'public_key_hex': public_key_bytes.hex()  # 130 محرف hex
      }
  ```
</CodeGroup>

#### مساعدات التحقق

استخدم دوال المساعدة هذه للتحقق من المفاتيح والمحتوى المشفّر قبل إرسال الطلبات.

<CodeGroup>
  ```javascript JavaScript theme={"dark"}
  function validateClientPubkey(pubkeyHex) {
    if (pubkeyHex.length !== 130 || !pubkeyHex.startsWith('04')) {
      throw new Error(`Client pubkey must be 130 hex chars starting with '04' (got ${pubkeyHex.length})`)
    }
  }

  function isValidEncrypted(s) {
    // الحد الأدنى: ephemeral_pub (65) + nonce (12) + tag (16) = 93 بايت = 186 محرف hex
    return s.length >= 186 && /^[0-9a-fA-F]+$/.test(s)
  }
  ```

  ```python Python theme={"dark"}
  def validate_client_pubkey(pubkey_hex: str) -> None:
      """Validate client public key format."""
      if len(pubkey_hex) != 130 or not pubkey_hex.startswith('04'):
          raise ValueError(f"Client pubkey must be 130 hex chars starting with '04' (got {len(pubkey_hex)})")

  def is_valid_encrypted(s: str) -> bool:
      """Check if string is valid hex-encrypted content."""
      # الحد الأدنى: ephemeral_pub (65) + nonce (12) + tag (16) = 93 بايت = 186 محرف hex
      return len(s) >= 186 and all(c in '0123456789abcdefABCDEF' for c in s)
  ```
</CodeGroup>

### الخطوة 3: جلب تصديق TEE والتحقق منه

يُثبت التصديق أن النموذج يعمل داخل TEE حقيقي. تحقق دائمًا من التصديق قبل الوثوق بمفتاح النموذج العام.

<Info>
  **مهم: طول الـ nonce** — يجب أن يكون nonce العميل بطول **32 بايت (64 محرف hex)**. تشترط بعض مزوّدي TEE 32 بايت بالضبط وترفض أي nonce أقصر.
</Info>

<CodeGroup>
  ```javascript JavaScript theme={"dark"}
  import crypto from 'crypto'

  async function fetchAndVerifyAttestation(modelId, apiKey) {
    // توليد nonce للعميل للحماية من الإعادة (32 بايت = 64 محرف hex)
    const clientNonce = crypto.randomBytes(32).toString('hex')

    const response = await fetch(
      `https://api.venice.ai/api/v1/tee/attestation?model=${encodeURIComponent(modelId)}&nonce=${clientNonce}`,
      { headers: { Authorization: `Bearer ${apiKey}` } }
    )

    const attestation = await response.json()

    // التحقق من التصديق
    if (attestation.verified !== true) {
      throw new Error('TEE attestation verification failed on server')
    }

    if (attestation.nonce !== clientNonce) {
      throw new Error('Attestation nonce mismatch - possible replay attack')
    }

    // الحصول على المفتاح العام للنموذج للتشفير
    const modelPublicKey = attestation.signing_key || attestation.signing_public_key
    if (!modelPublicKey) {
      throw new Error('No signing key in attestation response')
    }

    return {
      modelPublicKey,
      signingAddress: attestation.signing_address,
      attestation,
    }
  }
  ```

  ```python Python theme={"dark"}
  import secrets
  import requests

  def fetch_and_verify_attestation(model_id: str, api_key: str) -> dict:
      """Fetch and verify TEE attestation for a model."""
      # توليد nonce للعميل للحماية من الإعادة (32 بايت = 64 محرف hex)
      client_nonce = secrets.token_hex(32)

      response = requests.get(
          f'https://api.venice.ai/api/v1/tee/attestation',
          params={'model': model_id, 'nonce': client_nonce},
          headers={'Authorization': f'Bearer {api_key}'}
      )
      attestation = response.json()

      # التحقق من التصديق
      if attestation.get('verified') != True:
          raise ValueError('TEE attestation verification failed on server')

      if attestation.get('nonce') != client_nonce:
          raise ValueError('Attestation nonce mismatch - possible replay attack')

      # الحصول على المفتاح العام للنموذج للتشفير
      model_public_key = attestation.get('signing_key') or attestation.get('signing_public_key')
      if not model_public_key:
          raise ValueError('No signing key in attestation response')

      return {
          'model_public_key': model_public_key,
          'signing_address': attestation.get('signing_address'),
          'attestation': attestation
      }
  ```
</CodeGroup>

### الخطوة 4: تشفير الرسائل

قم بتشفير رسائل المستخدم والنظام قبل الإرسال. تحتاج رسائل دور `user` و`system` فقط إلى التشفير.

<Warning>
  عند وجود رؤوس E2EE، يجب تشفير **جميع** رسائل دور `user` و`system`. إرسال أي محتوى نصي عادي في هذه الأدوار سيؤدي إلى خطأ "Encrypted field is not valid hex".
</Warning>

<CodeGroup>
  ```javascript JavaScript theme={"dark"}
  import { gcm } from '@noble/ciphers/aes.js'
  import { hkdf } from '@noble/hashes/hkdf.js'
  import { sha256 } from '@noble/hashes/sha2.js'
  import { ec as EC } from 'elliptic'
  import crypto from 'crypto'

  const HKDF_INFO = new TextEncoder().encode('ecdsa_encryption')

  function encryptMessage(plaintext, modelPublicKeyHex) {
    const ec = new EC('secp256k1')

    // تطبيع المفتاح العام (إضافة بادئة 04 إذا لزم الأمر)
    let normalizedKey = modelPublicKeyHex
    if (!normalizedKey.startsWith('04') && normalizedKey.length === 128) {
      normalizedKey = '04' + normalizedKey
    }

    const modelPublicKey = ec.keyFromPublic(normalizedKey, 'hex')

    // توليد زوج مفاتيح مؤقت لهذه الرسالة
    const ephemeralKeyPair = ec.genKeyPair()

    // السر المشترك ECDH
    const sharedSecret = ephemeralKeyPair.derive(modelPublicKey.getPublic())
    const sharedSecretBytes = new Uint8Array(sharedSecret.toArray('be', 32))

    // اشتقاق مفتاح AES باستخدام HKDF
    const aesKey = hkdf(sha256, sharedSecretBytes, undefined, HKDF_INFO, 32)

    // توليد nonce عشوائي
    const nonce = crypto.randomBytes(12)

    // التشفير باستخدام AES-GCM
    const cipher = gcm(aesKey, nonce)
    const encrypted = cipher.encrypt(new TextEncoder().encode(plaintext))

    // الحصول على المفتاح العام المؤقت (غير مضغوط)
    const ephemeralPublic = new Uint8Array(ephemeralKeyPair.getPublic(false, 'array'))

    // الدمج: ephemeral_public (65 بايت) + nonce (12 بايت) + ciphertext
    const result = new Uint8Array(65 + 12 + encrypted.length)
    result.set(ephemeralPublic, 0)
    result.set(nonce, 65)
    result.set(encrypted, 65 + 12)

    return Buffer.from(result).toString('hex')
  }

  function encryptMessagesForE2EE(messages, modelPublicKey) {
    return messages.map(msg => {
      if (msg.role === 'user' || msg.role === 'system') {
        return {
          ...msg,
          content: encryptMessage(msg.content, modelPublicKey),
        }
      }
      return msg
    })
  }
  ```

  ```python Python theme={"dark"}
  from cryptography.hazmat.primitives.ciphers.aead import AESGCM
  from cryptography.hazmat.primitives.kdf.hkdf import HKDF
  from cryptography.hazmat.primitives import hashes
  from ecdsa import SECP256k1, VerifyingKey, SigningKey
  import os

  HKDF_INFO = b'ecdsa_encryption'

  def encrypt_message(plaintext: str, model_public_key_hex: str) -> str:
      """Encrypt a message using ECDH + HKDF + AES-GCM."""
      # تطبيع المفتاح العام
      key_hex = model_public_key_hex
      if not key_hex.startswith('04') and len(key_hex) == 128:
          key_hex = '04' + key_hex

      model_public_key_bytes = bytes.fromhex(key_hex)

      # تحليل المفتاح العام للنموذج (تخطي بادئة 04)
      model_verifying_key = VerifyingKey.from_string(
          model_public_key_bytes[1:],
          curve=SECP256k1
      )

      # توليد زوج مفاتيح مؤقت لهذه الرسالة
      ephemeral_private = SigningKey.generate(curve=SECP256k1)
      ephemeral_public = ephemeral_private.get_verifying_key()

      # ECDH: حساب السر المشترك
      shared_point = model_verifying_key.pubkey.point * ephemeral_private.privkey.secret_multiplier
      shared_secret = shared_point.x().to_bytes(32, 'big')

      # اشتقاق مفتاح AES باستخدام HKDF
      hkdf = HKDF(
          algorithm=hashes.SHA256(),
          length=32,
          salt=None,
          info=HKDF_INFO,
      )
      aes_key = hkdf.derive(shared_secret)

      # توليد nonce عشوائي
      nonce = os.urandom(12)

      # التشفير باستخدام AES-GCM
      aesgcm = AESGCM(aes_key)
      ciphertext = aesgcm.encrypt(nonce, plaintext.encode('utf-8'), None)

      # الحصول على المفتاح العام المؤقت (غير مضغوط: 04 || x || y)
      ephemeral_public_bytes = b'\x04' + ephemeral_public.to_string()

      # الدمج: ephemeral_public (65 بايت) + nonce (12 بايت) + ciphertext
      result = ephemeral_public_bytes + nonce + ciphertext

      return result.hex()

  def encrypt_messages_for_e2ee(messages: list, model_public_key: str) -> list:
      """Encrypt user and system messages."""
      encrypted_messages = []
      for msg in messages:
          if msg['role'] in ('user', 'system'):
              encrypted_messages.append({
                  **msg,
                  'content': encrypt_message(msg['content'], model_public_key)
              })
          else:
              encrypted_messages.append(msg)
      return encrypted_messages
  ```
</CodeGroup>

### الخطوة 5: إرسال الطلب مع رؤوس E2EE

ضمِّن الرؤوس المطلوبة لتمكين معالجة E2EE.

| الرأس                         | الوصف                                         |
| ----------------------------- | --------------------------------------------- |
| `X-Venice-TEE-Client-Pub-Key` | مفتاحك العام المؤقت (hex غير مضغوط، 130 محرف) |
| `X-Venice-TEE-Model-Pub-Key`  | المفتاح العام للنموذج من التصديق              |
| `X-Venice-TEE-Signing-Algo`   | دائمًا `ecdsa`                                |

<CodeGroup>
  ```javascript JavaScript theme={"dark"}
  async function sendE2EERequest(messages, model, e2eeContext, apiKey) {
    // تشفير الرسائل
    const encryptedMessages = encryptMessagesForE2EE(messages, e2eeContext.modelPublicKey)

    const response = await fetch('https://api.venice.ai/api/v1/chat/completions', {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${apiKey}`,
        'Content-Type': 'application/json',
        // رؤوس E2EE
        'X-Venice-TEE-Client-Pub-Key': e2eeContext.publicKeyHex,
        'X-Venice-TEE-Model-Pub-Key': e2eeContext.modelPublicKey,
        'X-Venice-TEE-Signing-Algo': 'ecdsa',
      },
      body: JSON.stringify({
        model,
        messages: encryptedMessages,
        stream: true, // يتطلب E2EE البث المتدفق
      }),
    })

    return response
  }
  ```

  ```python Python theme={"dark"}
  import requests

  def send_e2ee_request(
      messages: list,
      model: str,
      e2ee_context: dict,
      api_key: str
  ) -> requests.Response:
      """Send an E2EE-encrypted chat completion request."""
      # تشفير الرسائل
      encrypted_messages = encrypt_messages_for_e2ee(
          messages,
          e2ee_context['model_public_key']
      )

      response = requests.post(
          'https://api.venice.ai/api/v1/chat/completions',
          headers={
              'Authorization': f'Bearer {api_key}',
              'Content-Type': 'application/json',
              # رؤوس E2EE
              'X-Venice-TEE-Client-Pub-Key': e2ee_context['public_key_hex'],
              'X-Venice-TEE-Model-Pub-Key': e2ee_context['model_public_key'],
              'X-Venice-TEE-Signing-Algo': 'ecdsa'
          },
          json={
              'model': model,
              'messages': encrypted_messages,
              'stream': True  # يتطلب E2EE البث المتدفق
          },
          stream=True
      )

      return response
  ```
</CodeGroup>

### الخطوة 6: فك تشفير أجزاء الاستجابة

تكون الاستجابات من نماذج E2EE أجزاءً مشفّرة بترميز hex. فك تشفير كل جزء باستخدام مفتاحك الخاص.

<CodeGroup>
  ```javascript JavaScript theme={"dark"}
  import { gcm } from '@noble/ciphers/aes.js'
  import { hkdf } from '@noble/hashes/hkdf.js'
  import { sha256 } from '@noble/hashes/sha2.js'
  import { ec as EC } from 'elliptic'

  const HKDF_INFO = new TextEncoder().encode('ecdsa_encryption')

  function hexToBytes(hex) {
    const h = hex.startsWith('0x') ? hex.slice(2) : hex
    const bytes = new Uint8Array(h.length / 2)
    for (let i = 0; i < bytes.length; i++) {
      bytes[i] = parseInt(h.substring(i * 2, i * 2 + 2), 16)
    }
    return bytes
  }

  function isHexEncrypted(s) {
    // الحد الأدنى: ephemeral_pub (65) + nonce (12) + tag (16) = 93 بايت = 186 محرف hex
    if (s.length < 186) return false
    return /^[0-9a-fA-F]+$/.test(s)
  }

  function decryptChunk(ciphertextHex, clientPrivateKey) {
    const raw = hexToBytes(ciphertextHex)

    // تحليل المكونات
    const serverEphemeralPubKey = raw.slice(0, 65)
    const nonce = raw.slice(65, 65 + 12)
    const ciphertext = raw.slice(65 + 12)

    // ECDH مع مفتاح الخادم المؤقت
    const ec = new EC('secp256k1')
    const clientKey = ec.keyFromPrivate(Buffer.from(clientPrivateKey))
    const serverKey = ec.keyFromPublic(Buffer.from(serverEphemeralPubKey))
    const sharedSecret = clientKey.derive(serverKey.getPublic())
    const sharedSecretBytes = new Uint8Array(sharedSecret.toArray('be', 32))

    // اشتقاق مفتاح AES
    const aesKey = hkdf(sha256, sharedSecretBytes, undefined, HKDF_INFO, 32)

    // فك التشفير
    const cipher = gcm(aesKey, nonce)
    const plaintext = cipher.decrypt(ciphertext)

    return new TextDecoder().decode(plaintext)
  }

  // معالجة الاستجابة المتدفقة
  async function processE2EEStream(response, clientPrivateKey) {
    const reader = response.body.getReader()
    const decoder = new TextDecoder()
    let fullContent = ''

    while (true) {
      const { done, value } = await reader.read()
      if (done) break

      const text = decoder.decode(value)
      const lines = text.split('\n')

      for (const line of lines) {
        if (!line.startsWith('data: ')) continue
        const data = line.slice(6)
        if (data === '[DONE]') continue

        try {
          const chunk = JSON.parse(data)
          const content = chunk.choices?.[0]?.delta?.content

          if (content && isHexEncrypted(content)) {
            const decrypted = decryptChunk(content, clientPrivateKey)
            fullContent += decrypted
            process.stdout.write(decrypted) // إخراج في الوقت الفعلي
          } else if (content) {
            fullContent += content
            process.stdout.write(content)
          }
        } catch (e) {
          // تخطّي الأجزاء المشوّهة
        }
      }
    }

    return fullContent
  }
  ```

  ```python Python theme={"dark"}
  from cryptography.hazmat.primitives.ciphers.aead import AESGCM
  from cryptography.hazmat.primitives.kdf.hkdf import HKDF
  from cryptography.hazmat.primitives import hashes
  from ecdsa import SECP256k1, VerifyingKey, SigningKey
  import json
  import re

  HKDF_INFO = b'ecdsa_encryption'

  def is_hex_encrypted(s: str) -> bool:
      """Check if string looks like hex-encrypted content."""
      if len(s) < 186:  # الحد الأدنى: 65 + 12 + 16 = 93 بايت = 186 hex
          return False
      return bool(re.match(r'^[0-9a-fA-F]+$', s))

  def decrypt_chunk(ciphertext_hex: str, client_private_key: bytes) -> str:
      """Decrypt an E2EE response chunk."""
      raw = bytes.fromhex(ciphertext_hex)

      # تحليل المكونات
      server_ephemeral_pub = raw[:65]
      nonce = raw[65:77]
      ciphertext = raw[77:]

      # تحليل المفتاح العام المؤقت للخادم (تخطي بادئة 04)
      server_verifying_key = VerifyingKey.from_string(
          server_ephemeral_pub[1:],
          curve=SECP256k1
      )

      # إعادة بناء المفتاح الخاص للعميل
      client_signing_key = SigningKey.from_string(client_private_key, curve=SECP256k1)

      # ECDH: حساب السر المشترك
      shared_point = server_verifying_key.pubkey.point * client_signing_key.privkey.secret_multiplier
      shared_secret = shared_point.x().to_bytes(32, 'big')

      # اشتقاق مفتاح AES
      hkdf = HKDF(
          algorithm=hashes.SHA256(),
          length=32,
          salt=None,
          info=HKDF_INFO,
      )
      aes_key = hkdf.derive(shared_secret)

      # فك التشفير
      aesgcm = AESGCM(aes_key)
      plaintext = aesgcm.decrypt(nonce, ciphertext, None)

      return plaintext.decode('utf-8')

  def process_e2ee_stream(response, client_private_key: bytes) -> str:
      """Process streaming E2EE response."""
      full_content = ''

      for line in response.iter_lines():
          if not line:
              continue

          line_str = line.decode('utf-8')
          if not line_str.startswith('data: '):
              continue

          data = line_str[6:]
          if data == '[DONE]':
              continue

          try:
              chunk = json.loads(data)
              content = chunk.get('choices', [{}])[0].get('delta', {}).get('content', '')

              if content and is_hex_encrypted(content):
                  decrypted = decrypt_chunk(content, client_private_key)
                  full_content += decrypted
                  print(decrypted, end='', flush=True)  # إخراج في الوقت الفعلي
              elif content:
                  full_content += content
                  print(content, end='', flush=True)
          except json.JSONDecodeError:
              pass

      print()  # سطر جديد نهائي
      return full_content
  ```
</CodeGroup>

### مثال عملي كامل

<Tabs>
  <Tab title="JavaScript">
    ```javascript theme={"dark"}
    import elliptic from 'elliptic';
    import { gcm } from '@noble/ciphers/aes.js';
    import { hkdf } from '@noble/hashes/hkdf.js';
    import { sha256 } from '@noble/hashes/sha2.js';
    import crypto from 'crypto';

    const EC = elliptic.ec;

    const API_KEY = process.env.API_KEY_VENICE;
    const BASE_URL = 'https://api.venice.ai/api/v1';
    const MODEL = 'e2ee-qwen3-5-122b-a10b';
    const HKDF_INFO = new TextEncoder().encode('ecdsa_encryption');

    function hexToBytes(hex) {
      const bytes = new Uint8Array(hex.length / 2);
      for (let i = 0; i < bytes.length; i++) {
        bytes[i] = parseInt(hex.substring(i * 2, i * 2 + 2), 16);
      }
      return bytes;
    }

    async function main() {
      // الخطوة 1: توليد زوج مفاتيح مؤقت
      console.log('🔑 Generating ephemeral key pair...');
      const ec = new EC('secp256k1');
      const keyPair = ec.genKeyPair();
      const clientPublicKeyHex = keyPair.getPublic('hex');

      // الخطوة 2: جلب التصديق والتحقق منه
      console.log('🔍 Fetching TEE attestation...');
      const clientNonce = crypto.randomBytes(32).toString('hex'); // مطلوب 32 بايت
      const attestationRes = await fetch(
        `${BASE_URL}/tee/attestation?model=${MODEL}&nonce=${clientNonce}`,
        { headers: { Authorization: `Bearer ${API_KEY}` } }
      );
      const attestation = await attestationRes.json();

      if (attestation.verified !== true || attestation.nonce !== clientNonce) {
        throw new Error('Attestation verification failed');
      }

      const modelPublicKey = attestation.signing_key || attestation.signing_public_key;
      console.log('✅ TEE attestation verified');

      // الخطوة 3: تشفير الرسالة
      console.log('🔐 Encrypting message...');
      const plaintext = 'What is 2+2? Answer briefly.';

      // تطبيع وتحليل المفتاح العام للنموذج
      let normalizedKey = modelPublicKey;
      if (!normalizedKey.startsWith('04') && normalizedKey.length === 128) {
        normalizedKey = '04' + normalizedKey;
      }

      const modelKey = ec.keyFromPublic(normalizedKey, 'hex');
      const ephemeralKeyPair = ec.genKeyPair();
      const sharedSecret = ephemeralKeyPair.derive(modelKey.getPublic());
      const sharedSecretBytes = new Uint8Array(sharedSecret.toArray('be', 32));
      const aesKey = hkdf(sha256, sharedSecretBytes, undefined, HKDF_INFO, 32);
      const nonce = crypto.randomBytes(12);
      const cipher = gcm(aesKey, nonce);
      const encrypted = cipher.encrypt(new TextEncoder().encode(plaintext));
      const ephemeralPublic = new Uint8Array(ephemeralKeyPair.getPublic(false, 'array'));

      const result = new Uint8Array(65 + 12 + encrypted.length);
      result.set(ephemeralPublic, 0);
      result.set(nonce, 65);
      result.set(encrypted, 77);

      const encryptedContent = Buffer.from(result).toString('hex');
      const messages = [{ role: 'user', content: encryptedContent }];

      // الخطوة 4: إرسال طلب E2EE
      console.log('📤 Sending encrypted request...');
      const response = await fetch(`${BASE_URL}/chat/completions`, {
        method: 'POST',
        headers: {
          Authorization: `Bearer ${API_KEY}`,
          'Content-Type': 'application/json',
          'X-Venice-TEE-Client-Pub-Key': clientPublicKeyHex,
          'X-Venice-TEE-Model-Pub-Key': modelPublicKey,
          'X-Venice-TEE-Signing-Algo': 'ecdsa',
        },
        body: JSON.stringify({ model: MODEL, messages, stream: true }),
      });

      // الخطوة 5: فك تشفير الاستجابة
      console.log('📥 Decrypting response...\n');
      const reader = response.body.getReader();
      const decoder = new TextDecoder();

      while (true) {
        const { done, value } = await reader.read();
        if (done) break;

        const text = decoder.decode(value);
        for (const line of text.split('\n')) {
          if (!line.startsWith('data: ') || line.includes('[DONE]')) continue;

          try {
            const chunk = JSON.parse(line.slice(6));
            const content = chunk.choices?.[0]?.delta?.content;
            if (!content) continue;

            if (/^[0-9a-fA-F]+$/.test(content) && content.length >= 186) {
              // فك التشفير
              const raw = hexToBytes(content);
              const serverEphemeralPub = raw.slice(0, 65);
              const nonce = raw.slice(65, 77);
              const ciphertext = raw.slice(77);

              const serverKey = ec.keyFromPublic(Buffer.from(serverEphemeralPub));
              const sharedSecret = keyPair.derive(serverKey.getPublic());
              const aesKey = hkdf(sha256, new Uint8Array(sharedSecret.toArray('be', 32)), undefined, HKDF_INFO, 32);
              const cipher = gcm(aesKey, nonce);
              const plaintext = new TextDecoder().decode(cipher.decrypt(ciphertext));
              process.stdout.write(plaintext);
            } else {
              process.stdout.write(content);
            }
          } catch {}
        }
      }

      console.log('\n\n🔐 Response decrypted end-to-end');
    }

    main().catch(console.error);
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={"dark"}
    #!/usr/bin/env python3
    """Complete E2EE implementation example for Venice AI API."""

    import os
    import json
    import secrets
    import requests
    from cryptography.hazmat.primitives.ciphers.aead import AESGCM
    from cryptography.hazmat.primitives.kdf.hkdf import HKDF
    from cryptography.hazmat.primitives import hashes
    from ecdsa import SECP256k1, VerifyingKey, SigningKey

    API_KEY = os.environ.get('API_KEY_VENICE')
    BASE_URL = 'https://api.venice.ai/api/v1'
    MODEL = 'e2ee-qwen3-5-122b-a10b'
    HKDF_INFO = b'ecdsa_encryption'

    def main():
        # الخطوة 1: توليد زوج مفاتيح مؤقت
        print('🔑 Generating ephemeral key pair...')
        private_key = SigningKey.generate(curve=SECP256k1)
        public_key = private_key.get_verifying_key()
        client_public_key_hex = (b'\x04' + public_key.to_string()).hex()

        # الخطوة 2: جلب التصديق والتحقق منه
        print('🔍 Fetching TEE attestation...')
        client_nonce = secrets.token_hex(32)  # مطلوب 32 بايت
        attestation_res = requests.get(
            f'{BASE_URL}/tee/attestation',
            params={'model': MODEL, 'nonce': client_nonce},
            headers={'Authorization': f'Bearer {API_KEY}'},
            timeout=30
        )
        attestation = attestation_res.json()

        if attestation.get('verified') != True or attestation.get('nonce') != client_nonce:
            raise ValueError('Attestation verification failed')

        model_public_key = attestation.get('signing_key') or attestation.get('signing_public_key')
        print(f'✅ TEE attestation verified (provider: {attestation.get("tee_provider", "unknown")})')

        # الخطوة 3: تشفير الرسالة
        print('🔐 Encrypting message...')
        plaintext = 'What is 2+2? Answer briefly.'

        # تطبيع المفتاح العام
        key_hex = model_public_key
        if not key_hex.startswith('04') and len(key_hex) == 128:
            key_hex = '04' + key_hex

        model_key_bytes = bytes.fromhex(key_hex)
        model_verifying_key = VerifyingKey.from_string(model_key_bytes[1:], curve=SECP256k1)

        # ECDH
        ephemeral_private = SigningKey.generate(curve=SECP256k1)
        ephemeral_public = ephemeral_private.get_verifying_key()
        shared_point = model_verifying_key.pubkey.point * ephemeral_private.privkey.secret_multiplier
        shared_secret = shared_point.x().to_bytes(32, 'big')

        # اشتقاق مفتاح AES
        hkdf = HKDF(algorithm=hashes.SHA256(), length=32, salt=None, info=HKDF_INFO)
        aes_key = hkdf.derive(shared_secret)

        # التشفير
        nonce = os.urandom(12)
        aesgcm = AESGCM(aes_key)
        ciphertext = aesgcm.encrypt(nonce, plaintext.encode('utf-8'), None)

        ephemeral_public_bytes = b'\x04' + ephemeral_public.to_string()
        result = ephemeral_public_bytes + nonce + ciphertext
        encrypted_content = result.hex()

        messages = [{'role': 'user', 'content': encrypted_content}]

        # الخطوة 4: إرسال طلب E2EE
        print('📤 Sending encrypted request...')
        response = requests.post(
            f'{BASE_URL}/chat/completions',
            headers={
                'Authorization': f'Bearer {API_KEY}',
                'Content-Type': 'application/json',
                'X-Venice-TEE-Client-Pub-Key': client_public_key_hex,
                'X-Venice-TEE-Model-Pub-Key': model_public_key,
                'X-Venice-TEE-Signing-Algo': 'ecdsa'
            },
            json={'model': MODEL, 'messages': messages, 'stream': True},
            stream=True,
            timeout=60
        )

        # الخطوة 5: فك تشفير الاستجابة
        print('📥 Decrypting response...\n')

        for line in response.iter_lines():
            if not line:
                continue
            line_str = line.decode('utf-8')
            if not line_str.startswith('data: ') or '[DONE]' in line_str:
                continue

            try:
                chunk = json.loads(line_str[6:])
                content = chunk.get('choices', [{}])[0].get('delta', {}).get('content', '')
                if not content:
                    continue

                # تحقق إذا كان مشفّرًا
                if len(content) >= 186 and all(c in '0123456789abcdefABCDEF' for c in content):
                    raw = bytes.fromhex(content)
                    server_ephemeral_pub = raw[:65]
                    nonce = raw[65:77]
                    ciphertext = raw[77:]

                    server_verifying_key = VerifyingKey.from_string(server_ephemeral_pub[1:], curve=SECP256k1)
                    shared_point = server_verifying_key.pubkey.point * private_key.privkey.secret_multiplier
                    shared_secret = shared_point.x().to_bytes(32, 'big')

                    hkdf = HKDF(algorithm=hashes.SHA256(), length=32, salt=None, info=HKDF_INFO)
                    aes_key = hkdf.derive(shared_secret)

                    aesgcm = AESGCM(aes_key)
                    plaintext = aesgcm.decrypt(nonce, ciphertext, None)
                    print(plaintext.decode('utf-8'), end='', flush=True)
                else:
                    print(content, end='', flush=True)
            except Exception:
                pass

        print('\n\n🔐 Response decrypted end-to-end')

    if __name__ == '__main__':
        main()
    ```
  </Tab>
</Tabs>

### قيود E2EE

<Warning>
  يفرض E2EE بعض القيود نتيجة متطلبات التشفير:
</Warning>

| الميزة            | الحالة                                |
| ----------------- | ------------------------------------- |
| البث المتدفق      | **مطلوب** (لا يُدعم عدم البث)         |
| البحث على الويب   | **معطّل** (قد يكشف المحتوى)           |
| تحميل الملفات     | **غير مدعوم**                         |
| استدعاء الدوال    | **غير مدعوم**                         |
| موجّه نظام Venice | **معطّل** (يجب تشفيره من جانب العميل) |

### أفضل ممارسات الأمان

1. **ولّد أزواج مفاتيح جديدة لكل جلسة** — لا تُعد استخدام المفاتيح المؤقتة
2. **املأ المفاتيح الخاصة بالأصفار** — امسح بايتات المفتاح الخاص من الذاكرة عند الانتهاء
3. **تحقق من التصديق** — تأكد دائمًا من `verified: true` ومطابقة nonce
4. **افحص وضع التصحيح** — ارفض التصديقات من جيوب التصحيح
5. **استخدم البث المتدفق** — يتطلب E2EE البث للتجزئة الصحيحة للتشفير
6. **عالج الأخطاء بأناقة** — لا تُظهر أخطاء فك التشفير للمستخدمين
7. **استخدم nonce بحجم 32 بايت** — تتطلب مزوّدات TEE 32 بايت بالضبط

## أفضل الممارسات

<AccordionGroup>
  <Accordion title="تحقق دائمًا من التصديق في الإنتاج">
    لا تكتفِ بالثقة في استجابة `verified: true`. قم بتحليل اقتباس Intel TDX من جانب العميل وتحقق من أن القياسات تطابق القيم المتوقعة. بالنسبة إلى وحدات معالجة الرسومات من NVIDIA، تحقق من التصديق عبر خدمة التحقق من NVIDIA.
  </Accordion>

  <Accordion title="استخدم nonces جديدة">
    ولّد دائمًا nonce عشوائيًا جديدًا لكل طلب تصديق. يمنع ذلك هجمات إعادة التشغيل التي يمكن للمهاجم فيها تقديم تصديق قديم.
  </Accordion>

  <Accordion title="تحقق من ربط المفتاح">
    يجب أن يكون مفتاح التوقيع مرتبطًا بحقل TDX REPORTDATA. وهذا يُثبت أن المفتاح وُلّد داخل الجيب.
  </Accordion>

  <Accordion title="افحص وضع التصحيح">
    تحقق من أن تصديق TDX لا يحتوي على أعلام تصحيح مضبوطة. يمكن فحص جيب التصحيح ولا ينبغي الوثوق به في الإنتاج.
  </Accordion>

  <Accordion title="استخدم SDK الخاصة بنا لـ E2EE">
    يتطلب E2EE تنفيذًا تشفيريًا دقيقًا. استخدم SDK الرسمية الخاصة بنا بدلًا من تنفيذ البروتوكول بنفسك.
  </Accordion>
</AccordionGroup>

## التحقق من قدرات النموذج

يمكنك التحقق مما إذا كان النموذج يدعم TEE أو E2EE عبر نقطة نهاية النماذج:

<CodeGroup>
  ```bash cURL theme={"dark"}
  curl https://api.venice.ai/api/v1/models \
    -H "Authorization: Bearer $API_KEY_VENICE" | jq '.data[] | select(.model_spec.capabilities.supportsTeeAttestation == true or .model_spec.capabilities.supportsE2EE == true) | {id, tee: .model_spec.capabilities.supportsTeeAttestation, e2ee: .model_spec.capabilities.supportsE2EE}'
  ```

  ```python Python theme={"dark"}
  models = client.models.list()

  for model in models.data:
      caps = getattr(model, 'model_spec', {}).get('capabilities', {})
      if caps.get('supportsTeeAttestation') or caps.get('supportsE2EE'):
          print(f"{model.id}: TEE={caps.get('supportsTeeAttestation')}, E2EE={caps.get('supportsE2EE')}")
  ```
</CodeGroup>

## معالجة الأخطاء

| الخطأ                                 | السبب                            | الحل                             |
| ------------------------------------- | -------------------------------- | -------------------------------- |
| `TEE attestation verification failed` | لم يجتز التصديق التحقق           | أعد المحاولة أو اتصل بالدعم      |
| `Attestation nonce mismatch`          | هجوم إعادة تشغيل محتمل           | ولّد nonce جديدًا                |
| `TDX debug mode detected`             | الجيب في وضع التصحيح             | لا تستخدمه في الإنتاج            |
| `Failed to decrypt field`             | فشل فك تشفير E2EE من جانب الخادم | راجع تنفيذ التشفير لديك          |
| `E2EE requires streaming`             | طلب غير متدفق إلى نموذج E2EE     | اضبط `stream: true`              |
| `Encrypted field is not valid hex`    | إرسال نص عادي مع رؤوس E2EE       | شفّر جميع رسائل user/system      |
| `Invalid public key`                  | تنسيق مفتاح خاطئ                 | استخدم 130 محرف hex يبدأ بـ `04` |

## استكشاف الأخطاء وإصلاحها

<AccordionGroup>
  <Accordion title="502 Bad Gateway أو 'Nonce must be exactly 32 bytes'">
    طول الـ nonce غير صحيح. تتطلب مزوّدات TEE **32 بايت (64 محرف hex)** بالضبط.

    * استخدم `crypto.randomBytes(32).toString('hex')` (JS) أو `secrets.token_hex(32)` (Python)
    * خطأ شائع: `secrets.token_hex(16)` يُنتج 32 محرف hex (16 بايت)، وليس 32 بايت
  </Accordion>

  <Accordion title="فشل التحقق من التصديق">
    * تأكد من أن النموذج يدعم E2EE (`supportsE2EE: true`)
    * تحقق من أن مفتاح API صالح ولديه وصول إلى النموذج المطلوب
    * تحقق من اتصال الشبكة بـ Venice API
  </Accordion>

  <Accordion title="فشل فك التشفير">
    * تأكد من أنك تستخدم نفس المفتاح الخاص الذي ولّد المفتاح العام المرسل في الرؤوس
    * تحقق من أن محتوى الاستجابة مشفّر فعلًا بترميز hex (E2EE نشط)
    * تأكد من أن المفتاح العام للنموذج يطابق ما استُخدم للتشفير
  </Accordion>

  <Accordion title="Encrypted field is not valid hex">
    * يجب تشفير جميع رسائل دور `user` و`system` عند وجود رؤوس E2EE
    * تحقق من أن المحتوى المشفّر يجتاز التحقق `isValidEncrypted()` (الحد الأدنى 186 محرف hex)
    * تأكد من أن إخراج التشفير hex بأحرف صغيرة دون أي بادئات
  </Accordion>

  <Accordion title="أخطاء المفتاح العام غير الصالح">
    * يجب أن يكون المفتاح العام للعميل بطول **130 محرف hex** بالضبط ويبدأ بـ `04`
    * استخدم المساعد `validateClientPubkey()` للتحقق من التنسيق قبل الإرسال
    * تأكد من استخدام تنسيق المفتاح العام غير المضغوط (65 بايت = 130 محرف hex)
  </Accordion>

  <Accordion title="النموذج غير موجود">
    * تحقق من صحة معرّف النموذج وأنه يدعم E2EE
    * استخدم نقطة النهاية `/models` للتحقق من نماذج E2EE المتاحة
  </Accordion>
</AccordionGroup>

## الموارد

* [وثائق Intel TDX](https://www.intel.com/content/www/us/en/developer/tools/trust-domain-extensions/documentation.html)
* [NVIDIA Confidential Computing](https://developer.nvidia.com/confidential-computing)
