2022-07-08 19:17:56 +01:00
|
|
|
import NodeCache from "node-cache";
|
2023-04-29 16:30:59 +01:00
|
|
|
import { randomBytes } from "crypto";
|
2023-04-08 17:55:44 +01:00
|
|
|
import { nanoid } from 'nanoid';
|
2022-07-08 19:17:56 +01:00
|
|
|
|
2023-01-13 18:34:48 +00:00
|
|
|
import { sha256 } from "../sub/crypto.js";
|
2022-07-08 19:17:56 +01:00
|
|
|
import { streamLifespan } from "../config.js";
|
|
|
|
|
2023-01-13 18:34:48 +00:00
|
|
|
const streamCache = new NodeCache({ stdTTL: streamLifespan/1000, checkperiod: 10, deleteOnExpire: true });
|
2023-04-29 16:30:59 +01:00
|
|
|
const streamSalt = randomBytes(64).toString('hex');
|
2022-07-08 19:17:56 +01:00
|
|
|
|
2023-01-13 18:34:48 +00:00
|
|
|
streamCache.on("expired", (key) => {
|
|
|
|
streamCache.del(key);
|
|
|
|
});
|
|
|
|
|
2022-07-08 19:17:56 +01:00
|
|
|
export function createStream(obj) {
|
2023-04-08 17:55:44 +01:00
|
|
|
let streamID = nanoid(),
|
2022-07-08 19:17:56 +01:00
|
|
|
exp = Math.floor(new Date().getTime()) + streamLifespan,
|
2023-04-29 16:30:59 +01:00
|
|
|
ghmac = sha256(`${streamID},${obj.ip},${obj.service},${exp}`, streamSalt);
|
2022-11-12 16:40:11 +00:00
|
|
|
|
2023-01-13 18:34:48 +00:00
|
|
|
if (!streamCache.has(streamID)) {
|
|
|
|
streamCache.set(streamID, {
|
|
|
|
id: streamID,
|
|
|
|
service: obj.service,
|
|
|
|
type: obj.type,
|
|
|
|
urls: obj.u,
|
|
|
|
filename: obj.filename,
|
|
|
|
hmac: ghmac,
|
|
|
|
ip: obj.ip,
|
|
|
|
exp: exp,
|
|
|
|
isAudioOnly: !!obj.isAudioOnly,
|
|
|
|
audioFormat: obj.audioFormat,
|
|
|
|
time: obj.time ? obj.time : false,
|
|
|
|
copy: !!obj.copy,
|
|
|
|
mute: !!obj.mute,
|
|
|
|
metadata: obj.fileMetadata ? obj.fileMetadata : false
|
|
|
|
});
|
|
|
|
} else {
|
|
|
|
let streamInfo = streamCache.get(streamID);
|
|
|
|
exp = streamInfo.exp;
|
|
|
|
ghmac = streamInfo.hmac;
|
|
|
|
}
|
|
|
|
return `${process.env.selfURL}api/stream?t=${streamID}&e=${exp}&h=${ghmac}`;
|
2022-07-08 19:17:56 +01:00
|
|
|
}
|
|
|
|
|
2022-11-12 16:40:11 +00:00
|
|
|
export function verifyStream(ip, id, hmac, exp) {
|
2022-07-08 19:17:56 +01:00
|
|
|
try {
|
2023-04-08 17:55:44 +01:00
|
|
|
if (id.length === 21) {
|
|
|
|
let streamInfo = streamCache.get(id);
|
|
|
|
if (!streamInfo) return { error: 'this stream token does not exist', status: 400 };
|
|
|
|
|
2023-04-29 16:30:59 +01:00
|
|
|
let ghmac = sha256(`${id},${ip},${streamInfo.service},${exp}`, streamSalt);
|
2023-04-08 17:55:44 +01:00
|
|
|
if (String(hmac) === ghmac && String(exp) === String(streamInfo.exp) && ghmac === String(streamInfo.hmac)
|
|
|
|
&& String(ip) === streamInfo.ip && Number(exp) > Math.floor(new Date().getTime())) {
|
|
|
|
return streamInfo;
|
|
|
|
}
|
2023-02-09 14:45:17 +00:00
|
|
|
}
|
|
|
|
return { error: 'Unauthorized', status: 401 };
|
2022-07-08 19:17:56 +01:00
|
|
|
} catch (e) {
|
|
|
|
return { status: 500, body: { status: "error", text: "Internal Server Error" } };
|
|
|
|
}
|
2022-08-01 16:48:37 +01:00
|
|
|
}
|