-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathutils.ts
More file actions
95 lines (85 loc) · 2.3 KB
/
Copy pathutils.ts
File metadata and controls
95 lines (85 loc) · 2.3 KB
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
import { sha256 as rawSha256 } from "@oslojs/crypto/sha2";
import { encodeHexLowerCase } from "@oslojs/encoding";
import {
RandomReader,
generateRandomString as osloGenerateRandomString,
} from "@oslojs/crypto/random";
export const TOKEN_SUB_CLAIM_DIVIDER = "|";
export const REFRESH_TOKEN_DIVIDER = "|";
export function stringToNumber(value: string | undefined) {
return value !== undefined ? Number(value) : undefined;
}
export async function sha256(input: string) {
return encodeHexLowerCase(rawSha256(new TextEncoder().encode(input)));
}
export function generateRandomString(length: number, alphabet: string) {
const random: RandomReader = {
read(bytes) {
crypto.getRandomValues(bytes);
},
};
return osloGenerateRandomString(random, alphabet, length);
}
export function normalizeEmail(email: string): string {
return email.toLowerCase().trim();
}
export function logError(error: unknown) {
logWithLevel(
LOG_LEVELS.ERROR,
error instanceof Error
? error.message + "\n" + error.stack?.replace("\\n", "\n")
: error,
);
}
export const LOG_LEVELS = {
ERROR: "ERROR",
WARN: "WARN",
INFO: "INFO",
DEBUG: "DEBUG",
} as const;
type LogLevel = keyof typeof LOG_LEVELS;
export function logWithLevel(level: LogLevel, ...args: unknown[]) {
const configuredLogLevel =
LOG_LEVELS[
(process.env.AUTH_LOG_LEVEL as LogLevel | undefined) ?? "INFO"
] ?? "INFO";
switch (level) {
case "ERROR":
console.error(...args);
break;
case "WARN":
if (configuredLogLevel !== "ERROR") {
console.warn(...args);
}
break;
case "INFO":
if (configuredLogLevel === "INFO" || configuredLogLevel === "DEBUG") {
console.info(...args);
}
break;
case "DEBUG":
if (configuredLogLevel === "DEBUG") {
console.debug(...args);
}
break;
}
}
const UNREDACTED_LENGTH = 5;
export function maybeRedact(value: string) {
if (value === "") {
return "";
}
const shouldRedact = process.env.AUTH_LOG_SECRETS !== "true";
if (shouldRedact) {
if (value.length < UNREDACTED_LENGTH * 2) {
return "<redacted>";
}
return (
value.substring(0, UNREDACTED_LENGTH) +
"<redacted>" +
value.substring(value.length - UNREDACTED_LENGTH)
);
} else {
return value;
}
}