aboutsummaryrefslogtreecommitdiffstats
path: root/packages/shared/signedTokens.ts
blob: 14a26f60802e06fc0d602f893fde3d034a107d5c (plain) (blame)
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
import crypto from "node:crypto";
import { z } from "zod";

const zTokenPayload = z.object({
  payload: z.unknown(),
  expiresAt: z.number(),
});

const zSignedTokenPayload = z.object({
  payload: zTokenPayload,
  signature: z.string(),
});

/**
 * Returns the expiry date aligned to the specified interval.
 * If the time left until the next interval is less than the grace period,
 * it skips to the following interval.
 *
 * @param now - The current date and time (defaults to new Date()).
 * @param intervalSeconds - The interval in seconds (e.g., 1800 for 30 mins).
 * @param gracePeriodSeconds - The grace period in seconds.
 * @returns The calculated expiry Date.
 */
export function getAlignedExpiry(
  intervalSeconds: number,
  gracePeriodSeconds: number,
  now: Date = new Date(),
): number {
  const ms = now.getTime();
  const intervalMs = intervalSeconds * 1000;

  // Find the next interval
  const nextIntervalTime =
    Math.floor(ms / intervalMs) * intervalMs + intervalMs;

  // Time left until the next interval
  const timeLeft = nextIntervalTime - ms;

  // Decide which interval to use
  const finalIntervalTime =
    timeLeft < gracePeriodSeconds * 1000
      ? nextIntervalTime + intervalMs
      : nextIntervalTime;

  return finalIntervalTime;
}

export type SignedTokenPayload = z.infer<typeof zSignedTokenPayload>;

export function createSignedToken(
  payload: unknown,
  secret: string,
  expiryEpoch?: number,
): string {
  const expiresAt = expiryEpoch ?? Date.now() + 5 * 60 * 1000; // 5 minutes from now

  const toBeSigned: z.infer<typeof zTokenPayload> = {
    payload,
    expiresAt,
  };

  const payloadString = JSON.stringify(toBeSigned);
  const signature = crypto
    .createHmac("sha256", secret)
    .update(payloadString)
    .digest("hex");

  const tokenData: z.infer<typeof zSignedTokenPayload> = {
    payload: toBeSigned,
    signature,
  };

  return Buffer.from(JSON.stringify(tokenData)).toString("base64");
}

export function verifySignedToken<T>(
  token: string,
  secret: string,
  schema: z.ZodSchema<T>,
): T | null {
  try {
    const tokenData = zSignedTokenPayload.parse(
      JSON.parse(Buffer.from(token, "base64").toString()),
    );
    const { payload, signature } = tokenData;

    // Verify signature
    const expectedSignature = crypto
      .createHmac("sha256", secret)
      .update(JSON.stringify(payload))
      .digest("hex");

    if (signature !== expectedSignature) {
      return null;
    }
    // Check expiry
    if (Date.now() > payload.expiresAt) {
      return null;
    }

    return schema.parse(payload.payload);
  } catch {
    return null;
  }
}