diff --git a/docs/SKIN_DEVELOPMENT.md b/docs/SKIN_DEVELOPMENT.md index 3d26427..9393c5a 100644 --- a/docs/SKIN_DEVELOPMENT.md +++ b/docs/SKIN_DEVELOPMENT.md @@ -124,7 +124,7 @@ assets/brand.woff2 # 可选:自带字体 | 页面区域 | `data-ws-part` | | --- | --- | | 通用 | `app`、`app.toast`、`control`、`skin.trigger`、`skin.menu`、`skin.option`、`language.trigger`、`language.menu`、`language.option` | -| 首页 | `home`、`home.header`、`home.brand`、`home.header-tools`、`home.gateway-status`、`home.content`、`home.hero`、`home.hero.eyebrow`、`home.hero.title`、`home.hero.description`、`home.features`、`home.feature`、`home.visitors`、`home.join-card`、`home.join-card.waveform`、`home.join-card.sonar`、`home.join-title`、`home.join-description`、`home.notice`、`home.form`、`home.server-target`、`home.field-label`、`home.field`、`home.relay-choice`、`home.relay-choice.copy`、`home.server-history`、`home.server-history.group`、`home.favorite-toggle`、`home.identity`、`home.connect`、`home.security-note`、`home.footer`、`home.community-dialog` | +| 首页 | `home`、`home.header`、`home.brand`、`home.header-tools`、`home.gateway-status`、`home.content`、`home.hero`、`home.hero.eyebrow`、`home.hero.title`、`home.hero.description`、`home.features`、`home.feature`、`home.visitors`、`home.join-card`、`home.join-card.waveform`、`home.join-card.sonar`、`home.join-title`、`home.join-description`、`home.notice`、`home.form`、`home.server-target`、`home.field-label`、`home.field`、`home.relay-choice`、`home.relay-choice.copy`、`home.server-history`、`home.server-history.group`、`home.favorite-toggle`、`home.identity`、`home.identity-actions`、`home.identity-import.open`、`home.identity-export.button`、`home.identity-import-dialog`、`home.identity-import.header`、`home.identity-import.close`、`home.identity-import.textarea`、`home.identity-import.drop-zone`、`home.identity-import.file-button`、`home.identity-import.error`、`home.identity-import.security`、`home.identity-import.footer`、`home.identity-import.cancel`、`home.identity-import.submit`、`home.connect`、`home.security-note`、`home.footer`、`home.community-dialog` | | 语音工作区 | `voice.shell`、`voice.workspace`、`voice.header`、`voice.header-actions`、`voice.breadcrumbs`、`voice.performance`、`voice.performance.panel`、`voice.performance.route`、`voice.performance.metrics`、`voice.performance.status`、`voice.performance.webrtc-stats`、`voice.connection-status`、`voice.audio-status`、`voice.poke`、`voice.scroll`、`voice.content`、`voice.activity`、`voice.activity.artwork`、`voice.activity-heading`、`voice.screen-share-error`、`voice.members`、`voice.members.empty`、`voice.member`、`voice.member.avatar-wrap`、`voice.member.avatar`、`voice.member.name`、`voice.member.status`、`voice.member.live-indicator`、`voice.member.stop-share`、`voice.member.share-actions`、`voice.member-panel`、`voice.member-panel.heading`、`voice.member-panel.search`、`voice.member-panel.channels`、`voice.channel-group`、`voice.channel-group.heading`、`voice.channel-group.members`、`voice.member-row`、`voice.member-row.avatar`、`voice.member-row.copy`、`voice.member-row.flags`、`voice.member-row.volume`、`voice.whisper-strip`、`voice.audio-dock`、`voice.audio-dock.microphone`、`voice.audio-dock.microphone-panel`、`voice.audio-dock.output`、`voice.audio-dock.output-panel`、`voice.audio-settings`、`voice.mobile-more`、`voice.mobile-nav` | | 聊天与菜单 | `voice.chat`、`voice.chat.tabs`、`voice.chat.tab`、`voice.chat.heading`、`voice.chat.messages`、`voice.chat.event`、`voice.chat.message`、`voice.chat.message-avatar`、`voice.chat.message-body`、`voice.chat.message-bubble`、`voice.chat.empty`、`voice.chat.composer`、`voice.context-menu-backdrop`、`voice.context-menu`、`voice.context-menu.header`、`voice.context-menu.move-submenu` | | 屏幕共享 | `voice.screen-share-settings`、`voice.screen-share-settings.heading`、`voice.screen-share-settings.fields`、`voice.screen-share-settings.note`、`voice.screen-share-settings.actions`、`voice.screen-player`、`voice.screen-player.stage`、`voice.screen-player.video`、`voice.screen-player.placeholder`、`voice.screen-player.exit`、`voice.screen-player.viewers`、`voice.screen-player.viewer-avatar`、`voice.screen-player.live`、`voice.screen-player.source`、`voice.screen-player.controls`、`voice.screen-player.volume`、`voice.screen-player.fullscreen` | @@ -132,6 +132,8 @@ assets/brand.woff2 # 可选:自带字体 `voice.member.avatar` 是语音活动区头像;`voice.member-row.avatar` 是右侧成员树头像。状态属性还会使用 `current`、`drag-over`、`dragging`、`self`、`events-empty` 和 `messages-empty`。当前根节点以及屏幕共享播放器、弹窗、菜单都属于同一皮肤作用域。 +首页身份选项支持导入 TeamSpeak `.ini` 或身份字段,并可导出为 TeamSpeak `.ini`;导入弹窗解析身份的过程在浏览器本地完成。自定义皮肤可以分别调整身份操作按钮、粘贴区、拖放区域、安全提示和弹窗按钮,但不得隐藏或弱化权限继承与私钥安全提示。 + `voice.activity.artwork` 是位于语音活动区内容上方的固定装饰平面。皮肤可以在其上绘制带透明背景的立绘,让角色压住成员卡片或直播画面的边缘;平面本身不占布局空间、不拦截点击,成员和播放器控件仍保持可交互。只通过背景图及背景定位/缩放来适配素材,不改变其定位和层级。 `voice.member-panel` 的 `::before` 是成员栏耳机/场景插画层,宿主已固定它的尺寸、位置、透视和前后层级;皮肤只需提供透明背景素材并调整背景显示、滤镜或阴影,不能自行定位或改变尺寸。消息空状态的 `::before` / `::after` 预留给气泡等小型装饰,宿主负责形状位置;皮肤可以绘制边框、底色和点状背景,但标题和说明文字仍由 WebSpeak 翻译并保持可见。 diff --git a/package.json b/package.json index 3673559..e666349 100644 --- a/package.json +++ b/package.json @@ -11,7 +11,7 @@ "scripts": { "dev": "tsx src/index.ts", "build": "tsc", - "test": "node --import tsx --test src/admin/skin-registry.test.ts src/security/open-target-policy.test.ts src/server/visitor-count.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts scripts/docker-healthcheck.test.mjs web/src/services/skin-catalog.test.ts web/src/services/skin-pack.test.ts", + "test": "node --import tsx --test src/admin/skin-registry.test.ts src/security/open-target-policy.test.ts src/server/visitor-count.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts scripts/docker-healthcheck.test.mjs web/src/services/skin-catalog.test.ts web/src/services/skin-pack.test.ts web/src/services/identity-import.test.ts", "start": "node dist/index.js", "web:dev": "cd web && npx vite --host", "web:build": "cd web && npx vite build", diff --git a/web/src/i18n/web-client.ts b/web/src/i18n/web-client.ts index 6720414..0cb1cd1 100644 --- a/web/src/i18n/web-client.ts +++ b/web/src/i18n/web-client.ts @@ -55,6 +55,25 @@ export const webClientTranslations: Record> = { rememberIdentityHint: "仅保存在本设备,用于下次连接时保持身份。", rememberIdentityConcurrentWarning: "同一浏览器只能同时使用一条保持身份的连接;要开启第二条,请取消勾选或使用另一个浏览器。", identityOptions: "设备身份选项", + identityImport: "导入身份", + identityExport: "导出身份", + identityImportTitle: "导入 TeamSpeak 身份", + identityImportDescription: "粘贴 TeamSpeak 导出的 identity 字段或 .ini 文件内容,也可以拖入文件。", + identityImportPlaceholder: "粘贴 identity=... 或完整的 TeamSpeak 身份 .ini 内容", + identityDropZone: "将 .ini 或文本文件拖到这里", + identityChooseFile: "选择文件", + identityImportSecurity: "身份文件包含可继承服务器权限的私钥。导入解析仅在本机完成;连接时身份会发送给当前 WebSpeak 网关用于登录。请勿分享导出的文件。", + identityImportSubmit: "解析并导入", + identityImportCancel: "取消", + identityImportSuccess: "TeamSpeak 身份已导入并保存到本设备", + identityExportSuccess: "身份已导出为 TeamSpeak .ini 文件", + identityExportError: "身份导出失败,请重试。", + identityImportErrorEmpty: "请粘贴身份内容或拖入 .ini 文件。", + identityImportErrorTooLarge: "身份文本超过 128 KB,无法导入。", + identityImportErrorMultiple: "文件中包含多个身份,请一次粘贴或导入一个身份。", + identityImportErrorMalformed: "无法识别身份格式。请使用 TeamSpeak 导出的 .ini、identity 字段或 WebSpeak 身份串。", + identityImportErrorInvalidKey: "身份数据无效或已损坏,请检查导出内容。", + identityImportErrorUnsupported: "此浏览器不支持本地身份解析所需的安全加密功能。", localPersistenceUnavailable: "当前浏览器无法使用持久化存储,本次将使用临时身份。", favoriteServers: "常用服务器", recentServers: "最近连接", @@ -422,6 +441,25 @@ export const webClientTranslations: Record> = { rememberIdentityHint: "Stored only on this device and reused on the next connection.", rememberIdentityConcurrentWarning: "Only one connection can use this identity in the same browser. Clear this option for a second connection or use another browser.", identityOptions: "Device identity options", + identityImport: "Import identity", + identityExport: "Export identity", + identityImportTitle: "Import TeamSpeak identity", + identityImportDescription: "Paste the identity field or .ini contents exported by TeamSpeak, or drop the file here.", + identityImportPlaceholder: "Paste identity=... or the full TeamSpeak identity .ini contents", + identityDropZone: "Drop a .ini or text file here", + identityChooseFile: "Choose file", + identityImportSecurity: "Identity files contain a private key that can inherit server permissions. Import parsing stays in this browser; when connecting, the identity is sent to the WebSpeak gateway you are using to sign in. Do not share exported files.", + identityImportSubmit: "Parse and import", + identityImportCancel: "Cancel", + identityImportSuccess: "TeamSpeak identity imported and saved on this device", + identityExportSuccess: "Identity exported as a TeamSpeak .ini file", + identityExportError: "Identity export failed. Please try again.", + identityImportErrorEmpty: "Paste identity data or drop a .ini file first.", + identityImportErrorTooLarge: "Identity text exceeds 128 KB and cannot be imported.", + identityImportErrorMultiple: "The file contains multiple identities. Import one identity at a time.", + identityImportErrorMalformed: "Unrecognized identity format. Use a TeamSpeak .ini, identity field, or WebSpeak identity string.", + identityImportErrorInvalidKey: "The identity data is invalid or damaged. Check the exported content.", + identityImportErrorUnsupported: "This browser does not support the secure cryptography needed to parse identities locally.", localPersistenceUnavailable: "Persistent browser storage is unavailable; this session will use an ephemeral identity.", favoriteServers: "Favorites", recentServers: "Recent servers", @@ -792,6 +830,25 @@ webClientTranslations.de = { rememberIdentityHint: "Wird nur auf diesem Gerät gespeichert und bei der nächsten Verbindung wiederverwendet.", rememberIdentityConcurrentWarning: "Dieselbe Identität kann in einem Browser nur eine Verbindung gleichzeitig verwenden. Deaktiviere die Option für eine zweite Verbindung oder nutze einen anderen Browser.", identityOptions: "Identitätsoptionen des Geräts", + identityImport: "Identität importieren", + identityExport: "Identität exportieren", + identityImportTitle: "TeamSpeak-Identität importieren", + identityImportDescription: "Füge das von TeamSpeak exportierte identity-Feld oder den .ini-Inhalt ein, oder ziehe die Datei hierher.", + identityImportPlaceholder: "identity=... oder den vollständigen Inhalt der TeamSpeak-Identitäts-.ini einfügen", + identityDropZone: ".ini- oder Textdatei hier ablegen", + identityChooseFile: "Datei auswählen", + identityImportSecurity: "Identitätsdateien enthalten einen privaten Schlüssel, mit dem Serverberechtigungen übernommen werden können. Der Import wird lokal im Browser verarbeitet; beim Verbinden wird die Identität zur Anmeldung an das verwendete WebSpeak-Gateway gesendet. Exportierte Dateien nicht weitergeben.", + identityImportSubmit: "Prüfen und importieren", + identityImportCancel: "Abbrechen", + identityImportSuccess: "TeamSpeak-Identität importiert und auf diesem Gerät gespeichert", + identityExportSuccess: "Identität als TeamSpeak-.ini-Datei exportiert", + identityExportError: "Identität konnte nicht exportiert werden. Bitte versuche es erneut.", + identityImportErrorEmpty: "Füge Identitätsdaten ein oder lege zuerst eine .ini-Datei ab.", + identityImportErrorTooLarge: "Der Identitätstext ist größer als 128 KB und kann nicht importiert werden.", + identityImportErrorMultiple: "Die Datei enthält mehrere Identitäten. Bitte jeweils nur eine importieren.", + identityImportErrorMalformed: "Unbekanntes Format. Verwende eine TeamSpeak-.ini-Datei, ein identity-Feld oder eine WebSpeak-Identitätszeichenfolge.", + identityImportErrorInvalidKey: "Die Identitätsdaten sind ungültig oder beschädigt. Prüfe den Export.", + identityImportErrorUnsupported: "Dieser Browser unterstützt die sichere lokale Identitätsverarbeitung nicht.", localPersistenceUnavailable: "Dauerhafter Browserspeicher ist nicht verfügbar; diese Sitzung verwendet eine temporäre Identität.", favoriteServers: "Favoriten", recentServers: "Zuletzt verwendet", @@ -1189,6 +1246,25 @@ webClientTranslations.ru = { rememberIdentityHint: "Хранится только на этом устройстве и используется при следующем подключении.", rememberIdentityConcurrentWarning: "Одна личность может использоваться только одним подключением в этом браузере. Для второго подключения отключите эту опцию или используйте другой браузер.", identityOptions: "Настройки личности устройства", + identityImport: "Импорт личности", + identityExport: "Экспорт личности", + identityImportTitle: "Импорт личности TeamSpeak", + identityImportDescription: "Вставьте поле identity или содержимое .ini, экспортированное из TeamSpeak, либо перетащите файл сюда.", + identityImportPlaceholder: "Вставьте identity=... или полное содержимое файла .ini TeamSpeak", + identityDropZone: "Перетащите сюда файл .ini или текстовый файл", + identityChooseFile: "Выбрать файл", + identityImportSecurity: "Файл личности содержит закрытый ключ, позволяющий наследовать права на сервере. Импорт обрабатывается локально; при подключении личность отправляется используемому шлюзу WebSpeak для входа. Не передавайте экспортированный файл другим.", + identityImportSubmit: "Проверить и импортировать", + identityImportCancel: "Отмена", + identityImportSuccess: "Личность TeamSpeak импортирована и сохранена на этом устройстве", + identityExportSuccess: "Личность экспортирована в файл TeamSpeak .ini", + identityExportError: "Не удалось экспортировать личность. Повторите попытку.", + identityImportErrorEmpty: "Вставьте данные личности или перетащите файл .ini.", + identityImportErrorTooLarge: "Текст личности превышает 128 КБ и не может быть импортирован.", + identityImportErrorMultiple: "Файл содержит несколько личностей. Импортируйте их по одной.", + identityImportErrorMalformed: "Неизвестный формат. Используйте файл TeamSpeak .ini, поле identity или строку WebSpeak.", + identityImportErrorInvalidKey: "Данные личности недействительны или повреждены. Проверьте экспорт.", + identityImportErrorUnsupported: "Браузер не поддерживает безопасную криптографию для локального разбора личности.", enterVoice: "Войти в голосовое пространство", connectionAuthorized: "Данные подключения используются только для этой голосовой сессии", recentServers: "Недавние серверы", @@ -1343,6 +1419,25 @@ webClientTranslations.ja = { rememberIdentityHint: "この端末だけに保存し、次回の接続で再利用します。", rememberIdentityConcurrentWarning: "同じブラウザでは、この ID を同時に1接続だけ使用できます。2つ目の接続では無効にするか、別のブラウザを使ってください。", identityOptions: "端末 ID の設定", + identityImport: "ID をインポート", + identityExport: "ID をエクスポート", + identityImportTitle: "TeamSpeak ID をインポート", + identityImportDescription: "TeamSpeak からエクスポートした identity フィールドまたは .ini の内容を貼り付けるか、ファイルをここにドロップしてください。", + identityImportPlaceholder: "identity=... または TeamSpeak ID の .ini ファイル全体を貼り付け", + identityDropZone: ".ini またはテキストファイルをここにドロップ", + identityChooseFile: "ファイルを選択", + identityImportSecurity: "ID ファイルにはサーバー権限を引き継げる秘密鍵が含まれます。インポート解析はこのブラウザ内で行います。接続時にはログインのため使用中の WebSpeak ゲートウェイへ ID が送信されます。エクスポートしたファイルを共有しないでください。", + identityImportSubmit: "解析してインポート", + identityImportCancel: "キャンセル", + identityImportSuccess: "TeamSpeak ID をインポートし、この端末に保存しました", + identityExportSuccess: "TeamSpeak .ini ファイルとして ID をエクスポートしました", + identityExportError: "ID をエクスポートできませんでした。もう一度お試しください。", + identityImportErrorEmpty: "ID の内容を貼り付けるか、.ini ファイルをドロップしてください。", + identityImportErrorTooLarge: "ID のテキストが 128 KB を超えているため、インポートできません。", + identityImportErrorMultiple: "ファイルに複数の ID が含まれています。1つずつインポートしてください。", + identityImportErrorMalformed: "ID 形式を認識できません。TeamSpeak .ini、identity フィールド、または WebSpeak ID 文字列を使用してください。", + identityImportErrorInvalidKey: "ID データが無効か破損しています。エクスポート内容を確認してください。", + identityImportErrorUnsupported: "このブラウザは ID のローカル解析に必要な安全な暗号機能に対応していません。", enterVoice: "音声スペースに参加", connectionAuthorized: "接続情報は今回の音声セッションでのみ使用されます", recentServers: "最近のサーバー", diff --git a/web/src/services/identity-import.test.ts b/web/src/services/identity-import.test.ts new file mode 100644 index 0000000..d730cad --- /dev/null +++ b/web/src/services/identity-import.test.ts @@ -0,0 +1,98 @@ +import assert from "node:assert/strict"; +import { createECDH, createHash, webcrypto } from "node:crypto"; +import test from "node:test"; +import { exportTeamSpeakIdentity, IdentityImportError, importIdentityText } from "./identity-import.js"; + +if (!globalThis.crypto?.subtle) Object.defineProperty(globalThis, "crypto", { value: webcrypto }); + +function decodeBase64Url(value: string): Uint8Array { + const binary = atob(value.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(value.length / 4) * 4, "=")); + return Uint8Array.from(binary, (character) => character.charCodeAt(0)); +} + +function toBase64(value: Uint8Array): string { + return btoa(String.fromCharCode(...value)); +} + +function referenceTlv(tag: number, value: Uint8Array): Buffer { + const length = value.length < 128 ? Buffer.from([value.length]) : Buffer.from([0x81, value.length]); + return Buffer.concat([Buffer.from([tag]), length, Buffer.from(value)]); +} + +function referenceInteger(value: Uint8Array): Buffer { + let first = 0; + while (first < value.length - 1 && value[first] === 0) first++; + const significant = Buffer.from(value.subarray(first)); + return referenceTlv(0x02, (significant[0]! & 0x80) === 0 ? significant : Buffer.concat([Buffer.from([0]), significant])); +} + +function createReferenceTeamSpeakIni(): { ini: string; material: string } { + const scalar = Buffer.alloc(32); + scalar[31] = 1; + const ecdh = createECDH("prime256v1"); + ecdh.setPrivateKey(scalar); + const publicPoint = ecdh.getPublicKey(undefined, "uncompressed"); + const sequenceBody = Buffer.concat([ + referenceTlv(0x03, Buffer.from([0x07, 0x80])), + referenceInteger(Buffer.from([32])), + referenceInteger(publicPoint.subarray(1, 33)), + referenceInteger(publicPoint.subarray(33, 65)), + referenceInteger(scalar), + ]); + const privateDer = referenceTlv(0x30, sequenceBody); + const obfuscated = Buffer.from(privateDer.toString("base64"), "ascii"); + const staticKey = Buffer.from("b9dfaa7bee6ac57ac7b65f1094a1c155e747327bc2fe5d51c512023fe54a280201004e90ad1daaae1075d53b7d571c30e063b5a62a4a017bb394833aa0983e6e", "ascii"); + for (let i = 0; i < Math.min(100, obfuscated.length); i++) obfuscated[i] ^= staticKey[i]!; + const nul = obfuscated.indexOf(0, 20); + const hashEnd = nul < 0 ? obfuscated.length : nul; + const hash = createHash("sha1").update(obfuscated.subarray(20, hashEnd)).digest(); + for (let i = 0; i < 20; i++) obfuscated[i] ^= hash[i]!; + + return { + material: `${scalar.toString("base64")}:42`, + ini: `[Identity]\nid=Standard\nidentity="42V${obfuscated.toString("base64")}"\nnickname=Fixture\n`, + }; +} + +async function createSdkMaterial(): Promise { + const pair = await webcrypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, ["sign", "verify"]); + const jwk = await webcrypto.subtle.exportKey("jwk", pair.privateKey); + assert.ok(jwk.d); + return `${toBase64(decodeBase64Url(jwk.d))}:42`; +} + +test("exports an interoperable TeamSpeak INI and imports it back without changing the identity", async () => { + const material = await createSdkMaterial(); + const ini = await exportTeamSpeakIdentity(material); + + assert.match(ini, /^\[Identity\]\r?\nid=WebSpeak\r?\nidentity="42V[A-Za-z0-9+/]+=*"/); + assert.equal(await importIdentityText(ini), material); +}); + +test("imports a TeamSpeak-format keypair produced independently of the WebSpeak exporter", async () => { + const fixture = createReferenceTeamSpeakIni(); + assert.equal(await importIdentityText(fixture.ini), fixture.material); +}); + +test("imports a pasted TeamSpeak identity field and accepts WebSpeak identity strings", async () => { + const material = await createSdkMaterial(); + const ini = await exportTeamSpeakIdentity(material); + const identityLine = ini.split(/\r?\n/).find((line) => line.startsWith("identity=")); + assert.ok(identityLine); + + assert.equal(await importIdentityText(identityLine), material); + assert.equal(await importIdentityText(material), material); +}); + +test("rejects ambiguous and malformed input with stable error codes", async () => { + await assert.rejects(importIdentityText(""), (error: unknown) => error instanceof IdentityImportError && error.code === "empty"); + await assert.rejects(importIdentityText("identity=1VYWJj\nidentity=2VZGVm"), (error: unknown) => error instanceof IdentityImportError && error.code === "multiple"); + await assert.rejects(importIdentityText("not an identity"), (error: unknown) => error instanceof IdentityImportError && error.code === "malformed"); + await assert.rejects(importIdentityText("x".repeat(128 * 1024 + 1)), (error: unknown) => error instanceof IdentityImportError && error.code === "too-large"); +}); + +test("rejects a damaged TeamSpeak identity blob", async () => { + const ini = await exportTeamSpeakIdentity(await createSdkMaterial()); + const damaged = ini.replace(/identity="(\d+V)([A-Za-z0-9+/])/, (_match, prefix: string, firstByte: string) => `identity="${prefix}${firstByte === "A" ? "B" : "A"}`); + await assert.rejects(importIdentityText(damaged), (error: unknown) => error instanceof IdentityImportError && error.code === "invalid-key"); +}); diff --git a/web/src/services/identity-import.ts b/web/src/services/identity-import.ts new file mode 100644 index 0000000..0afc21d --- /dev/null +++ b/web/src/services/identity-import.ts @@ -0,0 +1,288 @@ +const MAX_IDENTITY_TEXT = 128 * 1024; +const P256_SIZE = 32; +const MAX_TEAM_SPEAK_OFFSET = 18_446_744_073_709_551_615n; +const TEAM_SPEAK_OBFUSCATION_KEY = "b9dfaa7bee6ac57ac7b65f1094a1c155e747327bc2fe5d51c512023fe54a280201004e90ad1daaae1075d53b7d571c30e063b5a62a4a017bb394833aa0983e6e"; + +export type IdentityImportErrorCode = "empty" | "too-large" | "multiple" | "malformed" | "invalid-key" | "unsupported"; + +export class IdentityImportError extends Error { + constructor(readonly code: IdentityImportErrorCode) { + super(code); + this.name = "IdentityImportError"; + } +} + +/** Parse a TeamSpeak 3 identity INI/value or a WebSpeak SDK identity string locally. */ +export async function importIdentityText(input: string): Promise { + if (input.length > MAX_IDENTITY_TEXT) throw new IdentityImportError("too-large"); + const text = input.replace(/^\uFEFF/, "").trim(); + if (!text) throw new IdentityImportError("empty"); + + const sdkMaterial = extractSdkMaterial(text); + if (sdkMaterial) return normalizeSdkMaterial(sdkMaterial); + + const iniIdentity = extractTeamSpeakIdentity(text); + if (!iniIdentity) throw new IdentityImportError("malformed"); + + const separator = iniIdentity.indexOf("V"); + if (separator <= 0 || separator === iniIdentity.length - 1) throw new IdentityImportError("malformed"); + const offset = parseOffset(iniIdentity.slice(0, separator)); + const encoded = iniIdentity.slice(separator + 1).replace(/\s/g, ""); + + try { + const obfuscated = decodeBase64(encoded); + if (obfuscated.length <= 20) throw new Error("short identity blob"); + + // TeamSpeak applies the static XOR first and then masks the first 20 bytes + // with SHA-1 of the remaining C-string. A zero byte inside that suffix is + // therefore the same terminator the native client sees. + const nul = obfuscated.indexOf(0, 20); + const hashEnd = nul < 0 ? obfuscated.length : nul; + const digest = new Uint8Array(await requireSubtleCrypto().digest("SHA-1", obfuscated.slice(20, hashEnd))); + for (let i = 0; i < 20; i++) obfuscated[i] ^= digest[i]!; + + xorStaticKey(obfuscated); + const derBase64 = bytesToAscii(obfuscated); + const privateDer = decodeBase64(derBase64); + const key = decodeTeamSpeakPrivateKey(privateDer); + const derived = await deriveP256Key(key.privateScalar); + if (!bytesEqual(key.x, derived.x) || !bytesEqual(key.y, derived.y)) throw new Error("keypair mismatch"); + + return `${bytesToBase64(key.privateScalar)}:${offset}`; + } catch (error) { + if (error instanceof IdentityImportError) throw error; + throw new IdentityImportError("invalid-key"); + } +} + +/** Export a WebSpeak identity as a TeamSpeak-compatible .ini file, in-browser. */ +export async function exportTeamSpeakIdentity(privateMaterial: string): Promise { + const normalized = await normalizeSdkMaterial(privateMaterial); + const splitAt = normalized.lastIndexOf(":"); + const privateScalar = decodeBase64(normalized.slice(0, splitAt)); + const offset = normalized.slice(splitAt + 1); + const key = await deriveP256Key(privateScalar); + const privateDer = encodeSequence([ + encodeTlv(0x03, new Uint8Array([0x07, 0x80])), // LTC BIT STRING: PK_PRIVATE flag = 1 bit + encodeInteger(new Uint8Array([P256_SIZE])), + encodeInteger(key.x), + encodeInteger(key.y), + encodeInteger(privateScalar), + ]); + + const obfuscated = new TextEncoder().encode(bytesToBase64(privateDer)); + xorStaticKey(obfuscated); + const nul = obfuscated.indexOf(0, 20); + const hashEnd = nul < 0 ? obfuscated.length : nul; + const digest = new Uint8Array(await requireSubtleCrypto().digest("SHA-1", obfuscated.slice(20, hashEnd))); + for (let i = 0; i < 20; i++) obfuscated[i] ^= digest[i]!; + + const identity = `${offset}V${bytesToBase64(obfuscated)}`; + return `[Identity]\r\nid=WebSpeak\r\nidentity="${identity}"\r\nnickname=WebSpeak\r\nphonetic_nickname=\r\n`; +} + +function extractSdkMaterial(text: string): string | null { + const match = text.match(/^(?:identity\s*=\s*)?["']?([A-Za-z0-9+/_=-]{4,64}):(\d+)["']?$/i); + return match ? `${match[1]}:${match[2]}` : null; +} + +function extractTeamSpeakIdentity(text: string): string | null { + const values: string[] = []; + for (const line of text.split(/\r?\n/)) { + const match = line.match(/^\s*identity\s*=\s*(.*?)\s*(?:[;#].*)?$/i); + if (match) values.push(match[1]!.trim().replace(/^(?:"(.*)"|'(.*)')$/, (_all, doubleQuoted, singleQuoted) => doubleQuoted ?? singleQuoted)); + } + if (values.length > 1) throw new IdentityImportError("multiple"); + if (values.length === 1) return values[0]!; + + const rawValue = text.replace(/[\s"']/g, ""); + return /^\d+V[A-Za-z0-9+/=_-]+$/i.test(rawValue) ? rawValue : null; +} + +function parseOffset(value: string): string { + if (!/^\d{1,20}$/.test(value)) throw new IdentityImportError("malformed"); + const offset = BigInt(value); + if (offset > MAX_TEAM_SPEAK_OFFSET) throw new IdentityImportError("malformed"); + return offset.toString(10); +} + +async function normalizeSdkMaterial(value: string): Promise { + const separator = value.lastIndexOf(":"); + if (separator <= 0 || separator === value.length - 1) throw new IdentityImportError("malformed"); + const offset = parseOffset(value.slice(separator + 1)); + try { + const encodedScalar = value.slice(0, separator).replace(/\s/g, ""); + const decoded = decodeBase64(encodedScalar); + if (decoded.length === 0 || decoded.length > P256_SIZE) throw new Error("invalid scalar size"); + const scalar = new Uint8Array(P256_SIZE); + scalar.set(decoded, P256_SIZE - decoded.length); + await deriveP256Key(scalar); + return `${bytesToBase64(scalar)}:${offset}`; + } catch (error) { + if (error instanceof IdentityImportError) throw error; + throw new IdentityImportError("invalid-key"); + } +} + +async function deriveP256Key(privateScalar: Uint8Array): Promise<{ privateScalar: Uint8Array; x: Uint8Array; y: Uint8Array }> { + const subtle = requireSubtleCrypto(); + const sec1 = encodeSequence([ + encodeInteger(new Uint8Array([1])), + encodeTlv(0x04, privateScalar), + encodeTlv(0xa0, encodeTlv(0x06, new Uint8Array([0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07]))), + ]); + const algorithm = encodeSequence([ + encodeTlv(0x06, new Uint8Array([0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01])), + encodeTlv(0x06, new Uint8Array([0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07])), + ]); + const pkcs8 = encodeSequence([ + encodeInteger(new Uint8Array([0])), + algorithm, + encodeTlv(0x04, sec1), + ]); + try { + const imported = await subtle.importKey("pkcs8", pkcs8, { name: "ECDSA", namedCurve: "P-256" }, true, ["sign"]); + const jwk = await subtle.exportKey("jwk", imported); + if (!jwk.x || !jwk.y || !jwk.d) throw new Error("missing curve coordinates"); + return { + privateScalar: base64UrlToBytes(jwk.d), + x: base64UrlToBytes(jwk.x), + y: base64UrlToBytes(jwk.y), + }; + } catch { + throw new Error("invalid P-256 private key"); + } +} + +function decodeTeamSpeakPrivateKey(der: Uint8Array): { privateScalar: Uint8Array; x: Uint8Array; y: Uint8Array } { + const sequence = readTlv(der, 0, 0x30); + if (sequence.end !== der.length) throw new Error("trailing DER data"); + let offset = 0; + const flags = readTlv(sequence.value, offset, 0x03); + offset = flags.end; + if (flags.value.length !== 2 || flags.value[0] !== 7 || (flags.value[1]! & 0x80) === 0) throw new Error("private key flag missing"); + + const size = readTlv(sequence.value, offset, 0x02); + offset = size.end; + if (integerToNumber(size.value) !== P256_SIZE) throw new Error("unexpected curve size"); + const xTlv = readTlv(sequence.value, offset, 0x02); + const x = normalizeInteger(xTlv.value, P256_SIZE); + offset = xTlv.end; + const yTlv = readTlv(sequence.value, offset, 0x02); + const y = normalizeInteger(yTlv.value, P256_SIZE); + offset = yTlv.end; + const privateTlv = readTlv(sequence.value, offset, 0x02); + const privateScalar = normalizeInteger(privateTlv.value, P256_SIZE); + offset = privateTlv.end; + if (offset !== sequence.value.length) throw new Error("unexpected DER fields"); + return { privateScalar, x, y }; +} + +function readTlv(data: Uint8Array, offset: number, tag: number): { value: Uint8Array; end: number } { + if (data[offset] !== tag) throw new Error("unexpected DER tag"); + let cursor = offset + 1; + const firstLength = data[cursor++]; + if (firstLength === undefined) throw new Error("truncated DER length"); + let length: number; + if (firstLength < 0x80) length = firstLength; + else { + const lengthBytes = firstLength & 0x7f; + if (lengthBytes < 1 || lengthBytes > 2 || cursor + lengthBytes > data.length) throw new Error("invalid DER length"); + length = 0; + for (let i = 0; i < lengthBytes; i++) length = length * 256 + data[cursor++]!; + } + const end = cursor + length; + if (end > data.length) throw new Error("truncated DER value"); + return { value: data.slice(cursor, end), end }; +} + +function integerToNumber(value: Uint8Array): number { + const normalized = normalizeInteger(value, 4); + return normalized.reduce((number, byte) => number * 256 + byte, 0); +} + +function normalizeInteger(value: Uint8Array, size: number): Uint8Array { + if (value.length === 0 || (value[0]! & 0x80) !== 0) throw new Error("negative or empty DER integer"); + let start = 0; + while (start < value.length - 1 && value[start] === 0) start++; + const significant = value.slice(start); + if (significant.length > size) throw new Error("DER integer too large"); + const normalized = new Uint8Array(size); + normalized.set(significant, size - significant.length); + return normalized; +} + +function encodeInteger(value: Uint8Array): Uint8Array { + let start = 0; + while (start < value.length - 1 && value[start] === 0) start++; + const significant = value.slice(start); + const positive = (significant[0]! & 0x80) === 0 ? significant : concatBytes(new Uint8Array([0]), significant); + return encodeTlv(0x02, positive); +} + +function encodeSequence(values: Uint8Array[]): Uint8Array { + return encodeTlv(0x30, concatBytes(...values)); +} + +function encodeTlv(tag: number, value: Uint8Array): Uint8Array { + return concatBytes(new Uint8Array([tag]), encodeDerLength(value.length), value); +} + +function encodeDerLength(length: number): Uint8Array { + if (length < 0x80) return new Uint8Array([length]); + if (length < 0x100) return new Uint8Array([0x81, length]); + return new Uint8Array([0x82, length >>> 8, length & 0xff]); +} + +function xorStaticKey(bytes: Uint8Array): void { + const key = new TextEncoder().encode(TEAM_SPEAK_OBFUSCATION_KEY); + for (let i = 0; i < Math.min(100, bytes.length); i++) bytes[i] ^= key[i]!; +} + +function decodeBase64(value: string): Uint8Array { + const normalized = value.replace(/\s/g, "").replace(/-/g, "+").replace(/_/g, "/"); + if (!normalized || !/^[A-Za-z0-9+/]*={0,2}$/.test(normalized) || normalized.length % 4 === 1) throw new Error("invalid base64"); + const padded = normalized.padEnd(Math.ceil(normalized.length / 4) * 4, "="); + const binary = atob(padded); + return Uint8Array.from(binary, (character) => character.charCodeAt(0)); +} + +function bytesToBase64(bytes: Uint8Array): string { + let binary = ""; + for (let offset = 0; offset < bytes.length; offset += 0x8000) { + binary += String.fromCharCode(...bytes.subarray(offset, offset + 0x8000)); + } + return btoa(binary); +} + +function base64UrlToBytes(value: string): Uint8Array { + return decodeBase64(value.replace(/-/g, "+").replace(/_/g, "/")); +} + +function bytesToAscii(bytes: Uint8Array): string { + let result = ""; + for (const byte of bytes) { + if (byte > 0x7f) throw new Error("non-ASCII identity data"); + result += String.fromCharCode(byte); + } + return result; +} + +function concatBytes(...parts: Uint8Array[]): Uint8Array { + const result = new Uint8Array(parts.reduce((total, part) => total + part.length, 0)); + let offset = 0; + for (const part of parts) { + result.set(part, offset); + offset += part.length; + } + return result; +} + +function bytesEqual(left: Uint8Array, right: Uint8Array): boolean { + return left.length === right.length && left.every((byte, index) => byte === right[index]); +} + +function requireSubtleCrypto(): SubtleCrypto { + if (!globalThis.crypto?.subtle) throw new IdentityImportError("unsupported"); + return globalThis.crypto.subtle; +} diff --git a/web/src/styles/web-client.css b/web/src/styles/web-client.css index 4a5a58a..d21c2b4 100644 --- a/web/src/styles/web-client.css +++ b/web/src/styles/web-client.css @@ -245,6 +245,29 @@ .remember-identity strong { font-size: 11px; font-weight: 700; } .remember-identity small { margin-top: 3px; color: #8b9994; font-size: 10px; line-height: 1.4; } .identity-warning { margin: 8px 0 0; color: #9a6a32; font-size: 10px; line-height: 1.45; } +.identity-controls { display: flex; align-items: center; justify-content: space-between; gap: 12px; } +.identity-controls .remember-identity { min-width: 0; flex: 1; } +.identity-actions { display: flex; flex: 0 0 auto; gap: 7px; } +.identity-action-button, .identity-file-button { min-height: 31px; padding: 0 10px; color: var(--accent); background: color-mix(in srgb, var(--accent) 9%, var(--surface-1)); border: 1px solid color-mix(in srgb, var(--accent) 22%, var(--border)); border-radius: 8px; font: inherit; font-size: 10px; font-weight: 700; cursor: pointer; } +.identity-action-button:hover, .identity-file-button:hover { background: color-mix(in srgb, var(--accent) 16%, var(--surface-1)); } +.identity-action-button:disabled { cursor: not-allowed; opacity: .48; } +.identity-import-backdrop { z-index: 50; } +.identity-import-modal { display: flex; width: min(620px, 100%); max-height: min(720px, calc(100dvh - 56px)); flex-direction: column; gap: 15px; overflow-y: auto; padding: 25px; color: var(--text-primary); background: var(--surface-1); border: 1px solid var(--border); border-radius: 18px; box-shadow: 0 20px 60px color-mix(in srgb, var(--text-primary) 22%, transparent); } +.identity-import-header { display: flex; align-items: flex-start; justify-content: space-between; gap: 18px; padding-right: 35px; } +.identity-import-header h2 { margin: 0; color: var(--text-primary); font-size: 20px; letter-spacing: -.035em; } +.identity-import-header p { margin: 7px 0 0; color: var(--text-muted); font-size: 11px; line-height: 1.5; } +.identity-import-textarea { display: block; width: 100%; min-height: 190px; resize: vertical; padding: 12px; color: var(--text-primary); background: var(--surface-2); border: 1px solid var(--border); border-radius: 10px; outline: none; font: 11px/1.55 ui-monospace, SFMono-Regular, Consolas, monospace; overflow-wrap: anywhere; } +.identity-import-textarea:focus { border-color: var(--accent); box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 17%, transparent); } +.identity-drop-zone { display: flex; align-items: center; justify-content: center; flex-wrap: wrap; gap: 10px; min-height: 58px; padding: 10px 14px; color: var(--text-muted); background: color-mix(in srgb, var(--accent) 5%, var(--surface-1)); border: 1px dashed color-mix(in srgb, var(--accent) 48%, var(--border)); border-radius: 10px; font-size: 11px; cursor: pointer; transition: background .16s, border-color .16s; } +.identity-drop-zone > .ui-icon { color: var(--accent); } +.identity-drop-zone.active, .identity-drop-zone:hover { background: color-mix(in srgb, var(--accent) 12%, var(--surface-1)); border-color: var(--accent); } +.identity-file-input { display: none; } +.identity-import-error { margin: -5px 0 0; color: var(--danger); font-size: 11px; line-height: 1.45; } +.identity-import-security { display: flex; align-items: flex-start; gap: 8px; margin: 0; padding: 11px 12px; color: var(--text-muted); background: color-mix(in srgb, var(--warning) 10%, var(--surface-1)); border-radius: 9px; font-size: 10px; line-height: 1.5; } +.identity-import-security .ui-icon { flex: 0 0 auto; color: var(--warning); } +.identity-import-footer { display: flex; align-items: center; justify-content: flex-end; gap: 15px; } +.identity-import-submit { min-height: 39px; padding: 0 16px; } +.identity-import-submit:disabled { cursor: not-allowed; opacity: .52; } .local-servers { display: grid; gap: 8px; margin: 1px 0 5px; } .local-server-group { display: flex; flex-wrap: wrap; align-items: center; gap: 5px; } .local-server-group > span { width: 100%; color: #87958f; font-size: 10px; font-weight: 700; } @@ -1236,3 +1259,19 @@ padding: 10px 12px; } } + +@media (max-width: 740px) { + .identity-import-backdrop { align-items: flex-end; padding: 0; } + .identity-import-modal { width: 100%; max-height: calc(100svh - env(safe-area-inset-top, 0px)); padding: 24px 19px calc(18px + env(safe-area-inset-bottom, 0px)); border-radius: 22px 22px 0 0; } + .identity-import-textarea { min-height: 24svh; } + .identity-drop-zone { justify-content: flex-start; } + .identity-import-footer .identity-import-submit { min-height: 46px; } +} + +@media (max-width: 420px) { + .identity-controls { align-items: flex-start; flex-direction: column; gap: 8px; } + .identity-actions { width: 100%; } + .identity-action-button { flex: 1; } + .identity-import-header { padding-right: 27px; } + .identity-import-header h2 { font-size: 18px; } +} diff --git a/web/src/views/WebClient.vue b/web/src/views/WebClient.vue index ce0694d..72941fb 100644 --- a/web/src/views/WebClient.vue +++ b/web/src/views/WebClient.vue @@ -74,7 +74,7 @@ -
{{ t('identityOptions') }}

{{ t('rememberIdentityConcurrentWarning') }}

+
{{ t('identityOptions') }}

{{ t('rememberIdentityConcurrentWarning') }}

+ +
+ {{ t('identityDropZone') }} +
+ + +

{{ t('identityImportSecurity') }}

+
+ + +
WebSpeak·{{ t('teamSpeakClient') }}·{{ t('browserSupport') }}
@@ -378,7 +392,7 @@