-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathauthenticateServiceToken.ts
More file actions
78 lines (59 loc) · 2 KB
/
Copy pathauthenticateServiceToken.ts
File metadata and controls
78 lines (59 loc) · 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
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
/*
* Copyright © 2026 Fells Code, LLC
* Licensed under the GNU Affero General Public License v3.0
* See LICENSE file in the project root for full license information
*/
import jwt, { JwtPayload } from 'jsonwebtoken';
import getLogger from '../utils/logger.js';
import { getSecret } from '../utils/secretsStore.js';
const logger = getLogger('authenticateServiceToken');
let cachedSecret: string | null = null;
const INTERNAL_SERVICE_TOKEN_ALGORITHMS = ['HS256', 'HS384', 'HS512'] as const;
interface InternalServiceTokenValidationOptions {
logInvalid?: boolean;
}
function getJwtAlgorithm(token: string): string | null {
const decoded = jwt.decode(token, { complete: true });
if (!decoded || typeof decoded !== 'object') {
return null;
}
const alg = (decoded as { header?: { alg?: unknown } }).header?.alg;
return typeof alg === 'string' ? alg : null;
}
function usesSupportedInternalServiceAlgorithm(token: string) {
const alg = getJwtAlgorithm(token);
if (!alg) {
return true;
}
return (INTERNAL_SERVICE_TOKEN_ALGORITHMS as readonly string[]).includes(alg);
}
async function getInternalSecret() {
if (cachedSecret) return cachedSecret;
cachedSecret = await getSecret('API_SERVICE_TOKEN');
return cachedSecret;
}
export async function validateInternalServiceToken(
token: string,
options: InternalServiceTokenValidationOptions = {},
): Promise<JwtPayload | null> {
const internalSecret = await getInternalSecret();
if (!token || !internalSecret) {
return null;
}
try {
if (!usesSupportedInternalServiceAlgorithm(token)) {
if (options.logInvalid) {
logger.warn('Rejected internal service token with unsupported algorithm');
}
return null;
}
return jwt.verify(token, internalSecret, {
algorithms: [...INTERNAL_SERVICE_TOKEN_ALGORITHMS],
}) as JwtPayload;
} catch (error: unknown) {
if (options.logInvalid) {
logger.error(`An error occured validating api to api service. ${error}`);
}
return null;
}
}