|
1 | | -import type { and, chain, IRules, or, race } from 'graphql-shield' |
2 | | -import { allow, rule, shield } from 'graphql-shield' |
| 1 | +import type { allow, and, chain, IRules, or, race } from 'graphql-shield' |
| 2 | +import { rule, shield } from 'graphql-shield' |
| 3 | +import type { GraphQLContext } from './context' |
3 | 4 | import type { Primitive } from './type-utils' |
4 | 5 |
|
| 6 | +export type ShieldOptions = NonNullable<Parameters<typeof shield>[1]> |
| 7 | + |
5 | 8 | type RuleCombinator = typeof chain | typeof race | typeof or | typeof and |
6 | 9 | // For whatever reason, graphql-shield doesn't export this type, but we can extract if from |
7 | 10 | // what it does export. |
8 | 11 | export type ShieldRule = ReturnType<(typeof allow)['getRules']>[number] |
| 12 | + |
| 13 | +/** |
| 14 | + * Thin typed wrapper around graphql-shield's `rule(...)` for building ad-hoc shield rules. |
| 15 | + * |
| 16 | + * Lets you pass a plain predicate (sync or async, or returning an `Error`) and get back a |
| 17 | + * {@link ShieldRule} with the `parent`, `args`, and `ctx` arguments typed to your generics — |
| 18 | + * graphql-shield's native `rule` types these as `any`. |
| 19 | + * |
| 20 | + * Defaults the rule's cache to `'strict'`; use `'contextual'` when the result depends only on |
| 21 | + * `ctx` (e.g. the current user), so it can be reused across fields in the same request. |
| 22 | + * |
| 23 | + * @param logic Predicate returning `true` to allow, `false` to deny, or an `Error` to deny with a specific error. |
| 24 | + * @param cache graphql-shield cache strategy. `'strict'` (default) keys on parent+args+ctx; `'contextual'` keys on ctx only. |
| 25 | + * |
| 26 | + * Usage: |
| 27 | + * |
| 28 | + * const isOwner = createRule<GraphQLContext, { ownerId: string }>( |
| 29 | + * (parent, _, ctx) => parent.ownerId === ctx.user?.id, |
| 30 | + * ) |
| 31 | + */ |
9 | 32 | export const createRule = <TContext, TParent = unknown, TArgs = unknown>( |
10 | 33 | logic: (parent: TParent, args: TArgs, ctx: TContext) => boolean | Promise<boolean> | Error, |
11 | 34 | cache: 'contextual' | 'strict' = 'strict', |
@@ -35,33 +58,113 @@ export function combineRuleWithAll<T>(schema: ShieldSchema<T>, rule: ShieldRule, |
35 | 58 | /** |
36 | 59 | * Creates graphql shield middleware making use of generics to type the definition of the rules. |
37 | 60 | * @param schema A mapping of schema objects to the shield rules that define the access to that object |
38 | | - * @param fallbackRule A fallback rule to apply to any object or property which doesn't have a defined rule. |
| 61 | + * @param options Shield options forwarded to `shield`. Defaults `allowExternalErrors` to `true`. |
39 | 62 | * |
40 | 63 | * Usage: |
41 | 64 | * import { Resolvers } from '../generated/types' |
42 | 65 | * |
| 66 | + * const isCoordinator = hasRoleRule(UserRoles.Coordinator) |
| 67 | + * const isSystemAdmin = hasRoleRule(UserRoles.SystemAdmin) |
| 68 | + * const isQualityAssurance = hasRoleRule(UserRoles.QualityAssurance) |
| 69 | + * |
| 70 | + * const isAuthorisedUser = or(isCoordinator, isSystemAdmin, isQualityAssurance) |
| 71 | + * const isDataAuthor = or(isCoordinator, isSystemAdmin) |
| 72 | + * |
43 | 73 | * const shieldSchema = createShieldSchema<Resolvers>({ |
44 | 74 | * Query: { |
45 | | - * getThings: allow, |
46 | | - * dontGetThings: deny, |
47 | | - * } |
48 | | - * }) |
49 | | - * |
50 | | - * let schema = makeExecutableSchema({...}) |
| 75 | + * '*': isAuthorisedUser, |
| 76 | + * user: isCoordinator, |
| 77 | + * findUsers: isCoordinator, |
| 78 | + * }, |
| 79 | + * Mutation: { |
| 80 | + * '*': isDataAuthor, |
| 81 | + * createUser: isCoordinator, |
| 82 | + * }, |
| 83 | + * // specific rules for mutations, types, fields... |
| 84 | + * }, { fallbackRule: isAuthorisedUser, fallbackError: unauthorisedError()}) |
51 | 85 | * |
52 | | - * schema = applyMiddleware(schema, shieldSchema) |
| 86 | + * const unprotected = makeExecutableSchema({...}) |
| 87 | + * return applyMiddleware(unprotected, shieldSchema) |
53 | 88 | */ |
54 | | -export function createShieldSchema<TRootResolvers>(schema: ShieldSchema<TRootResolvers>, fallbackRule: ShieldRule = allow) { |
| 89 | +export function createShieldSchema<TRootResolvers>(schema: ShieldSchema<TRootResolvers>, options?: ShieldOptions) { |
55 | 90 | return shield(schema as IRules, { |
56 | 91 | allowExternalErrors: true, |
57 | | - fallbackRule: fallbackRule, |
| 92 | + ...options, |
58 | 93 | }) |
59 | 94 | } |
60 | 95 |
|
| 96 | +/** |
| 97 | + * A shield rule tree typed against a resolver map (typically your generated `Resolvers` type). |
| 98 | + * |
| 99 | + * Mirrors the shape of `TResolver` so each type/field can be assigned a {@link ShieldRule}. |
| 100 | + * Object levels may also include a `'*'` key — a fallback rule applied to any field at that |
| 101 | + * level that doesn't have an explicit rule. Leaf (primitive) positions collapse to a single |
| 102 | + * {@link ShieldRule}. |
| 103 | + * |
| 104 | + * Usage: |
| 105 | + * |
| 106 | + * const schema: ShieldSchema<Resolvers> = { |
| 107 | + * Query: { |
| 108 | + * '*': isAuthorisedUser, |
| 109 | + * publicThing: allow, |
| 110 | + * }, |
| 111 | + * Mutation: { createUser: isCoordinator }, |
| 112 | + * } |
| 113 | + */ |
61 | 114 | export type ShieldSchema<TResolver> = TResolver extends Primitive |
62 | 115 | ? ShieldRule |
63 | 116 | : { |
64 | 117 | [key in keyof TResolver]?: ShieldSchema<TResolver[key]> | ShieldRule |
65 | 118 | } & { |
66 | 119 | '*'?: ShieldRule |
67 | 120 | } |
| 121 | + |
| 122 | +/** |
| 123 | + * Shield rule that passes when the current user has the given role. |
| 124 | + * @param role The role the user must have on `ctx.user.roles`. |
| 125 | + * @param ruleName Optional override for the rule's cache key. Defaults to `hasRole-${role}`. |
| 126 | + */ |
| 127 | +export function hasRoleRule(role: string, ruleName?: string) { |
| 128 | + return rule(ruleName ?? `hasRole-${role}`, { cache: 'contextual' })( |
| 129 | + (_, __, { user }: GraphQLContext) => user?.roles.includes(role) === true, |
| 130 | + ) |
| 131 | +} |
| 132 | + |
| 133 | +/** |
| 134 | + * Shield rule that passes when the current user has at least one of the given roles. |
| 135 | + * Rule name is derived from the roles; use {@link hasAnyRoleRuleWithName} to supply your own. |
| 136 | + * @param roles The set of roles, any of which satisfies the rule. |
| 137 | + */ |
| 138 | +export function hasAnyRoleRule(...roles: string[]) { |
| 139 | + return hasAnyRoleRuleWithName(`hasAnyRole-${roles.join(',')}`, ...roles) |
| 140 | +} |
| 141 | + |
| 142 | +/** |
| 143 | + * Shield rule that passes when the current user has at least one of the given roles, with an explicit rule name. |
| 144 | + * Prefer this over {@link hasAnyRoleRule} when the role list is large or dynamic and you want a stable cache key. |
| 145 | + * @param ruleName The name (and cache key) for the rule. |
| 146 | + * @param roles The set of roles, any of which satisfies the rule. |
| 147 | + */ |
| 148 | +export function hasAnyRoleRuleWithName(ruleName: string, ...roles: string[]) { |
| 149 | + return rule(ruleName, { cache: 'contextual' })((_, __, { user }: GraphQLContext) => { |
| 150 | + return user?.roles.some((role: string) => roles.includes(role)) === true |
| 151 | + }) |
| 152 | +} |
| 153 | + |
| 154 | +/** |
| 155 | + * Shield rule that passes when the current user has the given scope. |
| 156 | + * @param scope The scope the user must have on `ctx.user.scopes`. |
| 157 | + */ |
| 158 | +export function hasScopeRule(scope: string) { |
| 159 | + return rule(`hasScope-${scope}`, { cache: 'contextual' })((_, __, { user }: GraphQLContext) => user?.scopes.includes(scope) === true) |
| 160 | +} |
| 161 | + |
| 162 | +/** |
| 163 | + * Shield rule that passes when the current user has at least one of the given scopes. |
| 164 | + * @param scopes The set of scopes, any of which satisfies the rule. |
| 165 | + */ |
| 166 | +export function hasAnyScopeRule(...scopes: string[]) { |
| 167 | + return rule(`hasAnyScope-${scopes.join(',')}`, { cache: 'contextual' })( |
| 168 | + (_, __, { user }: GraphQLContext) => user?.scopes.some((scope: string) => scopes.includes(scope)) === true, |
| 169 | + ) |
| 170 | +} |
0 commit comments