forked from clerk/javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkeyless.ts
More file actions
49 lines (36 loc) · 1.26 KB
/
Copy pathkeyless.ts
File metadata and controls
49 lines (36 loc) · 1.26 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
import type { AccountlessApplication } from '@clerk/backend';
import hex from 'crypto-js/enc-hex';
import sha256 from 'crypto-js/sha256';
import { canUseKeyless__server } from '../utils/feature-flags';
const keylessCookiePrefix = `__clerk_keys_`;
const getKeylessCookieName = (): string => {
// eslint-disable-next-line turbo/no-undeclared-env-vars
const PATH = process.env.PWD;
// Handle gracefully missing PWD
if (!PATH) {
return `${keylessCookiePrefix}${0}`;
}
const lastThreeDirs = PATH.split('/').filter(Boolean).slice(-3).reverse().join('/');
// Hash the resulting string
const hash = hashString(lastThreeDirs);
return `${keylessCookiePrefix}${hash}`;
};
function hashString(str: string) {
return sha256(str).toString(hex).slice(0, 16); // Take only the first 16 characters
}
function getKeylessCookieValue(getter: (cookieName: string) => string | undefined): AccountlessApplication | undefined {
if (!canUseKeyless__server) {
return undefined;
}
const keylessCookieName = getKeylessCookieName();
let keyless;
try {
if (keylessCookieName) {
keyless = JSON.parse(getter(keylessCookieName) || '{}');
}
} catch {
keyless = undefined;
}
return keyless;
}
export { getKeylessCookieValue, getKeylessCookieName };