Repository navigation
Expand file tree
/
Copy pathauthorization.ts
More file actions
484 lines (428 loc) · 13.4 KB
/
Copy pathauthorization.ts
File metadata and controls
484 lines (428 loc) · 13.4 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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
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;
};
// Internal verdict for each authorization dimension.
// pass = caller asked, the dimension is satisfied
// fail = caller asked, the dimension is not satisfied (includes "data missing" - fail closed)
// skip = caller did not ask in this dimension; it does not contribute to the result
type CheckResult = 'pass' | 'fail' | 'skip';
type CheckOrgAuthorization = (
params: { role?: OrganizationCustomRoleKey; permission?: OrganizationCustomPermissionKey },
options: Pick<AuthorizationOptions, 'orgId' | 'orgRole' | 'orgPermissions'>,
) => CheckResult;
type CheckBillingAuthorization = (
params: { feature?: string; plan?: string },
options: Pick<AuthorizationOptions, 'plans' | 'features'>,
) => CheckResult;
type CheckReverificationAuthorization = (
params: {
reverification?: ReverificationConfig;
},
{ factorVerificationAge }: AuthorizationOptions,
) => CheckResult;
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 isValidFactorAge = (x: unknown): x is number =>
typeof x === 'number' && Number.isFinite(x) && (x === -1 || x >= 0);
const prefixWithOrg = (value: string) => value.replace(/^(org:)*/, 'org:');
/**
* Checks if a user has the required organization-level authorization.
* If both role and permission are provided, both must match (AND).
*/
const checkOrgAuthorization: CheckOrgAuthorization = (params, options) => {
const { orgId, orgRole, orgPermissions } = options;
const roleAsked = params.role !== undefined;
const permissionAsked = params.permission !== undefined;
if (!roleAsked && !permissionAsked) {
return 'skip';
}
// Asked with a non-string value (e.g. null cast through `as any`): fail closed
// rather than letting `prefixWithOrg` throw.
if (roleAsked && typeof params.role !== 'string') {
return 'fail';
}
if (permissionAsked && typeof params.permission !== 'string') {
return 'fail';
}
if (!orgId) {
return 'fail';
}
if (roleAsked) {
if (typeof orgRole !== 'string' || !orgRole) {
return 'fail';
}
if (prefixWithOrg(orgRole) !== prefixWithOrg(params.role as string)) {
return 'fail';
}
}
if (permissionAsked) {
if (!Array.isArray(orgPermissions)) {
return 'fail';
}
if (!orgPermissions.includes(prefixWithOrg(params.permission as string))) {
return 'fail';
}
}
return 'pass';
};
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);
};
/**
* Checks if a user is entitled to the requested feature or plan.
* If both feature and plan are provided, both must match (AND).
*/
const checkBillingAuthorization: CheckBillingAuthorization = (params, options) => {
const { features, plans } = options;
const featureAsked = params.feature !== undefined;
const planAsked = params.plan !== undefined;
if (!featureAsked && !planAsked) {
return 'skip';
}
// Asked with a non-string value: fail closed before handing to checkForFeatureOrPlan.
if (featureAsked && typeof params.feature !== 'string') {
return 'fail';
}
if (planAsked && typeof params.plan !== 'string') {
return 'fail';
}
if (featureAsked) {
if (typeof features !== 'string' || !features) {
return 'fail';
}
try {
if (!checkForFeatureOrPlan(features, params.feature as string)) {
return 'fail';
}
} catch {
return 'fail';
}
}
if (planAsked) {
if (typeof plans !== 'string' || !plans) {
return 'fail';
}
try {
if (!checkForFeatureOrPlan(plans, params.plan as string)) {
return 'fail';
}
} catch {
return 'fail';
}
}
return 'pass';
};
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.
* Handles different verification levels (first factor, second factor, multi-factor).
*/
const checkReverificationAuthorization: CheckReverificationAuthorization = (params, { factorVerificationAge }) => {
if (params.reverification === undefined) {
return 'skip';
}
if (!factorVerificationAge) {
return 'fail';
}
// Validate the tuple shape before comparing ages to defend against malformed JWT
// payloads or TS `as any` escapes. `factor1Age` / `factor2Age` must be numbers
// representing minutes (or -1 when a factor group is not enabled).
if (
!Array.isArray(factorVerificationAge) ||
factorVerificationAge.length !== 2 ||
!isValidFactorAge(factorVerificationAge[0]) ||
!isValidFactorAge(factorVerificationAge[1])
) {
return 'fail';
}
const getConfig = validateReverificationConfig(params.reverification);
if (!getConfig) {
return 'fail';
}
const { level, afterMinutes } = getConfig();
const [factor1Age, factor2Age] = factorVerificationAge;
// -1 indicates the factor group (1fa, 2fa) is not enabled.
// If neither factor is enrolled we cannot verify anything; fail closed.
if (factor1Age === -1 && factor2Age === -1) {
return 'fail';
}
const factor1FreshEnough = factor1Age !== -1 && afterMinutes > factor1Age;
const factor2FreshEnough = factor2Age !== -1 && afterMinutes > factor2Age;
switch (level) {
case 'first_factor':
return factor1FreshEnough ? 'pass' : 'fail';
case 'second_factor':
// Graceful downgrade: prefer second factor; fall back to whichever factor is
// enrolled when the other is missing.
if (factor2Age === -1) {
return factor1FreshEnough ? 'pass' : 'fail';
}
if (factor1Age === -1) {
return factor2FreshEnough ? 'pass' : 'fail';
}
return factor2FreshEnough ? 'pass' : 'fail';
case 'multi_factor':
// Graceful downgrade: no second factor enrolled falls back to first factor.
if (factor2Age === -1) {
return factor1FreshEnough ? 'pass' : 'fail';
}
// Second factor exists but first factor is not enrolled - we cannot satisfy
// the multi-factor requirement.
if (factor1Age === -1) {
return 'fail';
}
return factor1FreshEnough && factor2FreshEnough ? 'pass' : 'fail';
}
};
// At least one dimension must have passed, and every non-skip result must be a pass.
// This is an AND across asked dimensions with a fail-closed default: if a helper ever
// returns anything other than 'pass' or 'skip' (a typo, off-type, or future variant),
// it is treated as a denial.
const combine = (results: CheckResult[]): boolean =>
results.some(r => r === 'pass') && results.every(r => r === 'pass' || r === 'skip');
/**
* Creates a function for comprehensive user authorization checks.
* Combines organization, billing, and reverification checks. The returned function
* authorizes only when every requested dimension passes; any requested dimension
* that cannot be satisfied (including missing or malformed session data) denies
* the request. Fails if `userId` is missing.
*/
const createCheckAuthorization = (options: AuthorizationOptions): CheckAuthorizationWithCustomPermissions => {
return (params): boolean => {
if (!options.userId) {
return false;
}
return combine([
checkOrgAuthorization(params, options),
checkBillingAuthorization(params, options),
checkReverificationAuthorization(params, options),
]);
};
};
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;
}
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 && !orgId) {
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 };