All files / src/utils attachment-link.util.ts

33.33% Statements 5/15
30% Branches 3/10
0% Functions 0/3
35.71% Lines 5/14

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 211x   1x   1x       1x               1x        
import crypto from 'crypto';
 
const SECRET = process.env.ATTACHMENT_LINK_SECRET ?? 'change-me';
 
export function signAttachmentId(id: number): string {
  return crypto.createHmac('sha256', SECRET).update(String(id)).digest('hex').slice(0, 32);
}
 
export function verifyAttachmentToken(id: number, token: string): boolean {
  const expected = signAttachmentId(id);
  const a = Buffer.from(expected);
  const b = Buffer.from(token);
  if (a.length !== b.length) return false;
  return crypto.timingSafeEqual(a, b);
}
 
export function buildAttachmentViewUrl(id: number): string {
  const base = process.env.APP_PUBLIC_URL ?? '';
  const token = signAttachmentId(id);
  return `${base}/attachments/${id}/view?t=${token}`;
}