-
Notifications
You must be signed in to change notification settings - Fork 451
Expand file tree
/
Copy pathauthorization.ts
More file actions
399 lines (351 loc) · 11 KB
/
authorization.ts
File metadata and controls
399 lines (351 loc) · 11 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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
import type {
ActClaim,
CheckAuthorizationWithCustomPermissions,
GetToken,
JwtPayload,
OrganizationCustomPermissionKey,
OrganizationCustomRoleKey,
PendingSessionOptions,
ReverificationConfig,
SessionStatusClaim,
SessionVerificationLevel,
SessionVerificationTypes,
SignOut,
UseAuthReturn,
} from './types';
type TypesToConfig = Record<SessionVerificationTypes, Exclude<ReverificationConfig, SessionVerificationTypes>>;
type AuthorizationOptions = {
userId: string | null | undefined;
orgId: string | null | undefined;
orgRole: string | null | undefined;
orgPermissions: string[] | null | undefined;
factorVerificationAge: [number, number] | null;
features: string | null | undefined;
plans: string | null | undefined;
};
type CheckOrgAuthorization = (
params: { role?: OrganizationCustomRoleKey; permission?: OrganizationCustomPermissionKey },
options: Pick<AuthorizationOptions, 'orgId' | 'orgRole' | 'orgPermissions'>,
) => boolean | null;
type CheckBillingAuthorization = (
params: { feature?: string; plan?: string },
options: Pick<AuthorizationOptions, 'plans' | 'features'>,
) => boolean | null;
type CheckReverificationAuthorization = (
params: {
reverification?: ReverificationConfig;
},
{ factorVerificationAge }: AuthorizationOptions,
) => boolean | null;
const TYPES_TO_OBJECTS: TypesToConfig = {
strict_mfa: {
afterMinutes: 10,
level: 'multi_factor',
},
strict: {
afterMinutes: 10,
level: 'second_factor',
},
moderate: {
afterMinutes: 60,
level: 'second_factor',
},
lax: {
afterMinutes: 1_440,
level: 'second_factor',
},
};
const ALLOWED_LEVELS = new Set<SessionVerificationLevel>(['first_factor', 'second_factor', 'multi_factor']);
const ALLOWED_TYPES = new Set<SessionVerificationTypes>(['strict_mfa', 'strict', 'moderate', 'lax']);
const ORG_SCOPES = new Set(['o', 'org', 'organization']);
const USER_SCOPES = new Set(['u', 'user']);
// Helper functions
const isValidMaxAge = (maxAge: any) => typeof maxAge === 'number' && maxAge > 0;
const isValidLevel = (level: any) => ALLOWED_LEVELS.has(level);
const isValidVerificationType = (type: any) => ALLOWED_TYPES.has(type);
const prefixWithOrg = (value: string) => value.replace(/^(org:)*/, 'org:');
/**
* Checks if a user has the required organization-level authorization.
* Verifies if the user has the specified role or permission within their organization.
*
* @returns null, if unable to determine due to missing data or unspecified role/permission.
*/
const checkOrgAuthorization: CheckOrgAuthorization = (params, options) => {
const { orgId, orgRole, orgPermissions } = options;
if (!params.role && !params.permission) {
return null;
}
if (!orgId || !orgRole || !orgPermissions) {
return null;
}
if (params.permission) {
return orgPermissions.includes(prefixWithOrg(params.permission));
}
if (params.role) {
return prefixWithOrg(orgRole) === prefixWithOrg(params.role);
}
return null;
};
const checkForFeatureOrPlan = (claim: string, featureOrPlan: string) => {
const { org: orgFeatures, user: userFeatures } = splitByScope(claim);
const [rawScope, rawId] = featureOrPlan.split(':');
const hasExplicitScope = rawId !== undefined;
const scope = rawScope;
const id = rawId || rawScope;
if (hasExplicitScope && !ORG_SCOPES.has(scope) && !USER_SCOPES.has(scope)) {
throw new Error(`Invalid scope: ${scope}`);
}
if (hasExplicitScope) {
if (ORG_SCOPES.has(scope)) {
return orgFeatures.includes(id);
}
if (USER_SCOPES.has(scope)) {
return userFeatures.includes(id);
}
}
// Since org scoped features will not exist if there is not an active org, merging is safe.
return [...orgFeatures, ...userFeatures].includes(id);
};
const checkBillingAuthorization: CheckBillingAuthorization = (params, options) => {
const { features, plans } = options;
if (params.feature && features) {
return checkForFeatureOrPlan(features, params.feature);
}
if (params.plan && plans) {
return checkForFeatureOrPlan(plans, params.plan);
}
return null;
};
const splitByScope = (fea: string | null | undefined) => {
const org: string[] = [];
const user: string[] = [];
if (!fea) {
return { org, user };
}
const parts = fea.split(',');
for (let i = 0; i < parts.length; i++) {
const part = parts[i].trim();
const colonIndex = part.indexOf(':');
if (colonIndex === -1) {
throw new Error(`Invalid claim element (missing colon): ${part}`);
}
const scope = part.slice(0, colonIndex);
const value = part.slice(colonIndex + 1);
if (scope === 'o') {
org.push(value);
} else if (scope === 'u') {
user.push(value);
} else if (scope === 'ou' || scope === 'uo') {
org.push(value);
user.push(value);
}
}
return { org, user };
};
const validateReverificationConfig = (config: ReverificationConfig | undefined | null) => {
if (!config) {
return false;
}
const convertConfigToObject = (config: ReverificationConfig) => {
if (typeof config === 'string') {
return TYPES_TO_OBJECTS[config];
}
return config;
};
const isValidStringValue = typeof config === 'string' && isValidVerificationType(config);
const isValidObjectValue =
typeof config === 'object' && isValidLevel(config.level) && isValidMaxAge(config.afterMinutes);
if (isValidStringValue || isValidObjectValue) {
return convertConfigToObject.bind(null, config);
}
return false;
};
/**
* Evaluates if the user meets re-verification authentication requirements.
* Compares the user's factor verification ages against the specified maxAge.
* Handles different verification levels (first factor, second factor, multi-factor).
*
* @returns null, if requirements or verification data are missing.
*/
const checkReverificationAuthorization: CheckReverificationAuthorization = (params, { factorVerificationAge }) => {
if (!params.reverification || !factorVerificationAge) {
return null;
}
const isValidReverification = validateReverificationConfig(params.reverification);
if (!isValidReverification) {
return null;
}
const { level, afterMinutes } = isValidReverification();
const [factor1Age, factor2Age] = factorVerificationAge;
// -1 indicates the factor group (1fa,2fa) is not enabled
// -1 for 1fa is not a valid scenario, but we need to make sure we handle it properly
const isValidFactor1 = factor1Age !== -1 ? afterMinutes > factor1Age : null;
const isValidFactor2 = factor2Age !== -1 ? afterMinutes > factor2Age : null;
switch (level) {
case 'first_factor':
return isValidFactor1;
case 'second_factor':
return factor2Age !== -1 ? isValidFactor2 : isValidFactor1;
case 'multi_factor':
return factor2Age === -1 ? isValidFactor1 : isValidFactor1 && isValidFactor2;
}
};
/**
* Creates a function for comprehensive user authorization checks.
* Combines organization-level and reverification authentication checks.
* The returned function authorizes if both checks pass, or if at least one passes
* when the other is indeterminate. Fails if userId is missing.
*/
const createCheckAuthorization = (options: AuthorizationOptions): CheckAuthorizationWithCustomPermissions => {
return (params): boolean => {
if (!options.userId) {
return false;
}
const billingAuthorization = checkBillingAuthorization(params, options);
const orgAuthorization = checkOrgAuthorization(params, options);
const reverificationAuthorization = checkReverificationAuthorization(params, options);
if ([billingAuthorization || orgAuthorization, reverificationAuthorization].some(a => a === null)) {
return [billingAuthorization || orgAuthorization, reverificationAuthorization].some(a => a === true);
}
return [billingAuthorization || orgAuthorization, reverificationAuthorization].every(a => a === true);
};
};
type AuthStateOptions = {
authObject: {
userId?: string | null;
sessionId?: string | null;
sessionStatus?: SessionStatusClaim | null;
sessionClaims?: JwtPayload | null;
actor?: ActClaim | null;
orgId?: string | null;
orgRole?: OrganizationCustomRoleKey | null;
orgSlug?: string | null;
orgPermissions?: OrganizationCustomPermissionKey[] | null;
getToken: GetToken;
signOut: SignOut;
has: (params: Parameters<CheckAuthorizationWithCustomPermissions>[0]) => boolean;
};
options: PendingSessionOptions;
};
/**
* Shared utility function that centralizes auth state resolution logic,
* preventing duplication across different packages.
*
* @internal
*/
const resolveAuthState = ({
authObject: {
sessionId,
sessionStatus,
userId,
actor,
orgId,
orgRole,
orgSlug,
signOut,
getToken,
has,
sessionClaims,
},
options: { treatPendingAsSignedOut = true },
}: AuthStateOptions): UseAuthReturn | undefined => {
if (sessionId === undefined && userId === undefined) {
return {
actor: undefined,
getToken,
has: () => false,
isLoaded: false,
isSignedIn: undefined,
orgId: undefined,
orgRole: undefined,
orgSlug: undefined,
sessionClaims: undefined,
sessionId,
signOut,
userId,
} as const;
}
if (sessionId === null && userId === null) {
return {
actor: null,
getToken,
has: () => false,
isLoaded: true,
isSignedIn: false,
orgId: null,
orgRole: null,
orgSlug: null,
sessionClaims: null,
sessionId,
signOut,
userId,
} as const;
}
if (treatPendingAsSignedOut && sessionStatus === 'pending') {
return {
actor: null,
getToken,
has: () => false,
isLoaded: true,
isSignedIn: false,
orgId: null,
orgRole: null,
orgSlug: null,
sessionClaims: null,
sessionId: null,
signOut,
userId: null,
} as const;
}
// Session exists but claims aren't available yet (e.g. during client hydration
// before a token has been fetched). Treat as loading state.
if (!!sessionId && !!userId && !sessionClaims) {
return {
actor: undefined,
getToken,
has: () => false,
isLoaded: false,
isSignedIn: undefined,
orgId: undefined,
orgRole: undefined,
orgSlug: undefined,
sessionClaims: undefined,
sessionId: undefined,
signOut,
userId: undefined,
} as const;
}
if (!!sessionId && !!sessionClaims && !!userId && !!orgId && !!orgRole) {
return {
actor: actor || null,
getToken,
has,
isLoaded: true,
isSignedIn: true,
orgId,
orgRole,
orgSlug: orgSlug || null,
sessionClaims,
sessionId,
signOut,
userId,
} as const;
}
if (!!sessionId && !!sessionClaims && !!userId) {
return {
actor: actor || null,
getToken,
has,
isLoaded: true,
isSignedIn: true,
orgId: null,
orgRole: null,
orgSlug: null,
sessionClaims,
sessionId,
signOut,
userId,
} as const;
}
};
export { createCheckAuthorization, resolveAuthState, splitByScope, validateReverificationConfig };