@@ -35,36 +35,45 @@ export type AuthorizationEntity = {
35
35
* checkAuthorization(entity, "read", { tasks: ["task_5678"] }); // Returns true
36
36
* ```
37
37
*/
38
+ export type AuthorizationResult = { authorized : true } | { authorized : false ; reason : string } ;
39
+
40
+ /**
41
+ * Checks if the given entity is authorized to perform a specific action on a resource.
42
+ */
38
43
export function checkAuthorization (
39
44
entity : AuthorizationEntity ,
40
45
action : AuthorizationAction ,
41
46
resource : AuthorizationResources ,
42
47
superScopes ?: string [ ]
43
- ) {
48
+ ) : AuthorizationResult {
44
49
// "PRIVATE" is a secret key and has access to everything
45
50
if ( entity . type === "PRIVATE" ) {
46
- return true ;
51
+ return { authorized : true } ;
47
52
}
48
53
49
54
// "PUBLIC" is a deprecated key and has no access
50
55
if ( entity . type === "PUBLIC" ) {
51
- return false ;
56
+ return { authorized : false , reason : "PUBLIC type is deprecated and has no access" } ;
52
57
}
53
58
54
59
// If the entity has no permissions, deny access
55
60
if ( ! entity . scopes || entity . scopes . length === 0 ) {
56
- return false ;
61
+ return {
62
+ authorized : false ,
63
+ reason :
64
+ "Public Access Token has no permissions. See https://trigger.dev/docs/frontend/overview#authentication for more information." ,
65
+ } ;
57
66
}
58
67
59
68
// If the resource object is empty, deny access
60
69
if ( Object . keys ( resource ) . length === 0 ) {
61
- return false ;
70
+ return { authorized : false , reason : "Resource object is empty" } ;
62
71
}
63
72
64
73
// Check for any of the super scopes
65
74
if ( superScopes && superScopes . length > 0 ) {
66
75
if ( superScopes . some ( ( permission ) => entity . scopes ?. includes ( permission ) ) ) {
67
- return true ;
76
+ return { authorized : true } ;
68
77
}
69
78
}
70
79
@@ -94,10 +103,19 @@ export function checkAuthorization(
94
103
95
104
// If any resource is not authorized, return false
96
105
if ( ! resourceAuthorized ) {
97
- return false ;
106
+ return {
107
+ authorized : false ,
108
+ reason : `Public Access Token is missing required permissions. Permissions required for ${ resourceValues
109
+ . map ( ( v ) => `'${ action } :${ resourceType } :${ v } '` )
110
+ . join ( ", " ) } but token has the following permissions: ${ entity . scopes
111
+ . map ( ( s ) => `'${ s } '` )
112
+ . join (
113
+ ", "
114
+ ) } . See https://trigger.dev/docs/frontend/overview#authentication for more information.`,
115
+ } ;
98
116
}
99
117
}
100
118
101
119
// All resources are authorized
102
- return true ;
120
+ return { authorized : true } ;
103
121
}
0 commit comments