├── .gitignore ├── Dockerfile ├── LICENSE ├── README.md ├── bun.lockb ├── docker-compose.yml ├── package.json ├── render.yaml ├── src ├── index.ts └── routes │ ├── fetch.ts │ └── index.ts └── tsconfig.json /.gitignore: -------------------------------------------------------------------------------- 1 | # Based on https://raw.githubusercontent.com/github/gitignore/main/Node.gitignore 2 | 3 | # Logs 4 | 5 | logs 6 | _.log 7 | npm-debug.log_ 8 | yarn-debug.log* 9 | yarn-error.log* 10 | lerna-debug.log* 11 | .pnpm-debug.log* 12 | 13 | # Caches 14 | 15 | .cache 16 | 17 | # Diagnostic reports (https://nodejs.org/api/report.html) 18 | 19 | report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json 20 | 21 | # Runtime data 22 | 23 | pids 24 | _.pid 25 | _.seed 26 | *.pid.lock 27 | 28 | # Directory for instrumented libs generated by jscoverage/JSCover 29 | 30 | lib-cov 31 | 32 | # Coverage directory used by tools like istanbul 33 | 34 | coverage 35 | *.lcov 36 | 37 | # nyc test coverage 38 | 39 | .nyc_output 40 | 41 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 42 | 43 | .grunt 44 | 45 | # Bower dependency directory (https://bower.io/) 46 | 47 | bower_components 48 | 49 | # node-waf configuration 50 | 51 | .lock-wscript 52 | 53 | # Compiled binary addons (https://nodejs.org/api/addons.html) 54 | 55 | build/Release 56 | 57 | # Dependency directories 58 | 59 | node_modules/ 60 | jspm_packages/ 61 | 62 | # Snowpack dependency directory (https://snowpack.dev/) 63 | 64 | web_modules/ 65 | 66 | # TypeScript cache 67 | 68 | *.tsbuildinfo 69 | 70 | # Optional npm cache directory 71 | 72 | .npm 73 | 74 | # Optional eslint cache 75 | 76 | .eslintcache 77 | 78 | # Optional stylelint cache 79 | 80 | .stylelintcache 81 | 82 | # Microbundle cache 83 | 84 | .rpt2_cache/ 85 | .rts2_cache_cjs/ 86 | .rts2_cache_es/ 87 | .rts2_cache_umd/ 88 | 89 | # Optional REPL history 90 | 91 | .node_repl_history 92 | 93 | # Output of 'npm pack' 94 | 95 | *.tgz 96 | 97 | # Yarn Integrity file 98 | 99 | .yarn-integrity 100 | 101 | # dotenv environment variable files 102 | 103 | .env 104 | .env.development.local 105 | .env.test.local 106 | .env.production.local 107 | .env.local 108 | 109 | # parcel-bundler cache (https://parceljs.org/) 110 | 111 | .parcel-cache 112 | 113 | # Next.js build output 114 | 115 | .next 116 | out 117 | 118 | # Nuxt.js build / generate output 119 | 120 | .nuxt 121 | dist 122 | 123 | # Gatsby files 124 | 125 | # Comment in the public line in if your project uses Gatsby and not Next.js 126 | 127 | # https://nextjs.org/blog/next-9-1#public-directory-support 128 | 129 | # public 130 | 131 | # vuepress build output 132 | 133 | .vuepress/dist 134 | 135 | # vuepress v2.x temp and cache directory 136 | 137 | .temp 138 | 139 | # Docusaurus cache and generated files 140 | 141 | .docusaurus 142 | 143 | # Serverless directories 144 | 145 | .serverless/ 146 | 147 | # FuseBox cache 148 | 149 | .fusebox/ 150 | 151 | # DynamoDB Local files 152 | 153 | .dynamodb/ 154 | 155 | # TernJS port file 156 | 157 | .tern-port 158 | 159 | # Stores VSCode versions used for testing VSCode extensions 160 | 161 | .vscode-test 162 | 163 | # yarn v2 164 | 165 | .yarn/cache 166 | .yarn/unplugged 167 | .yarn/build-state.yml 168 | .yarn/install-state.gz 169 | .pnp.* 170 | 171 | # IntelliJ based IDEs 172 | .idea 173 | 174 | # Finder (MacOS) folder config 175 | .DS_Store 176 | 177 | backup.ts -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM oven/bun:1 2 | WORKDIR /app 3 | COPY . . 4 | RUN bun install 5 | 6 | EXPOSE 3000 7 | 8 | CMD ["bun", "start"] 9 | -------------------------------------------------------------------------------- /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 2024 Blue 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. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## No updates/fixes until October 2025 2 | 3 | # m3u8-proxy 4 | 5 | Join the [discord](https://discord.gg/88ArBFRcY8) for support 6 | 7 | `m3u8-proxy` is a TypeScript-based proxy server that serves M3U8 playlist files. It is designed to be lightweight, easy to deploy, and efficient for streaming purposes. 8 | 9 | # List of free instances 10 | 11 | I run a few free instances of this proxy server. You can use them for free. Here are the links: 12 | 13 | [Koyeb](https://renewed-georgeanne-nekonode-1aa70c0c.koyeb.app/), You can also deploy your own instance on Koyeb by clicking the button below. 14 | 15 | ## Note 16 | 17 | This proxy will work for most M3U8 files, but it may not work for all. If you encounter any issues, please open an issue on this repository. 18 | 19 | ## Features 20 | 21 | - **Serve M3U8 files**: Acts as a proxy server to handle and serve M3U8 files, ensuring smooth streaming experiences. 22 | - **Easy Deployment**: Quickly deployable to cloud platforms such as Koyeb. 23 | - **TypeScript**: Written in TypeScript for robust type safety and maintainability. 24 | - **Lightweight**: Minimal dependencies to keep the project fast and responsive. 25 | - **Efficient**: Designed to be efficient for streaming purposes. 26 | 27 | ## Try it out 28 | 29 | You can try out the proxy by making a request to the following URL: 30 | 31 | ``` 32 | https://renewed-georgeanne-nekonode-1aa70c0c.koyeb.app/fetch/?url=https://example.com/playlist.m3u8 33 | ``` 34 | 35 | Using this for Images: 36 | 37 | ``` 38 | https://renewed-georgeanne-nekonode-1aa70c0c.koyeb.app/fetch/image?url=https://upload.wikimedia.org/wikipedia/commons/b/b6/Image_created_with_a_mobile_phone.png 39 | ``` 40 | 41 | # Note 42 | 43 | You can use it to view website but you will not be able to view the js, css, svg, etc. files within the website. 44 | 45 | ## Deployment 46 | 47 | [![Deploy to Koyeb](https://www.koyeb.com/static/images/deploy/button.svg)](https://app.koyeb.com/deploy?name=simple-proxy&type=git&repository=DeveloperJosh/m3u8-proxy&branch=main&env[PORT]=3000&ports=3000;http;/&builder=dockerfile) 48 | -------------------------------------------------------------------------------- /bun.lockb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DeveloperJosh/m3u8-proxy/ecf7201746a8666a86e7eba17fb7d75ab0a88788/bun.lockb -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | services: 2 | app: 3 | build: 4 | context: . 5 | dockerfile: Dockerfile 6 | environment: 7 | - NODE_ENV=production 8 | - PORT=3000 # Edit as needed (edit the port in dockerfile too) 9 | ports: 10 | - "3000:3000" # Expose the app on port 3000, edit as needed(edit the port in dockerfile too) 11 | volumes: 12 | - .:/app 13 | command: ["bun", "start"] 14 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "m3u8-proxy", 3 | "type": "module", 4 | "packageManager": "bun@1.1.21", 5 | "devDependencies": { 6 | "@types/bun": "latest" 7 | }, 8 | "peerDependencies": { 9 | "typescript": "^5.0.0" 10 | }, 11 | "dependencies": { 12 | "@types/cors": "^2.8.17", 13 | "@types/debug": "^4.1.12", 14 | "@types/express": "^4.17.21", 15 | "@types/morgan": "^1.9.9", 16 | "@types/uuid": "^10.0.0", 17 | "axios": "^1.7.4", 18 | "cors": "^2.8.5", 19 | "debug": "^4.3.7", 20 | "express": "^4.19.2", 21 | "express-rate-limit": "^7.5.0", 22 | "m3u8-parser": "^7.2.0", 23 | "morgan": "^1.10.0", 24 | "node-cache": "^5.1.2", 25 | "uuid": "^11.0.3" 26 | }, 27 | "scripts": { 28 | "start": "bun src/index.ts", 29 | "dev": "bun src/index.ts --watch" 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /render.yaml: -------------------------------------------------------------------------------- 1 | services: 2 | - type: web 3 | name: simple-proxy 4 | env: standard 5 | buildCommand: bun install 6 | startCommand: bun start 7 | envVars: 8 | - key: NODE_ENV 9 | value: production 10 | autoDeploy: true 11 | healthCheckPath: /health 12 | plan: free 13 | runtime: node 14 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import express from 'express'; 2 | import morgan from 'morgan'; 3 | import cors from 'cors'; 4 | 5 | import indexRouter from './routes/index.ts'; 6 | import proxyRouter from './routes/fetch.ts'; 7 | 8 | const app = express(); 9 | 10 | app.use(express.json()); 11 | 12 | app.set('trust proxy', true); // this is for if you're behind a load balancer or a reverse proxy 13 | 14 | app.use(cors({ 15 | origin: '*', 16 | methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], 17 | allowedHeaders: ['Content-Type', 'Authorization'], 18 | maxAge: 3600, 19 | })); 20 | 21 | app.use(morgan('combined')); 22 | 23 | app.use('/', indexRouter); 24 | 25 | app.use('/fetch', proxyRouter); 26 | 27 | const PORT = process.env.PORT || 3000; 28 | app.listen(PORT, () => { 29 | console.log(`Server is running on port ${PORT}`); 30 | }); 31 | -------------------------------------------------------------------------------- /src/routes/fetch.ts: -------------------------------------------------------------------------------- 1 | import { Router, type Request, type Response } from 'express'; 2 | import axios from 'axios'; 3 | import crypto from 'crypto'; 4 | import debugLib from 'debug'; 5 | import NodeCache from 'node-cache'; 6 | import { v4 as uuidv4 } from 'uuid'; 7 | 8 | const router = Router(); 9 | const debug = debugLib('proxy:debug'); 10 | const cache = new NodeCache({ stdTTL: 600 }); // 600 seconds = 10 minutes 11 | 12 | const SECRET_KEY = process.env.SECRET_KEY || 'update-this-secret'; 13 | 14 | /** 15 | * generateSignedUrl 16 | * - Creates a signature for a resourceId 17 | * - Adds an expiration time (UNIX timestamp, 10 minutes from now) 18 | * - Returns a local endpoint: /segment/resource?resourceId=xxx&sig=yyy&exp=zzz 19 | */ 20 | function generateSignedUrl(resourceId: string, type: 'segment'): string { 21 | const exp = Math.floor(Date.now() / 1000) + 600; // 600 seconds = 10 minutes 22 | const signature = crypto 23 | .createHmac('sha256', SECRET_KEY) 24 | .update(`${resourceId}${exp}${type}`) 25 | .digest('hex'); 26 | 27 | return `/fetch/segment/resource?resourceId=${resourceId}&sig=${signature}&exp=${exp}`; 28 | } 29 | 30 | /** 31 | * verifySignedUrl 32 | * - Checks if the signature matches 33 | * - Checks if the expiration hasn't passed 34 | */ 35 | function verifySignedUrl( 36 | resourceId: string, 37 | sig: string, 38 | exp: string, 39 | type: 'segment' 40 | ): boolean { 41 | const now = Math.floor(Date.now() / 1000); 42 | if (parseInt(exp, 10) < now) { 43 | return false; 44 | } 45 | 46 | const expectedSig = crypto 47 | .createHmac('sha256', SECRET_KEY) 48 | .update(`${resourceId}${exp}${type}`) 49 | .digest('hex'); 50 | 51 | return sig === expectedSig; 52 | } 53 | 54 | /** 55 | * GET / 56 | * - Example route for fetching a remote M3U8 57 | * based on ?url=. 58 | * - Rewrites all lines that do *not* start with '#' (resources) to a signed local URL. 59 | * - Ref parameter is optional and can be used to set the Referer header. 60 | */ 61 | router.get('/', async (req: Request, res: Response) => { 62 | const { url, ref } = req.query; 63 | 64 | if (!url || typeof url !== 'string') { 65 | return res.status(400).json({ error: 'No URL provided' }); 66 | } 67 | 68 | try { 69 | debug(`Fetching M3U8 file from: ${url}`); 70 | 71 | const headers: Record = {}; 72 | if (ref && typeof ref === 'string') { 73 | headers['Referer'] = ref; 74 | } 75 | 76 | const response = await axios.get(url, { responseType: 'text', headers }); 77 | 78 | let m3u8Content = response.data as string; 79 | 80 | if (!m3u8Content.startsWith('#EXTM3U')) { 81 | debug('Not a valid M3U8 (no #EXTM3U at start), returning raw content'); 82 | return res.type('text/plain').send(m3u8Content); 83 | } 84 | 85 | const lines = m3u8Content.split('\n'); 86 | 87 | const transformed = lines.map((line) => { 88 | const trimmed = line.trim(); 89 | if (!trimmed || trimmed.startsWith('#')) { 90 | return line; 91 | } 92 | 93 | const resourceId = uuidv4(); 94 | 95 | const absoluteUrl = new URL(trimmed, url).href; 96 | 97 | cache.set(resourceId, absoluteUrl); 98 | 99 | const signedUrl = generateSignedUrl(resourceId, 'segment'); 100 | debug(`Rewriting line: "${trimmed}" -> "${signedUrl}"`); 101 | return signedUrl; 102 | }); 103 | 104 | const newM3U8 = transformed.join('\n'); 105 | 106 | res.setHeader('Content-Type', 'application/vnd.apple.mpegurl'); 107 | res.send(newM3U8); 108 | debug('Rewritten M3U8 sent to client'); 109 | } catch (error) { 110 | debug(`Failed to proxy M3U8. Error: ${(error as Error).message}`); 111 | res.status(500).json({ error: 'Failed to fetch M3U8 content' }); 112 | } 113 | }); 114 | 115 | /** 116 | * GET /segment/resource 117 | * - The player will request this route whenever it sees 118 | * a line in the M3U8 like "/segment/resource?resourceId=xx&sig=yyy&exp=zzz" 119 | */ 120 | router.get('/segment/resource', async (req: Request, res: Response) => { 121 | const { resourceId, sig, exp } = req.query; 122 | 123 | if (!resourceId || !sig || !exp) { 124 | return res.status(400).json({ error: 'Missing signed URL params' }); 125 | } 126 | 127 | if (!verifySignedUrl(resourceId as string, sig as string, exp as string, 'segment')) { 128 | return res.status(400).json({ error: 'Invalid or expired signed URL' }); 129 | } 130 | 131 | const realUrl = cache.get(resourceId as string); 132 | if (!realUrl) { 133 | return res.status(404).json({ error: 'Resource not found or expired' }); 134 | } 135 | 136 | try { 137 | debug(`Fetching actual resource from: ${realUrl}`); 138 | 139 | const segmentResp = await axios.get(realUrl, { responseType: 'arraybuffer' }); 140 | 141 | let contentType = segmentResp.headers['content-type']; 142 | if (!contentType) { 143 | contentType = 'application/octet-stream'; 144 | } 145 | 146 | res.setHeader('Content-Type', contentType); 147 | res.send(segmentResp.data); 148 | debug('Segment served successfully'); 149 | } catch (error) { 150 | debug(`Failed to fetch resource: ${(error as Error).message}`); 151 | res.status(500).json({ error: 'Error fetching segment content' }); 152 | } 153 | }); 154 | 155 | router.get('/image', async (req: Request, res: Response) => { 156 | const { url, ref } = req.query; 157 | if (!url || typeof url !== 'string') { 158 | return res.status(400).json({ error: 'No URL provided' }); 159 | } 160 | 161 | try { 162 | debug(`Fetching image from: ${url}`); 163 | 164 | const headers: Record = {}; 165 | if (ref && typeof ref === 'string') { 166 | headers['Referer'] = ref; 167 | } 168 | 169 | const response = await axios.get(url, { responseType: 'arraybuffer', headers }); 170 | 171 | const contentType = response.headers['content-type']; 172 | res.setHeader('Content-Type', contentType); 173 | res.send(response.data); 174 | debug('Image served successfully'); 175 | } catch (error) { 176 | debug(`Failed to fetch image: ${(error as Error).message}`); 177 | res.status(500).json({ error: 'Error fetching image content' }); 178 | } 179 | }); 180 | 181 | export default router; -------------------------------------------------------------------------------- /src/routes/index.ts: -------------------------------------------------------------------------------- 1 | import { Router, type Request, type Response } from 'express'; 2 | 3 | const router = Router(); 4 | 5 | let requestCount = 0; 6 | 7 | router.use((req, res, next) => { 8 | requestCount++; 9 | next(); 10 | }); 11 | 12 | router.get('/', (req: Request, res: Response) => { 13 | res.json( 14 | { 15 | message: 'NekoProxy is ready🎉', 16 | endpoints: [ 17 | { 18 | method: 'GET', 19 | usage: '/fetch', 20 | description: 'Fetch a video stream from a URL', 21 | query: { 22 | url: 'The URL of the video or image.', 23 | ref: 'The referrer URL' 24 | }, 25 | note: "no note" 26 | }, 27 | { 28 | method: 'GET', 29 | usage: '/fetch/image', 30 | description: 'Fetch an image from a URL', 31 | query: { 32 | url: 'The URL of the image.', 33 | ref: 'The referrer URL' 34 | } 35 | }, 36 | { 37 | method: 'GET', 38 | usage: '/fetch/segment', 39 | description: 'Fetch a video segment from a URL', 40 | query: { 41 | url: 'The URL of the video segment.' 42 | } 43 | }, 44 | { 45 | method: 'GET', 46 | usage: '/health', 47 | description: 'Check the health status of the server' 48 | }, 49 | { 50 | method: 'GET', 51 | usage: '/reqs', 52 | description: 'Check the total number of requests made to the server(Resets every time the server restarts)' 53 | } 54 | ] 55 | } 56 | ); 57 | }); 58 | 59 | router.get('/health', (req: Request, res: Response) => { 60 | res.json({ status: 'OK' }); 61 | }); 62 | 63 | router.get('/reqs', async (req: Request, res: Response) => { 64 | const count = requestCount; 65 | if (count >= 1000) { 66 | const formattedCount = count / 1000; 67 | return res.json({ requests: `${formattedCount}k` }); 68 | } 69 | res.json({ requests: count }); 70 | }); 71 | 72 | export default router; 73 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | // Enable latest features 4 | "lib": ["ESNext", "DOM"], 5 | "target": "ESNext", 6 | "module": "ESNext", 7 | "moduleDetection": "force", 8 | "jsx": "react-jsx", 9 | "allowJs": true, 10 | 11 | // Bundler mode 12 | "moduleResolution": "bundler", 13 | "allowImportingTsExtensions": true, 14 | "verbatimModuleSyntax": true, 15 | "noEmit": true, 16 | 17 | // Best practices 18 | "strict": true, 19 | "skipLibCheck": true, 20 | "noFallthroughCasesInSwitch": true, 21 | 22 | // Some stricter flags (disabled by default) 23 | "noUnusedLocals": false, 24 | "noUnusedParameters": false, 25 | "noPropertyAccessFromIndexSignature": false 26 | } 27 | } 28 | --------------------------------------------------------------------------------