mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-03 03:52:50 +08:00
feat: import and export TeamSpeak identities
This commit is contained in:
1 parent
0a4fff6f6f
commit
9e2b9bf564
7 files changed
+641
-4
No files matched your search
@@ -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 翻译并保持可见。
|
||||
|
||||
+1
-1
@@ -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",
|
||||
|
||||
@@ -55,6 +55,25 @@ export const webClientTranslations: Record<string, Record<string, string>> = {
|
||||
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<string, Record<string, string>> = {
|
||||
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: "最近のサーバー",
|
||||
|
||||
@@ -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<string> {
|
||||
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");
|
||||
});
|
||||
@@ -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<string> {
|
||||
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<string> {
|
||||
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<string> {
|
||||
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;
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
+117
-2
@@ -74,7 +74,7 @@
|
||||
<input id="channel" v-model="channel" :placeholder="t('emptyDefault')" @keyup.enter="doConnect" />
|
||||
</div>
|
||||
|
||||
<details class="identity-options" data-ws-part="home.identity"><summary>{{ t('identityOptions') }}</summary><label class="remember-identity"><input v-model="rememberIdentity" type="checkbox" /><span><strong>{{ t('rememberIdentity') }}</strong><small>{{ t('rememberIdentityHint') }}</small></span></label></details><p v-if="rememberIdentity" class="identity-warning">{{ t('rememberIdentityConcurrentWarning') }}</p>
|
||||
<details class="identity-options" data-ws-part="home.identity"><summary>{{ t('identityOptions') }}</summary><div class="identity-controls"><label class="remember-identity"><input v-model="rememberIdentity" type="checkbox" /><span><strong>{{ t('rememberIdentity') }}</strong><small>{{ t('rememberIdentityHint') }}</small></span></label><div class="identity-actions" data-ws-part="home.identity-actions"><button type="button" class="identity-action-button" data-ws-part="home.identity-import.open" @click="openIdentityImport">{{ t('identityImport') }}</button><button type="button" class="identity-action-button" data-ws-part="home.identity-export.button" :disabled="!rememberIdentity || !identityMaterial" @click="exportIdentity">{{ t('identityExport') }}</button></div></div></details><p v-if="rememberIdentity" class="identity-warning">{{ t('rememberIdentityConcurrentWarning') }}</p>
|
||||
|
||||
<button class="primary-button connect-button" data-ws-part="home.connect" :disabled="!canJoin || serverConfigLoading || !identityReady || voiceState.connecting" type="submit">
|
||||
<span v-if="voiceState.connecting" class="button-spinner"></span>
|
||||
@@ -87,6 +87,20 @@
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<div v-if="identityImportOpen" class="modal-backdrop identity-import-backdrop" @click.self="closeIdentityImport" tabindex="-1">
|
||||
<section ref="identityImportModal" class="identity-import-modal" data-ws-part="home.identity-import-dialog" role="dialog" aria-modal="true" aria-labelledby="identity-import-title" tabindex="-1" @keydown.esc="closeIdentityImport">
|
||||
<header class="identity-import-header" data-ws-part="home.identity-import.header"><div><h2 id="identity-import-title">{{ t('identityImportTitle') }}</h2><p>{{ t('identityImportDescription') }}</p></div><button type="button" class="qq-modal-close" data-ws-part="home.identity-import.close" :aria-label="t('close')" @click="closeIdentityImport"><Icon name="close" :size="18" /></button></header>
|
||||
<textarea v-model="identityImportText" class="identity-import-textarea" data-ws-part="home.identity-import.textarea" :placeholder="t('identityImportPlaceholder')" maxlength="131072" spellcheck="false"></textarea>
|
||||
<div :class="['identity-drop-zone', { active: identityDropActive }]" data-ws-part="home.identity-import.drop-zone" role="group" tabindex="0" @click="chooseIdentityFile" @keydown.enter.prevent="chooseIdentityFile" @keydown.space.prevent="chooseIdentityFile" @dragover.prevent="identityDropActive = true" @dragleave.prevent="identityDropActive = false" @drop.prevent.stop="onIdentityFileDrop">
|
||||
<Icon name="paperclip" :size="18" /><span>{{ t('identityDropZone') }}</span><button type="button" class="identity-file-button" data-ws-part="home.identity-import.file-button" @click.stop="chooseIdentityFile">{{ t('identityChooseFile') }}</button>
|
||||
</div>
|
||||
<input ref="identityFileInput" class="identity-file-input" type="file" accept=".ini,.txt,.identity,.wsi,text/plain" @change="onIdentityFileChange" />
|
||||
<p v-if="identityImportError" class="identity-import-error" data-ws-part="home.identity-import.error" role="alert">{{ identityImportError }}</p>
|
||||
<p class="identity-import-security" data-ws-part="home.identity-import.security"><Icon name="lock" :size="14" /> {{ t('identityImportSecurity') }}</p>
|
||||
<footer class="identity-import-footer" data-ws-part="home.identity-import.footer"><button type="button" class="text-button" data-ws-part="home.identity-import.cancel" @click="closeIdentityImport">{{ t('identityImportCancel') }}</button><button type="button" class="primary-button identity-import-submit" data-ws-part="home.identity-import.submit" :disabled="identityImportBusy || !identityImportText.trim()" @click="importIdentity">{{ identityImportBusy ? t('connecting') : t('identityImportSubmit') }}</button></footer>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<footer class="join-footer" data-ws-part="home.footer">
|
||||
<span>WebSpeak</span><span class="footer-separator">·</span><span>{{ t('teamSpeakClient') }}</span><span class="footer-spacer"></span><button type="button" class="clear-local-button" @click="clearBrowserData">{{ t('clearLocalData') }}</button><span class="footer-separator">·</span><span>{{ t('browserSupport') }}</span>
|
||||
</footer>
|
||||
@@ -378,7 +392,7 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, onUnmounted, reactive, ref, shallowRef, watch } from "vue";
|
||||
import { computed, nextTick, onMounted, onUnmounted, reactive, ref, shallowRef, watch } from "vue";
|
||||
import Icon from "../components/Icon.vue";
|
||||
import LanguageSwitcher from "../components/LanguageSwitcher.vue";
|
||||
import SkinSwitcher, { type SkinOption } from "../components/SkinSwitcher.vue";
|
||||
@@ -394,6 +408,7 @@ import { useWebClientI18n } from "../composables/useWebClientI18n.js";
|
||||
import { useWebClientPublicConfig } from "../composables/useWebClientPublicConfig.js";
|
||||
import { useWebClientServerHistory } from "../composables/useWebClientServerHistory.js";
|
||||
import { getInitialLanguage, type Language } from "../i18n/web-client.js";
|
||||
import { exportTeamSpeakIdentity, IdentityImportError, importIdentityText } from "../services/identity-import.js";
|
||||
import { clearLocalData as clearStoredLocalData, isLocalPersistenceAvailable, listInstalledSkins, loadLocalPreferences, loadStoredIdentity, removeStoredIdentity, saveLocalPreferences, saveStoredIdentity } from "../services/local-persistence.js";
|
||||
import type { InstalledSkin, SkinHomeCopy } from "../services/skin-pack.js";
|
||||
import { getPublicDefaultSkinId, isPublicSkinEnabled, listPublicSkins, type SkinCatalogEntry } from "../services/skin-catalog.js";
|
||||
@@ -507,6 +522,13 @@ const serverHost = ref(initialTarget.address);
|
||||
const serverPort = ref(initialTarget.port);
|
||||
const serverPassword = ref("");
|
||||
const rememberIdentity = ref(localStorage.getItem("webspeak:remember-identity") !== "0");
|
||||
const identityImportOpen = ref(false);
|
||||
const identityImportText = ref("");
|
||||
const identityImportError = ref("");
|
||||
const identityImportBusy = ref(false);
|
||||
const identityDropActive = ref(false);
|
||||
const identityFileInput = ref<HTMLInputElement | null>(null);
|
||||
const identityImportModal = ref<HTMLElement | null>(null);
|
||||
const accelerationRelayId = ref("");
|
||||
const browserError = ref("");
|
||||
const memberQuery = ref("");
|
||||
@@ -1003,6 +1025,99 @@ function doShare() {
|
||||
navigator.clipboard?.writeText(invite.toString()).then(() => showToast(t("copiedToast")), () => showToast(t("copyFailedToast")));
|
||||
}
|
||||
|
||||
function openIdentityImport(): void {
|
||||
identityImportText.value = "";
|
||||
identityImportError.value = "";
|
||||
identityImportOpen.value = true;
|
||||
void nextTick(() => identityImportModal.value?.focus());
|
||||
}
|
||||
|
||||
function closeIdentityImport(): void {
|
||||
if (identityImportBusy.value) return;
|
||||
identityImportOpen.value = false;
|
||||
identityDropActive.value = false;
|
||||
}
|
||||
|
||||
function chooseIdentityFile(): void {
|
||||
identityFileInput.value?.click();
|
||||
}
|
||||
|
||||
function onIdentityFileChange(event: Event): void {
|
||||
const input = event.currentTarget as HTMLInputElement;
|
||||
const file = input.files?.[0];
|
||||
input.value = "";
|
||||
void readIdentityFile(file);
|
||||
}
|
||||
|
||||
function onIdentityFileDrop(event: DragEvent): void {
|
||||
identityDropActive.value = false;
|
||||
void readIdentityFile(event.dataTransfer?.files[0]);
|
||||
}
|
||||
|
||||
async function readIdentityFile(file?: File): Promise<void> {
|
||||
if (!file) return;
|
||||
if (file.size > 128 * 1024) {
|
||||
identityImportError.value = t("identityImportErrorTooLarge");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const bytes = new Uint8Array(await file.arrayBuffer());
|
||||
let encoding = "utf-8";
|
||||
if (bytes[0] === 0xff && bytes[1] === 0xfe) encoding = "utf-16le";
|
||||
else if (bytes[0] === 0xfe && bytes[1] === 0xff) encoding = "utf-16be";
|
||||
identityImportText.value = new TextDecoder(encoding, { fatal: true }).decode(bytes);
|
||||
identityImportError.value = identityImportText.value.trim() ? "" : t("identityImportErrorEmpty");
|
||||
} catch {
|
||||
identityImportError.value = t("identityImportErrorMalformed");
|
||||
}
|
||||
}
|
||||
|
||||
async function importIdentity(): Promise<void> {
|
||||
if (identityImportBusy.value) return;
|
||||
identityImportBusy.value = true;
|
||||
identityImportError.value = "";
|
||||
try {
|
||||
const material = await importIdentityText(identityImportText.value);
|
||||
// Imported identity material is only used if remembered identities are enabled.
|
||||
rememberIdentity.value = true;
|
||||
identityMaterial.value = material;
|
||||
identityImportOpen.value = false;
|
||||
identityImportText.value = "";
|
||||
showToast(t("identityImportSuccess"));
|
||||
} catch (error) {
|
||||
const code = error instanceof IdentityImportError ? error.code : "invalid-key";
|
||||
const errorKey = ({
|
||||
empty: "identityImportErrorEmpty",
|
||||
"too-large": "identityImportErrorTooLarge",
|
||||
multiple: "identityImportErrorMultiple",
|
||||
malformed: "identityImportErrorMalformed",
|
||||
"invalid-key": "identityImportErrorInvalidKey",
|
||||
unsupported: "identityImportErrorUnsupported",
|
||||
} as const)[code];
|
||||
identityImportError.value = t(errorKey);
|
||||
} finally {
|
||||
identityImportBusy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function exportIdentity(): Promise<void> {
|
||||
if (!rememberIdentity.value || !identityMaterial.value) return;
|
||||
try {
|
||||
const content = await exportTeamSpeakIdentity(identityMaterial.value);
|
||||
const url = URL.createObjectURL(new Blob([content], { type: "text/plain;charset=utf-8" }));
|
||||
const link = document.createElement("a");
|
||||
link.href = url;
|
||||
link.download = "webspeak-identity.ini";
|
||||
document.body.append(link);
|
||||
link.click();
|
||||
link.remove();
|
||||
window.setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||
showToast(t("identityExportSuccess"));
|
||||
} catch {
|
||||
showToast(t("identityExportError"));
|
||||
}
|
||||
}
|
||||
|
||||
async function clearBrowserData(): Promise<void> {
|
||||
if (!window.confirm(t("clearLocalDataConfirm"))) return;
|
||||
await clearStoredLocalData();
|
||||
|
||||
Reference in new issue
Block a user