-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathencodingUtils.ts
More file actions
44 lines (34 loc) · 1.2 KB
/
encodingUtils.ts
File metadata and controls
44 lines (34 loc) · 1.2 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
import base64url from 'base64url';
export const ID_MAX_LENGTH = 32;
export function isValidId(id: unknown): id is string {
return typeof id === 'string' && id.length <= ID_MAX_LENGTH && /^[ -~]+$/.test(id);
}
export function isValidUtf8Input(input: unknown): input is string {
if (typeof input !== 'string' || input.length !== 16) {
return false;
}
try {
const buffer = Buffer.from(input, 'utf8');
return buffer.toString('utf8') === input;
} catch {
return false;
}
}
export function isValidBase64UrlInput(input: unknown): input is string {
return typeof input === 'string' && /^[A-Za-z0-9_-]{60,64}$/.test(input);
}
export function isValidHexInput(input: unknown): input is string {
return typeof input === 'string' && /^[A-Fa-f0-9]{90,96}$/.test(input);
}
export function base64urlToUtf8(input: string): string {
return base64url.toBuffer(input).toString('utf8');
}
export function utf8ToBase64url(input: string): string {
return base64url(Buffer.from(input, 'utf8'));
}
export function hexToUtf8(input: string): string {
return Buffer.from(input, 'hex').toString('utf8');
}
export function utf8ToHex(input: string): string {
return Buffer.from(input, 'utf8').toString('hex');
}