├── .gitignore ├── .prettierignore ├── Containerfile ├── LICENSE ├── README.md ├── app.vue ├── components ├── FileProgress.vue ├── LanguageSwitcher.vue ├── PeerCard.vue ├── ProgressBar.vue ├── ThemeSwitcher.vue └── dialog │ ├── Dialog.vue │ └── SessionDialog.vue ├── i18n └── locales │ ├── de.json │ ├── en.json │ ├── ko.json │ └── tr.json ├── layouts └── default.vue ├── nuxt.config.ts ├── package.json ├── pages └── index.vue ├── pnpm-lock.yaml ├── public ├── apple-touch-icon.png ├── favicon.ico └── robots.txt ├── services ├── crypto.ts ├── signaling.ts ├── store.ts └── webrtc.ts ├── tailwind.config.ts ├── tsconfig.json └── utils ├── alias.ts ├── base64.test.ts ├── base64.ts ├── fileSaver.ts ├── fileSize.ts ├── nonce.ts ├── streamController.test.ts ├── streamController.ts └── userAgent.ts /.gitignore: -------------------------------------------------------------------------------- 1 | # Nuxt dev/build outputs 2 | .output 3 | .data 4 | .nuxt 5 | .nitro 6 | .cache 7 | dist 8 | 9 | # Node dependencies 10 | node_modules 11 | 12 | # Logs 13 | logs 14 | *.log 15 | 16 | # Misc 17 | .DS_Store 18 | .fleet 19 | .idea 20 | 21 | # Local env files 22 | .env 23 | .env.* 24 | !.env.example 25 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | pnpm-lock.yaml -------------------------------------------------------------------------------- /Containerfile: -------------------------------------------------------------------------------- 1 | FROM node:24-bookworm AS builder 2 | 3 | WORKDIR /data 4 | 5 | COPY ./ /data 6 | 7 | RUN corepack enable pnpm && \ 8 | pnpm install && \ 9 | pnpm run generate 10 | 11 | FROM nginxinc/nginx-unprivileged:stable-alpine-slim 12 | COPY --from=builder /data/.output/public /usr/share/nginx/html 13 | 14 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2022-2025 Tien Do Nam 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # LocalSend Web App 2 | 3 | A web app integrating WebRTC and WebSockets to share files with other LocalSend peers (browsers, or native versions). 4 | 5 | Live: https://web.localsend.org 6 | 7 | ## Setup 8 | 9 | Make sure to install [pnpm](https://pnpm.io). 10 | 11 | ```bash 12 | npm install -g pnpm 13 | ``` 14 | 15 | Get dependencies 16 | 17 | ```bash 18 | pnpm install 19 | ``` 20 | 21 | Start the development server 22 | 23 | ```bash 24 | pnpm run dev 25 | ``` 26 | 27 | ## Deployment 28 | 29 | Generates the static website in the `dist` directory. 30 | 31 | ```bash 32 | pnpm run generate 33 | ``` 34 | 35 | ### Self-hosting 36 | 37 | 1. Clone this repo 38 | 2. Build: `docker build --tag localsend-web --file Containerfile` 39 | 3. Run: `docker run --rm --publish 8080:8080 localsend-web` 40 | 41 | ## Contributing 42 | 43 | ### Adding a new language 44 | 45 | 1. Add new JSON file in `i18n/locales/` directory. 46 | 2. Add the new language in `nuxt.config.ts`. 47 | -------------------------------------------------------------------------------- /app.vue: -------------------------------------------------------------------------------- 1 | 10 | -------------------------------------------------------------------------------- /components/FileProgress.vue: -------------------------------------------------------------------------------- 1 | 11 | 12 | 24 | -------------------------------------------------------------------------------- /components/LanguageSwitcher.vue: -------------------------------------------------------------------------------- 1 | 27 | 28 | 67 | -------------------------------------------------------------------------------- /components/PeerCard.vue: -------------------------------------------------------------------------------- 1 | 19 | 20 | 44 | -------------------------------------------------------------------------------- /components/ProgressBar.vue: -------------------------------------------------------------------------------- 1 | 9 | 10 | 15 | -------------------------------------------------------------------------------- /components/ThemeSwitcher.vue: -------------------------------------------------------------------------------- 1 | 21 | 22 | 27 | -------------------------------------------------------------------------------- /components/dialog/Dialog.vue: -------------------------------------------------------------------------------- 1 | 17 | 18 | 23 | 24 | 34 | -------------------------------------------------------------------------------- /components/dialog/SessionDialog.vue: -------------------------------------------------------------------------------- 1 | 30 | 44 | -------------------------------------------------------------------------------- /i18n/locales/de.json: -------------------------------------------------------------------------------- 1 | { 2 | "index": { 3 | "seo": { 4 | "title": "LocalSend Web", 5 | "description": "Teile Dateien zwischen deinem Browser und anderen Geräten, auf denen LocalSend ausgeführt wird." 6 | }, 7 | "connecting": "Verbinde...", 8 | "empty": { 9 | "title": "Öffne LocalSend auf einem anderen Gerät.", 10 | "deviceHint": "Öffne diese Seite in einem anderen Browser oder native Version (v1.18.0 oder neuer).", 11 | "lanHint": "Nur Geräte im selben Netzwerk werden angezeigt." 12 | }, 13 | "you": "Du bist:", 14 | "pin": { 15 | "label": "PIN: ", 16 | "none": "keine" 17 | }, 18 | "enterAlias": "Name eingeben", 19 | "enterPin": "PIN eingeben", 20 | "progress": { 21 | "titleSending": "Sende Dateien...", 22 | "titleReceiving": "Empfange Dateien..." 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /i18n/locales/en.json: -------------------------------------------------------------------------------- 1 | { 2 | "index": { 3 | "seo": { 4 | "title": "LocalSend Web", 5 | "description": "Share files between your browser and other devices running LocalSend." 6 | }, 7 | "connecting": "Connecting...", 8 | "empty": { 9 | "title": "Open LocalSend on another device.", 10 | "deviceHint": "Open this site in another browser or native version (v1.18.0 or newer).", 11 | "lanHint": "Only devices in the same network are shown." 12 | }, 13 | "you": "You are:", 14 | "pin": { 15 | "label": "PIN: ", 16 | "none": "none" 17 | }, 18 | "enterAlias": "Enter name", 19 | "enterPin": "Enter PIN", 20 | "progress": { 21 | "titleSending": "Sending files...", 22 | "titleReceiving": "Receiving files..." 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /i18n/locales/ko.json: -------------------------------------------------------------------------------- 1 | { 2 | "index": { 3 | "seo": { 4 | "title": "LocalSend Web", 5 | "description": "브라우저와 LocalSend를 실행하는 다른 장치 간에 파일을 공유하세요." 6 | }, 7 | "connecting": "연결 중...", 8 | "empty": { 9 | "title": "다른 장치에서 LocalSend를 실행하세요.", 10 | "deviceHint": "다른 브라우저 또는 기본 버전(v1.18.0 이상)에서 이 사이트를 엽니다.", 11 | "lanHint": "동일 네트워크에 있는 장치만 표시됩니다." 12 | }, 13 | "you": "당신은:", 14 | "pin": { 15 | "label": "PIN: ", 16 | "none": "없음" 17 | }, 18 | "enterAlias": "이름 입력", 19 | "enterPin": "PIN 입력", 20 | "progress": { 21 | "titleSending": "파일 전송중...", 22 | "titleReceiving": "파일 받는중..." 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /i18n/locales/tr.json: -------------------------------------------------------------------------------- 1 | { 2 | "index": { 3 | "seo": { 4 | "title": "LocalSend Web", 5 | "description": "Tarayıcınız ve LocalSend çalıştıran diğer cihazlar arasında dosya paylaşın." 6 | }, 7 | "connecting": "Bağlanıyor...", 8 | "empty": { 9 | "title": "LocalSend'i başka bir cihazda açın.", 10 | "deviceHint": "Bu siteyi başka bir tarayıcıda veya yerel sürümde (v1.18.0 veya daha yeni) açın.", 11 | "lanHint": "Sadece aynı ağda bulunan cihazlar gösterilir." 12 | }, 13 | "you": "Cihaz adı:", 14 | "pin": { 15 | "label": "PIN: ", 16 | "none": "yok" 17 | }, 18 | "enterAlias": "Ad girin", 19 | "enterPin": "PIN girin", 20 | "progress": { 21 | "titleSending": "Dosyalar gönderiliyor...", 22 | "titleReceiving": "Dosyalar alınıyor..." 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /layouts/default.vue: -------------------------------------------------------------------------------- 1 | 16 | 17 | 45 | -------------------------------------------------------------------------------- /nuxt.config.ts: -------------------------------------------------------------------------------- 1 | // https://nuxt.com/docs/api/configuration/nuxt-config 2 | export default defineNuxtConfig({ 3 | compatibilityDate: "2024-11-01", 4 | modules: ["@nuxtjs/tailwindcss", "@nuxtjs/i18n", "@nuxt/icon"], 5 | devtools: { enabled: true }, 6 | app: { 7 | head: { 8 | link: [ 9 | { 10 | rel: "icon", 11 | href: "/favicon.ico", 12 | }, 13 | { 14 | rel: "apple-touch-icon", 15 | sizes: "180x180", 16 | href: "/apple-touch-icon.png", 17 | }, 18 | ], 19 | }, 20 | }, 21 | i18n: { 22 | baseUrl: "https://web.localsend.org", 23 | strategy: "prefix_except_default", 24 | defaultLocale: "en", 25 | locales: [ 26 | { 27 | code: "de", 28 | language: "de-DE", 29 | file: "de.json", 30 | name: "Deutsch", 31 | }, 32 | { 33 | code: "en", 34 | language: "en-US", 35 | file: "en.json", 36 | name: "English", 37 | isCatchallLocale: true, 38 | }, 39 | { 40 | code: "ko", 41 | language: "ko-KR", 42 | file: "ko.json", 43 | name: "한국어", 44 | }, 45 | { 46 | code: "tr", 47 | language: "tr-TR", 48 | file: "tr.json", 49 | name: "Türkçe", 50 | }, 51 | ], 52 | }, 53 | nitro: { 54 | prerender: { 55 | autoSubfolderIndex: false, 56 | }, 57 | }, 58 | }); 59 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nuxt-app", 3 | "private": true, 4 | "type": "module", 5 | "scripts": { 6 | "format": "prettier --write .", 7 | "build": "nuxt build", 8 | "test": "vitest", 9 | "dev": "nuxt dev", 10 | "generate": "nuxt generate", 11 | "preview": "nuxt preview", 12 | "postinstall": "nuxt prepare" 13 | }, 14 | "dependencies": { 15 | "@vueuse/core": "^12.5.0", 16 | "@vueuse/nuxt": "^12.5.0", 17 | "nuxt": "^3.15.2", 18 | "pako": "^2.1.0", 19 | "vue": "^3.5.13", 20 | "vue-router": "^4.5.0" 21 | }, 22 | "devDependencies": { 23 | "@nuxt/icon": "^1.10.3", 24 | "@nuxtjs/i18n": "^9.1.3", 25 | "@nuxtjs/tailwindcss": "^6.13.1", 26 | "@types/pako": "^2.0.3", 27 | "prettier": "3.4.2", 28 | "tailwindcss": "^3.4.17", 29 | "vitest": "^3.0.4" 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /pages/index.vue: -------------------------------------------------------------------------------- 1 | 74 | 75 | 187 | 188 | 198 | -------------------------------------------------------------------------------- /public/apple-touch-icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/localsend/web/06ca8d86e82f26d1dc5807aa7202fb5e9103e5a4/public/apple-touch-icon.png -------------------------------------------------------------------------------- /public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/localsend/web/06ca8d86e82f26d1dc5807aa7202fb5e9103e5a4/public/favicon.ico -------------------------------------------------------------------------------- /public/robots.txt: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /services/crypto.ts: -------------------------------------------------------------------------------- 1 | import { decodeBase64, encodeBase64 } from "~/utils/base64"; 2 | 3 | const cryptoParams = { 4 | ed25519: { 5 | identifier: "ed25519", 6 | generate: { name: "Ed25519" }, 7 | import: { name: "Ed25519" }, 8 | sign: { name: "Ed25519" }, 9 | }, 10 | rsaPss: { 11 | identifier: "rsa-pss", 12 | generate: { 13 | name: "RSA-PSS", 14 | modulusLength: 2048, 15 | publicExponent: new Uint8Array([1, 0, 1]), 16 | hash: "SHA-256", 17 | }, 18 | import: { 19 | name: "RSA-PSS", 20 | hash: "SHA-256", 21 | }, 22 | sign: { 23 | name: "RSA-PSS", 24 | saltLength: 32, 25 | }, 26 | }, 27 | }; 28 | 29 | // TODO: Change to Ed25519 when supported by all browsers. 30 | // Currently, Chrome does not support Ed25519 in the WebCrypto API. 31 | // https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/generateKey#browser_compatibility 32 | const selectedParams = cryptoParams.rsaPss; 33 | 34 | /** 35 | * Generate a key pair (publicKey + privateKey). 36 | * Both keys are exportable. 37 | */ 38 | export async function generateKeyPair(): Promise { 39 | return (await window.crypto.subtle.generateKey( 40 | selectedParams.generate, 41 | true, 42 | ["sign", "verify"], 43 | )) as CryptoKeyPair; 44 | } 45 | 46 | export async function cryptoKeyToPem(cryptoKey: CryptoKey): Promise { 47 | const exported = await window.crypto.subtle.exportKey("spki", cryptoKey); 48 | const exportedAsBase64 = btoa( 49 | String.fromCharCode(...new Uint8Array(exported)), 50 | ); 51 | 52 | // Format as PEM 53 | const pemHeader = "-----BEGIN PUBLIC KEY-----\n"; 54 | const pemFooter = "\n-----END PUBLIC KEY-----"; 55 | const pemBody = exportedAsBase64.match(/.{1,64}/g)!.join("\n"); // Wrap lines at 64 chars 56 | 57 | return pemHeader + pemBody + pemFooter; 58 | } 59 | 60 | export async function publicKeyFromDer(der: Uint8Array): Promise { 61 | return await window.crypto.subtle.importKey( 62 | "spki", 63 | der, 64 | selectedParams.import, 65 | true, 66 | ["verify"], 67 | ); 68 | } 69 | 70 | export async function publicKeyFromPem(pem: string): Promise { 71 | // Remove PEM header and footer 72 | const pemBody = pem 73 | .split("\n") 74 | .filter((line) => !line.includes("-----")) 75 | .join(""); 76 | 77 | // Decode the base64 body 78 | const der = new Uint8Array( 79 | atob(pemBody) 80 | .split("") 81 | .map((c) => c.charCodeAt(0)), 82 | ); 83 | 84 | return publicKeyFromDer(der); 85 | } 86 | 87 | /** 88 | * Generates a client token with the following structure: 89 | * 90 | * HASH_METHOD.HASH.SALT_BASE64.SIGN_METHOD.SIGN 91 | * 92 | * 1) HASH_METHOD (e.g. "sha256") 93 | * 2) HASH (base64-url-no-padding of sha256(publicKeyDER + SALT)) 94 | * 3) SALT_BASE64 (base64-url-no-padding of 8 bytes = timestamp [u64]) 95 | * 4) SIGN_METHOD (e.g. "ed25519") 96 | * 5) SIGN (base64-url-no-padding of Ed25519 signature over HASH) 97 | */ 98 | export async function generateClientTokenFromCurrentTimestamp( 99 | key: CryptoKeyPair, 100 | ): Promise { 101 | const salt = unixTimestampU64(); 102 | return await generateClientTokenFromNonce(key, salt); 103 | } 104 | 105 | export async function generateClientTokenFromNonce( 106 | key: CryptoKeyPair, 107 | nonce: Uint8Array, 108 | ): Promise { 109 | const publicKeyDER = new Uint8Array( 110 | await window.crypto.subtle.exportKey("spki", key.publicKey), 111 | ); 112 | const hashInput = concatBytes(publicKeyDER, nonce); 113 | const digest = await window.crypto.subtle.digest("SHA-256", hashInput); 114 | const signature = await window.crypto.subtle.sign( 115 | selectedParams.sign, 116 | key.privateKey, 117 | digest, 118 | ); 119 | 120 | const hashMethod = "sha256"; 121 | const hashBase64 = encodeBase64(new Uint8Array(digest)); 122 | const saltBase64 = encodeBase64(nonce); 123 | const signMethod = selectedParams.identifier; 124 | const signatureBase64 = encodeBase64(new Uint8Array(signature)); 125 | 126 | return [hashMethod, hashBase64, saltBase64, signMethod, signatureBase64].join( 127 | ".", 128 | ); 129 | } 130 | 131 | export async function verifyToken( 132 | publicKey: CryptoKey, 133 | token: string, 134 | ): Promise { 135 | const parts = token.split("."); 136 | if (parts.length !== 5) { 137 | return false; 138 | } 139 | 140 | const [hashMethod, hashB64, saltB64, signMethod, signB64] = parts; 141 | 142 | if (hashMethod !== "sha256") { 143 | return false; 144 | } 145 | 146 | if (signMethod !== selectedParams.identifier) { 147 | return false; 148 | } 149 | 150 | // Decode the salt (8 bytes, big-endian u64, in SECONDS) 151 | const saltBuffer = decodeBase64(saltB64); 152 | if (saltBuffer.byteLength !== 8) { 153 | return false; 154 | } 155 | const saltSeconds = Number(decodeU64(saltBuffer)); 156 | 157 | const nowInSeconds = Math.floor(Date.now() / 1000); 158 | if (nowInSeconds - saltSeconds > 60 * 60) { 159 | // Fingerprint is older than 1h, reject 160 | return false; 161 | } 162 | 163 | const publicKeyDER = await crypto.subtle.exportKey("spki", publicKey); 164 | const hashInput = concatBytes(new Uint8Array(publicKeyDER), saltBuffer); 165 | 166 | // Recompute the SHA-256 hash 167 | const digest = await crypto.subtle.digest("SHA-256", hashInput); 168 | const recomputedHashB64 = encodeBase64(new Uint8Array(digest)); 169 | 170 | if (recomputedHashB64 !== hashB64) { 171 | return false; 172 | } 173 | 174 | const signatureBuffer = decodeBase64(signB64); 175 | return await crypto.subtle.verify( 176 | selectedParams.sign, 177 | publicKey, 178 | signatureBuffer, 179 | digest, 180 | ); 181 | } 182 | 183 | function unixTimestampU64(): Uint8Array { 184 | const nowInSeconds = Math.floor(Date.now() / 1000); 185 | return encodeU64(BigInt(nowInSeconds)); 186 | } 187 | 188 | function encodeU64(value: bigint): Uint8Array { 189 | const saltBuffer = new ArrayBuffer(8); 190 | const saltView = new DataView(saltBuffer); 191 | saltView.setBigUint64(0, value, true); 192 | return new Uint8Array(saltBuffer); 193 | } 194 | 195 | function decodeU64(buffer: Uint8Array): bigint { 196 | const saltView = new DataView(typedArrayToBuffer(buffer)); 197 | return saltView.getBigUint64(0, true); 198 | } 199 | 200 | function concatBytes(...arrays: Uint8Array[]): Uint8Array { 201 | const totalLength = arrays.reduce((acc, arr) => acc + arr.length, 0); 202 | const result = new Uint8Array(totalLength); 203 | let offset = 0; 204 | for (const arr of arrays) { 205 | result.set(arr, offset); 206 | offset += arr.length; 207 | } 208 | return result; 209 | } 210 | 211 | function typedArrayToBuffer(array: Uint8Array): ArrayBuffer { 212 | return array.buffer.slice( 213 | array.byteOffset, 214 | array.byteLength + array.byteOffset, 215 | ); 216 | } 217 | -------------------------------------------------------------------------------- /services/signaling.ts: -------------------------------------------------------------------------------- 1 | import { encodeStringToBase64 } from "~/utils/base64"; 2 | 3 | export class SignalingConnection { 4 | private _socket: WebSocket; 5 | private _onAnswer: OnAnswer | null = null; 6 | 7 | private constructor(socket: WebSocket) { 8 | this._socket = socket; 9 | } 10 | 11 | /** 12 | * Connects to the signaling server. 13 | * @param url The URL of the signaling server. 14 | * @param info The client info to send to the server. 15 | * @param onMessage The callback to call when a message is received. 16 | * @param generateNewInfo The function to generate and publish a new info. 17 | * @param onClose The callback to call when the connection is closed. 18 | */ 19 | public static async connect({ 20 | url, 21 | info, 22 | onMessage, 23 | generateNewInfo, 24 | onClose, 25 | }: { 26 | url: string; 27 | info: ClientInfoWithoutId; 28 | onMessage: OnMessageCallback; 29 | generateNewInfo: () => Promise; 30 | onClose: () => void; 31 | }): Promise { 32 | console.log(`Connecting to ${url}`); 33 | 34 | const encodedInfo = encodeStringToBase64(JSON.stringify(info)); 35 | const socket = await new Promise((resolve, reject) => { 36 | const ws = new WebSocket(`${url}?d=${encodedInfo}`); 37 | ws.onopen = () => resolve(ws); 38 | ws.onerror = (err) => reject(err); 39 | }); 40 | 41 | // ping every 120 seconds to keep the connection alive 42 | const pingInterval = setInterval(() => { 43 | socket.send(""); 44 | }, 120 * 1000); 45 | 46 | // every half hour, generate a new fingerprint 47 | const fingerprintInterval = setInterval( 48 | async () => { 49 | const info = await generateNewInfo(); 50 | socket.send( 51 | JSON.stringify({ 52 | type: "UPDATE", 53 | info: info, 54 | } as WsClientUpdateMessage), 55 | ); 56 | }, 57 | 30 * 60 * 1000, 58 | ); 59 | 60 | socket.onclose = () => { 61 | console.log("Signaling connection closed"); 62 | clearInterval(pingInterval); 63 | clearInterval(fingerprintInterval); 64 | onClose(); 65 | }; 66 | 67 | console.log("Signaling connection established"); 68 | 69 | const instance = new SignalingConnection(socket); 70 | 71 | socket.onmessage = (event) => { 72 | const message = JSON.parse(event.data) as WsServerMessage; 73 | console.log(`WS in: ${event.data}`); 74 | if ( 75 | message.type === "ANSWER" && 76 | instance._onAnswer && 77 | message.sessionId === instance._onAnswer.sessionId 78 | ) { 79 | instance._onAnswer.callback(message); 80 | instance._onAnswer = null; 81 | } 82 | onMessage(message); 83 | }; 84 | 85 | return instance; 86 | } 87 | 88 | public send(message: WsClientMessage) { 89 | console.log(`WS out: ${JSON.stringify(message)}`); 90 | this._socket.send(JSON.stringify(message)); 91 | } 92 | 93 | public async waitForAnswer(sessionId: string): Promise { 94 | return await new Promise((resolve) => { 95 | this._onAnswer = { 96 | sessionId, 97 | callback: (message) => resolve(message), 98 | }; 99 | }); 100 | } 101 | 102 | public async waitUntilClose(): Promise { 103 | return new Promise((resolve) => { 104 | this._socket.addEventListener("close", () => { 105 | resolve(); 106 | }); 107 | }); 108 | } 109 | } 110 | 111 | type OnAnswer = { 112 | sessionId: string; 113 | callback: (message: AnswerMessage) => void; 114 | }; 115 | 116 | export type ClientInfoWithoutId = { 117 | alias: string; 118 | version: string; 119 | deviceModel?: string; 120 | deviceType?: PeerDeviceType; 121 | token: string; 122 | }; 123 | 124 | export type ClientInfo = ClientInfoWithoutId & { id: string }; 125 | 126 | export enum PeerDeviceType { 127 | mobile = "mobile", 128 | desktop = "desktop", 129 | web = "web", 130 | headless = "headless", 131 | server = "server", 132 | } 133 | 134 | export type WsServerMessage = 135 | | HelloMessage 136 | | JoinMessage 137 | | LeftMessage 138 | | UpdateMessage 139 | | OfferMessage 140 | | AnswerMessage 141 | | ErrorMessage; 142 | 143 | export type HelloMessage = { 144 | type: "HELLO"; 145 | client: ClientInfo; 146 | peers: ClientInfo[]; 147 | }; 148 | 149 | export type JoinMessage = { 150 | type: "JOIN"; 151 | peer: ClientInfo; 152 | }; 153 | 154 | export type UpdateMessage = { 155 | type: "UPDATE"; 156 | peer: ClientInfo; 157 | }; 158 | 159 | export type LeftMessage = { 160 | type: "LEFT"; 161 | peerId: string; 162 | }; 163 | 164 | export type WsServerSdpMessage = { 165 | peer: ClientInfo; 166 | sessionId: string; 167 | sdp: string; 168 | }; 169 | 170 | export type OfferMessage = WsServerSdpMessage & { type: "OFFER" }; 171 | 172 | export type AnswerMessage = WsServerSdpMessage & { type: "ANSWER" }; 173 | 174 | export type ErrorMessage = { 175 | type: "ERROR"; 176 | code: number; 177 | }; 178 | 179 | type OnMessageCallback = (message: WsServerMessage) => void; 180 | 181 | export type WsClientMessage = WsClientUpdateMessage | WsClientSdpMessage; 182 | 183 | export type WsClientUpdateMessage = { 184 | type: "UPDATE"; 185 | info: ClientInfoWithoutId; 186 | }; 187 | 188 | export type WsClientSdpMessage = { 189 | type: "OFFER" | "ANSWER"; 190 | sessionId: string; 191 | target: string; 192 | sdp: string; 193 | }; 194 | -------------------------------------------------------------------------------- /services/store.ts: -------------------------------------------------------------------------------- 1 | import type { 2 | ClientInfo, 3 | ClientInfoWithoutId, 4 | WsServerMessage, 5 | WsServerSdpMessage, 6 | } from "~/services/signaling"; 7 | import { SignalingConnection } from "~/services/signaling"; 8 | import { 9 | defaultStun, 10 | type FileDto, 11 | type FileProgress, 12 | receiveFiles, 13 | sendFiles, 14 | } from "~/services/webrtc"; 15 | import { generateClientTokenFromCurrentTimestamp } from "~/services/crypto"; 16 | 17 | export enum SessionState { 18 | idle = "idle", 19 | sending = "sending", 20 | receiving = "receiving", 21 | } 22 | 23 | export type FileState = { 24 | id: string; 25 | name: string; 26 | curr: number; 27 | total: number; 28 | state: "pending" | "skipped" | "sending" | "finished" | "error"; 29 | error?: string; 30 | }; 31 | 32 | export const store = reactive({ 33 | // Whether the connection loop has started 34 | _loopStarted: false, 35 | 36 | // Client information of the current user that we send to the server 37 | _proposingClient: null as ClientInfoWithoutId | null, 38 | 39 | _onPin: null as (() => Promise) | null, 40 | 41 | // Public and private key pair for signing and verifying messages 42 | key: null as CryptoKeyPair | null, 43 | 44 | /// PIN code used before receiving or sending files 45 | pin: null as string | null, 46 | 47 | // Signaling connection to the server 48 | signaling: null as SignalingConnection | null, 49 | 50 | // Client information of the current user that we received from the server 51 | client: null as ClientInfo | null, 52 | 53 | // List of peers connected to the same room 54 | peers: [] as ClientInfo[], 55 | 56 | // Current session information 57 | session: { 58 | state: SessionState.idle, 59 | curr: 0, 60 | total: 1, // Avoid division by zero 61 | fileState: {} as Record, 62 | }, 63 | }); 64 | 65 | export async function setupConnection({ 66 | info, 67 | onPin, 68 | }: { 69 | info: ClientInfoWithoutId; 70 | onPin: () => Promise; 71 | }) { 72 | store._proposingClient = info; 73 | store._onPin = onPin; 74 | if (!store._loopStarted) { 75 | store._loopStarted = true; 76 | connectionLoop().then(() => console.log("Connection loop ended")); 77 | } 78 | } 79 | 80 | async function connectionLoop() { 81 | while (true) { 82 | try { 83 | store.signaling = await SignalingConnection.connect({ 84 | url: "wss://public.localsend.org/v1/ws", 85 | info: store._proposingClient!, 86 | onMessage: (data: WsServerMessage) => { 87 | switch (data.type) { 88 | case "HELLO": 89 | store.client = data.client; 90 | store.peers = data.peers; 91 | break; 92 | case "JOIN": 93 | store.peers = [...store.peers, data.peer]; 94 | break; 95 | case "UPDATE": 96 | store.peers = store.peers.map((p) => 97 | p.id === data.peer.id ? data.peer : p, 98 | ); 99 | break; 100 | case "LEFT": 101 | store.peers = store.peers.filter((p) => p.id !== data.peerId); 102 | break; 103 | case "OFFER": 104 | acceptOffer({ offer: data, onPin: store._onPin! }); 105 | break; 106 | case "ANSWER": 107 | break; 108 | } 109 | }, 110 | generateNewInfo: async () => { 111 | const token = await generateClientTokenFromCurrentTimestamp( 112 | store.key!, 113 | ); 114 | updateClientTokenState(token); 115 | return { ...store._proposingClient!, token }; 116 | }, 117 | onClose: () => { 118 | store.signaling = null; 119 | store.client = null; 120 | store.peers = []; 121 | }, 122 | }); 123 | 124 | await store.signaling.waitUntilClose(); 125 | } catch (error) { 126 | console.log("Retrying connection in 5 seconds..."); 127 | await new Promise((resolve) => setTimeout(resolve, 5000)); // Wait before retrying 128 | } 129 | } 130 | } 131 | 132 | export function updateAliasState(alias: string) { 133 | store._proposingClient!.alias = alias; 134 | store.client!.alias = alias; 135 | } 136 | 137 | function updateClientTokenState(token: string) { 138 | store._proposingClient!.token = token; 139 | store.client!.token = token; 140 | } 141 | 142 | const PIN_MAX_TRIES = 3; 143 | 144 | export async function startSendSession({ 145 | files, 146 | targetId, 147 | onPin, 148 | }: { 149 | files: FileList; 150 | targetId: string; 151 | onPin: () => Promise; 152 | }): Promise { 153 | store.session.state = SessionState.sending; 154 | const fileState: Record = {}; 155 | 156 | const fileDtoList = convertFileListToDto(files); 157 | const fileMap = fileDtoList.reduce( 158 | (acc, file) => { 159 | acc[file.id] = files[parseInt(file.id)]; 160 | fileState[file.id] = { 161 | id: file.id, 162 | name: file.fileName, 163 | curr: 0, 164 | total: file.size, 165 | state: "pending", 166 | }; 167 | return acc; 168 | }, 169 | {} as Record, 170 | ); 171 | 172 | store.session.fileState = fileState; 173 | store.session.curr = 0; 174 | store.session.total = fileDtoList.reduce((acc, file) => acc + file.size, 0); 175 | 176 | try { 177 | await sendFiles({ 178 | signaling: store.signaling as SignalingConnection, 179 | stunServers: defaultStun, 180 | fileDtoList: fileDtoList, 181 | fileMap: fileMap, 182 | targetId: targetId, 183 | signingKey: store.key!, 184 | pin: store.pin ? { pin: store.pin, maxTries: PIN_MAX_TRIES } : undefined, 185 | onPin: onPin, 186 | onFilesSkip: (fileIds) => { 187 | for (const id of fileIds) { 188 | store.session.fileState[id].state = "skipped"; 189 | } 190 | }, 191 | onFileProgress: onFileProgress, 192 | }); 193 | } finally { 194 | store.session.state = SessionState.idle; 195 | } 196 | } 197 | 198 | function convertFileListToDto(files: FileList): FileDto[] { 199 | const result: FileDto[] = []; 200 | for (let i = 0; i < files.length; i++) { 201 | const file = files[i]; 202 | result.push({ 203 | id: i.toString(), 204 | fileName: file.name, 205 | size: file.size, 206 | fileType: file.type, 207 | metadata: { 208 | modified: new Date(file.lastModified).toISOString(), 209 | }, 210 | }); 211 | } 212 | 213 | return result; 214 | } 215 | 216 | export async function acceptOffer({ 217 | offer, 218 | onPin, 219 | }: { 220 | offer: WsServerSdpMessage; 221 | onPin: () => Promise; 222 | }) { 223 | store.session.state = SessionState.receiving; 224 | 225 | try { 226 | await receiveFiles({ 227 | signaling: store.signaling as SignalingConnection, 228 | stunServers: defaultStun, 229 | offer: offer, 230 | signingKey: store.key!, 231 | pin: store.pin ? { pin: store.pin, maxTries: PIN_MAX_TRIES } : undefined, 232 | onPin: onPin, 233 | selectFiles: async (files) => { 234 | // Select all files 235 | store.session.curr = 0; 236 | store.session.total = files.reduce((acc, file) => acc + file.size, 0); 237 | store.session.fileState = {}; 238 | for (const file of files) { 239 | store.session.fileState[file.id] = { 240 | id: file.id, 241 | name: file.fileName, 242 | curr: 0, 243 | total: file.size, 244 | state: "pending", 245 | }; 246 | } 247 | return files.map((file) => file.id); 248 | }, 249 | onFileProgress: onFileProgress, 250 | }); 251 | } finally { 252 | store.session.state = SessionState.idle; 253 | } 254 | } 255 | 256 | function onFileProgress(progress: FileProgress) { 257 | store.session.fileState[progress.id].curr = progress.curr; 258 | store.session.curr = Object.values(store.session.fileState).reduce( 259 | (acc, file) => acc + file.curr, 260 | 0, 261 | ); 262 | if (progress.success) { 263 | store.session.fileState[progress.id].state = "finished"; 264 | } else if (progress.error) { 265 | store.session.fileState[progress.id].state = "error"; 266 | store.session.fileState[progress.id].error = progress.error; 267 | } 268 | } 269 | -------------------------------------------------------------------------------- /services/webrtc.ts: -------------------------------------------------------------------------------- 1 | import { 2 | SignalingConnection, 3 | type WsServerSdpMessage, 4 | } from "~/services/signaling"; 5 | import { decodeBase64, encodeBase64 } from "~/utils/base64"; 6 | import { StreamController } from "~/utils/streamController"; 7 | import pako from "pako"; 8 | import { saveFileFromBytes } from "~/utils/fileSaver"; 9 | import { generateNonce, validateNonce } from "~/utils/nonce"; 10 | import { generateClientTokenFromNonce } from "~/services/crypto"; 11 | 12 | export const protocolVersion = "2.3"; 13 | 14 | export const defaultStun = ["stun:stun.l.google.com:19302"]; 15 | 16 | export async function sendFiles({ 17 | signaling, 18 | stunServers, 19 | fileDtoList, 20 | fileMap, 21 | targetId, 22 | signingKey, 23 | pin, 24 | onPin, 25 | onFilesSkip, 26 | onFileProgress, 27 | }: { 28 | signaling: SignalingConnection; 29 | stunServers: string[]; 30 | fileDtoList: FileDto[]; 31 | fileMap: Record; 32 | targetId: string; 33 | signingKey: CryptoKeyPair; 34 | pin?: PinConfig; 35 | onPin: () => Promise; 36 | onFilesSkip: (fileIds: string[]) => void; 37 | onFileProgress: (progress: FileProgress) => void; 38 | }) { 39 | console.log("Sending to target:", targetId); 40 | console.log("Sending files:", fileDtoList); 41 | 42 | const peerConnection = await createPeerConnection(stunServers); 43 | 44 | const dataChannel = peerConnection.createDataChannel("data"); 45 | dataChannel.binaryType = "arraybuffer"; 46 | const dataChannelStream = createStreamController(dataChannel); 47 | const dataChannelOpened = new Promise((resolve) => { 48 | dataChannel.onopen = () => resolve(); 49 | }); 50 | 51 | console.log("Creating offer..."); 52 | 53 | const offer = await peerConnection.createOffer(); 54 | await peerConnection.setLocalDescription(offer); 55 | await waitICEGathering(peerConnection); 56 | const localSdp = peerConnection.localDescription!.sdp; 57 | 58 | console.log("Local SDP: ", localSdp); 59 | 60 | const sessionId = Math.random().toString(36).substring(2, 15); 61 | 62 | signaling.send({ 63 | type: "OFFER", 64 | sessionId: sessionId, 65 | target: targetId, 66 | sdp: encodeSdp(localSdp), 67 | }); 68 | 69 | console.log("Waiting for answer..."); 70 | 71 | const answer = await signaling.waitForAnswer(sessionId); 72 | const answerSdp = decodeSdp(answer.sdp); 73 | 74 | console.log("Received answer SDP: ", answerSdp); 75 | 76 | await peerConnection.setRemoteDescription({ 77 | type: "answer", 78 | sdp: answerSdp, 79 | }); 80 | 81 | await dataChannelOpened; 82 | 83 | console.log("Data channel opened. Exchanging nonce..."); 84 | 85 | const localNonce = await generateNonce(); 86 | dataChannel.send( 87 | JSON.stringify({ 88 | nonce: encodeBase64(localNonce), 89 | } as RTCNonceMessage), 90 | ); 91 | const remoteNonce = await receiveNonce(dataChannelStream); 92 | const nonce = new Uint8Array(localNonce.length + remoteNonce.length); 93 | nonce.set(localNonce); 94 | nonce.set(remoteNonce, localNonce.length); 95 | 96 | console.log("Nonce exchanged. Exchanging token..."); 97 | 98 | const localToken = await generateClientTokenFromNonce(signingKey, nonce); 99 | dataChannel.send( 100 | JSON.stringify({ 101 | token: localToken, 102 | } as RTCTokenRequest), 103 | ); 104 | 105 | const tokenResponseRaw = await dataChannelStream.readNext(); 106 | if (typeof tokenResponseRaw !== "string") { 107 | throw new Error("Expected string"); 108 | } 109 | const tokenResponse = JSON.parse(tokenResponseRaw) as RTCTokenResponse; 110 | if (tokenResponse.status === "INVALID_SIGNATURE") { 111 | console.error("Invalid signature"); 112 | return; 113 | } 114 | 115 | let remoteToken: string; 116 | if (tokenResponse.status === "OK") { 117 | remoteToken = tokenResponse.token; 118 | } else if (tokenResponse.status === "PIN_REQUIRED") { 119 | remoteToken = tokenResponse.token; 120 | await handlePin( 121 | dataChannelStream, 122 | dataChannel, 123 | onPin, 124 | false, 125 | (response) => { 126 | const parsed = JSON.parse(response) as RTCPinReceivingResponse; 127 | if ( 128 | parsed.status === "PIN_REQUIRED" || 129 | parsed.status === "TOO_MANY_ATTEMPTS" 130 | ) { 131 | return parsed.status; 132 | } 133 | return 1; 134 | }, 135 | ); 136 | } else { 137 | console.error("Invalid response"); 138 | return; 139 | } 140 | 141 | console.log(`Received token: ${remoteToken}`); 142 | 143 | if (pin) { 144 | let remotePin = ""; 145 | let pinTry = 0; 146 | 147 | while (true) { 148 | if (remotePin === pin.pin) { 149 | break; 150 | } 151 | 152 | if (pinTry >= pin.maxTries) { 153 | sendStringInChunks( 154 | dataChannel, 155 | JSON.stringify({ 156 | status: "TOO_MANY_ATTEMPTS", 157 | } as RTCPinSendingResponse), 158 | ); 159 | 160 | sendDelimiter(dataChannel); 161 | 162 | await waitBufferEmpty(dataChannel); 163 | return; 164 | } 165 | 166 | sendStringInChunks( 167 | dataChannel, 168 | JSON.stringify({ 169 | status: "PIN_REQUIRED", 170 | } as RTCPinSendingResponse), 171 | ); 172 | 173 | sendDelimiter(dataChannel); 174 | 175 | const remotePinRaw = await dataChannelStream.readNext(); 176 | if (typeof remotePinRaw !== "string") { 177 | throw new Error("Expected string"); 178 | } 179 | remotePin = (JSON.parse(remotePinRaw) as RTCPinMessage).pin; 180 | pinTry++; 181 | } 182 | } 183 | 184 | sendStringInChunks( 185 | dataChannel, 186 | JSON.stringify({ 187 | status: "OK", 188 | files: fileDtoList, 189 | } as RTCPinSendingResponse), 190 | ); 191 | 192 | sendDelimiter(dataChannel); 193 | 194 | console.log("Sent file list. Waiting for selection..."); 195 | 196 | let fileListResponseRaw = await receiveStringFromChunks(dataChannelStream); 197 | let fileListResponse = JSON.parse(fileListResponseRaw) as RTCFileListResponse; 198 | let fileTokens: Record; 199 | if (fileListResponse.status === "OK") { 200 | fileTokens = fileListResponse.files; 201 | } else if (fileListResponse.status === "PAIR") { 202 | console.log("Pairing required. Reject..."); 203 | dataChannel.send( 204 | JSON.stringify({ 205 | status: "PAIR_DECLINED", 206 | } as RTCPairResponse), 207 | ); 208 | fileListResponseRaw = await receiveStringFromChunks(dataChannelStream); 209 | fileListResponse = JSON.parse(fileListResponseRaw) as RTCFileListResponse; 210 | if (fileListResponse.status === "OK") { 211 | fileTokens = fileListResponse.files; 212 | } else { 213 | return; 214 | } 215 | } else { 216 | return; 217 | } 218 | 219 | console.log( 220 | `Selected files: ${Object.keys(fileTokens).length} / ${fileDtoList.length}`, 221 | ); 222 | 223 | const skippedFiles: string[] = []; 224 | fileDtoList = fileDtoList.filter((file) => { 225 | const hasToken = fileTokens[file.id]; 226 | if (!hasToken) { 227 | skippedFiles.push(file.id); 228 | } 229 | return hasToken; 230 | }); 231 | 232 | if (skippedFiles.length > 0) { 233 | onFilesSkip(skippedFiles); 234 | } 235 | 236 | const startTime = Date.now(); 237 | 238 | const firstFileDto = fileDtoList[0]; 239 | dataChannel.send( 240 | JSON.stringify({ 241 | id: firstFileDto.id, 242 | token: fileTokens[firstFileDto.id], 243 | } as RTCSendFileHeaderRequest), 244 | ); 245 | 246 | for (let i = 0; i < fileDtoList.length; i++) { 247 | const fileDto = fileDtoList[i]; 248 | 249 | const file = fileMap[fileDto.id]; 250 | const fileSize = file.size; 251 | console.log(`Sending file: ${fileDto.fileName}`); 252 | await sendFileInChunks(dataChannel, file, (bytes) => { 253 | onFileProgress({ 254 | id: fileDto.id, 255 | curr: bytes, 256 | }); 257 | }); 258 | 259 | if (i + 1 < fileDtoList.length) { 260 | const nextFileDto = fileDtoList[i + 1]; 261 | const fileToken = fileTokens[nextFileDto.id]; 262 | 263 | dataChannel.send( 264 | JSON.stringify({ 265 | id: nextFileDto.id, 266 | token: fileToken, 267 | } as RTCSendFileHeaderRequest), 268 | ); 269 | } else { 270 | sendDelimiter(dataChannel); 271 | } 272 | 273 | console.log("Waiting for file status..."); 274 | const fileStatus = await dataChannelStream.readNext(); 275 | if (typeof fileStatus !== "string") { 276 | throw new Error("Expected string"); 277 | } 278 | 279 | const response = JSON.parse(fileStatus) as RTCSendFileResponse; 280 | onFileProgress({ 281 | id: fileDto.id, 282 | curr: fileSize, 283 | success: response.success, 284 | error: response.error, 285 | }); 286 | } 287 | 288 | const sumSize = fileDtoList.reduce((sum, file) => sum + file.size, 0); 289 | 290 | console.log( 291 | `Finished in ${Date.now() - startTime} ms. Speed: ${(sumSize * 1000) / (Date.now() - startTime) / (1024 * 1024)} MB/s`, 292 | ); 293 | 294 | dataChannel.close(); 295 | peerConnection.close(); 296 | 297 | console.log("Connection closed"); 298 | } 299 | 300 | export async function receiveFiles({ 301 | signaling, 302 | stunServers, 303 | offer, 304 | signingKey, 305 | pin, 306 | onPin, 307 | selectFiles, 308 | onFileProgress, 309 | }: { 310 | signaling: SignalingConnection; 311 | stunServers: string[]; 312 | offer: WsServerSdpMessage; 313 | signingKey: CryptoKeyPair; 314 | pin?: PinConfig; 315 | onPin: () => Promise; 316 | selectFiles: (files: FileDto[]) => Promise; 317 | onFileProgress: (progress: FileProgress) => void; 318 | }) { 319 | console.log("Accepting offer from:", offer.peer.id); 320 | console.log("Remote SDP: ", decodeSdp(offer.sdp)); 321 | 322 | const peerConnection = await createPeerConnection(stunServers); 323 | 324 | const dataChannelPromise = new Promise((resolve) => { 325 | peerConnection.ondatachannel = (event) => { 326 | resolve(event.channel); 327 | }; 328 | }); 329 | 330 | await peerConnection.setRemoteDescription({ 331 | type: "offer", 332 | sdp: decodeSdp(offer.sdp), 333 | }); 334 | 335 | console.log("Creating answer..."); 336 | const answer = await peerConnection.createAnswer(); 337 | await peerConnection.setLocalDescription(answer); 338 | await waitICEGathering(peerConnection); 339 | const localSdp = peerConnection.localDescription!.sdp; 340 | 341 | console.log("Local SDP: ", localSdp); 342 | 343 | signaling.send({ 344 | type: "ANSWER", 345 | sessionId: offer.sessionId, 346 | target: offer.peer.id, 347 | sdp: encodeSdp(localSdp), 348 | }); 349 | 350 | console.log("Waiting for data channel..."); 351 | 352 | const dataChannel = await dataChannelPromise; 353 | dataChannel.binaryType = "arraybuffer"; 354 | 355 | console.log("Received data channel"); 356 | 357 | const dataChannelStream = createStreamController(dataChannel); 358 | 359 | await new Promise((resolve) => { 360 | dataChannel.onopen = () => resolve(); 361 | }); 362 | 363 | console.log("Data channel opened. Exchanging nonce..."); 364 | 365 | const remoteNonce = await receiveNonce(dataChannelStream); 366 | const localNonce = await generateNonce(); 367 | dataChannel.send( 368 | JSON.stringify({ 369 | nonce: encodeBase64(localNonce), 370 | } as RTCNonceMessage), 371 | ); 372 | const nonce = new Uint8Array(localNonce.length + remoteNonce.length); 373 | nonce.set(remoteNonce); 374 | nonce.set(localNonce, remoteNonce.length); 375 | 376 | const remoteTokenRaw = await dataChannelStream.readNext(); 377 | if (typeof remoteTokenRaw !== "string") { 378 | throw new Error("Expected string"); 379 | } 380 | 381 | const remoteToken = JSON.parse(remoteTokenRaw) as RTCTokenRequest; 382 | console.log(`Received token: ${remoteToken.token}`); 383 | 384 | const localToken = await generateClientTokenFromNonce(signingKey, nonce); 385 | if (pin) { 386 | let remotePin = ""; 387 | let pinTry = 0; 388 | 389 | dataChannel.send( 390 | JSON.stringify({ 391 | status: "PIN_REQUIRED", 392 | token: localToken, 393 | } as RTCTokenResponse), 394 | ); 395 | 396 | while (true) { 397 | if (remotePin === pin.pin) { 398 | break; 399 | } 400 | 401 | if (pinTry >= pin.maxTries) { 402 | dataChannel.send( 403 | JSON.stringify({ 404 | status: "TOO_MANY_ATTEMPTS", 405 | } as RTCPinReceivingResponse), 406 | ); 407 | 408 | await waitBufferEmpty(dataChannel); 409 | return; 410 | } 411 | 412 | if (pinTry !== 0) { 413 | dataChannel.send( 414 | JSON.stringify({ 415 | status: "PIN_REQUIRED", 416 | } as RTCPinReceivingResponse), 417 | ); 418 | } 419 | 420 | const remotePinRaw = await dataChannelStream.readNext(); 421 | if (typeof remotePinRaw !== "string") { 422 | throw new Error("Expected string"); 423 | } 424 | remotePin = (JSON.parse(remotePinRaw) as RTCPinMessage).pin; 425 | pinTry++; 426 | } 427 | 428 | dataChannel.send( 429 | JSON.stringify({ 430 | status: "OK", 431 | } as RTCPinReceivingResponse), 432 | ); 433 | } else { 434 | dataChannel.send( 435 | JSON.stringify({ 436 | status: "OK", 437 | token: localToken, 438 | } as RTCTokenResponse), 439 | ); 440 | } 441 | 442 | console.log("Waiting for sender PIN status..."); 443 | 444 | let pinSendingResponseRaw = await receiveStringFromChunks(dataChannelStream); 445 | let pinSendingResponse = JSON.parse( 446 | pinSendingResponseRaw, 447 | ) as RTCPinSendingResponse; 448 | let fileList: FileDto[]; 449 | switch (pinSendingResponse.status) { 450 | case "OK": 451 | fileList = pinSendingResponse.files; 452 | break; 453 | case "TOO_MANY_ATTEMPTS": 454 | console.error("Too many attempts"); 455 | return; 456 | case "PIN_REQUIRED": 457 | fileList = await handlePin( 458 | dataChannelStream, 459 | dataChannel, 460 | onPin, 461 | true, 462 | (response) => { 463 | const parsed = JSON.parse(response) as RTCPinSendingResponse; 464 | if ( 465 | parsed.status === "PIN_REQUIRED" || 466 | parsed.status === "TOO_MANY_ATTEMPTS" 467 | ) { 468 | return parsed.status; 469 | } 470 | return parsed.files; 471 | }, 472 | ); 473 | break; 474 | } 475 | 476 | console.log("Received file list:", fileList); 477 | 478 | const selectedFiles = await selectFiles(fileList); 479 | 480 | const selectedFilesMap: Record = {}; 481 | const selectedFilesTokens: Record = {}; 482 | for (const file of fileList) { 483 | if (selectedFiles.includes(file.id)) { 484 | selectedFilesMap[file.id] = file; 485 | selectedFilesTokens[file.id] = Math.random().toString(); 486 | } 487 | } 488 | 489 | console.log(`Selected files: ${selectedFiles.length} / ${fileList.length}`); 490 | 491 | sendStringInChunks( 492 | dataChannel, 493 | JSON.stringify({ 494 | status: "OK", 495 | files: selectedFilesTokens, 496 | } as RTCFileListResponse), 497 | ); 498 | 499 | sendDelimiter(dataChannel); 500 | 501 | console.log("Receiving files..."); 502 | 503 | const dataChannelIterator = dataChannelStream.createAsyncIterator(); 504 | let fileState: { id: string; chunks: ArrayBuffer[]; curr: number } | null = 505 | null; 506 | for await (const chunk of dataChannelIterator.asyncIterator) { 507 | if (typeof chunk === "string") { 508 | if (fileState) { 509 | saveFileFromBytes( 510 | new Blob(fileState.chunks), 511 | selectedFilesMap[fileState.id].fileName, 512 | ); 513 | 514 | onFileProgress({ 515 | id: fileState.id, 516 | curr: fileState.curr, 517 | success: true, 518 | }); 519 | 520 | // Send status of last file 521 | dataChannel.send( 522 | JSON.stringify({ 523 | id: fileState.id, 524 | success: true, 525 | } as RTCSendFileResponse), 526 | ); 527 | 528 | if (chunk.length <= 1) { 529 | // End of all files 530 | // Wait for the last status to be sent 531 | fileState = null; 532 | await waitBufferEmpty(dataChannel); 533 | break; 534 | } 535 | } 536 | 537 | const header = JSON.parse(chunk) as RTCSendFileHeaderRequest; 538 | fileState = { 539 | id: header.id, 540 | chunks: [], 541 | curr: 0, 542 | }; 543 | } else { 544 | if (!fileState) { 545 | throw new Error("Expected file state"); 546 | } 547 | fileState.chunks.push(chunk); 548 | fileState.curr += chunk.byteLength; 549 | onFileProgress({ 550 | id: fileState.id, 551 | curr: fileState.curr, 552 | }); 553 | } 554 | } 555 | dataChannelIterator.releaseLock(); 556 | 557 | dataChannel.close(); 558 | peerConnection.close(); 559 | } 560 | 561 | async function createPeerConnection( 562 | stunServers: string[], 563 | ): Promise { 564 | const peerConnection = new RTCPeerConnection({ 565 | iceServers: 566 | stunServers.length === 0 567 | ? undefined 568 | : [ 569 | { 570 | urls: stunServers, 571 | }, 572 | ], 573 | }); 574 | 575 | peerConnection.onicecandidateerror = (event) => { 576 | console.error("ICE candidate error:", event); 577 | }; 578 | 579 | peerConnection.oniceconnectionstatechange = () => { 580 | console.log( 581 | "ICE connection state:", 582 | peerConnection.iceConnectionState, 583 | peerConnection 584 | .getConfiguration() 585 | .iceServers?.map((server) => server.urls), 586 | ); 587 | }; 588 | 589 | return peerConnection; 590 | } 591 | 592 | function createStreamController(dataChannel: RTCDataChannel) { 593 | const dataChannelStream = new StreamController(); 594 | dataChannel.onmessage = (event) => { 595 | dataChannelStream.add(event.data); 596 | }; 597 | return dataChannelStream; 598 | } 599 | 600 | export type PinConfig = { 601 | pin: string; 602 | maxTries: number; 603 | }; 604 | 605 | export type FileProgress = { 606 | id: string; 607 | curr: number; 608 | success?: boolean; 609 | error?: string; 610 | }; 611 | 612 | export type FileDto = { 613 | id: string; 614 | fileName: string; 615 | size: number; 616 | fileType: string; 617 | sha256?: string; 618 | preview?: string; 619 | metadata?: FileMetadata; 620 | }; 621 | 622 | export type FileMetadata = { 623 | modified?: string; 624 | accessed?: string; 625 | }; 626 | 627 | type RTCNonceMessage = { 628 | nonce: string; 629 | }; 630 | 631 | type RTCTokenRequest = { 632 | token: string; 633 | }; 634 | 635 | type RTCTokenResponse = 636 | | { 637 | status: "OK"; 638 | token: string; 639 | } 640 | | { 641 | status: "PIN_REQUIRED"; 642 | token: string; 643 | } 644 | | { 645 | status: "INVALID_SIGNATURE"; 646 | }; 647 | 648 | type RTCPinMessage = { 649 | pin: string; 650 | }; 651 | 652 | type RTCPinReceivingResponse = { 653 | status: "OK" | "PIN_REQUIRED" | "TOO_MANY_ATTEMPTS"; 654 | }; 655 | 656 | type RTCPinSendingResponse = 657 | | { 658 | status: "OK"; 659 | files: FileDto[]; 660 | } 661 | | { 662 | status: "PIN_REQUIRED"; 663 | } 664 | | { 665 | status: "TOO_MANY_ATTEMPTS"; 666 | }; 667 | 668 | type RTCFileListResponse = 669 | | { 670 | status: "OK"; 671 | files: Record; 672 | } 673 | | { 674 | status: "PAIR"; 675 | publicKey: string; 676 | } 677 | | { 678 | status: "DECLINED"; 679 | } 680 | | { 681 | status: "INVALID_SIGNATURE"; 682 | }; 683 | 684 | type RTCPairResponse = 685 | | { 686 | status: "OK"; 687 | publicKey: string; 688 | } 689 | | { 690 | status: "PAIR_DECLINED"; 691 | } 692 | | { 693 | status: "INVALID_SIGNATURE"; 694 | }; 695 | 696 | type RTCSendFileHeaderRequest = { 697 | id: string; 698 | token: string; 699 | }; 700 | 701 | type RTCSendFileResponse = { 702 | id: string; 703 | success: boolean; 704 | error?: string; 705 | }; 706 | 707 | function encodeSdp(s: string): string { 708 | const data = new TextEncoder().encode(s); 709 | const compressed = pako.deflate(data); 710 | return encodeBase64(compressed); 711 | } 712 | 713 | function decodeSdp(s: string): string { 714 | const compressed = decodeBase64(s); 715 | const decompressed = pako.inflate(compressed); 716 | 717 | if (!decompressed) { 718 | throw new Error("Decompression failed."); 719 | } 720 | 721 | return new TextDecoder().decode(decompressed); 722 | } 723 | 724 | async function receiveNonce( 725 | dataChannelStream: StreamController, 726 | ): Promise { 727 | const remoteNonce = await dataChannelStream.readNext(); 728 | if (typeof remoteNonce !== "string") { 729 | throw new Error("Expected string"); 730 | } 731 | 732 | const nonceMsg = JSON.parse(remoteNonce) as RTCNonceMessage; 733 | const decodedNonce = decodeBase64(nonceMsg.nonce); 734 | 735 | if (!validateNonce(decodedNonce)) { 736 | throw new Error("Invalid remote nonce"); 737 | } 738 | 739 | return decodedNonce; 740 | } 741 | 742 | // Note: Type must be **not** a string. 743 | async function handlePin( 744 | dataChannelStream: StreamController, 745 | dataChannel: RTCDataChannel, 746 | onPin: () => Promise, 747 | receiveInChunks: boolean, 748 | parseResponse: (response: string) => T | "PIN_REQUIRED" | "TOO_MANY_ATTEMPTS", 749 | ): Promise { 750 | while (true) { 751 | const pin = await onPin(); 752 | if (!pin) { 753 | dataChannel.close(); 754 | throw new Error("PIN required"); 755 | } 756 | 757 | dataChannel.send( 758 | JSON.stringify({ 759 | pin: pin, 760 | } as RTCPinMessage), 761 | ); 762 | 763 | let response: string; 764 | if (receiveInChunks) { 765 | response = await receiveStringFromChunks(dataChannelStream); 766 | } else { 767 | const tmp = await dataChannelStream.readNext(); 768 | if (typeof tmp !== "string") { 769 | throw new Error("Expected string"); 770 | } 771 | response = tmp; 772 | } 773 | 774 | const parsedResponse = parseResponse(response); 775 | if (parsedResponse && typeof parsedResponse !== "string") { 776 | return parsedResponse as T; 777 | } 778 | 779 | switch (parsedResponse) { 780 | case "PIN_REQUIRED": 781 | break; 782 | case "TOO_MANY_ATTEMPTS": 783 | throw new Error("Too many attempts"); 784 | } 785 | } 786 | } 787 | 788 | async function receiveStringFromChunks( 789 | dataChannelStream: StreamController, 790 | ): Promise { 791 | let dataChannelIterator = dataChannelStream.createAsyncIterator(); 792 | let chunks: ArrayBuffer[] = []; 793 | for await (const chunk of dataChannelIterator.asyncIterator) { 794 | if (typeof chunk === "string") { 795 | break; 796 | } 797 | chunks.push(chunk); 798 | } 799 | dataChannelIterator.releaseLock(); 800 | 801 | return arrayBufferToString(chunks); 802 | } 803 | 804 | function sendDelimiter(dataChannel: RTCDataChannel) { 805 | dataChannel.send("0"); 806 | } 807 | 808 | const CHUNK_SIZE = 16 * 1024; // 16 KiB 809 | 810 | const MAX_BUFFERED_AMOUNT = 1024 * 1024; // 1 MiB 811 | 812 | function sendStringInChunks(dataChannel: RTCDataChannel, str: string) { 813 | const utf8Binary = new TextEncoder().encode(str); 814 | for (let i = 0; i < utf8Binary.length; i += CHUNK_SIZE) { 815 | dataChannel.send(utf8Binary.slice(i, i + CHUNK_SIZE)); 816 | } 817 | } 818 | 819 | /** 820 | * Send a file in chunks. 821 | * It buffers until CHUNK_SIZE is reached and splits if the buffer too large. 822 | * @param dataChannel 823 | * @param file 824 | * @param onProgress 825 | */ 826 | async function sendFileInChunks( 827 | dataChannel: RTCDataChannel, 828 | file: File, 829 | onProgress: (bytes: number) => void, 830 | ) { 831 | const reader = file.stream().getReader(); 832 | let buffer = new Uint8Array(0); 833 | let bytesSent = 0; 834 | 835 | while (true) { 836 | const { done, value } = await reader.read(); 837 | if (done) { 838 | // No more data from file; send remaining buffer if it has any data. 839 | if (buffer.length > 0) { 840 | dataChannel.send(buffer); 841 | } 842 | break; 843 | } 844 | 845 | const newBuffer = new Uint8Array(buffer.length + value.length); 846 | newBuffer.set(buffer); 847 | newBuffer.set(value, buffer.length); 848 | buffer = newBuffer; 849 | 850 | // As long as the buffer is large enough to contain at least one chunk, send chunks. 851 | while (buffer.length >= CHUNK_SIZE) { 852 | while (dataChannel.bufferedAmount > MAX_BUFFERED_AMOUNT) { 853 | await new Promise((resolve) => setTimeout(resolve, 50)); 854 | } 855 | 856 | const chunkToSend = buffer.slice(0, CHUNK_SIZE); 857 | dataChannel.send(chunkToSend); 858 | 859 | bytesSent += chunkToSend.length; 860 | onProgress(bytesSent); 861 | 862 | // Remove the chunk from buffer 863 | buffer = buffer.slice(CHUNK_SIZE); 864 | } 865 | } 866 | } 867 | 868 | function arrayBufferToString(arrayBuffers: ArrayBuffer[]): string { 869 | const totalLength = arrayBuffers.reduce( 870 | (sum, buffer) => sum + buffer.byteLength, 871 | 0, 872 | ); 873 | const combinedArray = new Uint8Array(totalLength); 874 | let offset = 0; 875 | arrayBuffers.forEach((buffer) => { 876 | combinedArray.set(new Uint8Array(buffer), offset); 877 | offset += buffer.byteLength; 878 | }); 879 | return new TextDecoder().decode(combinedArray); 880 | } 881 | 882 | async function waitBufferEmpty(dataChannel: RTCDataChannel) { 883 | while (dataChannel.bufferedAmount > 0) { 884 | await new Promise((resolve) => setTimeout(resolve, 50)); 885 | } 886 | } 887 | 888 | async function waitICEGathering(localConnection: RTCPeerConnection) { 889 | if (localConnection.iceGatheringState === "complete") { 890 | return; 891 | } 892 | 893 | await new Promise((resolve) => { 894 | localConnection.onicegatheringstatechange = () => { 895 | if (localConnection.iceGatheringState === "complete") { 896 | resolve(); 897 | } 898 | }; 899 | }); 900 | } 901 | -------------------------------------------------------------------------------- /tailwind.config.ts: -------------------------------------------------------------------------------- 1 | import type { Config } from "tailwindcss"; 2 | 3 | export default >{ 4 | darkMode: "class", 5 | }; 6 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | // https://nuxt.com/docs/guide/concepts/typescript 3 | "extends": "./.nuxt/tsconfig.json" 4 | } 5 | -------------------------------------------------------------------------------- /utils/alias.ts: -------------------------------------------------------------------------------- 1 | const adjectives = [ 2 | "Adorable", 3 | "Beautiful", 4 | "Big", 5 | "Bright", 6 | "Clean", 7 | "Clever", 8 | "Cool", 9 | "Cute", 10 | "Cunning", 11 | "Determined", 12 | "Energetic", 13 | "Efficient", 14 | "Fantastic", 15 | "Fast", 16 | "Fine", 17 | "Fresh", 18 | "Good", 19 | "Gorgeous", 20 | "Great", 21 | "Handsome", 22 | "Hot", 23 | "Kind", 24 | "Lovely", 25 | "Mystic", 26 | "Neat", 27 | "Nice", 28 | "Patient", 29 | "Pretty", 30 | "Powerful", 31 | "Rich", 32 | "Secret", 33 | "Smart", 34 | "Solid", 35 | "Special", 36 | "Strategic", 37 | "Strong", 38 | "Tidy", 39 | "Wise", 40 | ]; 41 | 42 | const fruits = [ 43 | "Apple", 44 | "Avocado", 45 | "Banana", 46 | "Blackberry", 47 | "Blueberry", 48 | "Broccoli", 49 | "Carrot", 50 | "Cherry", 51 | "Coconut", 52 | "Grape", 53 | "Lemon", 54 | "Lettuce", 55 | "Mango", 56 | "Melon", 57 | "Mushroom", 58 | "Onion", 59 | "Orange", 60 | "Papaya", 61 | "Peach", 62 | "Pear", 63 | "Pineapple", 64 | "Potato", 65 | "Pumpkin", 66 | "Raspberry", 67 | "Strawberry", 68 | "Tomato", 69 | ]; 70 | 71 | export function generateRandomAlias(): string { 72 | const adjective = adjectives[Math.floor(Math.random() * adjectives.length)]; 73 | const fruit = fruits[Math.floor(Math.random() * fruits.length)]; 74 | return `${adjective} ${fruit}`; 75 | } 76 | -------------------------------------------------------------------------------- /utils/base64.test.ts: -------------------------------------------------------------------------------- 1 | import { expect, test } from "vitest"; 2 | import { encodeStringToBase64 } from "./base64"; 3 | 4 | test("Should encode string correctly", () => { 5 | const data = { 6 | alias: "Cute Orange", 7 | version: "2.3", 8 | deviceModel: "Samsung", 9 | deviceType: "mobile", 10 | fingerprint: "123456", 11 | }; 12 | const encoded = encodeStringToBase64(JSON.stringify(data)); 13 | expect(encoded).toBe( 14 | "eyJhbGlhcyI6IkN1dGUgT3JhbmdlIiwidmVyc2lvbiI6IjIuMyIsImRldmljZU1vZGVsIjoiU2Ftc3VuZyIsImRldmljZVR5cGUiOiJtb2JpbGUiLCJmaW5nZXJwcmludCI6IjEyMzQ1NiJ9", 15 | ); 16 | }); 17 | 18 | test("Should not add padding", () => { 19 | const encoded = encodeStringToBase64("abcd"); 20 | expect(encoded).toBe("YWJjZA"); 21 | }); 22 | 23 | test("Should use URI encoding", () => { 24 | const encoded = encodeStringToBase64("==?"); 25 | expect(encoded).toBe("PT0_"); 26 | }); 27 | -------------------------------------------------------------------------------- /utils/base64.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Encodes a string in base64 representing the string in UTF-8. 3 | * @param str 4 | */ 5 | export function encodeStringToBase64(str: string): string { 6 | return encodeBase64(new TextEncoder().encode(str)); 7 | } 8 | 9 | /** 10 | * Encodes a binary in base64. 11 | * @param binary 12 | */ 13 | export function encodeBase64(binary: Uint8Array): string { 14 | const binaryString = Array.from(binary) 15 | .map((byte) => String.fromCharCode(byte)) 16 | .join(""); 17 | 18 | // Encode to Base64 19 | const base64 = btoa(binaryString); 20 | 21 | // Make Base64 URL-safe 22 | return base64.replaceAll("=", "").replaceAll("+", "-").replaceAll("/", "_"); 23 | } 24 | 25 | /** 26 | * Decodes a base64 string to a binary. 27 | * @param base64 28 | */ 29 | export function decodeBase64(base64: string): Uint8Array { 30 | // Revert URL safety 31 | const padded = base64.padEnd( 32 | base64.length + ((4 - (base64.length % 4)) % 4), 33 | "=", 34 | ); 35 | const urlSafe = padded.replaceAll("-", "+").replaceAll("_", "/"); 36 | 37 | // Decode from Base64 38 | const binaryString = atob(urlSafe); 39 | 40 | return Uint8Array.from(binaryString, (c) => c.charCodeAt(0)); 41 | } 42 | -------------------------------------------------------------------------------- /utils/fileSaver.ts: -------------------------------------------------------------------------------- 1 | export function saveFileFromBytes( 2 | blob: Blob, 3 | fileName: string, 4 | mimeType = "application/octet-stream", 5 | ) { 6 | // Generate a temporary URL for the Blob 7 | const url = URL.createObjectURL(blob); 8 | 9 | // Create a hidden anchor element 10 | const a = document.createElement("a"); 11 | a.href = url; 12 | a.download = fileName; // Specify the file name 13 | 14 | document.body.appendChild(a); 15 | a.click(); 16 | document.body.removeChild(a); 17 | 18 | URL.revokeObjectURL(url); 19 | } 20 | -------------------------------------------------------------------------------- /utils/fileSize.ts: -------------------------------------------------------------------------------- 1 | export function formatBytes(bytes: number): string { 2 | if (bytes < 1024) { 3 | return bytes + " B"; 4 | } else if (bytes < 1024 * 1024) { 5 | return (bytes / 1024).toFixed(1) + " KB"; 6 | } else if (bytes < 1024 * 1024 * 1024) { 7 | return (bytes / (1024 * 1024)).toFixed(1) + " MB"; 8 | } else { 9 | return (bytes / (1024 * 1024 * 1024)).toFixed(1) + " GB"; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /utils/nonce.ts: -------------------------------------------------------------------------------- 1 | export async function generateNonce(): Promise { 2 | const nonce = new Uint8Array(32); 3 | window.crypto.getRandomValues(nonce); 4 | return nonce; 5 | } 6 | 7 | export function validateNonce(nonce: Uint8Array): boolean { 8 | return nonce.byteLength >= 16 && nonce.byteLength <= 128; 9 | } 10 | -------------------------------------------------------------------------------- /utils/streamController.test.ts: -------------------------------------------------------------------------------- 1 | import { expect, test } from "vitest"; 2 | import { StreamController } from "./streamController"; 3 | 4 | test("Should add data to stream", async () => { 5 | const streamController = new StreamController(); 6 | streamController.add(1); 7 | streamController.add(2); 8 | streamController.add(3); 9 | 10 | const { asyncIterator } = streamController.createAsyncIterator(); 11 | 12 | let emitted = []; 13 | 14 | for await (const value of asyncIterator) { 15 | emitted.push(value); 16 | if (value === 3) { 17 | break; 18 | } 19 | } 20 | 21 | expect(emitted).toEqual([1, 2, 3]); 22 | }); 23 | 24 | test("Should be able to resume after break", async () => { 25 | const streamController = new StreamController(); 26 | streamController.add(1); 27 | streamController.add(2); 28 | streamController.add(3); 29 | 30 | const iterator = streamController.createAsyncIterator(); 31 | 32 | let emitted = []; 33 | 34 | for await (const value of iterator.asyncIterator) { 35 | emitted.push(value); 36 | 37 | if (emitted.length === 2) { 38 | break; 39 | } 40 | } 41 | 42 | iterator.releaseLock(); 43 | expect(emitted).toEqual([1, 2]); 44 | streamController.add(10); 45 | 46 | for await (const value of streamController.createAsyncIterator() 47 | .asyncIterator) { 48 | emitted.push(value); 49 | 50 | if (value === 10) { 51 | break; 52 | } 53 | } 54 | 55 | expect(emitted).toEqual([1, 2, 3, 10]); 56 | }); 57 | -------------------------------------------------------------------------------- /utils/streamController.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * A simple stream controller like in Dart language. 3 | */ 4 | export class StreamController { 5 | private _stream: ReadableStream; 6 | private _controller: ReadableStreamDefaultController; 7 | 8 | constructor() { 9 | let controller!: ReadableStreamDefaultController; 10 | this._stream = new ReadableStream({ 11 | start(c) { 12 | controller = c; 13 | }, 14 | }); 15 | this._controller = controller; 16 | } 17 | 18 | public add(data: T) { 19 | this._controller.enqueue(data); 20 | } 21 | 22 | public async readNext(): Promise { 23 | const reader = this._stream.getReader(); 24 | 25 | try { 26 | const { value, done } = await reader.read(); 27 | if (done) { 28 | throw new Error("No more data"); 29 | } 30 | return value as T; 31 | } finally { 32 | reader.releaseLock(); 33 | } 34 | } 35 | 36 | public createAsyncIterator() { 37 | let reader: ReadableStreamDefaultReader; 38 | const asyncIterator = this._createAsyncIterator((r) => (reader = r)); 39 | return { 40 | asyncIterator: asyncIterator as AsyncGenerator, 41 | releaseLock: () => reader.releaseLock(), 42 | }; 43 | } 44 | 45 | private async *_createAsyncIterator( 46 | onReader: (reader: ReadableStreamDefaultReader) => void, 47 | ) { 48 | const reader = this._stream.getReader(); 49 | onReader(reader); 50 | try { 51 | while (true) { 52 | const { value, done } = await reader.read(); 53 | if (done) break; 54 | yield value; 55 | } 56 | } finally { 57 | reader.releaseLock(); 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /utils/userAgent.ts: -------------------------------------------------------------------------------- 1 | export function getAgentInfoString(userAgent: string): string { 2 | const browser = getBrowser(userAgent); 3 | const os = getOS(userAgent); 4 | if (browser && os) { 5 | return `${os} • ${browser}`; 6 | } else if (browser) { 7 | return browser; 8 | } else if (os) { 9 | return os; 10 | } else { 11 | return "Unknown"; 12 | } 13 | } 14 | 15 | export function getBrowser(userAgent: string): string | null { 16 | if (userAgent.includes("Firefox")) { 17 | return "Firefox"; 18 | } else if (userAgent.includes("Chrome")) { 19 | return "Chrome"; 20 | } else if (userAgent.includes("Safari")) { 21 | return "Safari"; 22 | } else if (userAgent.includes("Opera") || userAgent.includes("OPR")) { 23 | return "Opera"; 24 | } else if (userAgent.includes("Edg")) { 25 | return "Edge"; 26 | } else if (userAgent.includes("MSIE") || userAgent.includes("Trident")) { 27 | return "Internet Explorer"; 28 | } else if (userAgent.includes("insomnia")) { 29 | return "Insomnia"; 30 | } else { 31 | return null; 32 | } 33 | } 34 | 35 | export function getOS(userAgent: string): string | null { 36 | if (userAgent.includes("Win")) { 37 | return "Windows"; 38 | } else if (userAgent.includes("Android")) { 39 | return "Android"; 40 | } else if (userAgent.includes("Macintosh")) { 41 | return "macOS"; 42 | } else if ( 43 | userAgent.includes("iPhone") || 44 | userAgent.includes("iPad") || 45 | userAgent.includes("iPod") 46 | ) { 47 | return "iOS"; 48 | } else if (userAgent.includes("X11")) { 49 | return "Linux"; 50 | } else { 51 | return null; 52 | } 53 | } 54 | --------------------------------------------------------------------------------