[Skip to content](https://github.com/peronecode/moisa-addon/blob/main/src/http/moisaHandler.js#start-of-content)

You signed in with another tab or window. [Reload](https://github.com/peronecode/moisa-addon/blob/main/src/http/moisaHandler.js) to refresh your session.You signed out in another tab or window. [Reload](https://github.com/peronecode/moisa-addon/blob/main/src/http/moisaHandler.js) to refresh your session.You switched accounts on another tab or window. [Reload](https://github.com/peronecode/moisa-addon/blob/main/src/http/moisaHandler.js) to refresh your session.Dismiss alert

{{ message }}

[peronecode](https://github.com/peronecode)/ **[moisa-addon](https://github.com/peronecode/moisa-addon)** Public

- [Notifications](https://github.com/login?return_to=%2Fperonecode%2Fmoisa-addon) You must be signed in to change notification settings
- [Fork\\
5](https://github.com/login?return_to=%2Fperonecode%2Fmoisa-addon)
- [Star\\
2](https://github.com/login?return_to=%2Fperonecode%2Fmoisa-addon)


## Collapse file tree

## Files

main

Search this repository(forward slash)` forward slash/`

/

# moisaHandler.js

Copy path

Blame

More file actions

Blame

More file actions

## Latest commit

[![peronecode](https://avatars.githubusercontent.com/u/5048812?v=4&size=40)](https://github.com/peronecode)[peronecode](https://github.com/peronecode/moisa-addon/commits?author=peronecode)

[Release 1.0.0](https://github.com/peronecode/moisa-addon/commit/514f8a7d31b62284883e53fc7731e21ebd3b65c5)

success

6 months agoJan 8, 2026

[514f8a7](https://github.com/peronecode/moisa-addon/commit/514f8a7d31b62284883e53fc7731e21ebd3b65c5) · 6 months agoJan 8, 2026

## History

[History](https://github.com/peronecode/moisa-addon/commits/main/src/http/moisaHandler.js)

Open commit details

[View commit history for this file.](https://github.com/peronecode/moisa-addon/commits/main/src/http/moisaHandler.js) History

320 lines (275 loc) · 9.58 KB

/

# moisaHandler.js

Copy path

Top

## File metadata and controls

- Code

- Blame


320 lines (275 loc) · 9.58 KB

[Raw](https://github.com/peronecode/moisa-addon/raw/refs/heads/main/src/http/moisaHandler.js)

Copy raw file

Download raw file

You must be signed in to make or propose changes

More edit options

Open symbols panel

Edit and raw actions

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

constaddonInterface=require('../addon');

const{ log, logError }=require('../utils/logger');

constfs=require('fs');

constpath=require('path');

/\*\*

\\* Decode a \`config=<base64>\` query parameter into a plain object.

\*/

functiondecodeConfig(query){

if(!query\|\|!query.config)returnnull;

try{

constjson=Buffer.from(String(query.config),'base64').toString('utf8');

constcfg=JSON.parse(json);

returncfg&&typeofcfg==='object' ? cfg : null;

}catch{

returnnull;

}

}

/\*\*

\\* Main HTTP handler used both for local \`server.js\` and Vercel \`api/moisa.js\`.

\*

\\* Routes:

\\* \- GET /favicon.ico – 32x32 browser tab icon.

\\* \- GET /assets/\* – static assets (PNG/SVG/WebP icons, logos, etc.).

\\* \- GET /manifest.json – Stremio addon manifest (includes \`logo\` field).

\\* \- GET /stream/:type/:id.json – Stremio stream resource.

\\* \- GET /play?infoHash=... – proxy that resolves to a direct TorrServer URL.

\\* \- GET /config or /configure – lightweight HTML config UI.

\*/

module.exports=async(req,res)=>{

// Derive a full URL object from the incoming request.

constbaseProto=

req.headers\['x-forwarded-proto'\]\|\|

(req.connection&&req.connection.encrypted)

? 'https'

: 'http';

constbaseHost=req.headers.host\|\|'localhost';

constfullUrl=newURL(req.url,\`${baseProto}://${baseHost}\`);

constbaseUrl=\`${baseProto}://${baseHost}\`;

// Normalized path relative to the API root, e.g. "/manifest.json".

constpathname=fullUrl.pathname.replace(/^\\/api\\/moisa/,'')\|\|'/';

constquery=Object.fromEntries(fullUrl.searchParams.entries());

// CORS – needed for Stremio Web.

res.setHeader('Access-Control-Allow-Origin','\*');

res.setHeader(

'Access-Control-Allow-Headers',

'Origin, X-Requested-With, Content-Type, Accept'

);

res.setHeader('Access-Control-Allow-Methods','GET, OPTIONS');

if(req.method==='OPTIONS'){

res.statusCode=204;

res.end();

return;

}

// ---------------------------------------------------------------------------

// Favicon: /favicon.ico -> 32x32 PNG icon used in the browser tab.

// ---------------------------------------------------------------------------

if(pathname==='/favicon.ico'){

constfaviconPath=path.join(

\_\_dirname,

'..',

'..',

'assets',

'moisa-addon-icon-32.png'

);

fs.stat(faviconPath,(err,stat)=>{

if(err\|\|!stat.isFile()){

res.statusCode=404;

res.end('Not found');

return;

}

res.setHeader('Content-Type','image/png');

conststream=fs.createReadStream(faviconPath);

stream.on('error',()=>{

res.statusCode=500;

res.end('Error reading favicon');

});

stream.pipe(res);

});

return;

}

// ---------------------------------------------------------------------------

// Static assets: /assets/\* – icons and other static files for the addon.

// ---------------------------------------------------------------------------

if(pathname.startsWith('/assets/')){

constassetRelPath=pathname.replace(/^\\/assets\\//,'');

constassetPath=path.join(\_\_dirname,'..','..','assets',assetRelPath);

fs.stat(assetPath,(err,stat)=>{

if(err\|\|!stat.isFile()){

res.statusCode=404;

res.end('Not found');

return;

}

constext=path.extname(assetPath).toLowerCase();

constmimeTypes={

'.png': 'image/png',

'.jpg': 'image/jpeg',

'.jpeg': 'image/jpeg',

'.gif': 'image/gif',

'.svg': 'image/svg+xml',

'.webp': 'image/webp'

};

res.setHeader(

'Content-Type',

mimeTypes\[ext\]\|\|'application/octet-stream'

);

conststream=fs.createReadStream(assetPath);

stream.on('error',()=>{

res.statusCode=500;

res.end('Error reading asset');

});

stream.pipe(res);

});

return;

}

// ---------------------------------------------------------------------------

// Configuration page – HTML UI used in the browser to generate the addon URL.

// HTML is kept in a separate file (\`configure.html\`) to avoid inline markup.

// ---------------------------------------------------------------------------

if(pathname==='/config'\|\|pathname==='/configure'){

consthtmlPath=path.join(\_\_dirname,'configure.html');

fs.readFile(htmlPath,'utf8',(err,content)=>{

if(err){

logError('Failed to read configure.html',{

message: err.message\|\|String(err),

stack: err.stack

});

res.statusCode=500;

res.end('Internal server error');

return;

}

res.setHeader('Content-Type','text/html; charset=utf-8');

res.statusCode=200;

res.end(content);

});

return;

}

// ---------------------------------------------------------------------------

// Manifest

// ---------------------------------------------------------------------------

if(pathname==='/'\|\|pathname==='/manifest.json'){

res.setHeader('Content-Type','application/json; charset=utf-8');

res.statusCode=200;

constmanifest={

...addonInterface.manifest,

// Use a single static 256x256 PNG icon for the addon logo.

logo: \`${baseUrl}/assets/moisa-addon-icon-256.png\`

};

res.end(JSON.stringify(manifest));

return;

}

// ---------------------------------------------------------------------------

// Stream: /stream/:type/:id.json

// ---------------------------------------------------------------------------

if(pathname.startsWith('/stream/')){

constparts=pathname.split('/').filter(Boolean);

if(parts.length<3){

res.statusCode=404;

res.end(JSON.stringify({err: 'not found'}));

return;

}

consttype=parts\[1\];

constrawId=parts\[2\].replace(/\\.json$/,'');

constid=decodeURIComponent(rawId);

constproto=

req.headers\['x-forwarded-proto'\]\|\|req.connection.encrypted

? 'https'

: 'http';

consthost=req.headers.host;

constbaseUrl=\`${proto}://${host}\`;

constcfg=decodeConfig(query);

constextra={

...(query\|\|{}),

...(cfg&&cfg.torrserver ? {torrserver: cfg.torrserver} : {}),

...(cfg&&cfg.torrentioPathPrefix

? {torrentioPathPrefix: cfg.torrentioPathPrefix}

: {}),

\_base: baseUrl

};

log('HTTP /stream',{ type, id, extra });

try{

constresponse=awaitaddonInterface.get('stream',type,id,extra);

res.setHeader('Content-Type','application/json; charset=utf-8');

res.statusCode=200;

res.end(JSON.stringify(response));

}catch(err){

logError('Moisa HTTP stream handler error',{

message: err.message\|\|String(err),

stack: err.stack

});

res.statusCode=500;

res.end(JSON.stringify({err: 'handler error'}));

}

return;

}

// ---------------------------------------------------------------------------

// Play proxy: /play?infoHash=...

// ---------------------------------------------------------------------------

if(pathname==='/play'){

constcfg=decodeConfig(query);

constinfoHash=query.infoHash;

consttype=query.type;

constid=query.id;

constfilename=query.filename;

constfileIndex=

query.fileIndex!==undefined ? parseInt(query.fileIndex,10) : undefined;

if(!infoHash\|\|!type\|\|!id){

res.statusCode=400;

res.end(JSON.stringify({err: 'missing required parameters'}));

return;

}

// Keep precedence consistent with the /stream handler:

// 1) explicit ?torrserver=... (set by the addon when building /play URLs)

// 2) cfg.torrserver decoded from ?config=...

// 3) TORRSERVER\_URL from env

// 4) localhost default

consttorrServerBase=

query.torrserver\|\|

(cfg&&cfg.torrserver)\|\|

process.env.TORRSERVER\_URL\|\|

'http://127.0.0.1:8090';

constseason=

query.season!==undefined ? parseInt(query.season,10) : undefined;

constepisode=

query.episode!==undefined ? parseInt(query.episode,10) : undefined;

log('HTTP /play request',{

type,

id,

infoHash,

torrServerBase,

season,

episode,

filename,

fileIndex

});

try{

constdirectUrl=awaitaddonInterface.resolvePlayUrl({

torrServerBase,

type,

id,

infoHash,

season: Number.isNaN(season) ? undefined : season,

episode: Number.isNaN(episode) ? undefined : episode,

filename,

fileIndex: Number.isNaN(fileIndex) ? undefined : fileIndex

});

if(!directUrl){

res.statusCode=404;

res.end(JSON.stringify({err: 'unable to resolve stream'}));

return;

}

log('HTTP /play redirect',{

type,

id,

infoHash,

location: directUrl

});

res.statusCode=302;

res.setHeader('Location',directUrl);

res.end();

}catch(err){

logError('Moisa HTTP play proxy error',{

message: err.message\|\|String(err),

stack: err.stack

});

res.statusCode=500;

res.end(JSON.stringify({err: 'play handler error'}));

}

return;

}

// ---------------------------------------------------------------------------

// Fallback 404

// ---------------------------------------------------------------------------

res.statusCode=404;

res.end(JSON.stringify({err: 'not found'}));

};

You can’t perform that action at this time.