@plinthjs/authorization 0.1.1 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +31 -31
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +38 -38
- package/dist/index.d.ts +38 -38
- package/dist/index.js +31 -31
- package/dist/index.js.map +1 -1
- package/package.json +5 -5
package/dist/index.cjs
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
// src/authorization-error.ts
|
|
4
4
|
var AuthorizationError = class extends Error {
|
|
5
|
-
/** The HTTP status this renders as
|
|
5
|
+
/** The HTTP status this renders as - the denying response's status, or the default `403`. */
|
|
6
6
|
status;
|
|
7
7
|
/** The error code attached to the denying {@link Response}, when any. */
|
|
8
8
|
code;
|
|
@@ -40,21 +40,21 @@ var Response = class _Response {
|
|
|
40
40
|
errCode;
|
|
41
41
|
statusCode;
|
|
42
42
|
/**
|
|
43
|
-
* Build an allowing response
|
|
43
|
+
* Build an allowing response - the `Response::allow` equivalent. The optional `message` and
|
|
44
44
|
* `code` are preserved so callers can surface a reason even on success.
|
|
45
45
|
*/
|
|
46
46
|
static allow(message, code) {
|
|
47
47
|
return new _Response(true, message ?? null, code ?? null);
|
|
48
48
|
}
|
|
49
49
|
/**
|
|
50
|
-
* Build a denying response
|
|
50
|
+
* Build a denying response - the `Response::deny` equivalent. The optional `message` and `code`
|
|
51
51
|
* describe why the action was refused.
|
|
52
52
|
*/
|
|
53
53
|
static deny(message, code) {
|
|
54
54
|
return new _Response(false, message ?? null, code ?? null);
|
|
55
55
|
}
|
|
56
56
|
/**
|
|
57
|
-
* Build a denying response that should render with the given HTTP status
|
|
57
|
+
* Build a denying response that should render with the given HTTP status - the
|
|
58
58
|
* `Response::denyWithStatus` equivalent. The status is carried onto the
|
|
59
59
|
* {@link AuthorizationError} thrown by {@link Response.authorize}, so the HTTP exception handler
|
|
60
60
|
* renders e.g. a `404` instead of the default `403`.
|
|
@@ -63,37 +63,37 @@ var Response = class _Response {
|
|
|
63
63
|
return new _Response(false, message ?? null, code ?? null, status);
|
|
64
64
|
}
|
|
65
65
|
/**
|
|
66
|
-
* Build a denying response that renders as a `404 Not Found`
|
|
66
|
+
* Build a denying response that renders as a `404 Not Found` - the `Response::denyAsNotFound`
|
|
67
67
|
* equivalent, used to hide a resource's existence from unauthorized users.
|
|
68
68
|
*/
|
|
69
69
|
static denyAsNotFound(message, code) {
|
|
70
70
|
return _Response.denyWithStatus(404, message, code);
|
|
71
71
|
}
|
|
72
|
-
/** Whether the decision allows the action
|
|
72
|
+
/** Whether the decision allows the action - the `Response::allowed` equivalent. */
|
|
73
73
|
allowed() {
|
|
74
74
|
return this.granted;
|
|
75
75
|
}
|
|
76
|
-
/** Whether the decision denies the action
|
|
76
|
+
/** Whether the decision denies the action - the `Response::denied` equivalent. */
|
|
77
77
|
denied() {
|
|
78
78
|
return !this.granted;
|
|
79
79
|
}
|
|
80
|
-
/** The attached message, or `null` when none was given
|
|
80
|
+
/** The attached message, or `null` when none was given - the `Response::message` equivalent. */
|
|
81
81
|
message() {
|
|
82
82
|
return this.msg;
|
|
83
83
|
}
|
|
84
|
-
/** The attached error code, or `null` when none was given
|
|
84
|
+
/** The attached error code, or `null` when none was given - the `Response::code` equivalent. */
|
|
85
85
|
code() {
|
|
86
86
|
return this.errCode;
|
|
87
87
|
}
|
|
88
88
|
/**
|
|
89
89
|
* The HTTP status a denial should render as, or `null` when none was set (denials default to
|
|
90
|
-
* `403` downstream)
|
|
90
|
+
* `403` downstream) - the `Response::status` equivalent.
|
|
91
91
|
*/
|
|
92
92
|
status() {
|
|
93
93
|
return this.statusCode;
|
|
94
94
|
}
|
|
95
95
|
/**
|
|
96
|
-
* Assert this response allows the action
|
|
96
|
+
* Assert this response allows the action - the `Response::authorize` equivalent. Returns the
|
|
97
97
|
* response (for chaining) when allowed; otherwise throws so a denial bubbles up to the caller.
|
|
98
98
|
*
|
|
99
99
|
* @throws {AuthorizationError} when {@link Response.denied}, carrying this response (and its
|
|
@@ -112,7 +112,7 @@ function toResponse(result) {
|
|
|
112
112
|
var RESOURCE_ABILITIES = ["viewAny", "view", "create", "update", "delete"];
|
|
113
113
|
var Gate = class _Gate {
|
|
114
114
|
/**
|
|
115
|
-
* @param defaultUser The user implicitly used when a check omits one
|
|
115
|
+
* @param defaultUser The user implicitly used when a check omits one - set by {@link Gate.forUser}.
|
|
116
116
|
*/
|
|
117
117
|
constructor(defaultUser) {
|
|
118
118
|
this.defaultUser = defaultUser;
|
|
@@ -123,7 +123,7 @@ var Gate = class _Gate {
|
|
|
123
123
|
beforeCallbacks = [];
|
|
124
124
|
afterCallbacks = [];
|
|
125
125
|
/**
|
|
126
|
-
* Define a named ability
|
|
126
|
+
* Define a named ability - the `Gate::define` equivalent. The callback receives the user and the
|
|
127
127
|
* check's extra arguments and returns a boolean or {@link Response}. Redefining replaces it.
|
|
128
128
|
*/
|
|
129
129
|
define(ability, callback) {
|
|
@@ -132,18 +132,18 @@ var Gate = class _Gate {
|
|
|
132
132
|
}
|
|
133
133
|
/**
|
|
134
134
|
* Whether every given ability has been defined (directly via {@link Gate.define} or
|
|
135
|
-
* {@link Gate.resource})
|
|
135
|
+
* {@link Gate.resource}) - the `Gate::has` equivalent. Policy methods are not consulted, matching
|
|
136
136
|
*/
|
|
137
137
|
has(ability) {
|
|
138
138
|
const list = typeof ability === "string" ? [ability] : ability;
|
|
139
139
|
return list.every((name) => this.abilityCallbacks.has(name));
|
|
140
140
|
}
|
|
141
|
-
/** The names of every defined ability
|
|
141
|
+
/** The names of every defined ability - the `Gate::abilities` listing. */
|
|
142
142
|
abilities() {
|
|
143
143
|
return [...this.abilityCallbacks.keys()];
|
|
144
144
|
}
|
|
145
145
|
/**
|
|
146
|
-
* Register a policy for a resource key
|
|
146
|
+
* Register a policy for a resource key - the `Gate::policy` equivalent. `resourceKey` is either a
|
|
147
147
|
* class constructor or a string tag; when an ability is not defined directly, the gate resolves it
|
|
148
148
|
* to `policy[ability](user, resource, ...args)` using the matching policy.
|
|
149
149
|
*/
|
|
@@ -152,7 +152,7 @@ var Gate = class _Gate {
|
|
|
152
152
|
return this;
|
|
153
153
|
}
|
|
154
154
|
/**
|
|
155
|
-
* Register the standard resource abilities for a policy
|
|
155
|
+
* Register the standard resource abilities for a policy - the `Gate::resource` equivalent. Defines
|
|
156
156
|
* `{name}.viewAny`, `{name}.view`, `{name}.create`, `{name}.update`, and `{name}.delete` (override
|
|
157
157
|
* the list via `abilities`), each dispatching to the matching method on `policy`. The policy's
|
|
158
158
|
* method receives the user and the check's extra arguments, e.g. `allows('posts.update', user, post)`
|
|
@@ -167,7 +167,7 @@ var Gate = class _Gate {
|
|
|
167
167
|
return this;
|
|
168
168
|
}
|
|
169
169
|
/**
|
|
170
|
-
* Register a `before` hook
|
|
170
|
+
* Register a `before` hook - the `Gate::before` equivalent. Hooks run in registration order ahead
|
|
171
171
|
* of every check; the first to return a boolean/{@link Response} decides, `undefined` defers.
|
|
172
172
|
*/
|
|
173
173
|
before(callback) {
|
|
@@ -175,7 +175,7 @@ var Gate = class _Gate {
|
|
|
175
175
|
return this;
|
|
176
176
|
}
|
|
177
177
|
/**
|
|
178
|
-
* Register an `after` hook
|
|
178
|
+
* Register an `after` hook - the `Gate::after` equivalent. Hooks run only when nothing else
|
|
179
179
|
* decided; the first to return a boolean/{@link Response} supplies the verdict.
|
|
180
180
|
*/
|
|
181
181
|
after(callback) {
|
|
@@ -183,7 +183,7 @@ var Gate = class _Gate {
|
|
|
183
183
|
return this;
|
|
184
184
|
}
|
|
185
185
|
/**
|
|
186
|
-
* Return a gate bound to `user` as its default
|
|
186
|
+
* Return a gate bound to `user` as its default - the `Gate::forUser` equivalent. The returned gate
|
|
187
187
|
* shares this gate's abilities, policies, and hooks (by reference) so later registrations are seen.
|
|
188
188
|
*/
|
|
189
189
|
forUser(user) {
|
|
@@ -195,7 +195,7 @@ var Gate = class _Gate {
|
|
|
195
195
|
return gate;
|
|
196
196
|
}
|
|
197
197
|
/**
|
|
198
|
-
* Resolve the raw {@link Response} for an ability
|
|
198
|
+
* Resolve the raw {@link Response} for an ability - the `Gate::inspect` equivalent. Runs `before`
|
|
199
199
|
* hooks (short-circuiting), then the ability or resolved policy method, then `after` hooks. A guest
|
|
200
200
|
* with no allowing decision is denied. When no callback exists at all the result is a denial.
|
|
201
201
|
*/
|
|
@@ -215,28 +215,28 @@ var Gate = class _Gate {
|
|
|
215
215
|
}
|
|
216
216
|
return Response.deny();
|
|
217
217
|
}
|
|
218
|
-
/** Whether the ability is allowed
|
|
218
|
+
/** Whether the ability is allowed - the `Gate::allows` equivalent. */
|
|
219
219
|
allows(ability, user, ...args) {
|
|
220
220
|
return this.inspect(ability, user, ...args).allowed();
|
|
221
221
|
}
|
|
222
|
-
/** Whether the ability is denied
|
|
222
|
+
/** Whether the ability is denied - the `Gate::denies` equivalent. */
|
|
223
223
|
denies(ability, user, ...args) {
|
|
224
224
|
return this.inspect(ability, user, ...args).denied();
|
|
225
225
|
}
|
|
226
|
-
/** Alias of {@link Gate.allows}
|
|
226
|
+
/** Alias of {@link Gate.allows} - the `Gate::check` equivalent. */
|
|
227
227
|
check(ability, user, ...args) {
|
|
228
228
|
return this.allows(ability, user, ...args);
|
|
229
229
|
}
|
|
230
|
-
/** Whether *any* of the abilities is allowed
|
|
230
|
+
/** Whether *any* of the abilities is allowed - the `Gate::any` equivalent. */
|
|
231
231
|
any(abilities, user, ...args) {
|
|
232
232
|
return abilities.some((ability) => this.allows(ability, user, ...args));
|
|
233
233
|
}
|
|
234
|
-
/** Whether *none* of the abilities is allowed
|
|
234
|
+
/** Whether *none* of the abilities is allowed - the `Gate::none` equivalent. */
|
|
235
235
|
none(abilities, user, ...args) {
|
|
236
236
|
return !this.any(abilities, user, ...args);
|
|
237
237
|
}
|
|
238
238
|
/**
|
|
239
|
-
* Assert the ability and return its allowing {@link Response}
|
|
239
|
+
* Assert the ability and return its allowing {@link Response} - the `Gate::authorize` equivalent.
|
|
240
240
|
*
|
|
241
241
|
* @throws {AuthorizationError} when the ability is denied, carrying the denying response.
|
|
242
242
|
*/
|
|
@@ -244,7 +244,7 @@ var Gate = class _Gate {
|
|
|
244
244
|
return this.inspect(ability, user, ...args).authorize();
|
|
245
245
|
}
|
|
246
246
|
/**
|
|
247
|
-
* Authorize when an ad-hoc condition holds
|
|
247
|
+
* Authorize when an ad-hoc condition holds - the `Gate::allowIf` equivalent. `condition` is a
|
|
248
248
|
* boolean, a {@link Response}, or a callback receiving the gate's default user. Returns the
|
|
249
249
|
* allowing {@link Response}; a falsy/denying condition throws an {@link AuthorizationError}
|
|
250
250
|
* carrying `message`/`code`.
|
|
@@ -253,13 +253,13 @@ var Gate = class _Gate {
|
|
|
253
253
|
return this.authorizeOnDemand(condition, message, code, true);
|
|
254
254
|
}
|
|
255
255
|
/**
|
|
256
|
-
* Deny when an ad-hoc condition holds
|
|
256
|
+
* Deny when an ad-hoc condition holds - the `Gate::denyIf` equivalent. The inverse of
|
|
257
257
|
* {@link Gate.allowIf}: a truthy condition throws, a falsy one authorizes.
|
|
258
258
|
*/
|
|
259
259
|
denyIf(condition, message, code) {
|
|
260
260
|
return this.authorizeOnDemand(condition, message, code, false);
|
|
261
261
|
}
|
|
262
|
-
/** Evaluate an ad-hoc condition and authorize it
|
|
262
|
+
/** Evaluate an ad-hoc condition and authorize it - the conventional `authorizeOnDemand`. */
|
|
263
263
|
authorizeOnDemand(condition, message, code, allowWhenResponseIs) {
|
|
264
264
|
const result = typeof condition === "function" ? condition(this.defaultUser) : condition;
|
|
265
265
|
const response = result instanceof Response ? result : result === allowWhenResponseIs ? Response.allow(message, code) : Response.deny(message, code);
|
|
@@ -280,7 +280,7 @@ var Gate = class _Gate {
|
|
|
280
280
|
return method.bind(policy);
|
|
281
281
|
}
|
|
282
282
|
/**
|
|
283
|
-
* Find the policy registered for a model
|
|
283
|
+
* Find the policy registered for a model - the `Gate::getPolicyFor` equivalent. Resolves a string
|
|
284
284
|
* tag, a class constructor, or an instance (by its constructor) to its policy, or `undefined` when
|
|
285
285
|
* none is registered.
|
|
286
286
|
*/
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/authorization-error.ts","../src/response.ts","../src/gate.ts","../src/index.ts"],"names":[],"mappings":";;;AAgBO,IAAM,kBAAA,GAAN,cAAiC,KAAA,CAAM;AAAA;AAAA,EAEnC,MAAA;AAAA;AAAA,EAEA,IAAA;AAAA;AAAA,EAEA,QAAA;AAAA;AAAA;AAAA;AAAA,EAKT,YAAY,QAAA,EAAoB;AAC9B,IAAA,KAAA,CAAM,QAAA,CAAS,OAAA,EAAQ,IAAK,8BAA8B,CAAA;AAC1D,IAAA,IAAA,CAAK,IAAA,GAAO,oBAAA;AACZ,IAAA,IAAA,CAAK,QAAA,GAAW,QAAA;AAChB,IAAA,IAAA,CAAK,IAAA,GAAO,SAAS,IAAA,EAAK;AAC1B,IAAA,IAAA,CAAK,MAAA,GAAS,QAAA,CAAS,MAAA,EAAO,IAAK,GAAA;AAEnC,IAAA,MAAA,CAAO,cAAA,CAAe,IAAA,EAAM,GAAA,CAAA,MAAA,CAAW,SAAS,CAAA;AAAA,EAClD;AACF;;;ACjBO,IAAM,QAAA,GAAN,MAAM,SAAA,CAAS;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOZ,YACW,OAAA,EACA,GAAA,GAAqB,MACrB,OAAA,GAAkC,IAAA,EAClC,aAA4B,IAAA,EAC7C;AAJiB,IAAA,IAAA,CAAA,OAAA,GAAA,OAAA;AACA,IAAA,IAAA,CAAA,GAAA,GAAA,GAAA;AACA,IAAA,IAAA,CAAA,OAAA,GAAA,OAAA;AACA,IAAA,IAAA,CAAA,UAAA,GAAA,UAAA;AAAA,EAChB;AAAA,EAJgB,OAAA;AAAA,EACA,GAAA;AAAA,EACA,OAAA;AAAA,EACA,UAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOnB,OAAO,KAAA,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AAA,CAAS,GAAA,CAAI,KAAkB,CAAA;AAAA,IAC7C;AACA,IAAA,IAAI,KAAA,KAAU,IAAA,IAAQ,OAAO,KAAA,KAAU,QAAA,EAAU;AAC/C,MAAA,MAAM,OAAQ,KAAA,CAAsC,WAAA;AACpD,MAAA,IAAI,SAAS,MAAA,EAAW,OAAO,IAAA,CAAK,QAAA,CAAS,IAAI,IAAI,CAAA;AAAA,IACvD;AACA,IAAA,OAAO,MAAA;AAAA,EACT;AACF;;;AC9SO,IAAM,OAAA,GAAU","file":"index.cjs","sourcesContent":["/**\n * The authorization failure.\n * Thrown by {@link Gate.authorize}/{@link Response.authorize} when an ability is denied. It carries a\n * structural `status` (read by `@plinthjs/http`'s exception handler so the response renders with the\n * right code — `403` by default, or whatever the denying {@link Response} set via `denyWithStatus`/\n * `denyAsNotFound`) alongside the response and its error code, so callers can inspect why.\n */\n\nimport type { Response } from './response'\n\n/**\n * `AuthorizationError`. Carries the\n * denying {@link Response} (so callers can read its message/code) and a structural `status` so\n * `@plinthjs/http`'s handler renders it without this package depending on the HTTP layer. The status is\n * the response's own (e.g. `404` from `denyAsNotFound`), falling back to the `403`.\n */\nexport class AuthorizationError extends Error {\n /** The HTTP status this renders as — the denying response's status, or the default `403`. */\n readonly status: number\n /** The error code attached to the denying {@link Response}, when any. */\n readonly code: string | number | null\n /** The full denying {@link Response} that triggered this error. */\n readonly response: Response\n\n /**\n * @param response The denying {@link Response}; its message becomes the error message.\n */\n constructor(response: Response) {\n super(response.message() ?? 'This action is unauthorized.')\n this.name = 'AuthorizationError'\n this.response = response\n this.code = response.code()\n this.status = response.status() ?? 403\n // Restore the prototype chain when targeting ES2022 down-levels.\n Object.setPrototypeOf(this, new.target.prototype)\n }\n}\n","/**\n * Authorization responses. A\n * {@link Response} is the rich result of an authorization check: it carries an allowed/denied\n * verdict plus an optional human-readable message, an optional error code, and (for denials) an\n * optional HTTP status. Gate check callbacks may return a bare boolean (which the {@link Gate}\n * normalizes into a {@link Response}) or build one explicitly via\n * {@link Response.allow}/{@link Response.deny}/{@link Response.denyWithStatus} to attach a message\n * the UI can surface or a status the HTTP layer should render (e.g. a `404` that hides existence).\n */\n\nimport { AuthorizationError } from './authorization-error'\n\n/**\n * `Response`. Immutable result of an\n * authorization decision: it is either allowed or denied, optionally with a message, an error\n * code, and (when denied) an HTTP status override. Construct one through the\n * {@link Response.allow}/{@link Response.deny}/{@link Response.denyWithStatus} factories rather\n * than the constructor.\n */\nexport class Response {\n /**\n * @param granted Whether the decision allows the action.\n * @param msg Optional human-readable explanation (typically used on denial).\n * @param errCode Optional machine-readable error code attached to the decision.\n * @param statusCode Optional HTTP status a denial should render as (defaults to `403` downstream).\n */\n private constructor(\n private readonly granted: boolean,\n private readonly msg: string | null = null,\n private readonly errCode: string | number | null = null,\n private readonly statusCode: number | null = null,\n ) {}\n\n /**\n * Build an allowing response — the `Response::allow` equivalent. The optional `message` and\n * `code` are preserved so callers can surface a reason even on success.\n */\n static allow(message?: string, code?: string | number): Response {\n return new Response(true, message ?? null, code ?? null)\n }\n\n /**\n * Build a denying response — the `Response::deny` equivalent. The optional `message` and `code`\n * describe why the action was refused.\n */\n static deny(message?: string, code?: string | number): Response {\n return new Response(false, message ?? null, code ?? null)\n }\n\n /**\n * Build a denying response that should render with the given HTTP status — the\n * `Response::denyWithStatus` equivalent. The status is carried onto the\n * {@link AuthorizationError} thrown by {@link Response.authorize}, so the HTTP exception handler\n * renders e.g. a `404` instead of the default `403`.\n */\n static denyWithStatus(status: number, message?: string, code?: string | number): Response {\n return new Response(false, message ?? null, code ?? null, status)\n }\n\n /**\n * Build a denying response that renders as a `404 Not Found` — the `Response::denyAsNotFound`\n * equivalent, used to hide a resource's existence from unauthorized users.\n */\n static denyAsNotFound(message?: string, code?: string | number): Response {\n return Response.denyWithStatus(404, message, code)\n }\n\n /** Whether the decision allows the action — the `Response::allowed` equivalent. */\n allowed(): boolean {\n return this.granted\n }\n\n /** Whether the decision denies the action — the `Response::denied` equivalent. */\n denied(): boolean {\n return !this.granted\n }\n\n /** The attached message, or `null` when none was given — the `Response::message` equivalent. */\n message(): string | null {\n return this.msg\n }\n\n /** The attached error code, or `null` when none was given — the `Response::code` equivalent. */\n code(): string | number | null {\n return this.errCode\n }\n\n /**\n * The HTTP status a denial should render as, or `null` when none was set (denials default to\n * `403` downstream) — the `Response::status` equivalent.\n */\n status(): number | null {\n return this.statusCode\n }\n\n /**\n * Assert this response allows the action — the `Response::authorize` equivalent. Returns the\n * response (for chaining) when allowed; otherwise throws so a denial bubbles up to the caller.\n *\n * @throws {AuthorizationError} when {@link Response.denied}, carrying this response (and its\n * status, when one was set via {@link Response.denyWithStatus}).\n */\n authorize(): this {\n if (!this.granted) throw new AuthorizationError(this)\n return this\n }\n}\n","/**\n * The authorization gate. A {@link Gate}\n * holds the registry of named abilities (defined via callbacks) and resource policies, then answers\n * authorization questions about them: `allows`/`denies`/`check` return booleans, `inspect` returns\n * the raw {@link Response} (including any HTTP status a denial set via `denyWithStatus`),\n * `authorize` throws an {@link AuthorizationError} on denial, and `allowIf`/`denyIf` authorize\n * ad-hoc conditions. `has` reports whether abilities are defined and `abilities` lists them.\n * `before` hooks can short-circuit a decision (e.g. super-admins) and `after` hooks fill in a\n * verdict when nothing else decided. Guests (a `null`/`undefined` user) are denied unless a\n * `before` allows them.\n */\n\nimport { Response } from './response'\n\n// Re-exported here so existing importers of `AuthorizationError` from this module keep working.\nexport { AuthorizationError } from './authorization-error'\n\n/**\n * The result an ability/hook callback may return. A bare boolean is normalized into a\n * {@link Response}; `undefined` from a hook means \"no opinion — keep resolving\".\n */\nexport type AbilityResult = boolean | Response\n\n/**\n * An ability callback — the closure passed to `Gate::define`. Receives the authenticated user\n * followed by the check's extra arguments and returns a boolean or {@link Response}. The gate denies\n * guests before this runs, so `user` is always a real user here. The extra args are typed loosely so\n * callbacks may declare their own concrete parameter types (e.g. `(user, post: Post) => ...`).\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- variadic ability args must accept any concrete param types declared by callbacks\nexport type AbilityCallback<User> = (user: User, ...args: any[]) => AbilityResult\n\n/**\n * A `before` hook — the `Gate::before` equivalent. Runs ahead of every check; returning a boolean\n * or {@link Response} short-circuits the decision, while `undefined` defers to the ability/policy.\n */\nexport type BeforeCallback<User> = (\n user: User,\n ability: string,\n args: unknown[],\n) => AbilityResult | undefined\n\n/**\n * An `after` hook — the `Gate::after` equivalent. Runs only when no `before` hook or ability/policy\n * produced a decision; returning a boolean or {@link Response} supplies the verdict.\n */\nexport type AfterCallback<User> = (\n user: User,\n ability: string,\n args: unknown[],\n) => AbilityResult | undefined\n\n/**\n * The condition accepted by {@link Gate.allowIf}/{@link Gate.denyIf} — a boolean, a prebuilt\n * {@link Response}, or a callback receiving the gate's default user (set via {@link Gate.forUser};\n * `null`/`undefined` for guests) and returning either.\n */\nexport type GateCondition<User> = AbilityResult | ((user: User | null | undefined) => AbilityResult)\n\n/** A resource policy — a plain object (or class instance) whose methods are ability callbacks. */\nexport type Policy<User> = Record<string, AbilityCallback<User>>\n\n/** Normalize an ability/hook result into a {@link Response}. */\nfunction toResponse(result: AbilityResult): Response {\n return result instanceof Response ? result : result ? Response.allow() : Response.deny()\n}\n\n/** A key used to look up a policy: either a string tag or a class constructor. */\ntype PolicyKey = string | (new (...args: never[]) => unknown)\n\n/**\n * The standard CRUD abilities registered by {@link Gate.resource} — mirrors the methods the reference framework's\n * `Gate::resource` maps by default (`viewAny`, `view`, `create`, `update`, `delete`).\n */\nconst RESOURCE_ABILITIES: readonly string[] = ['viewAny', 'view', 'create', 'update', 'delete']\n\n/**\n * `Gate`. Registers abilities and policies, then\n * resolves authorization decisions for a user. The user type is generic; pass the application's\n * user shape (it always includes the guest sentinels `null`/`undefined`).\n *\n * @typeParam User The authenticated user shape; checks may also receive `null`/`undefined` guests.\n */\nexport class Gate<User = unknown> {\n private readonly abilityCallbacks = new Map<string, AbilityCallback<User>>()\n private readonly policies = new Map<PolicyKey, Policy<User>>()\n private readonly beforeCallbacks: BeforeCallback<User | null | undefined>[] = []\n private readonly afterCallbacks: AfterCallback<User | null | undefined>[] = []\n\n /**\n * @param defaultUser The user implicitly used when a check omits one — set by {@link Gate.forUser}.\n */\n constructor(private readonly defaultUser?: User | null | undefined) {}\n\n /**\n * Define a named ability — the `Gate::define` equivalent. The callback receives the user and the\n * check's extra arguments and returns a boolean or {@link Response}. Redefining replaces it.\n */\n define(ability: string, callback: AbilityCallback<User>): this {\n this.abilityCallbacks.set(ability, callback)\n return this\n }\n\n /**\n * Whether every given ability has been defined (directly via {@link Gate.define} or\n * {@link Gate.resource}) — the `Gate::has` equivalent. Policy methods are not consulted, matching\n */\n has(ability: string | readonly string[]): boolean {\n const list = typeof ability === 'string' ? [ability] : ability\n return list.every((name) => this.abilityCallbacks.has(name))\n }\n\n /** The names of every defined ability — the `Gate::abilities` listing. */\n abilities(): string[] {\n return [...this.abilityCallbacks.keys()]\n }\n\n /**\n * Register a policy for a resource key — the `Gate::policy` equivalent. `resourceKey` is either a\n * class constructor or a string tag; when an ability is not defined directly, the gate resolves it\n * to `policy[ability](user, resource, ...args)` using the matching policy.\n */\n policy(resourceKey: PolicyKey, policy: Policy<User>): this {\n this.policies.set(resourceKey, policy)\n return this\n }\n\n /**\n * Register the standard resource abilities for a policy — the `Gate::resource` equivalent. Defines\n * `{name}.viewAny`, `{name}.view`, `{name}.create`, `{name}.update`, and `{name}.delete` (override\n * the list via `abilities`), each dispatching to the matching method on `policy`. The policy's\n * method receives the user and the check's extra arguments, e.g. `allows('posts.update', user, post)`\n * routes to `policy.update(user, post)`. Methods absent from the policy resolve to a denial.\n */\n resource(\n name: string,\n policy: Policy<User>,\n abilities: readonly string[] = RESOURCE_ABILITIES,\n ): this {\n for (const ability of abilities) {\n const method = policy[ability]\n if (typeof method !== 'function') continue\n // Bind so the policy method keeps its `this`; forward the user and any extra check args.\n this.define(`${name}.${ability}`, method.bind(policy))\n }\n return this\n }\n\n /**\n * Register a `before` hook — the `Gate::before` equivalent. Hooks run in registration order ahead\n * of every check; the first to return a boolean/{@link Response} decides, `undefined` defers.\n */\n before(callback: BeforeCallback<User | null | undefined>): this {\n this.beforeCallbacks.push(callback)\n return this\n }\n\n /**\n * Register an `after` hook — the `Gate::after` equivalent. Hooks run only when nothing else\n * decided; the first to return a boolean/{@link Response} supplies the verdict.\n */\n after(callback: AfterCallback<User | null | undefined>): this {\n this.afterCallbacks.push(callback)\n return this\n }\n\n /**\n * Return a gate bound to `user` as its default — the `Gate::forUser` equivalent. The returned gate\n * shares this gate's abilities, policies, and hooks (by reference) so later registrations are seen.\n */\n forUser(user: User | null | undefined): Gate<User> {\n const gate = new Gate<User>(user)\n // Share the underlying registries so the bound gate mirrors this one.\n Reflect.set(gate, 'abilityCallbacks', this.abilityCallbacks)\n Reflect.set(gate, 'policies', this.policies)\n Reflect.set(gate, 'beforeCallbacks', this.beforeCallbacks)\n Reflect.set(gate, 'afterCallbacks', this.afterCallbacks)\n return gate\n }\n\n /**\n * Resolve the raw {@link Response} for an ability — the `Gate::inspect` equivalent. Runs `before`\n * hooks (short-circuiting), then the ability or resolved policy method, then `after` hooks. A guest\n * with no allowing decision is denied. When no callback exists at all the result is a denial.\n */\n inspect(\n ability: string,\n user: User | null | undefined = this.defaultUser,\n ...args: unknown[]\n ): Response {\n // `before` hooks run for everyone (including guests) and may grant access outright.\n for (const hook of this.beforeCallbacks) {\n const result = hook(user, ability, args)\n if (result !== undefined) return toResponse(result)\n }\n\n const callback = this.resolve(ability, args)\n if (callback !== undefined) {\n // Guests are denied at defined abilities unless a `before` hook already allowed them above.\n if (user === null || user === undefined) return Response.deny()\n // `user` is narrowed to a real `User` here, matching the ability callback's contract.\n return toResponse(callback(user, ...args))\n }\n\n // Nothing defined decided — let `after` hooks supply a verdict.\n for (const hook of this.afterCallbacks) {\n const result = hook(user, ability, args)\n if (result !== undefined) return toResponse(result)\n }\n\n return Response.deny()\n }\n\n /** Whether the ability is allowed — the `Gate::allows` equivalent. */\n allows(ability: string, user?: User | null, ...args: unknown[]): boolean {\n return this.inspect(ability, user, ...args).allowed()\n }\n\n /** Whether the ability is denied — the `Gate::denies` equivalent. */\n denies(ability: string, user?: User | null, ...args: unknown[]): boolean {\n return this.inspect(ability, user, ...args).denied()\n }\n\n /** Alias of {@link Gate.allows} — the `Gate::check` equivalent. */\n check(ability: string, user?: User | null, ...args: unknown[]): boolean {\n return this.allows(ability, user, ...args)\n }\n\n /** Whether *any* of the abilities is allowed — the `Gate::any` equivalent. */\n any(abilities: string[], user?: User | null, ...args: unknown[]): boolean {\n return abilities.some((ability) => this.allows(ability, user, ...args))\n }\n\n /** Whether *none* of the abilities is allowed — the `Gate::none` equivalent. */\n none(abilities: string[], user?: User | null, ...args: unknown[]): boolean {\n return !this.any(abilities, user, ...args)\n }\n\n /**\n * Assert the ability and return its allowing {@link Response} — the `Gate::authorize` equivalent.\n *\n * @throws {AuthorizationError} when the ability is denied, carrying the denying response.\n */\n authorize(ability: string, user?: User | null, ...args: unknown[]): Response {\n return this.inspect(ability, user, ...args).authorize()\n }\n\n /**\n * Authorize when an ad-hoc condition holds — the `Gate::allowIf` equivalent. `condition` is a\n * boolean, a {@link Response}, or a callback receiving the gate's default user. Returns the\n * allowing {@link Response}; a falsy/denying condition throws an {@link AuthorizationError}\n * carrying `message`/`code`.\n */\n allowIf(condition: GateCondition<User>, message?: string, code?: string | number): Response {\n return this.authorizeOnDemand(condition, message, code, true)\n }\n\n /**\n * Deny when an ad-hoc condition holds — the `Gate::denyIf` equivalent. The inverse of\n * {@link Gate.allowIf}: a truthy condition throws, a falsy one authorizes.\n */\n denyIf(condition: GateCondition<User>, message?: string, code?: string | number): Response {\n return this.authorizeOnDemand(condition, message, code, false)\n }\n\n /** Evaluate an ad-hoc condition and authorize it — the conventional `authorizeOnDemand`. */\n private authorizeOnDemand(\n condition: GateCondition<User>,\n message: string | undefined,\n code: string | number | undefined,\n allowWhenResponseIs: boolean,\n ): Response {\n const result = typeof condition === 'function' ? condition(this.defaultUser) : condition\n const response =\n result instanceof Response\n ? result\n : result === allowWhenResponseIs\n ? Response.allow(message, code)\n : Response.deny(message, code)\n return response.authorize()\n }\n\n /**\n * Resolve the callback for an ability: a directly defined one wins, otherwise look for a policy\n * keyed by the first argument (a string tag or the resource's constructor) exposing the ability.\n */\n private resolve(ability: string, args: unknown[]): AbilityCallback<User> | undefined {\n const direct = this.abilityCallbacks.get(ability)\n if (direct !== undefined) return direct\n\n const resource = args[0]\n const policy = this.getPolicyFor(resource)\n if (policy === undefined) return undefined\n\n const method = policy[ability]\n if (typeof method !== 'function') return undefined\n\n // Bind so the policy method keeps its `this`; the resource stays the first arg to the method.\n return method.bind(policy)\n }\n\n /**\n * Find the policy registered for a model — the `Gate::getPolicyFor` equivalent. Resolves a string\n * tag, a class constructor, or an instance (by its constructor) to its policy, or `undefined` when\n * none is registered.\n */\n getPolicyFor(model: unknown): Policy<User> | undefined {\n if (typeof model === 'string') {\n return this.policies.get(model)\n }\n if (typeof model === 'function') {\n return this.policies.get(model as PolicyKey)\n }\n if (model !== null && typeof model === 'object') {\n const ctor = (model as { constructor?: PolicyKey }).constructor\n if (ctor !== undefined) return this.policies.get(ctor)\n }\n return undefined\n }\n}\n","/**\n * @plinthjs/authorization.\n *\n * A {@link Gate} that registers named abilities and resource {@link Policy} objects, then answers\n * authorization questions: `allows`/`denies`/`check` booleans, `inspect` for the raw {@link Response},\n * `any`/`none` across several abilities, and `authorize` which throws {@link AuthorizationError} on\n * denial. `resource` registers the standard `viewAny`/`view`/`create`/`update`/`delete` abilities for\n * a policy, `getPolicyFor` looks a policy up by model, `has`/`abilities` report what is defined,\n * `allowIf`/`denyIf` authorize ad-hoc conditions, `before`/`after` hooks short-circuit or backfill\n * decisions, `forUser` binds a default user, and guests (`null`/`undefined`) are denied unless a\n * `before` hook allows them. {@link Response} carries an allow/deny verdict plus an optional message,\n * code, and (via `denyWithStatus`/`denyAsNotFound`) an HTTP status for the denial, and its\n * `authorize` throws when denied. {@link AuthorizationError} carries a structural `status` (the\n * response's, defaulting to `403`) so `@plinthjs/http`'s handler renders it correctly.\n */\n\n/** The Plinth version this build of `authorization` ships with. */\nexport const VERSION = '0.1.0'\n\nexport { AuthorizationError } from './authorization-error'\nexport {\n type AbilityCallback,\n type AbilityResult,\n type AfterCallback,\n type BeforeCallback,\n Gate,\n type GateCondition,\n type Policy,\n} from './gate'\nexport { Response } from './response'\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/authorization-error.ts","../src/response.ts","../src/gate.ts","../src/index.ts"],"names":[],"mappings":";;;AAgBO,IAAM,kBAAA,GAAN,cAAiC,KAAA,CAAM;AAAA;AAAA,EAEnC,MAAA;AAAA;AAAA,EAEA,IAAA;AAAA;AAAA,EAEA,QAAA;AAAA;AAAA;AAAA;AAAA,EAKT,YAAY,QAAA,EAAoB;AAC9B,IAAA,KAAA,CAAM,QAAA,CAAS,OAAA,EAAQ,IAAK,8BAA8B,CAAA;AAC1D,IAAA,IAAA,CAAK,IAAA,GAAO,oBAAA;AACZ,IAAA,IAAA,CAAK,QAAA,GAAW,QAAA;AAChB,IAAA,IAAA,CAAK,IAAA,GAAO,SAAS,IAAA,EAAK;AAC1B,IAAA,IAAA,CAAK,MAAA,GAAS,QAAA,CAAS,MAAA,EAAO,IAAK,GAAA;AAEnC,IAAA,MAAA,CAAO,cAAA,CAAe,IAAA,EAAM,GAAA,CAAA,MAAA,CAAW,SAAS,CAAA;AAAA,EAClD;AACF;;;ACjBO,IAAM,QAAA,GAAN,MAAM,SAAA,CAAS;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOZ,YACW,OAAA,EACA,GAAA,GAAqB,MACrB,OAAA,GAAkC,IAAA,EAClC,aAA4B,IAAA,EAC7C;AAJiB,IAAA,IAAA,CAAA,OAAA,GAAA,OAAA;AACA,IAAA,IAAA,CAAA,GAAA,GAAA,GAAA;AACA,IAAA,IAAA,CAAA,OAAA,GAAA,OAAA;AACA,IAAA,IAAA,CAAA,UAAA,GAAA,UAAA;AAAA,EAChB;A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A,CAAS,GAAA,CAAI,KAAK,CAAA;AAAA,IAChC;AACA,IAAA,IAAI,OAAO,UAAU,UAAA,EAAY;AAC/B,MAAA,OAAO,IAAA,CAAK,QAAA,CAAS,GAAA,CAAI,KAAkB,CAAA;AAAA,IAC7C;AACA,IAAA,IAAI,KAAA,KAAU,IAAA,IAAQ,OAAO,KAAA,KAAU,QAAA,EAAU;AAC/C,MAAA,MAAM,OAAQ,KAAA,CAAsC,WAAA;AACpD,MAAA,IAAI,SAAS,MAAA,EAAW,OAAO,IAAA,CAAK,QAAA,CAAS,IAAI,IAAI,CAAA;AAAA,IACvD;AACA,IAAA,OAAO,MAAA;AAAA,EACT;AACF;;;AC9SO,IAAM,OAAA,GAAU","file":"index.cjs","sourcesContent":["/**\n * The authorization failure.\n * Thrown by {@link Gate.authorize}/{@link Response.authorize} when an ability is denied. It carries a\n * structural `status` (read by `@plinthjs/http`'s exception handler so the response renders with the\n * right code - `403` by default, or whatever the denying {@link Response} set via `denyWithStatus`/\n * `denyAsNotFound`) alongside the response and its error code, so callers can inspect why.\n */\n\nimport type { Response } from './response'\n\n/**\n * `AuthorizationError`. Carries the\n * denying {@link Response} (so callers can read its message/code) and a structural `status` so\n * `@plinthjs/http`'s handler renders it without this package depending on the HTTP layer. The status is\n * the response's own (e.g. `404` from `denyAsNotFound`), falling back to the `403`.\n */\nexport class AuthorizationError extends Error {\n /** The HTTP status this renders as - the denying response's status, or the default `403`. */\n readonly status: number\n /** The error code attached to the denying {@link Response}, when any. */\n readonly code: string | number | null\n /** The full denying {@link Response} that triggered this error. */\n readonly response: Response\n\n /**\n * @param response The denying {@link Response}; its message becomes the error message.\n */\n constructor(response: Response) {\n super(response.message() ?? 'This action is unauthorized.')\n this.name = 'AuthorizationError'\n this.response = response\n this.code = response.code()\n this.status = response.status() ?? 403\n // Restore the prototype chain when targeting ES2022 down-levels.\n Object.setPrototypeOf(this, new.target.prototype)\n }\n}\n","/**\n * Authorization responses. A\n * {@link Response} is the rich result of an authorization check: it carries an allowed/denied\n * verdict plus an optional human-readable message, an optional error code, and (for denials) an\n * optional HTTP status. Gate check callbacks may return a bare boolean (which the {@link Gate}\n * normalizes into a {@link Response}) or build one explicitly via\n * {@link Response.allow}/{@link Response.deny}/{@link Response.denyWithStatus} to attach a message\n * the UI can surface or a status the HTTP layer should render (e.g. a `404` that hides existence).\n */\n\nimport { AuthorizationError } from './authorization-error'\n\n/**\n * `Response`. Immutable result of an\n * authorization decision: it is either allowed or denied, optionally with a message, an error\n * code, and (when denied) an HTTP status override. Construct one through the\n * {@link Response.allow}/{@link Response.deny}/{@link Response.denyWithStatus} factories rather\n * than the constructor.\n */\nexport class Response {\n /**\n * @param granted Whether the decision allows the action.\n * @param msg Optional human-readable explanation (typically used on denial).\n * @param errCode Optional machine-readable error code attached to the decision.\n * @param statusCode Optional HTTP status a denial should render as (defaults to `403` downstream).\n */\n private constructor(\n private readonly granted: boolean,\n private readonly msg: string | null = null,\n private readonly errCode: string | number | null = null,\n private readonly statusCode: number | null = null,\n ) {}\n\n /**\n * Build an allowing response - the `Response::allow` equivalent. The optional `message` and\n * `code` are preserved so callers can surface a reason even on success.\n */\n static allow(message?: string, code?: string | number): Response {\n return new Response(true, message ?? null, code ?? null)\n }\n\n /**\n * Build a denying response - the `Response::deny` equivalent. The optional `message` and `code`\n * describe why the action was refused.\n */\n static deny(message?: string, code?: string | number): Response {\n return new Response(false, message ?? null, code ?? null)\n }\n\n /**\n * Build a denying response that should render with the given HTTP status - the\n * `Response::denyWithStatus` equivalent. The status is carried onto the\n * {@link AuthorizationError} thrown by {@link Response.authorize}, so the HTTP exception handler\n * renders e.g. a `404` instead of the default `403`.\n */\n static denyWithStatus(status: number, message?: string, code?: string | number): Response {\n return new Response(false, message ?? null, code ?? null, status)\n }\n\n /**\n * Build a denying response that renders as a `404 Not Found` - the `Response::denyAsNotFound`\n * equivalent, used to hide a resource's existence from unauthorized users.\n */\n static denyAsNotFound(message?: string, code?: string | number): Response {\n return Response.denyWithStatus(404, message, code)\n }\n\n /** Whether the decision allows the action - the `Response::allowed` equivalent. */\n allowed(): boolean {\n return this.granted\n }\n\n /** Whether the decision denies the action - the `Response::denied` equivalent. */\n denied(): boolean {\n return !this.granted\n }\n\n /** The attached message, or `null` when none was given - the `Response::message` equivalent. */\n message(): string | null {\n return this.msg\n }\n\n /** The attached error code, or `null` when none was given - the `Response::code` equivalent. */\n code(): string | number | null {\n return this.errCode\n }\n\n /**\n * The HTTP status a denial should render as, or `null` when none was set (denials default to\n * `403` downstream) - the `Response::status` equivalent.\n */\n status(): number | null {\n return this.statusCode\n }\n\n /**\n * Assert this response allows the action - the `Response::authorize` equivalent. Returns the\n * response (for chaining) when allowed; otherwise throws so a denial bubbles up to the caller.\n *\n * @throws {AuthorizationError} when {@link Response.denied}, carrying this response (and its\n * status, when one was set via {@link Response.denyWithStatus}).\n */\n authorize(): this {\n if (!this.granted) throw new AuthorizationError(this)\n return this\n }\n}\n","/**\n * The authorization gate. A {@link Gate}\n * holds the registry of named abilities (defined via callbacks) and resource policies, then answers\n * authorization questions about them: `allows`/`denies`/`check` return booleans, `inspect` returns\n * the raw {@link Response} (including any HTTP status a denial set via `denyWithStatus`),\n * `authorize` throws an {@link AuthorizationError} on denial, and `allowIf`/`denyIf` authorize\n * ad-hoc conditions. `has` reports whether abilities are defined and `abilities` lists them.\n * `before` hooks can short-circuit a decision (e.g. super-admins) and `after` hooks fill in a\n * verdict when nothing else decided. Guests (a `null`/`undefined` user) are denied unless a\n * `before` allows them.\n */\n\nimport { Response } from './response'\n\n// Re-exported here so existing importers of `AuthorizationError` from this module keep working.\nexport { AuthorizationError } from './authorization-error'\n\n/**\n * The result an ability/hook callback may return. A bare boolean is normalized into a\n * {@link Response}; `undefined` from a hook means \"no opinion - keep resolving\".\n */\nexport type AbilityResult = boolean | Response\n\n/**\n * An ability callback - the closure passed to `Gate::define`. Receives the authenticated user\n * followed by the check's extra arguments and returns a boolean or {@link Response}. The gate denies\n * guests before this runs, so `user` is always a real user here. The extra args are typed loosely so\n * callbacks may declare their own concrete parameter types (e.g. `(user, post: Post) => ...`).\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- variadic ability args must accept any concrete param types declared by callbacks\nexport type AbilityCallback<User> = (user: User, ...args: any[]) => AbilityResult\n\n/**\n * A `before` hook - the `Gate::before` equivalent. Runs ahead of every check; returning a boolean\n * or {@link Response} short-circuits the decision, while `undefined` defers to the ability/policy.\n */\nexport type BeforeCallback<User> = (\n user: User,\n ability: string,\n args: unknown[],\n) => AbilityResult | undefined\n\n/**\n * An `after` hook - the `Gate::after` equivalent. Runs only when no `before` hook or ability/policy\n * produced a decision; returning a boolean or {@link Response} supplies the verdict.\n */\nexport type AfterCallback<User> = (\n user: User,\n ability: string,\n args: unknown[],\n) => AbilityResult | undefined\n\n/**\n * The condition accepted by {@link Gate.allowIf}/{@link Gate.denyIf} - a boolean, a prebuilt\n * {@link Response}, or a callback receiving the gate's default user (set via {@link Gate.forUser};\n * `null`/`undefined` for guests) and returning either.\n */\nexport type GateCondition<User> = AbilityResult | ((user: User | null | undefined) => AbilityResult)\n\n/** A resource policy - a plain object (or class instance) whose methods are ability callbacks. */\nexport type Policy<User> = Record<string, AbilityCallback<User>>\n\n/** Normalize an ability/hook result into a {@link Response}. */\nfunction toResponse(result: AbilityResult): Response {\n return result instanceof Response ? result : result ? Response.allow() : Response.deny()\n}\n\n/** A key used to look up a policy: either a string tag or a class constructor. */\ntype PolicyKey = string | (new (...args: never[]) => unknown)\n\n/**\n * The standard CRUD abilities registered by {@link Gate.resource} - mirrors the methods the reference framework's\n * `Gate::resource` maps by default (`viewAny`, `view`, `create`, `update`, `delete`).\n */\nconst RESOURCE_ABILITIES: readonly string[] = ['viewAny', 'view', 'create', 'update', 'delete']\n\n/**\n * `Gate`. Registers abilities and policies, then\n * resolves authorization decisions for a user. The user type is generic; pass the application's\n * user shape (it always includes the guest sentinels `null`/`undefined`).\n *\n * @typeParam User The authenticated user shape; checks may also receive `null`/`undefined` guests.\n */\nexport class Gate<User = unknown> {\n private readonly abilityCallbacks = new Map<string, AbilityCallback<User>>()\n private readonly policies = new Map<PolicyKey, Policy<User>>()\n private readonly beforeCallbacks: BeforeCallback<User | null | undefined>[] = []\n private readonly afterCallbacks: AfterCallback<User | null | undefined>[] = []\n\n /**\n * @param defaultUser The user implicitly used when a check omits one - set by {@link Gate.forUser}.\n */\n constructor(private readonly defaultUser?: User | null | undefined) {}\n\n /**\n * Define a named ability - the `Gate::define` equivalent. The callback receives the user and the\n * check's extra arguments and returns a boolean or {@link Response}. Redefining replaces it.\n */\n define(ability: string, callback: AbilityCallback<User>): this {\n this.abilityCallbacks.set(ability, callback)\n return this\n }\n\n /**\n * Whether every given ability has been defined (directly via {@link Gate.define} or\n * {@link Gate.resource}) - the `Gate::has` equivalent. Policy methods are not consulted, matching\n */\n has(ability: string | readonly string[]): boolean {\n const list = typeof ability === 'string' ? [ability] : ability\n return list.every((name) => this.abilityCallbacks.has(name))\n }\n\n /** The names of every defined ability - the `Gate::abilities` listing. */\n abilities(): string[] {\n return [...this.abilityCallbacks.keys()]\n }\n\n /**\n * Register a policy for a resource key - the `Gate::policy` equivalent. `resourceKey` is either a\n * class constructor or a string tag; when an ability is not defined directly, the gate resolves it\n * to `policy[ability](user, resource, ...args)` using the matching policy.\n */\n policy(resourceKey: PolicyKey, policy: Policy<User>): this {\n this.policies.set(resourceKey, policy)\n return this\n }\n\n /**\n * Register the standard resource abilities for a policy - the `Gate::resource` equivalent. Defines\n * `{name}.viewAny`, `{name}.view`, `{name}.create`, `{name}.update`, and `{name}.delete` (override\n * the list via `abilities`), each dispatching to the matching method on `policy`. The policy's\n * method receives the user and the check's extra arguments, e.g. `allows('posts.update', user, post)`\n * routes to `policy.update(user, post)`. Methods absent from the policy resolve to a denial.\n */\n resource(\n name: string,\n policy: Policy<User>,\n abilities: readonly string[] = RESOURCE_ABILITIES,\n ): this {\n for (const ability of abilities) {\n const method = policy[ability]\n if (typeof method !== 'function') continue\n // Bind so the policy method keeps its `this`; forward the user and any extra check args.\n this.define(`${name}.${ability}`, method.bind(policy))\n }\n return this\n }\n\n /**\n * Register a `before` hook - the `Gate::before` equivalent. Hooks run in registration order ahead\n * of every check; the first to return a boolean/{@link Response} decides, `undefined` defers.\n */\n before(callback: BeforeCallback<User | null | undefined>): this {\n this.beforeCallbacks.push(callback)\n return this\n }\n\n /**\n * Register an `after` hook - the `Gate::after` equivalent. Hooks run only when nothing else\n * decided; the first to return a boolean/{@link Response} supplies the verdict.\n */\n after(callback: AfterCallback<User | null | undefined>): this {\n this.afterCallbacks.push(callback)\n return this\n }\n\n /**\n * Return a gate bound to `user` as its default - the `Gate::forUser` equivalent. The returned gate\n * shares this gate's abilities, policies, and hooks (by reference) so later registrations are seen.\n */\n forUser(user: User | null | undefined): Gate<User> {\n const gate = new Gate<User>(user)\n // Share the underlying registries so the bound gate mirrors this one.\n Reflect.set(gate, 'abilityCallbacks', this.abilityCallbacks)\n Reflect.set(gate, 'policies', this.policies)\n Reflect.set(gate, 'beforeCallbacks', this.beforeCallbacks)\n Reflect.set(gate, 'afterCallbacks', this.afterCallbacks)\n return gate\n }\n\n /**\n * Resolve the raw {@link Response} for an ability - the `Gate::inspect` equivalent. Runs `before`\n * hooks (short-circuiting), then the ability or resolved policy method, then `after` hooks. A guest\n * with no allowing decision is denied. When no callback exists at all the result is a denial.\n */\n inspect(\n ability: string,\n user: User | null | undefined = this.defaultUser,\n ...args: unknown[]\n ): Response {\n // `before` hooks run for everyone (including guests) and may grant access outright.\n for (const hook of this.beforeCallbacks) {\n const result = hook(user, ability, args)\n if (result !== undefined) return toResponse(result)\n }\n\n const callback = this.resolve(ability, args)\n if (callback !== undefined) {\n // Guests are denied at defined abilities unless a `before` hook already allowed them above.\n if (user === null || user === undefined) return Response.deny()\n // `user` is narrowed to a real `User` here, matching the ability callback's contract.\n return toResponse(callback(user, ...args))\n }\n\n // Nothing defined decided - let `after` hooks supply a verdict.\n for (const hook of this.afterCallbacks) {\n const result = hook(user, ability, args)\n if (result !== undefined) return toResponse(result)\n }\n\n return Response.deny()\n }\n\n /** Whether the ability is allowed - the `Gate::allows` equivalent. */\n allows(ability: string, user?: User | null, ...args: unknown[]): boolean {\n return this.inspect(ability, user, ...args).allowed()\n }\n\n /** Whether the ability is denied - the `Gate::denies` equivalent. */\n denies(ability: string, user?: User | null, ...args: unknown[]): boolean {\n return this.inspect(ability, user, ...args).denied()\n }\n\n /** Alias of {@link Gate.allows} - the `Gate::check` equivalent. */\n check(ability: string, user?: User | null, ...args: unknown[]): boolean {\n return this.allows(ability, user, ...args)\n }\n\n /** Whether *any* of the abilities is allowed - the `Gate::any` equivalent. */\n any(abilities: string[], user?: User | null, ...args: unknown[]): boolean {\n return abilities.some((ability) => this.allows(ability, user, ...args))\n }\n\n /** Whether *none* of the abilities is allowed - the `Gate::none` equivalent. */\n none(abilities: string[], user?: User | null, ...args: unknown[]): boolean {\n return !this.any(abilities, user, ...args)\n }\n\n /**\n * Assert the ability and return its allowing {@link Response} - the `Gate::authorize` equivalent.\n *\n * @throws {AuthorizationError} when the ability is denied, carrying the denying response.\n */\n authorize(ability: string, user?: User | null, ...args: unknown[]): Response {\n return this.inspect(ability, user, ...args).authorize()\n }\n\n /**\n * Authorize when an ad-hoc condition holds - the `Gate::allowIf` equivalent. `condition` is a\n * boolean, a {@link Response}, or a callback receiving the gate's default user. Returns the\n * allowing {@link Response}; a falsy/denying condition throws an {@link AuthorizationError}\n * carrying `message`/`code`.\n */\n allowIf(condition: GateCondition<User>, message?: string, code?: string | number): Response {\n return this.authorizeOnDemand(condition, message, code, true)\n }\n\n /**\n * Deny when an ad-hoc condition holds - the `Gate::denyIf` equivalent. The inverse of\n * {@link Gate.allowIf}: a truthy condition throws, a falsy one authorizes.\n */\n denyIf(condition: GateCondition<User>, message?: string, code?: string | number): Response {\n return this.authorizeOnDemand(condition, message, code, false)\n }\n\n /** Evaluate an ad-hoc condition and authorize it - the conventional `authorizeOnDemand`. */\n private authorizeOnDemand(\n condition: GateCondition<User>,\n message: string | undefined,\n code: string | number | undefined,\n allowWhenResponseIs: boolean,\n ): Response {\n const result = typeof condition === 'function' ? condition(this.defaultUser) : condition\n const response =\n result instanceof Response\n ? result\n : result === allowWhenResponseIs\n ? Response.allow(message, code)\n : Response.deny(message, code)\n return response.authorize()\n }\n\n /**\n * Resolve the callback for an ability: a directly defined one wins, otherwise look for a policy\n * keyed by the first argument (a string tag or the resource's constructor) exposing the ability.\n */\n private resolve(ability: string, args: unknown[]): AbilityCallback<User> | undefined {\n const direct = this.abilityCallbacks.get(ability)\n if (direct !== undefined) return direct\n\n const resource = args[0]\n const policy = this.getPolicyFor(resource)\n if (policy === undefined) return undefined\n\n const method = policy[ability]\n if (typeof method !== 'function') return undefined\n\n // Bind so the policy method keeps its `this`; the resource stays the first arg to the method.\n return method.bind(policy)\n }\n\n /**\n * Find the policy registered for a model - the `Gate::getPolicyFor` equivalent. Resolves a string\n * tag, a class constructor, or an instance (by its constructor) to its policy, or `undefined` when\n * none is registered.\n */\n getPolicyFor(model: unknown): Policy<User> | undefined {\n if (typeof model === 'string') {\n return this.policies.get(model)\n }\n if (typeof model === 'function') {\n return this.policies.get(model as PolicyKey)\n }\n if (model !== null && typeof model === 'object') {\n const ctor = (model as { constructor?: PolicyKey }).constructor\n if (ctor !== undefined) return this.policies.get(ctor)\n }\n return undefined\n }\n}\n","/**\n * @plinthjs/authorization.\n *\n * A {@link Gate} that registers named abilities and resource {@link Policy} objects, then answers\n * authorization questions: `allows`/`denies`/`check` booleans, `inspect` for the raw {@link Response},\n * `any`/`none` across several abilities, and `authorize` which throws {@link AuthorizationError} on\n * denial. `resource` registers the standard `viewAny`/`view`/`create`/`update`/`delete` abilities for\n * a policy, `getPolicyFor` looks a policy up by model, `has`/`abilities` report what is defined,\n * `allowIf`/`denyIf` authorize ad-hoc conditions, `before`/`after` hooks short-circuit or backfill\n * decisions, `forUser` binds a default user, and guests (`null`/`undefined`) are denied unless a\n * `before` hook allows them. {@link Response} carries an allow/deny verdict plus an optional message,\n * code, and (via `denyWithStatus`/`denyAsNotFound`) an HTTP status for the denial, and its\n * `authorize` throws when denied. {@link AuthorizationError} carries a structural `status` (the\n * response's, defaulting to `403`) so `@plinthjs/http`'s handler renders it correctly.\n */\n\n/** The Plinth version this build of `authorization` ships with. */\nexport const VERSION = '0.1.0'\n\nexport { AuthorizationError } from './authorization-error'\nexport {\n type AbilityCallback,\n type AbilityResult,\n type AfterCallback,\n type BeforeCallback,\n Gate,\n type GateCondition,\n type Policy,\n} from './gate'\nexport { Response } from './response'\n"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -27,42 +27,42 @@ declare class Response {
|
|
|
27
27
|
*/
|
|
28
28
|
private constructor();
|
|
29
29
|
/**
|
|
30
|
-
* Build an allowing response
|
|
30
|
+
* Build an allowing response - the `Response::allow` equivalent. The optional `message` and
|
|
31
31
|
* `code` are preserved so callers can surface a reason even on success.
|
|
32
32
|
*/
|
|
33
33
|
static allow(message?: string, code?: string | number): Response;
|
|
34
34
|
/**
|
|
35
|
-
* Build a denying response
|
|
35
|
+
* Build a denying response - the `Response::deny` equivalent. The optional `message` and `code`
|
|
36
36
|
* describe why the action was refused.
|
|
37
37
|
*/
|
|
38
38
|
static deny(message?: string, code?: string | number): Response;
|
|
39
39
|
/**
|
|
40
|
-
* Build a denying response that should render with the given HTTP status
|
|
40
|
+
* Build a denying response that should render with the given HTTP status - the
|
|
41
41
|
* `Response::denyWithStatus` equivalent. The status is carried onto the
|
|
42
42
|
* {@link AuthorizationError} thrown by {@link Response.authorize}, so the HTTP exception handler
|
|
43
43
|
* renders e.g. a `404` instead of the default `403`.
|
|
44
44
|
*/
|
|
45
45
|
static denyWithStatus(status: number, message?: string, code?: string | number): Response;
|
|
46
46
|
/**
|
|
47
|
-
* Build a denying response that renders as a `404 Not Found`
|
|
47
|
+
* Build a denying response that renders as a `404 Not Found` - the `Response::denyAsNotFound`
|
|
48
48
|
* equivalent, used to hide a resource's existence from unauthorized users.
|
|
49
49
|
*/
|
|
50
50
|
static denyAsNotFound(message?: string, code?: string | number): Response;
|
|
51
|
-
/** Whether the decision allows the action
|
|
51
|
+
/** Whether the decision allows the action - the `Response::allowed` equivalent. */
|
|
52
52
|
allowed(): boolean;
|
|
53
|
-
/** Whether the decision denies the action
|
|
53
|
+
/** Whether the decision denies the action - the `Response::denied` equivalent. */
|
|
54
54
|
denied(): boolean;
|
|
55
|
-
/** The attached message, or `null` when none was given
|
|
55
|
+
/** The attached message, or `null` when none was given - the `Response::message` equivalent. */
|
|
56
56
|
message(): string | null;
|
|
57
|
-
/** The attached error code, or `null` when none was given
|
|
57
|
+
/** The attached error code, or `null` when none was given - the `Response::code` equivalent. */
|
|
58
58
|
code(): string | number | null;
|
|
59
59
|
/**
|
|
60
60
|
* The HTTP status a denial should render as, or `null` when none was set (denials default to
|
|
61
|
-
* `403` downstream)
|
|
61
|
+
* `403` downstream) - the `Response::status` equivalent.
|
|
62
62
|
*/
|
|
63
63
|
status(): number | null;
|
|
64
64
|
/**
|
|
65
|
-
* Assert this response allows the action
|
|
65
|
+
* Assert this response allows the action - the `Response::authorize` equivalent. Returns the
|
|
66
66
|
* response (for chaining) when allowed; otherwise throws so a denial bubbles up to the caller.
|
|
67
67
|
*
|
|
68
68
|
* @throws {AuthorizationError} when {@link Response.denied}, carrying this response (and its
|
|
@@ -75,7 +75,7 @@ declare class Response {
|
|
|
75
75
|
* The authorization failure.
|
|
76
76
|
* Thrown by {@link Gate.authorize}/{@link Response.authorize} when an ability is denied. It carries a
|
|
77
77
|
* structural `status` (read by `@plinthjs/http`'s exception handler so the response renders with the
|
|
78
|
-
* right code
|
|
78
|
+
* right code - `403` by default, or whatever the denying {@link Response} set via `denyWithStatus`/
|
|
79
79
|
* `denyAsNotFound`) alongside the response and its error code, so callers can inspect why.
|
|
80
80
|
*/
|
|
81
81
|
|
|
@@ -86,7 +86,7 @@ declare class Response {
|
|
|
86
86
|
* the response's own (e.g. `404` from `denyAsNotFound`), falling back to the `403`.
|
|
87
87
|
*/
|
|
88
88
|
declare class AuthorizationError extends Error {
|
|
89
|
-
/** The HTTP status this renders as
|
|
89
|
+
/** The HTTP status this renders as - the denying response's status, or the default `403`. */
|
|
90
90
|
readonly status: number;
|
|
91
91
|
/** The error code attached to the denying {@link Response}, when any. */
|
|
92
92
|
readonly code: string | number | null;
|
|
@@ -112,33 +112,33 @@ declare class AuthorizationError extends Error {
|
|
|
112
112
|
|
|
113
113
|
/**
|
|
114
114
|
* The result an ability/hook callback may return. A bare boolean is normalized into a
|
|
115
|
-
* {@link Response}; `undefined` from a hook means "no opinion
|
|
115
|
+
* {@link Response}; `undefined` from a hook means "no opinion - keep resolving".
|
|
116
116
|
*/
|
|
117
117
|
type AbilityResult = boolean | Response;
|
|
118
118
|
/**
|
|
119
|
-
* An ability callback
|
|
119
|
+
* An ability callback - the closure passed to `Gate::define`. Receives the authenticated user
|
|
120
120
|
* followed by the check's extra arguments and returns a boolean or {@link Response}. The gate denies
|
|
121
121
|
* guests before this runs, so `user` is always a real user here. The extra args are typed loosely so
|
|
122
122
|
* callbacks may declare their own concrete parameter types (e.g. `(user, post: Post) => ...`).
|
|
123
123
|
*/
|
|
124
124
|
type AbilityCallback<User> = (user: User, ...args: any[]) => AbilityResult;
|
|
125
125
|
/**
|
|
126
|
-
* A `before` hook
|
|
126
|
+
* A `before` hook - the `Gate::before` equivalent. Runs ahead of every check; returning a boolean
|
|
127
127
|
* or {@link Response} short-circuits the decision, while `undefined` defers to the ability/policy.
|
|
128
128
|
*/
|
|
129
129
|
type BeforeCallback<User> = (user: User, ability: string, args: unknown[]) => AbilityResult | undefined;
|
|
130
130
|
/**
|
|
131
|
-
* An `after` hook
|
|
131
|
+
* An `after` hook - the `Gate::after` equivalent. Runs only when no `before` hook or ability/policy
|
|
132
132
|
* produced a decision; returning a boolean or {@link Response} supplies the verdict.
|
|
133
133
|
*/
|
|
134
134
|
type AfterCallback<User> = (user: User, ability: string, args: unknown[]) => AbilityResult | undefined;
|
|
135
135
|
/**
|
|
136
|
-
* The condition accepted by {@link Gate.allowIf}/{@link Gate.denyIf}
|
|
136
|
+
* The condition accepted by {@link Gate.allowIf}/{@link Gate.denyIf} - a boolean, a prebuilt
|
|
137
137
|
* {@link Response}, or a callback receiving the gate's default user (set via {@link Gate.forUser};
|
|
138
138
|
* `null`/`undefined` for guests) and returning either.
|
|
139
139
|
*/
|
|
140
140
|
type GateCondition<User> = AbilityResult | ((user: User | null | undefined) => AbilityResult);
|
|
141
|
-
/** A resource policy
|
|
141
|
+
/** A resource policy - a plain object (or class instance) whose methods are ability callbacks. */
|
|
142
142
|
type Policy<User> = Record<string, AbilityCallback<User>>;
|
|
143
143
|
/** A key used to look up a policy: either a string tag or a class constructor. */
|
|
144
144
|
type PolicyKey = string | (new (...args: never[]) => unknown);
|
|
@@ -156,29 +156,29 @@ declare class Gate<User = unknown> {
|
|
|
156
156
|
private readonly beforeCallbacks;
|
|
157
157
|
private readonly afterCallbacks;
|
|
158
158
|
/**
|
|
159
|
-
* @param defaultUser The user implicitly used when a check omits one
|
|
159
|
+
* @param defaultUser The user implicitly used when a check omits one - set by {@link Gate.forUser}.
|
|
160
160
|
*/
|
|
161
161
|
constructor(defaultUser?: User | null | undefined);
|
|
162
162
|
/**
|
|
163
|
-
* Define a named ability
|
|
163
|
+
* Define a named ability - the `Gate::define` equivalent. The callback receives the user and the
|
|
164
164
|
* check's extra arguments and returns a boolean or {@link Response}. Redefining replaces it.
|
|
165
165
|
*/
|
|
166
166
|
define(ability: string, callback: AbilityCallback<User>): this;
|
|
167
167
|
/**
|
|
168
168
|
* Whether every given ability has been defined (directly via {@link Gate.define} or
|
|
169
|
-
* {@link Gate.resource})
|
|
169
|
+
* {@link Gate.resource}) - the `Gate::has` equivalent. Policy methods are not consulted, matching
|
|
170
170
|
*/
|
|
171
171
|
has(ability: string | readonly string[]): boolean;
|
|
172
|
-
/** The names of every defined ability
|
|
172
|
+
/** The names of every defined ability - the `Gate::abilities` listing. */
|
|
173
173
|
abilities(): string[];
|
|
174
174
|
/**
|
|
175
|
-
* Register a policy for a resource key
|
|
175
|
+
* Register a policy for a resource key - the `Gate::policy` equivalent. `resourceKey` is either a
|
|
176
176
|
* class constructor or a string tag; when an ability is not defined directly, the gate resolves it
|
|
177
177
|
* to `policy[ability](user, resource, ...args)` using the matching policy.
|
|
178
178
|
*/
|
|
179
179
|
policy(resourceKey: PolicyKey, policy: Policy<User>): this;
|
|
180
180
|
/**
|
|
181
|
-
* Register the standard resource abilities for a policy
|
|
181
|
+
* Register the standard resource abilities for a policy - the `Gate::resource` equivalent. Defines
|
|
182
182
|
* `{name}.viewAny`, `{name}.view`, `{name}.create`, `{name}.update`, and `{name}.delete` (override
|
|
183
183
|
* the list via `abilities`), each dispatching to the matching method on `policy`. The policy's
|
|
184
184
|
* method receives the user and the check's extra arguments, e.g. `allows('posts.update', user, post)`
|
|
@@ -186,55 +186,55 @@ declare class Gate<User = unknown> {
|
|
|
186
186
|
*/
|
|
187
187
|
resource(name: string, policy: Policy<User>, abilities?: readonly string[]): this;
|
|
188
188
|
/**
|
|
189
|
-
* Register a `before` hook
|
|
189
|
+
* Register a `before` hook - the `Gate::before` equivalent. Hooks run in registration order ahead
|
|
190
190
|
* of every check; the first to return a boolean/{@link Response} decides, `undefined` defers.
|
|
191
191
|
*/
|
|
192
192
|
before(callback: BeforeCallback<User | null | undefined>): this;
|
|
193
193
|
/**
|
|
194
|
-
* Register an `after` hook
|
|
194
|
+
* Register an `after` hook - the `Gate::after` equivalent. Hooks run only when nothing else
|
|
195
195
|
* decided; the first to return a boolean/{@link Response} supplies the verdict.
|
|
196
196
|
*/
|
|
197
197
|
after(callback: AfterCallback<User | null | undefined>): this;
|
|
198
198
|
/**
|
|
199
|
-
* Return a gate bound to `user` as its default
|
|
199
|
+
* Return a gate bound to `user` as its default - the `Gate::forUser` equivalent. The returned gate
|
|
200
200
|
* shares this gate's abilities, policies, and hooks (by reference) so later registrations are seen.
|
|
201
201
|
*/
|
|
202
202
|
forUser(user: User | null | undefined): Gate<User>;
|
|
203
203
|
/**
|
|
204
|
-
* Resolve the raw {@link Response} for an ability
|
|
204
|
+
* Resolve the raw {@link Response} for an ability - the `Gate::inspect` equivalent. Runs `before`
|
|
205
205
|
* hooks (short-circuiting), then the ability or resolved policy method, then `after` hooks. A guest
|
|
206
206
|
* with no allowing decision is denied. When no callback exists at all the result is a denial.
|
|
207
207
|
*/
|
|
208
208
|
inspect(ability: string, user?: User | null | undefined, ...args: unknown[]): Response;
|
|
209
|
-
/** Whether the ability is allowed
|
|
209
|
+
/** Whether the ability is allowed - the `Gate::allows` equivalent. */
|
|
210
210
|
allows(ability: string, user?: User | null, ...args: unknown[]): boolean;
|
|
211
|
-
/** Whether the ability is denied
|
|
211
|
+
/** Whether the ability is denied - the `Gate::denies` equivalent. */
|
|
212
212
|
denies(ability: string, user?: User | null, ...args: unknown[]): boolean;
|
|
213
|
-
/** Alias of {@link Gate.allows}
|
|
213
|
+
/** Alias of {@link Gate.allows} - the `Gate::check` equivalent. */
|
|
214
214
|
check(ability: string, user?: User | null, ...args: unknown[]): boolean;
|
|
215
|
-
/** Whether *any* of the abilities is allowed
|
|
215
|
+
/** Whether *any* of the abilities is allowed - the `Gate::any` equivalent. */
|
|
216
216
|
any(abilities: string[], user?: User | null, ...args: unknown[]): boolean;
|
|
217
|
-
/** Whether *none* of the abilities is allowed
|
|
217
|
+
/** Whether *none* of the abilities is allowed - the `Gate::none` equivalent. */
|
|
218
218
|
none(abilities: string[], user?: User | null, ...args: unknown[]): boolean;
|
|
219
219
|
/**
|
|
220
|
-
* Assert the ability and return its allowing {@link Response}
|
|
220
|
+
* Assert the ability and return its allowing {@link Response} - the `Gate::authorize` equivalent.
|
|
221
221
|
*
|
|
222
222
|
* @throws {AuthorizationError} when the ability is denied, carrying the denying response.
|
|
223
223
|
*/
|
|
224
224
|
authorize(ability: string, user?: User | null, ...args: unknown[]): Response;
|
|
225
225
|
/**
|
|
226
|
-
* Authorize when an ad-hoc condition holds
|
|
226
|
+
* Authorize when an ad-hoc condition holds - the `Gate::allowIf` equivalent. `condition` is a
|
|
227
227
|
* boolean, a {@link Response}, or a callback receiving the gate's default user. Returns the
|
|
228
228
|
* allowing {@link Response}; a falsy/denying condition throws an {@link AuthorizationError}
|
|
229
229
|
* carrying `message`/`code`.
|
|
230
230
|
*/
|
|
231
231
|
allowIf(condition: GateCondition<User>, message?: string, code?: string | number): Response;
|
|
232
232
|
/**
|
|
233
|
-
* Deny when an ad-hoc condition holds
|
|
233
|
+
* Deny when an ad-hoc condition holds - the `Gate::denyIf` equivalent. The inverse of
|
|
234
234
|
* {@link Gate.allowIf}: a truthy condition throws, a falsy one authorizes.
|
|
235
235
|
*/
|
|
236
236
|
denyIf(condition: GateCondition<User>, message?: string, code?: string | number): Response;
|
|
237
|
-
/** Evaluate an ad-hoc condition and authorize it
|
|
237
|
+
/** Evaluate an ad-hoc condition and authorize it - the conventional `authorizeOnDemand`. */
|
|
238
238
|
private authorizeOnDemand;
|
|
239
239
|
/**
|
|
240
240
|
* Resolve the callback for an ability: a directly defined one wins, otherwise look for a policy
|
|
@@ -242,7 +242,7 @@ declare class Gate<User = unknown> {
|
|
|
242
242
|
*/
|
|
243
243
|
private resolve;
|
|
244
244
|
/**
|
|
245
|
-
* Find the policy registered for a model
|
|
245
|
+
* Find the policy registered for a model - the `Gate::getPolicyFor` equivalent. Resolves a string
|
|
246
246
|
* tag, a class constructor, or an instance (by its constructor) to its policy, or `undefined` when
|
|
247
247
|
* none is registered.
|
|
248
248
|
*/
|
package/dist/index.d.ts
CHANGED
|
@@ -27,42 +27,42 @@ declare class Response {
|
|
|
27
27
|
*/
|
|
28
28
|
private constructor();
|
|
29
29
|
/**
|
|
30
|
-
* Build an allowing response
|
|
30
|
+
* Build an allowing response - the `Response::allow` equivalent. The optional `message` and
|
|
31
31
|
* `code` are preserved so callers can surface a reason even on success.
|
|
32
32
|
*/
|
|
33
33
|
static allow(message?: string, code?: string | number): Response;
|
|
34
34
|
/**
|
|
35
|
-
* Build a denying response
|
|
35
|
+
* Build a denying response - the `Response::deny` equivalent. The optional `message` and `code`
|
|
36
36
|
* describe why the action was refused.
|
|
37
37
|
*/
|
|
38
38
|
static deny(message?: string, code?: string | number): Response;
|
|
39
39
|
/**
|
|
40
|
-
* Build a denying response that should render with the given HTTP status
|
|
40
|
+
* Build a denying response that should render with the given HTTP status - the
|
|
41
41
|
* `Response::denyWithStatus` equivalent. The status is carried onto the
|
|
42
42
|
* {@link AuthorizationError} thrown by {@link Response.authorize}, so the HTTP exception handler
|
|
43
43
|
* renders e.g. a `404` instead of the default `403`.
|
|
44
44
|
*/
|
|
45
45
|
static denyWithStatus(status: number, message?: string, code?: string | number): Response;
|
|
46
46
|
/**
|
|
47
|
-
* Build a denying response that renders as a `404 Not Found`
|
|
47
|
+
* Build a denying response that renders as a `404 Not Found` - the `Response::denyAsNotFound`
|
|
48
48
|
* equivalent, used to hide a resource's existence from unauthorized users.
|
|
49
49
|
*/
|
|
50
50
|
static denyAsNotFound(message?: string, code?: string | number): Response;
|
|
51
|
-
/** Whether the decision allows the action
|
|
51
|
+
/** Whether the decision allows the action - the `Response::allowed` equivalent. */
|
|
52
52
|
allowed(): boolean;
|
|
53
|
-
/** Whether the decision denies the action
|
|
53
|
+
/** Whether the decision denies the action - the `Response::denied` equivalent. */
|
|
54
54
|
denied(): boolean;
|
|
55
|
-
/** The attached message, or `null` when none was given
|
|
55
|
+
/** The attached message, or `null` when none was given - the `Response::message` equivalent. */
|
|
56
56
|
message(): string | null;
|
|
57
|
-
/** The attached error code, or `null` when none was given
|
|
57
|
+
/** The attached error code, or `null` when none was given - the `Response::code` equivalent. */
|
|
58
58
|
code(): string | number | null;
|
|
59
59
|
/**
|
|
60
60
|
* The HTTP status a denial should render as, or `null` when none was set (denials default to
|
|
61
|
-
* `403` downstream)
|
|
61
|
+
* `403` downstream) - the `Response::status` equivalent.
|
|
62
62
|
*/
|
|
63
63
|
status(): number | null;
|
|
64
64
|
/**
|
|
65
|
-
* Assert this response allows the action
|
|
65
|
+
* Assert this response allows the action - the `Response::authorize` equivalent. Returns the
|
|
66
66
|
* response (for chaining) when allowed; otherwise throws so a denial bubbles up to the caller.
|
|
67
67
|
*
|
|
68
68
|
* @throws {AuthorizationError} when {@link Response.denied}, carrying this response (and its
|
|
@@ -75,7 +75,7 @@ declare class Response {
|
|
|
75
75
|
* The authorization failure.
|
|
76
76
|
* Thrown by {@link Gate.authorize}/{@link Response.authorize} when an ability is denied. It carries a
|
|
77
77
|
* structural `status` (read by `@plinthjs/http`'s exception handler so the response renders with the
|
|
78
|
-
* right code
|
|
78
|
+
* right code - `403` by default, or whatever the denying {@link Response} set via `denyWithStatus`/
|
|
79
79
|
* `denyAsNotFound`) alongside the response and its error code, so callers can inspect why.
|
|
80
80
|
*/
|
|
81
81
|
|
|
@@ -86,7 +86,7 @@ declare class Response {
|
|
|
86
86
|
* the response's own (e.g. `404` from `denyAsNotFound`), falling back to the `403`.
|
|
87
87
|
*/
|
|
88
88
|
declare class AuthorizationError extends Error {
|
|
89
|
-
/** The HTTP status this renders as
|
|
89
|
+
/** The HTTP status this renders as - the denying response's status, or the default `403`. */
|
|
90
90
|
readonly status: number;
|
|
91
91
|
/** The error code attached to the denying {@link Response}, when any. */
|
|
92
92
|
readonly code: string | number | null;
|
|
@@ -112,33 +112,33 @@ declare class AuthorizationError extends Error {
|
|
|
112
112
|
|
|
113
113
|
/**
|
|
114
114
|
* The result an ability/hook callback may return. A bare boolean is normalized into a
|
|
115
|
-
* {@link Response}; `undefined` from a hook means "no opinion
|
|
115
|
+
* {@link Response}; `undefined` from a hook means "no opinion - keep resolving".
|
|
116
116
|
*/
|
|
117
117
|
type AbilityResult = boolean | Response;
|
|
118
118
|
/**
|
|
119
|
-
* An ability callback
|
|
119
|
+
* An ability callback - the closure passed to `Gate::define`. Receives the authenticated user
|
|
120
120
|
* followed by the check's extra arguments and returns a boolean or {@link Response}. The gate denies
|
|
121
121
|
* guests before this runs, so `user` is always a real user here. The extra args are typed loosely so
|
|
122
122
|
* callbacks may declare their own concrete parameter types (e.g. `(user, post: Post) => ...`).
|
|
123
123
|
*/
|
|
124
124
|
type AbilityCallback<User> = (user: User, ...args: any[]) => AbilityResult;
|
|
125
125
|
/**
|
|
126
|
-
* A `before` hook
|
|
126
|
+
* A `before` hook - the `Gate::before` equivalent. Runs ahead of every check; returning a boolean
|
|
127
127
|
* or {@link Response} short-circuits the decision, while `undefined` defers to the ability/policy.
|
|
128
128
|
*/
|
|
129
129
|
type BeforeCallback<User> = (user: User, ability: string, args: unknown[]) => AbilityResult | undefined;
|
|
130
130
|
/**
|
|
131
|
-
* An `after` hook
|
|
131
|
+
* An `after` hook - the `Gate::after` equivalent. Runs only when no `before` hook or ability/policy
|
|
132
132
|
* produced a decision; returning a boolean or {@link Response} supplies the verdict.
|
|
133
133
|
*/
|
|
134
134
|
type AfterCallback<User> = (user: User, ability: string, args: unknown[]) => AbilityResult | undefined;
|
|
135
135
|
/**
|
|
136
|
-
* The condition accepted by {@link Gate.allowIf}/{@link Gate.denyIf}
|
|
136
|
+
* The condition accepted by {@link Gate.allowIf}/{@link Gate.denyIf} - a boolean, a prebuilt
|
|
137
137
|
* {@link Response}, or a callback receiving the gate's default user (set via {@link Gate.forUser};
|
|
138
138
|
* `null`/`undefined` for guests) and returning either.
|
|
139
139
|
*/
|
|
140
140
|
type GateCondition<User> = AbilityResult | ((user: User | null | undefined) => AbilityResult);
|
|
141
|
-
/** A resource policy
|
|
141
|
+
/** A resource policy - a plain object (or class instance) whose methods are ability callbacks. */
|
|
142
142
|
type Policy<User> = Record<string, AbilityCallback<User>>;
|
|
143
143
|
/** A key used to look up a policy: either a string tag or a class constructor. */
|
|
144
144
|
type PolicyKey = string | (new (...args: never[]) => unknown);
|
|
@@ -156,29 +156,29 @@ declare class Gate<User = unknown> {
|
|
|
156
156
|
private readonly beforeCallbacks;
|
|
157
157
|
private readonly afterCallbacks;
|
|
158
158
|
/**
|
|
159
|
-
* @param defaultUser The user implicitly used when a check omits one
|
|
159
|
+
* @param defaultUser The user implicitly used when a check omits one - set by {@link Gate.forUser}.
|
|
160
160
|
*/
|
|
161
161
|
constructor(defaultUser?: User | null | undefined);
|
|
162
162
|
/**
|
|
163
|
-
* Define a named ability
|
|
163
|
+
* Define a named ability - the `Gate::define` equivalent. The callback receives the user and the
|
|
164
164
|
* check's extra arguments and returns a boolean or {@link Response}. Redefining replaces it.
|
|
165
165
|
*/
|
|
166
166
|
define(ability: string, callback: AbilityCallback<User>): this;
|
|
167
167
|
/**
|
|
168
168
|
* Whether every given ability has been defined (directly via {@link Gate.define} or
|
|
169
|
-
* {@link Gate.resource})
|
|
169
|
+
* {@link Gate.resource}) - the `Gate::has` equivalent. Policy methods are not consulted, matching
|
|
170
170
|
*/
|
|
171
171
|
has(ability: string | readonly string[]): boolean;
|
|
172
|
-
/** The names of every defined ability
|
|
172
|
+
/** The names of every defined ability - the `Gate::abilities` listing. */
|
|
173
173
|
abilities(): string[];
|
|
174
174
|
/**
|
|
175
|
-
* Register a policy for a resource key
|
|
175
|
+
* Register a policy for a resource key - the `Gate::policy` equivalent. `resourceKey` is either a
|
|
176
176
|
* class constructor or a string tag; when an ability is not defined directly, the gate resolves it
|
|
177
177
|
* to `policy[ability](user, resource, ...args)` using the matching policy.
|
|
178
178
|
*/
|
|
179
179
|
policy(resourceKey: PolicyKey, policy: Policy<User>): this;
|
|
180
180
|
/**
|
|
181
|
-
* Register the standard resource abilities for a policy
|
|
181
|
+
* Register the standard resource abilities for a policy - the `Gate::resource` equivalent. Defines
|
|
182
182
|
* `{name}.viewAny`, `{name}.view`, `{name}.create`, `{name}.update`, and `{name}.delete` (override
|
|
183
183
|
* the list via `abilities`), each dispatching to the matching method on `policy`. The policy's
|
|
184
184
|
* method receives the user and the check's extra arguments, e.g. `allows('posts.update', user, post)`
|
|
@@ -186,55 +186,55 @@ declare class Gate<User = unknown> {
|
|
|
186
186
|
*/
|
|
187
187
|
resource(name: string, policy: Policy<User>, abilities?: readonly string[]): this;
|
|
188
188
|
/**
|
|
189
|
-
* Register a `before` hook
|
|
189
|
+
* Register a `before` hook - the `Gate::before` equivalent. Hooks run in registration order ahead
|
|
190
190
|
* of every check; the first to return a boolean/{@link Response} decides, `undefined` defers.
|
|
191
191
|
*/
|
|
192
192
|
before(callback: BeforeCallback<User | null | undefined>): this;
|
|
193
193
|
/**
|
|
194
|
-
* Register an `after` hook
|
|
194
|
+
* Register an `after` hook - the `Gate::after` equivalent. Hooks run only when nothing else
|
|
195
195
|
* decided; the first to return a boolean/{@link Response} supplies the verdict.
|
|
196
196
|
*/
|
|
197
197
|
after(callback: AfterCallback<User | null | undefined>): this;
|
|
198
198
|
/**
|
|
199
|
-
* Return a gate bound to `user` as its default
|
|
199
|
+
* Return a gate bound to `user` as its default - the `Gate::forUser` equivalent. The returned gate
|
|
200
200
|
* shares this gate's abilities, policies, and hooks (by reference) so later registrations are seen.
|
|
201
201
|
*/
|
|
202
202
|
forUser(user: User | null | undefined): Gate<User>;
|
|
203
203
|
/**
|
|
204
|
-
* Resolve the raw {@link Response} for an ability
|
|
204
|
+
* Resolve the raw {@link Response} for an ability - the `Gate::inspect` equivalent. Runs `before`
|
|
205
205
|
* hooks (short-circuiting), then the ability or resolved policy method, then `after` hooks. A guest
|
|
206
206
|
* with no allowing decision is denied. When no callback exists at all the result is a denial.
|
|
207
207
|
*/
|
|
208
208
|
inspect(ability: string, user?: User | null | undefined, ...args: unknown[]): Response;
|
|
209
|
-
/** Whether the ability is allowed
|
|
209
|
+
/** Whether the ability is allowed - the `Gate::allows` equivalent. */
|
|
210
210
|
allows(ability: string, user?: User | null, ...args: unknown[]): boolean;
|
|
211
|
-
/** Whether the ability is denied
|
|
211
|
+
/** Whether the ability is denied - the `Gate::denies` equivalent. */
|
|
212
212
|
denies(ability: string, user?: User | null, ...args: unknown[]): boolean;
|
|
213
|
-
/** Alias of {@link Gate.allows}
|
|
213
|
+
/** Alias of {@link Gate.allows} - the `Gate::check` equivalent. */
|
|
214
214
|
check(ability: string, user?: User | null, ...args: unknown[]): boolean;
|
|
215
|
-
/** Whether *any* of the abilities is allowed
|
|
215
|
+
/** Whether *any* of the abilities is allowed - the `Gate::any` equivalent. */
|
|
216
216
|
any(abilities: string[], user?: User | null, ...args: unknown[]): boolean;
|
|
217
|
-
/** Whether *none* of the abilities is allowed
|
|
217
|
+
/** Whether *none* of the abilities is allowed - the `Gate::none` equivalent. */
|
|
218
218
|
none(abilities: string[], user?: User | null, ...args: unknown[]): boolean;
|
|
219
219
|
/**
|
|
220
|
-
* Assert the ability and return its allowing {@link Response}
|
|
220
|
+
* Assert the ability and return its allowing {@link Response} - the `Gate::authorize` equivalent.
|
|
221
221
|
*
|
|
222
222
|
* @throws {AuthorizationError} when the ability is denied, carrying the denying response.
|
|
223
223
|
*/
|
|
224
224
|
authorize(ability: string, user?: User | null, ...args: unknown[]): Response;
|
|
225
225
|
/**
|
|
226
|
-
* Authorize when an ad-hoc condition holds
|
|
226
|
+
* Authorize when an ad-hoc condition holds - the `Gate::allowIf` equivalent. `condition` is a
|
|
227
227
|
* boolean, a {@link Response}, or a callback receiving the gate's default user. Returns the
|
|
228
228
|
* allowing {@link Response}; a falsy/denying condition throws an {@link AuthorizationError}
|
|
229
229
|
* carrying `message`/`code`.
|
|
230
230
|
*/
|
|
231
231
|
allowIf(condition: GateCondition<User>, message?: string, code?: string | number): Response;
|
|
232
232
|
/**
|
|
233
|
-
* Deny when an ad-hoc condition holds
|
|
233
|
+
* Deny when an ad-hoc condition holds - the `Gate::denyIf` equivalent. The inverse of
|
|
234
234
|
* {@link Gate.allowIf}: a truthy condition throws, a falsy one authorizes.
|
|
235
235
|
*/
|
|
236
236
|
denyIf(condition: GateCondition<User>, message?: string, code?: string | number): Response;
|
|
237
|
-
/** Evaluate an ad-hoc condition and authorize it
|
|
237
|
+
/** Evaluate an ad-hoc condition and authorize it - the conventional `authorizeOnDemand`. */
|
|
238
238
|
private authorizeOnDemand;
|
|
239
239
|
/**
|
|
240
240
|
* Resolve the callback for an ability: a directly defined one wins, otherwise look for a policy
|
|
@@ -242,7 +242,7 @@ declare class Gate<User = unknown> {
|
|
|
242
242
|
*/
|
|
243
243
|
private resolve;
|
|
244
244
|
/**
|
|
245
|
-
* Find the policy registered for a model
|
|
245
|
+
* Find the policy registered for a model - the `Gate::getPolicyFor` equivalent. Resolves a string
|
|
246
246
|
* tag, a class constructor, or an instance (by its constructor) to its policy, or `undefined` when
|
|
247
247
|
* none is registered.
|
|
248
248
|
*/
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// src/authorization-error.ts
|
|
2
2
|
var AuthorizationError = class extends Error {
|
|
3
|
-
/** The HTTP status this renders as
|
|
3
|
+
/** The HTTP status this renders as - the denying response's status, or the default `403`. */
|
|
4
4
|
status;
|
|
5
5
|
/** The error code attached to the denying {@link Response}, when any. */
|
|
6
6
|
code;
|
|
@@ -38,21 +38,21 @@ var Response = class _Response {
|
|
|
38
38
|
errCode;
|
|
39
39
|
statusCode;
|
|
40
40
|
/**
|
|
41
|
-
* Build an allowing response
|
|
41
|
+
* Build an allowing response - the `Response::allow` equivalent. The optional `message` and
|
|
42
42
|
* `code` are preserved so callers can surface a reason even on success.
|
|
43
43
|
*/
|
|
44
44
|
static allow(message, code) {
|
|
45
45
|
return new _Response(true, message ?? null, code ?? null);
|
|
46
46
|
}
|
|
47
47
|
/**
|
|
48
|
-
* Build a denying response
|
|
48
|
+
* Build a denying response - the `Response::deny` equivalent. The optional `message` and `code`
|
|
49
49
|
* describe why the action was refused.
|
|
50
50
|
*/
|
|
51
51
|
static deny(message, code) {
|
|
52
52
|
return new _Response(false, message ?? null, code ?? null);
|
|
53
53
|
}
|
|
54
54
|
/**
|
|
55
|
-
* Build a denying response that should render with the given HTTP status
|
|
55
|
+
* Build a denying response that should render with the given HTTP status - the
|
|
56
56
|
* `Response::denyWithStatus` equivalent. The status is carried onto the
|
|
57
57
|
* {@link AuthorizationError} thrown by {@link Response.authorize}, so the HTTP exception handler
|
|
58
58
|
* renders e.g. a `404` instead of the default `403`.
|
|
@@ -61,37 +61,37 @@ var Response = class _Response {
|
|
|
61
61
|
return new _Response(false, message ?? null, code ?? null, status);
|
|
62
62
|
}
|
|
63
63
|
/**
|
|
64
|
-
* Build a denying response that renders as a `404 Not Found`
|
|
64
|
+
* Build a denying response that renders as a `404 Not Found` - the `Response::denyAsNotFound`
|
|
65
65
|
* equivalent, used to hide a resource's existence from unauthorized users.
|
|
66
66
|
*/
|
|
67
67
|
static denyAsNotFound(message, code) {
|
|
68
68
|
return _Response.denyWithStatus(404, message, code);
|
|
69
69
|
}
|
|
70
|
-
/** Whether the decision allows the action
|
|
70
|
+
/** Whether the decision allows the action - the `Response::allowed` equivalent. */
|
|
71
71
|
allowed() {
|
|
72
72
|
return this.granted;
|
|
73
73
|
}
|
|
74
|
-
/** Whether the decision denies the action
|
|
74
|
+
/** Whether the decision denies the action - the `Response::denied` equivalent. */
|
|
75
75
|
denied() {
|
|
76
76
|
return !this.granted;
|
|
77
77
|
}
|
|
78
|
-
/** The attached message, or `null` when none was given
|
|
78
|
+
/** The attached message, or `null` when none was given - the `Response::message` equivalent. */
|
|
79
79
|
message() {
|
|
80
80
|
return this.msg;
|
|
81
81
|
}
|
|
82
|
-
/** The attached error code, or `null` when none was given
|
|
82
|
+
/** The attached error code, or `null` when none was given - the `Response::code` equivalent. */
|
|
83
83
|
code() {
|
|
84
84
|
return this.errCode;
|
|
85
85
|
}
|
|
86
86
|
/**
|
|
87
87
|
* The HTTP status a denial should render as, or `null` when none was set (denials default to
|
|
88
|
-
* `403` downstream)
|
|
88
|
+
* `403` downstream) - the `Response::status` equivalent.
|
|
89
89
|
*/
|
|
90
90
|
status() {
|
|
91
91
|
return this.statusCode;
|
|
92
92
|
}
|
|
93
93
|
/**
|
|
94
|
-
* Assert this response allows the action
|
|
94
|
+
* Assert this response allows the action - the `Response::authorize` equivalent. Returns the
|
|
95
95
|
* response (for chaining) when allowed; otherwise throws so a denial bubbles up to the caller.
|
|
96
96
|
*
|
|
97
97
|
* @throws {AuthorizationError} when {@link Response.denied}, carrying this response (and its
|
|
@@ -110,7 +110,7 @@ function toResponse(result) {
|
|
|
110
110
|
var RESOURCE_ABILITIES = ["viewAny", "view", "create", "update", "delete"];
|
|
111
111
|
var Gate = class _Gate {
|
|
112
112
|
/**
|
|
113
|
-
* @param defaultUser The user implicitly used when a check omits one
|
|
113
|
+
* @param defaultUser The user implicitly used when a check omits one - set by {@link Gate.forUser}.
|
|
114
114
|
*/
|
|
115
115
|
constructor(defaultUser) {
|
|
116
116
|
this.defaultUser = defaultUser;
|
|
@@ -121,7 +121,7 @@ var Gate = class _Gate {
|
|
|
121
121
|
beforeCallbacks = [];
|
|
122
122
|
afterCallbacks = [];
|
|
123
123
|
/**
|
|
124
|
-
* Define a named ability
|
|
124
|
+
* Define a named ability - the `Gate::define` equivalent. The callback receives the user and the
|
|
125
125
|
* check's extra arguments and returns a boolean or {@link Response}. Redefining replaces it.
|
|
126
126
|
*/
|
|
127
127
|
define(ability, callback) {
|
|
@@ -130,18 +130,18 @@ var Gate = class _Gate {
|
|
|
130
130
|
}
|
|
131
131
|
/**
|
|
132
132
|
* Whether every given ability has been defined (directly via {@link Gate.define} or
|
|
133
|
-
* {@link Gate.resource})
|
|
133
|
+
* {@link Gate.resource}) - the `Gate::has` equivalent. Policy methods are not consulted, matching
|
|
134
134
|
*/
|
|
135
135
|
has(ability) {
|
|
136
136
|
const list = typeof ability === "string" ? [ability] : ability;
|
|
137
137
|
return list.every((name) => this.abilityCallbacks.has(name));
|
|
138
138
|
}
|
|
139
|
-
/** The names of every defined ability
|
|
139
|
+
/** The names of every defined ability - the `Gate::abilities` listing. */
|
|
140
140
|
abilities() {
|
|
141
141
|
return [...this.abilityCallbacks.keys()];
|
|
142
142
|
}
|
|
143
143
|
/**
|
|
144
|
-
* Register a policy for a resource key
|
|
144
|
+
* Register a policy for a resource key - the `Gate::policy` equivalent. `resourceKey` is either a
|
|
145
145
|
* class constructor or a string tag; when an ability is not defined directly, the gate resolves it
|
|
146
146
|
* to `policy[ability](user, resource, ...args)` using the matching policy.
|
|
147
147
|
*/
|
|
@@ -150,7 +150,7 @@ var Gate = class _Gate {
|
|
|
150
150
|
return this;
|
|
151
151
|
}
|
|
152
152
|
/**
|
|
153
|
-
* Register the standard resource abilities for a policy
|
|
153
|
+
* Register the standard resource abilities for a policy - the `Gate::resource` equivalent. Defines
|
|
154
154
|
* `{name}.viewAny`, `{name}.view`, `{name}.create`, `{name}.update`, and `{name}.delete` (override
|
|
155
155
|
* the list via `abilities`), each dispatching to the matching method on `policy`. The policy's
|
|
156
156
|
* method receives the user and the check's extra arguments, e.g. `allows('posts.update', user, post)`
|
|
@@ -165,7 +165,7 @@ var Gate = class _Gate {
|
|
|
165
165
|
return this;
|
|
166
166
|
}
|
|
167
167
|
/**
|
|
168
|
-
* Register a `before` hook
|
|
168
|
+
* Register a `before` hook - the `Gate::before` equivalent. Hooks run in registration order ahead
|
|
169
169
|
* of every check; the first to return a boolean/{@link Response} decides, `undefined` defers.
|
|
170
170
|
*/
|
|
171
171
|
before(callback) {
|
|
@@ -173,7 +173,7 @@ var Gate = class _Gate {
|
|
|
173
173
|
return this;
|
|
174
174
|
}
|
|
175
175
|
/**
|
|
176
|
-
* Register an `after` hook
|
|
176
|
+
* Register an `after` hook - the `Gate::after` equivalent. Hooks run only when nothing else
|
|
177
177
|
* decided; the first to return a boolean/{@link Response} supplies the verdict.
|
|
178
178
|
*/
|
|
179
179
|
after(callback) {
|
|
@@ -181,7 +181,7 @@ var Gate = class _Gate {
|
|
|
181
181
|
return this;
|
|
182
182
|
}
|
|
183
183
|
/**
|
|
184
|
-
* Return a gate bound to `user` as its default
|
|
184
|
+
* Return a gate bound to `user` as its default - the `Gate::forUser` equivalent. The returned gate
|
|
185
185
|
* shares this gate's abilities, policies, and hooks (by reference) so later registrations are seen.
|
|
186
186
|
*/
|
|
187
187
|
forUser(user) {
|
|
@@ -193,7 +193,7 @@ var Gate = class _Gate {
|
|
|
193
193
|
return gate;
|
|
194
194
|
}
|
|
195
195
|
/**
|
|
196
|
-
* Resolve the raw {@link Response} for an ability
|
|
196
|
+
* Resolve the raw {@link Response} for an ability - the `Gate::inspect` equivalent. Runs `before`
|
|
197
197
|
* hooks (short-circuiting), then the ability or resolved policy method, then `after` hooks. A guest
|
|
198
198
|
* with no allowing decision is denied. When no callback exists at all the result is a denial.
|
|
199
199
|
*/
|
|
@@ -213,28 +213,28 @@ var Gate = class _Gate {
|
|
|
213
213
|
}
|
|
214
214
|
return Response.deny();
|
|
215
215
|
}
|
|
216
|
-
/** Whether the ability is allowed
|
|
216
|
+
/** Whether the ability is allowed - the `Gate::allows` equivalent. */
|
|
217
217
|
allows(ability, user, ...args) {
|
|
218
218
|
return this.inspect(ability, user, ...args).allowed();
|
|
219
219
|
}
|
|
220
|
-
/** Whether the ability is denied
|
|
220
|
+
/** Whether the ability is denied - the `Gate::denies` equivalent. */
|
|
221
221
|
denies(ability, user, ...args) {
|
|
222
222
|
return this.inspect(ability, user, ...args).denied();
|
|
223
223
|
}
|
|
224
|
-
/** Alias of {@link Gate.allows}
|
|
224
|
+
/** Alias of {@link Gate.allows} - the `Gate::check` equivalent. */
|
|
225
225
|
check(ability, user, ...args) {
|
|
226
226
|
return this.allows(ability, user, ...args);
|
|
227
227
|
}
|
|
228
|
-
/** Whether *any* of the abilities is allowed
|
|
228
|
+
/** Whether *any* of the abilities is allowed - the `Gate::any` equivalent. */
|
|
229
229
|
any(abilities, user, ...args) {
|
|
230
230
|
return abilities.some((ability) => this.allows(ability, user, ...args));
|
|
231
231
|
}
|
|
232
|
-
/** Whether *none* of the abilities is allowed
|
|
232
|
+
/** Whether *none* of the abilities is allowed - the `Gate::none` equivalent. */
|
|
233
233
|
none(abilities, user, ...args) {
|
|
234
234
|
return !this.any(abilities, user, ...args);
|
|
235
235
|
}
|
|
236
236
|
/**
|
|
237
|
-
* Assert the ability and return its allowing {@link Response}
|
|
237
|
+
* Assert the ability and return its allowing {@link Response} - the `Gate::authorize` equivalent.
|
|
238
238
|
*
|
|
239
239
|
* @throws {AuthorizationError} when the ability is denied, carrying the denying response.
|
|
240
240
|
*/
|
|
@@ -242,7 +242,7 @@ var Gate = class _Gate {
|
|
|
242
242
|
return this.inspect(ability, user, ...args).authorize();
|
|
243
243
|
}
|
|
244
244
|
/**
|
|
245
|
-
* Authorize when an ad-hoc condition holds
|
|
245
|
+
* Authorize when an ad-hoc condition holds - the `Gate::allowIf` equivalent. `condition` is a
|
|
246
246
|
* boolean, a {@link Response}, or a callback receiving the gate's default user. Returns the
|
|
247
247
|
* allowing {@link Response}; a falsy/denying condition throws an {@link AuthorizationError}
|
|
248
248
|
* carrying `message`/`code`.
|
|
@@ -251,13 +251,13 @@ var Gate = class _Gate {
|
|
|
251
251
|
return this.authorizeOnDemand(condition, message, code, true);
|
|
252
252
|
}
|
|
253
253
|
/**
|
|
254
|
-
* Deny when an ad-hoc condition holds
|
|
254
|
+
* Deny when an ad-hoc condition holds - the `Gate::denyIf` equivalent. The inverse of
|
|
255
255
|
* {@link Gate.allowIf}: a truthy condition throws, a falsy one authorizes.
|
|
256
256
|
*/
|
|
257
257
|
denyIf(condition, message, code) {
|
|
258
258
|
return this.authorizeOnDemand(condition, message, code, false);
|
|
259
259
|
}
|
|
260
|
-
/** Evaluate an ad-hoc condition and authorize it
|
|
260
|
+
/** Evaluate an ad-hoc condition and authorize it - the conventional `authorizeOnDemand`. */
|
|
261
261
|
authorizeOnDemand(condition, message, code, allowWhenResponseIs) {
|
|
262
262
|
const result = typeof condition === "function" ? condition(this.defaultUser) : condition;
|
|
263
263
|
const response = result instanceof Response ? result : result === allowWhenResponseIs ? Response.allow(message, code) : Response.deny(message, code);
|
|
@@ -278,7 +278,7 @@ var Gate = class _Gate {
|
|
|
278
278
|
return method.bind(policy);
|
|
279
279
|
}
|
|
280
280
|
/**
|
|
281
|
-
* Find the policy registered for a model
|
|
281
|
+
* Find the policy registered for a model - the `Gate::getPolicyFor` equivalent. Resolves a string
|
|
282
282
|
* tag, a class constructor, or an instance (by its constructor) to its policy, or `undefined` when
|
|
283
283
|
* none is registered.
|
|
284
284
|
*/
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/authorization-error.ts","../src/response.ts","../src/gate.ts","../src/index.ts"],"names":[],"mappings":";AAgBO,IAAM,kBAAA,GAAN,cAAiC,KAAA,CAAM;AAAA;AAAA,EAEnC,MAAA;AAAA;AAAA,EAEA,IAAA;AAAA;AAAA,EAEA,QAAA;AAAA;AAAA;AAAA;AAAA,EAKT,YAAY,QAAA,EAAoB;AAC9B,IAAA,KAAA,CAAM,QAAA,CAAS,OAAA,EAAQ,IAAK,8BAA8B,CAAA;AAC1D,IAAA,IAAA,CAAK,IAAA,GAAO,oBAAA;AACZ,IAAA,IAAA,CAAK,QAAA,GAAW,QAAA;AAChB,IAAA,IAAA,CAAK,IAAA,GAAO,SAAS,IAAA,EAAK;AAC1B,IAAA,IAAA,CAAK,MAAA,GAAS,QAAA,CAAS,MAAA,EAAO,IAAK,GAAA;AAEnC,IAAA,MAAA,CAAO,cAAA,CAAe,IAAA,EAAM,GAAA,CAAA,MAAA,CAAW,SAAS,CAAA;AAAA,EAClD;AACF;;;ACjBO,IAAM,QAAA,GAAN,MAAM,SAAA,CAAS;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOZ,YACW,OAAA,EACA,GAAA,GAAqB,MACrB,OAAA,GAAkC,IAAA,EAClC,aAA4B,IAAA,EAC7C;AAJiB,IAAA,IAAA,CAAA,OAAA,GAAA,OAAA;AACA,IAAA,IAAA,CAAA,GAAA,GAAA,GAAA;AACA,IAAA,IAAA,CAAA,OAAA,GAAA,OAAA;AACA,IAAA,IAAA,CAAA,UAAA,GAAA,UAAA;AAAA,EAChB;AAAA,EAJgB,OAAA;AAAA,EACA,GAAA;AAAA,EACA,OAAA;AAAA,EACA,UAAA;AAAA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UAAA,EAAY;AAC/B,MAAA,OAAO,IAAA,CAAK,QAAA,CAAS,GAAA,CAAI,KAAkB,CAAA;AAAA,IAC7C;AACA,IAAA,IAAI,KAAA,KAAU,IAAA,IAAQ,OAAO,KAAA,KAAU,QAAA,EAAU;AAC/C,MAAA,MAAM,OAAQ,KAAA,CAAsC,WAAA;AACpD,MAAA,IAAI,SAAS,MAAA,EAAW,OAAO,IAAA,CAAK,QAAA,CAAS,IAAI,IAAI,CAAA;AAAA,IACvD;AACA,IAAA,OAAO,MAAA;AAAA,EACT;AACF;;;AC9SO,IAAM,OAAA,GAAU","file":"index.js","sourcesContent":["/**\n * The authorization failure.\n * Thrown by {@link Gate.authorize}/{@link Response.authorize} when an ability is denied. It carries a\n * structural `status` (read by `@plinthjs/http`'s exception handler so the response renders with the\n * right code — `403` by default, or whatever the denying {@link Response} set via `denyWithStatus`/\n * `denyAsNotFound`) alongside the response and its error code, so callers can inspect why.\n */\n\nimport type { Response } from './response'\n\n/**\n * `AuthorizationError`. Carries the\n * denying {@link Response} (so callers can read its message/code) and a structural `status` so\n * `@plinthjs/http`'s handler renders it without this package depending on the HTTP layer. The status is\n * the response's own (e.g. `404` from `denyAsNotFound`), falling back to the `403`.\n */\nexport class AuthorizationError extends Error {\n /** The HTTP status this renders as — the denying response's status, or the default `403`. */\n readonly status: number\n /** The error code attached to the denying {@link Response}, when any. */\n readonly code: string | number | null\n /** The full denying {@link Response} that triggered this error. */\n readonly response: Response\n\n /**\n * @param response The denying {@link Response}; its message becomes the error message.\n */\n constructor(response: Response) {\n super(response.message() ?? 'This action is unauthorized.')\n this.name = 'AuthorizationError'\n this.response = response\n this.code = response.code()\n this.status = response.status() ?? 403\n // Restore the prototype chain when targeting ES2022 down-levels.\n Object.setPrototypeOf(this, new.target.prototype)\n }\n}\n","/**\n * Authorization responses. A\n * {@link Response} is the rich result of an authorization check: it carries an allowed/denied\n * verdict plus an optional human-readable message, an optional error code, and (for denials) an\n * optional HTTP status. Gate check callbacks may return a bare boolean (which the {@link Gate}\n * normalizes into a {@link Response}) or build one explicitly via\n * {@link Response.allow}/{@link Response.deny}/{@link Response.denyWithStatus} to attach a message\n * the UI can surface or a status the HTTP layer should render (e.g. a `404` that hides existence).\n */\n\nimport { AuthorizationError } from './authorization-error'\n\n/**\n * `Response`. Immutable result of an\n * authorization decision: it is either allowed or denied, optionally with a message, an error\n * code, and (when denied) an HTTP status override. Construct one through the\n * {@link Response.allow}/{@link Response.deny}/{@link Response.denyWithStatus} factories rather\n * than the constructor.\n */\nexport class Response {\n /**\n * @param granted Whether the decision allows the action.\n * @param msg Optional human-readable explanation (typically used on denial).\n * @param errCode Optional machine-readable error code attached to the decision.\n * @param statusCode Optional HTTP status a denial should render as (defaults to `403` downstream).\n */\n private constructor(\n private readonly granted: boolean,\n private readonly msg: string | null = null,\n private readonly errCode: string | number | null = null,\n private readonly statusCode: number | null = null,\n ) {}\n\n /**\n * Build an allowing response — the `Response::allow` equivalent. The optional `message` and\n * `code` are preserved so callers can surface a reason even on success.\n */\n static allow(message?: string, code?: string | number): Response {\n return new Response(true, message ?? null, code ?? null)\n }\n\n /**\n * Build a denying response — the `Response::deny` equivalent. The optional `message` and `code`\n * describe why the action was refused.\n */\n static deny(message?: string, code?: string | number): Response {\n return new Response(false, message ?? null, code ?? null)\n }\n\n /**\n * Build a denying response that should render with the given HTTP status — the\n * `Response::denyWithStatus` equivalent. The status is carried onto the\n * {@link AuthorizationError} thrown by {@link Response.authorize}, so the HTTP exception handler\n * renders e.g. a `404` instead of the default `403`.\n */\n static denyWithStatus(status: number, message?: string, code?: string | number): Response {\n return new Response(false, message ?? null, code ?? null, status)\n }\n\n /**\n * Build a denying response that renders as a `404 Not Found` — the `Response::denyAsNotFound`\n * equivalent, used to hide a resource's existence from unauthorized users.\n */\n static denyAsNotFound(message?: string, code?: string | number): Response {\n return Response.denyWithStatus(404, message, code)\n }\n\n /** Whether the decision allows the action — the `Response::allowed` equivalent. */\n allowed(): boolean {\n return this.granted\n }\n\n /** Whether the decision denies the action — the `Response::denied` equivalent. */\n denied(): boolean {\n return !this.granted\n }\n\n /** The attached message, or `null` when none was given — the `Response::message` equivalent. */\n message(): string | null {\n return this.msg\n }\n\n /** The attached error code, or `null` when none was given — the `Response::code` equivalent. */\n code(): string | number | null {\n return this.errCode\n }\n\n /**\n * The HTTP status a denial should render as, or `null` when none was set (denials default to\n * `403` downstream) — the `Response::status` equivalent.\n */\n status(): number | null {\n return this.statusCode\n }\n\n /**\n * Assert this response allows the action — the `Response::authorize` equivalent. Returns the\n * response (for chaining) when allowed; otherwise throws so a denial bubbles up to the caller.\n *\n * @throws {AuthorizationError} when {@link Response.denied}, carrying this response (and its\n * status, when one was set via {@link Response.denyWithStatus}).\n */\n authorize(): this {\n if (!this.granted) throw new AuthorizationError(this)\n return this\n }\n}\n","/**\n * The authorization gate. A {@link Gate}\n * holds the registry of named abilities (defined via callbacks) and resource policies, then answers\n * authorization questions about them: `allows`/`denies`/`check` return booleans, `inspect` returns\n * the raw {@link Response} (including any HTTP status a denial set via `denyWithStatus`),\n * `authorize` throws an {@link AuthorizationError} on denial, and `allowIf`/`denyIf` authorize\n * ad-hoc conditions. `has` reports whether abilities are defined and `abilities` lists them.\n * `before` hooks can short-circuit a decision (e.g. super-admins) and `after` hooks fill in a\n * verdict when nothing else decided. Guests (a `null`/`undefined` user) are denied unless a\n * `before` allows them.\n */\n\nimport { Response } from './response'\n\n// Re-exported here so existing importers of `AuthorizationError` from this module keep working.\nexport { AuthorizationError } from './authorization-error'\n\n/**\n * The result an ability/hook callback may return. A bare boolean is normalized into a\n * {@link Response}; `undefined` from a hook means \"no opinion — keep resolving\".\n */\nexport type AbilityResult = boolean | Response\n\n/**\n * An ability callback — the closure passed to `Gate::define`. Receives the authenticated user\n * followed by the check's extra arguments and returns a boolean or {@link Response}. The gate denies\n * guests before this runs, so `user` is always a real user here. The extra args are typed loosely so\n * callbacks may declare their own concrete parameter types (e.g. `(user, post: Post) => ...`).\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- variadic ability args must accept any concrete param types declared by callbacks\nexport type AbilityCallback<User> = (user: User, ...args: any[]) => AbilityResult\n\n/**\n * A `before` hook — the `Gate::before` equivalent. Runs ahead of every check; returning a boolean\n * or {@link Response} short-circuits the decision, while `undefined` defers to the ability/policy.\n */\nexport type BeforeCallback<User> = (\n user: User,\n ability: string,\n args: unknown[],\n) => AbilityResult | undefined\n\n/**\n * An `after` hook — the `Gate::after` equivalent. Runs only when no `before` hook or ability/policy\n * produced a decision; returning a boolean or {@link Response} supplies the verdict.\n */\nexport type AfterCallback<User> = (\n user: User,\n ability: string,\n args: unknown[],\n) => AbilityResult | undefined\n\n/**\n * The condition accepted by {@link Gate.allowIf}/{@link Gate.denyIf} — a boolean, a prebuilt\n * {@link Response}, or a callback receiving the gate's default user (set via {@link Gate.forUser};\n * `null`/`undefined` for guests) and returning either.\n */\nexport type GateCondition<User> = AbilityResult | ((user: User | null | undefined) => AbilityResult)\n\n/** A resource policy — a plain object (or class instance) whose methods are ability callbacks. */\nexport type Policy<User> = Record<string, AbilityCallback<User>>\n\n/** Normalize an ability/hook result into a {@link Response}. */\nfunction toResponse(result: AbilityResult): Response {\n return result instanceof Response ? result : result ? Response.allow() : Response.deny()\n}\n\n/** A key used to look up a policy: either a string tag or a class constructor. */\ntype PolicyKey = string | (new (...args: never[]) => unknown)\n\n/**\n * The standard CRUD abilities registered by {@link Gate.resource} — mirrors the methods the reference framework's\n * `Gate::resource` maps by default (`viewAny`, `view`, `create`, `update`, `delete`).\n */\nconst RESOURCE_ABILITIES: readonly string[] = ['viewAny', 'view', 'create', 'update', 'delete']\n\n/**\n * `Gate`. Registers abilities and policies, then\n * resolves authorization decisions for a user. The user type is generic; pass the application's\n * user shape (it always includes the guest sentinels `null`/`undefined`).\n *\n * @typeParam User The authenticated user shape; checks may also receive `null`/`undefined` guests.\n */\nexport class Gate<User = unknown> {\n private readonly abilityCallbacks = new Map<string, AbilityCallback<User>>()\n private readonly policies = new Map<PolicyKey, Policy<User>>()\n private readonly beforeCallbacks: BeforeCallback<User | null | undefined>[] = []\n private readonly afterCallbacks: AfterCallback<User | null | undefined>[] = []\n\n /**\n * @param defaultUser The user implicitly used when a check omits one — set by {@link Gate.forUser}.\n */\n constructor(private readonly defaultUser?: User | null | undefined) {}\n\n /**\n * Define a named ability — the `Gate::define` equivalent. The callback receives the user and the\n * check's extra arguments and returns a boolean or {@link Response}. Redefining replaces it.\n */\n define(ability: string, callback: AbilityCallback<User>): this {\n this.abilityCallbacks.set(ability, callback)\n return this\n }\n\n /**\n * Whether every given ability has been defined (directly via {@link Gate.define} or\n * {@link Gate.resource}) — the `Gate::has` equivalent. Policy methods are not consulted, matching\n */\n has(ability: string | readonly string[]): boolean {\n const list = typeof ability === 'string' ? [ability] : ability\n return list.every((name) => this.abilityCallbacks.has(name))\n }\n\n /** The names of every defined ability — the `Gate::abilities` listing. */\n abilities(): string[] {\n return [...this.abilityCallbacks.keys()]\n }\n\n /**\n * Register a policy for a resource key — the `Gate::policy` equivalent. `resourceKey` is either a\n * class constructor or a string tag; when an ability is not defined directly, the gate resolves it\n * to `policy[ability](user, resource, ...args)` using the matching policy.\n */\n policy(resourceKey: PolicyKey, policy: Policy<User>): this {\n this.policies.set(resourceKey, policy)\n return this\n }\n\n /**\n * Register the standard resource abilities for a policy — the `Gate::resource` equivalent. Defines\n * `{name}.viewAny`, `{name}.view`, `{name}.create`, `{name}.update`, and `{name}.delete` (override\n * the list via `abilities`), each dispatching to the matching method on `policy`. The policy's\n * method receives the user and the check's extra arguments, e.g. `allows('posts.update', user, post)`\n * routes to `policy.update(user, post)`. Methods absent from the policy resolve to a denial.\n */\n resource(\n name: string,\n policy: Policy<User>,\n abilities: readonly string[] = RESOURCE_ABILITIES,\n ): this {\n for (const ability of abilities) {\n const method = policy[ability]\n if (typeof method !== 'function') continue\n // Bind so the policy method keeps its `this`; forward the user and any extra check args.\n this.define(`${name}.${ability}`, method.bind(policy))\n }\n return this\n }\n\n /**\n * Register a `before` hook — the `Gate::before` equivalent. Hooks run in registration order ahead\n * of every check; the first to return a boolean/{@link Response} decides, `undefined` defers.\n */\n before(callback: BeforeCallback<User | null | undefined>): this {\n this.beforeCallbacks.push(callback)\n return this\n }\n\n /**\n * Register an `after` hook — the `Gate::after` equivalent. Hooks run only when nothing else\n * decided; the first to return a boolean/{@link Response} supplies the verdict.\n */\n after(callback: AfterCallback<User | null | undefined>): this {\n this.afterCallbacks.push(callback)\n return this\n }\n\n /**\n * Return a gate bound to `user` as its default — the `Gate::forUser` equivalent. The returned gate\n * shares this gate's abilities, policies, and hooks (by reference) so later registrations are seen.\n */\n forUser(user: User | null | undefined): Gate<User> {\n const gate = new Gate<User>(user)\n // Share the underlying registries so the bound gate mirrors this one.\n Reflect.set(gate, 'abilityCallbacks', this.abilityCallbacks)\n Reflect.set(gate, 'policies', this.policies)\n Reflect.set(gate, 'beforeCallbacks', this.beforeCallbacks)\n Reflect.set(gate, 'afterCallbacks', this.afterCallbacks)\n return gate\n }\n\n /**\n * Resolve the raw {@link Response} for an ability — the `Gate::inspect` equivalent. Runs `before`\n * hooks (short-circuiting), then the ability or resolved policy method, then `after` hooks. A guest\n * with no allowing decision is denied. When no callback exists at all the result is a denial.\n */\n inspect(\n ability: string,\n user: User | null | undefined = this.defaultUser,\n ...args: unknown[]\n ): Response {\n // `before` hooks run for everyone (including guests) and may grant access outright.\n for (const hook of this.beforeCallbacks) {\n const result = hook(user, ability, args)\n if (result !== undefined) return toResponse(result)\n }\n\n const callback = this.resolve(ability, args)\n if (callback !== undefined) {\n // Guests are denied at defined abilities unless a `before` hook already allowed them above.\n if (user === null || user === undefined) return Response.deny()\n // `user` is narrowed to a real `User` here, matching the ability callback's contract.\n return toResponse(callback(user, ...args))\n }\n\n // Nothing defined decided — let `after` hooks supply a verdict.\n for (const hook of this.afterCallbacks) {\n const result = hook(user, ability, args)\n if (result !== undefined) return toResponse(result)\n }\n\n return Response.deny()\n }\n\n /** Whether the ability is allowed — the `Gate::allows` equivalent. */\n allows(ability: string, user?: User | null, ...args: unknown[]): boolean {\n return this.inspect(ability, user, ...args).allowed()\n }\n\n /** Whether the ability is denied — the `Gate::denies` equivalent. */\n denies(ability: string, user?: User | null, ...args: unknown[]): boolean {\n return this.inspect(ability, user, ...args).denied()\n }\n\n /** Alias of {@link Gate.allows} — the `Gate::check` equivalent. */\n check(ability: string, user?: User | null, ...args: unknown[]): boolean {\n return this.allows(ability, user, ...args)\n }\n\n /** Whether *any* of the abilities is allowed — the `Gate::any` equivalent. */\n any(abilities: string[], user?: User | null, ...args: unknown[]): boolean {\n return abilities.some((ability) => this.allows(ability, user, ...args))\n }\n\n /** Whether *none* of the abilities is allowed — the `Gate::none` equivalent. */\n none(abilities: string[], user?: User | null, ...args: unknown[]): boolean {\n return !this.any(abilities, user, ...args)\n }\n\n /**\n * Assert the ability and return its allowing {@link Response} — the `Gate::authorize` equivalent.\n *\n * @throws {AuthorizationError} when the ability is denied, carrying the denying response.\n */\n authorize(ability: string, user?: User | null, ...args: unknown[]): Response {\n return this.inspect(ability, user, ...args).authorize()\n }\n\n /**\n * Authorize when an ad-hoc condition holds — the `Gate::allowIf` equivalent. `condition` is a\n * boolean, a {@link Response}, or a callback receiving the gate's default user. Returns the\n * allowing {@link Response}; a falsy/denying condition throws an {@link AuthorizationError}\n * carrying `message`/`code`.\n */\n allowIf(condition: GateCondition<User>, message?: string, code?: string | number): Response {\n return this.authorizeOnDemand(condition, message, code, true)\n }\n\n /**\n * Deny when an ad-hoc condition holds — the `Gate::denyIf` equivalent. The inverse of\n * {@link Gate.allowIf}: a truthy condition throws, a falsy one authorizes.\n */\n denyIf(condition: GateCondition<User>, message?: string, code?: string | number): Response {\n return this.authorizeOnDemand(condition, message, code, false)\n }\n\n /** Evaluate an ad-hoc condition and authorize it — the conventional `authorizeOnDemand`. */\n private authorizeOnDemand(\n condition: GateCondition<User>,\n message: string | undefined,\n code: string | number | undefined,\n allowWhenResponseIs: boolean,\n ): Response {\n const result = typeof condition === 'function' ? condition(this.defaultUser) : condition\n const response =\n result instanceof Response\n ? result\n : result === allowWhenResponseIs\n ? Response.allow(message, code)\n : Response.deny(message, code)\n return response.authorize()\n }\n\n /**\n * Resolve the callback for an ability: a directly defined one wins, otherwise look for a policy\n * keyed by the first argument (a string tag or the resource's constructor) exposing the ability.\n */\n private resolve(ability: string, args: unknown[]): AbilityCallback<User> | undefined {\n const direct = this.abilityCallbacks.get(ability)\n if (direct !== undefined) return direct\n\n const resource = args[0]\n const policy = this.getPolicyFor(resource)\n if (policy === undefined) return undefined\n\n const method = policy[ability]\n if (typeof method !== 'function') return undefined\n\n // Bind so the policy method keeps its `this`; the resource stays the first arg to the method.\n return method.bind(policy)\n }\n\n /**\n * Find the policy registered for a model — the `Gate::getPolicyFor` equivalent. Resolves a string\n * tag, a class constructor, or an instance (by its constructor) to its policy, or `undefined` when\n * none is registered.\n */\n getPolicyFor(model: unknown): Policy<User> | undefined {\n if (typeof model === 'string') {\n return this.policies.get(model)\n }\n if (typeof model === 'function') {\n return this.policies.get(model as PolicyKey)\n }\n if (model !== null && typeof model === 'object') {\n const ctor = (model as { constructor?: PolicyKey }).constructor\n if (ctor !== undefined) return this.policies.get(ctor)\n }\n return undefined\n }\n}\n","/**\n * @plinthjs/authorization.\n *\n * A {@link Gate} that registers named abilities and resource {@link Policy} objects, then answers\n * authorization questions: `allows`/`denies`/`check` booleans, `inspect` for the raw {@link Response},\n * `any`/`none` across several abilities, and `authorize` which throws {@link AuthorizationError} on\n * denial. `resource` registers the standard `viewAny`/`view`/`create`/`update`/`delete` abilities for\n * a policy, `getPolicyFor` looks a policy up by model, `has`/`abilities` report what is defined,\n * `allowIf`/`denyIf` authorize ad-hoc conditions, `before`/`after` hooks short-circuit or backfill\n * decisions, `forUser` binds a default user, and guests (`null`/`undefined`) are denied unless a\n * `before` hook allows them. {@link Response} carries an allow/deny verdict plus an optional message,\n * code, and (via `denyWithStatus`/`denyAsNotFound`) an HTTP status for the denial, and its\n * `authorize` throws when denied. {@link AuthorizationError} carries a structural `status` (the\n * response's, defaulting to `403`) so `@plinthjs/http`'s handler renders it correctly.\n */\n\n/** The Plinth version this build of `authorization` ships with. */\nexport const VERSION = '0.1.0'\n\nexport { AuthorizationError } from './authorization-error'\nexport {\n type AbilityCallback,\n type AbilityResult,\n type AfterCallback,\n type BeforeCallback,\n Gate,\n type GateCondition,\n type Policy,\n} from './gate'\nexport { Response } from './response'\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/authorization-error.ts","../src/response.ts","../src/gate.ts","../src/index.ts"],"names":[],"mappings":";AAgBO,IAAM,kBAAA,GAAN,cAAiC,KAAA,CAAM;AAAA;AAAA,EAEnC,MAAA;AAAA;AAAA,EAEA,IAAA;AAAA;AAAA,EAEA,QAAA;AAAA;AAAA;AAAA;AAAA,EAKT,YAAY,QAAA,EAAoB;AAC9B,IAAA,KAAA,CAAM,QAAA,CAAS,OAAA,EAAQ,IAAK,8BAA8B,CAAA;AAC1D,IAAA,IAAA,CAAK,IAAA,GAAO,oBAAA;AACZ,IAAA,IAAA,CAAK,QAAA,GAAW,QAAA;AAChB,IAAA,IAAA,CAAK,IAAA,GAAO,SAAS,IAAA,EAAK;AAC1B,IAAA,IAAA,CAAK,MAAA,GAAS,QAAA,CAAS,MAAA,EAAO,IAAK,GAAA;AAEnC,IAAA,MAAA,CAAO,cAAA,CAAe,IAAA,EAAM,GAAA,CAAA,MAAA,CAAW,SAAS,CAAA;AAAA,EAClD;AACF;;;ACjBO,IAAM,QAAA,GAAN,MAAM,SAAA,CAAS;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOZ,YACW,OAAA,EACA,GAAA,GAAqB,MACrB,OAAA,GAAkC,IAAA,EAClC,aAA4B,IAAA,EAC7C;AAJiB,IAAA,IAAA,CAAA,OAAA,GAAA,OAAA;AACA,IAAA,IAAA,CAAA,GAAA,GAAA,GAAA;AACA,IAAA,IAAA,CAAA,OAAA,GAAA,OAAA;AACA,IAAA,IAA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AAU;AAC7B,MAAA,OAAO,IAAA,CAAK,QAAA,CAAS,GAAA,CAAI,KAAK,CAAA;AAAA,IAChC;AACA,IAAA,IAAI,OAAO,UAAU,UAAA,EAAY;AAC/B,MAAA,OAAO,IAAA,CAAK,QAAA,CAAS,GAAA,CAAI,KAAkB,CAAA;AAAA,IAC7C;AACA,IAAA,IAAI,KAAA,KAAU,IAAA,IAAQ,OAAO,KAAA,KAAU,QAAA,EAAU;AAC/C,MAAA,MAAM,OAAQ,KAAA,CAAsC,WAAA;AACpD,MAAA,IAAI,SAAS,MAAA,EAAW,OAAO,IAAA,CAAK,QAAA,CAAS,IAAI,IAAI,CAAA;AAAA,IACvD;AACA,IAAA,OAAO,MAAA;AAAA,EACT;AACF;;;AC9SO,IAAM,OAAA,GAAU","file":"index.js","sourcesContent":["/**\n * The authorization failure.\n * Thrown by {@link Gate.authorize}/{@link Response.authorize} when an ability is denied. It carries a\n * structural `status` (read by `@plinthjs/http`'s exception handler so the response renders with the\n * right code - `403` by default, or whatever the denying {@link Response} set via `denyWithStatus`/\n * `denyAsNotFound`) alongside the response and its error code, so callers can inspect why.\n */\n\nimport type { Response } from './response'\n\n/**\n * `AuthorizationError`. Carries the\n * denying {@link Response} (so callers can read its message/code) and a structural `status` so\n * `@plinthjs/http`'s handler renders it without this package depending on the HTTP layer. The status is\n * the response's own (e.g. `404` from `denyAsNotFound`), falling back to the `403`.\n */\nexport class AuthorizationError extends Error {\n /** The HTTP status this renders as - the denying response's status, or the default `403`. */\n readonly status: number\n /** The error code attached to the denying {@link Response}, when any. */\n readonly code: string | number | null\n /** The full denying {@link Response} that triggered this error. */\n readonly response: Response\n\n /**\n * @param response The denying {@link Response}; its message becomes the error message.\n */\n constructor(response: Response) {\n super(response.message() ?? 'This action is unauthorized.')\n this.name = 'AuthorizationError'\n this.response = response\n this.code = response.code()\n this.status = response.status() ?? 403\n // Restore the prototype chain when targeting ES2022 down-levels.\n Object.setPrototypeOf(this, new.target.prototype)\n }\n}\n","/**\n * Authorization responses. A\n * {@link Response} is the rich result of an authorization check: it carries an allowed/denied\n * verdict plus an optional human-readable message, an optional error code, and (for denials) an\n * optional HTTP status. Gate check callbacks may return a bare boolean (which the {@link Gate}\n * normalizes into a {@link Response}) or build one explicitly via\n * {@link Response.allow}/{@link Response.deny}/{@link Response.denyWithStatus} to attach a message\n * the UI can surface or a status the HTTP layer should render (e.g. a `404` that hides existence).\n */\n\nimport { AuthorizationError } from './authorization-error'\n\n/**\n * `Response`. Immutable result of an\n * authorization decision: it is either allowed or denied, optionally with a message, an error\n * code, and (when denied) an HTTP status override. Construct one through the\n * {@link Response.allow}/{@link Response.deny}/{@link Response.denyWithStatus} factories rather\n * than the constructor.\n */\nexport class Response {\n /**\n * @param granted Whether the decision allows the action.\n * @param msg Optional human-readable explanation (typically used on denial).\n * @param errCode Optional machine-readable error code attached to the decision.\n * @param statusCode Optional HTTP status a denial should render as (defaults to `403` downstream).\n */\n private constructor(\n private readonly granted: boolean,\n private readonly msg: string | null = null,\n private readonly errCode: string | number | null = null,\n private readonly statusCode: number | null = null,\n ) {}\n\n /**\n * Build an allowing response - the `Response::allow` equivalent. The optional `message` and\n * `code` are preserved so callers can surface a reason even on success.\n */\n static allow(message?: string, code?: string | number): Response {\n return new Response(true, message ?? null, code ?? null)\n }\n\n /**\n * Build a denying response - the `Response::deny` equivalent. The optional `message` and `code`\n * describe why the action was refused.\n */\n static deny(message?: string, code?: string | number): Response {\n return new Response(false, message ?? null, code ?? null)\n }\n\n /**\n * Build a denying response that should render with the given HTTP status - the\n * `Response::denyWithStatus` equivalent. The status is carried onto the\n * {@link AuthorizationError} thrown by {@link Response.authorize}, so the HTTP exception handler\n * renders e.g. a `404` instead of the default `403`.\n */\n static denyWithStatus(status: number, message?: string, code?: string | number): Response {\n return new Response(false, message ?? null, code ?? null, status)\n }\n\n /**\n * Build a denying response that renders as a `404 Not Found` - the `Response::denyAsNotFound`\n * equivalent, used to hide a resource's existence from unauthorized users.\n */\n static denyAsNotFound(message?: string, code?: string | number): Response {\n return Response.denyWithStatus(404, message, code)\n }\n\n /** Whether the decision allows the action - the `Response::allowed` equivalent. */\n allowed(): boolean {\n return this.granted\n }\n\n /** Whether the decision denies the action - the `Response::denied` equivalent. */\n denied(): boolean {\n return !this.granted\n }\n\n /** The attached message, or `null` when none was given - the `Response::message` equivalent. */\n message(): string | null {\n return this.msg\n }\n\n /** The attached error code, or `null` when none was given - the `Response::code` equivalent. */\n code(): string | number | null {\n return this.errCode\n }\n\n /**\n * The HTTP status a denial should render as, or `null` when none was set (denials default to\n * `403` downstream) - the `Response::status` equivalent.\n */\n status(): number | null {\n return this.statusCode\n }\n\n /**\n * Assert this response allows the action - the `Response::authorize` equivalent. Returns the\n * response (for chaining) when allowed; otherwise throws so a denial bubbles up to the caller.\n *\n * @throws {AuthorizationError} when {@link Response.denied}, carrying this response (and its\n * status, when one was set via {@link Response.denyWithStatus}).\n */\n authorize(): this {\n if (!this.granted) throw new AuthorizationError(this)\n return this\n }\n}\n","/**\n * The authorization gate. A {@link Gate}\n * holds the registry of named abilities (defined via callbacks) and resource policies, then answers\n * authorization questions about them: `allows`/`denies`/`check` return booleans, `inspect` returns\n * the raw {@link Response} (including any HTTP status a denial set via `denyWithStatus`),\n * `authorize` throws an {@link AuthorizationError} on denial, and `allowIf`/`denyIf` authorize\n * ad-hoc conditions. `has` reports whether abilities are defined and `abilities` lists them.\n * `before` hooks can short-circuit a decision (e.g. super-admins) and `after` hooks fill in a\n * verdict when nothing else decided. Guests (a `null`/`undefined` user) are denied unless a\n * `before` allows them.\n */\n\nimport { Response } from './response'\n\n// Re-exported here so existing importers of `AuthorizationError` from this module keep working.\nexport { AuthorizationError } from './authorization-error'\n\n/**\n * The result an ability/hook callback may return. A bare boolean is normalized into a\n * {@link Response}; `undefined` from a hook means \"no opinion - keep resolving\".\n */\nexport type AbilityResult = boolean | Response\n\n/**\n * An ability callback - the closure passed to `Gate::define`. Receives the authenticated user\n * followed by the check's extra arguments and returns a boolean or {@link Response}. The gate denies\n * guests before this runs, so `user` is always a real user here. The extra args are typed loosely so\n * callbacks may declare their own concrete parameter types (e.g. `(user, post: Post) => ...`).\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- variadic ability args must accept any concrete param types declared by callbacks\nexport type AbilityCallback<User> = (user: User, ...args: any[]) => AbilityResult\n\n/**\n * A `before` hook - the `Gate::before` equivalent. Runs ahead of every check; returning a boolean\n * or {@link Response} short-circuits the decision, while `undefined` defers to the ability/policy.\n */\nexport type BeforeCallback<User> = (\n user: User,\n ability: string,\n args: unknown[],\n) => AbilityResult | undefined\n\n/**\n * An `after` hook - the `Gate::after` equivalent. Runs only when no `before` hook or ability/policy\n * produced a decision; returning a boolean or {@link Response} supplies the verdict.\n */\nexport type AfterCallback<User> = (\n user: User,\n ability: string,\n args: unknown[],\n) => AbilityResult | undefined\n\n/**\n * The condition accepted by {@link Gate.allowIf}/{@link Gate.denyIf} - a boolean, a prebuilt\n * {@link Response}, or a callback receiving the gate's default user (set via {@link Gate.forUser};\n * `null`/`undefined` for guests) and returning either.\n */\nexport type GateCondition<User> = AbilityResult | ((user: User | null | undefined) => AbilityResult)\n\n/** A resource policy - a plain object (or class instance) whose methods are ability callbacks. */\nexport type Policy<User> = Record<string, AbilityCallback<User>>\n\n/** Normalize an ability/hook result into a {@link Response}. */\nfunction toResponse(result: AbilityResult): Response {\n return result instanceof Response ? result : result ? Response.allow() : Response.deny()\n}\n\n/** A key used to look up a policy: either a string tag or a class constructor. */\ntype PolicyKey = string | (new (...args: never[]) => unknown)\n\n/**\n * The standard CRUD abilities registered by {@link Gate.resource} - mirrors the methods the reference framework's\n * `Gate::resource` maps by default (`viewAny`, `view`, `create`, `update`, `delete`).\n */\nconst RESOURCE_ABILITIES: readonly string[] = ['viewAny', 'view', 'create', 'update', 'delete']\n\n/**\n * `Gate`. Registers abilities and policies, then\n * resolves authorization decisions for a user. The user type is generic; pass the application's\n * user shape (it always includes the guest sentinels `null`/`undefined`).\n *\n * @typeParam User The authenticated user shape; checks may also receive `null`/`undefined` guests.\n */\nexport class Gate<User = unknown> {\n private readonly abilityCallbacks = new Map<string, AbilityCallback<User>>()\n private readonly policies = new Map<PolicyKey, Policy<User>>()\n private readonly beforeCallbacks: BeforeCallback<User | null | undefined>[] = []\n private readonly afterCallbacks: AfterCallback<User | null | undefined>[] = []\n\n /**\n * @param defaultUser The user implicitly used when a check omits one - set by {@link Gate.forUser}.\n */\n constructor(private readonly defaultUser?: User | null | undefined) {}\n\n /**\n * Define a named ability - the `Gate::define` equivalent. The callback receives the user and the\n * check's extra arguments and returns a boolean or {@link Response}. Redefining replaces it.\n */\n define(ability: string, callback: AbilityCallback<User>): this {\n this.abilityCallbacks.set(ability, callback)\n return this\n }\n\n /**\n * Whether every given ability has been defined (directly via {@link Gate.define} or\n * {@link Gate.resource}) - the `Gate::has` equivalent. Policy methods are not consulted, matching\n */\n has(ability: string | readonly string[]): boolean {\n const list = typeof ability === 'string' ? [ability] : ability\n return list.every((name) => this.abilityCallbacks.has(name))\n }\n\n /** The names of every defined ability - the `Gate::abilities` listing. */\n abilities(): string[] {\n return [...this.abilityCallbacks.keys()]\n }\n\n /**\n * Register a policy for a resource key - the `Gate::policy` equivalent. `resourceKey` is either a\n * class constructor or a string tag; when an ability is not defined directly, the gate resolves it\n * to `policy[ability](user, resource, ...args)` using the matching policy.\n */\n policy(resourceKey: PolicyKey, policy: Policy<User>): this {\n this.policies.set(resourceKey, policy)\n return this\n }\n\n /**\n * Register the standard resource abilities for a policy - the `Gate::resource` equivalent. Defines\n * `{name}.viewAny`, `{name}.view`, `{name}.create`, `{name}.update`, and `{name}.delete` (override\n * the list via `abilities`), each dispatching to the matching method on `policy`. The policy's\n * method receives the user and the check's extra arguments, e.g. `allows('posts.update', user, post)`\n * routes to `policy.update(user, post)`. Methods absent from the policy resolve to a denial.\n */\n resource(\n name: string,\n policy: Policy<User>,\n abilities: readonly string[] = RESOURCE_ABILITIES,\n ): this {\n for (const ability of abilities) {\n const method = policy[ability]\n if (typeof method !== 'function') continue\n // Bind so the policy method keeps its `this`; forward the user and any extra check args.\n this.define(`${name}.${ability}`, method.bind(policy))\n }\n return this\n }\n\n /**\n * Register a `before` hook - the `Gate::before` equivalent. Hooks run in registration order ahead\n * of every check; the first to return a boolean/{@link Response} decides, `undefined` defers.\n */\n before(callback: BeforeCallback<User | null | undefined>): this {\n this.beforeCallbacks.push(callback)\n return this\n }\n\n /**\n * Register an `after` hook - the `Gate::after` equivalent. Hooks run only when nothing else\n * decided; the first to return a boolean/{@link Response} supplies the verdict.\n */\n after(callback: AfterCallback<User | null | undefined>): this {\n this.afterCallbacks.push(callback)\n return this\n }\n\n /**\n * Return a gate bound to `user` as its default - the `Gate::forUser` equivalent. The returned gate\n * shares this gate's abilities, policies, and hooks (by reference) so later registrations are seen.\n */\n forUser(user: User | null | undefined): Gate<User> {\n const gate = new Gate<User>(user)\n // Share the underlying registries so the bound gate mirrors this one.\n Reflect.set(gate, 'abilityCallbacks', this.abilityCallbacks)\n Reflect.set(gate, 'policies', this.policies)\n Reflect.set(gate, 'beforeCallbacks', this.beforeCallbacks)\n Reflect.set(gate, 'afterCallbacks', this.afterCallbacks)\n return gate\n }\n\n /**\n * Resolve the raw {@link Response} for an ability - the `Gate::inspect` equivalent. Runs `before`\n * hooks (short-circuiting), then the ability or resolved policy method, then `after` hooks. A guest\n * with no allowing decision is denied. When no callback exists at all the result is a denial.\n */\n inspect(\n ability: string,\n user: User | null | undefined = this.defaultUser,\n ...args: unknown[]\n ): Response {\n // `before` hooks run for everyone (including guests) and may grant access outright.\n for (const hook of this.beforeCallbacks) {\n const result = hook(user, ability, args)\n if (result !== undefined) return toResponse(result)\n }\n\n const callback = this.resolve(ability, args)\n if (callback !== undefined) {\n // Guests are denied at defined abilities unless a `before` hook already allowed them above.\n if (user === null || user === undefined) return Response.deny()\n // `user` is narrowed to a real `User` here, matching the ability callback's contract.\n return toResponse(callback(user, ...args))\n }\n\n // Nothing defined decided - let `after` hooks supply a verdict.\n for (const hook of this.afterCallbacks) {\n const result = hook(user, ability, args)\n if (result !== undefined) return toResponse(result)\n }\n\n return Response.deny()\n }\n\n /** Whether the ability is allowed - the `Gate::allows` equivalent. */\n allows(ability: string, user?: User | null, ...args: unknown[]): boolean {\n return this.inspect(ability, user, ...args).allowed()\n }\n\n /** Whether the ability is denied - the `Gate::denies` equivalent. */\n denies(ability: string, user?: User | null, ...args: unknown[]): boolean {\n return this.inspect(ability, user, ...args).denied()\n }\n\n /** Alias of {@link Gate.allows} - the `Gate::check` equivalent. */\n check(ability: string, user?: User | null, ...args: unknown[]): boolean {\n return this.allows(ability, user, ...args)\n }\n\n /** Whether *any* of the abilities is allowed - the `Gate::any` equivalent. */\n any(abilities: string[], user?: User | null, ...args: unknown[]): boolean {\n return abilities.some((ability) => this.allows(ability, user, ...args))\n }\n\n /** Whether *none* of the abilities is allowed - the `Gate::none` equivalent. */\n none(abilities: string[], user?: User | null, ...args: unknown[]): boolean {\n return !this.any(abilities, user, ...args)\n }\n\n /**\n * Assert the ability and return its allowing {@link Response} - the `Gate::authorize` equivalent.\n *\n * @throws {AuthorizationError} when the ability is denied, carrying the denying response.\n */\n authorize(ability: string, user?: User | null, ...args: unknown[]): Response {\n return this.inspect(ability, user, ...args).authorize()\n }\n\n /**\n * Authorize when an ad-hoc condition holds - the `Gate::allowIf` equivalent. `condition` is a\n * boolean, a {@link Response}, or a callback receiving the gate's default user. Returns the\n * allowing {@link Response}; a falsy/denying condition throws an {@link AuthorizationError}\n * carrying `message`/`code`.\n */\n allowIf(condition: GateCondition<User>, message?: string, code?: string | number): Response {\n return this.authorizeOnDemand(condition, message, code, true)\n }\n\n /**\n * Deny when an ad-hoc condition holds - the `Gate::denyIf` equivalent. The inverse of\n * {@link Gate.allowIf}: a truthy condition throws, a falsy one authorizes.\n */\n denyIf(condition: GateCondition<User>, message?: string, code?: string | number): Response {\n return this.authorizeOnDemand(condition, message, code, false)\n }\n\n /** Evaluate an ad-hoc condition and authorize it - the conventional `authorizeOnDemand`. */\n private authorizeOnDemand(\n condition: GateCondition<User>,\n message: string | undefined,\n code: string | number | undefined,\n allowWhenResponseIs: boolean,\n ): Response {\n const result = typeof condition === 'function' ? condition(this.defaultUser) : condition\n const response =\n result instanceof Response\n ? result\n : result === allowWhenResponseIs\n ? Response.allow(message, code)\n : Response.deny(message, code)\n return response.authorize()\n }\n\n /**\n * Resolve the callback for an ability: a directly defined one wins, otherwise look for a policy\n * keyed by the first argument (a string tag or the resource's constructor) exposing the ability.\n */\n private resolve(ability: string, args: unknown[]): AbilityCallback<User> | undefined {\n const direct = this.abilityCallbacks.get(ability)\n if (direct !== undefined) return direct\n\n const resource = args[0]\n const policy = this.getPolicyFor(resource)\n if (policy === undefined) return undefined\n\n const method = policy[ability]\n if (typeof method !== 'function') return undefined\n\n // Bind so the policy method keeps its `this`; the resource stays the first arg to the method.\n return method.bind(policy)\n }\n\n /**\n * Find the policy registered for a model - the `Gate::getPolicyFor` equivalent. Resolves a string\n * tag, a class constructor, or an instance (by its constructor) to its policy, or `undefined` when\n * none is registered.\n */\n getPolicyFor(model: unknown): Policy<User> | undefined {\n if (typeof model === 'string') {\n return this.policies.get(model)\n }\n if (typeof model === 'function') {\n return this.policies.get(model as PolicyKey)\n }\n if (model !== null && typeof model === 'object') {\n const ctor = (model as { constructor?: PolicyKey }).constructor\n if (ctor !== undefined) return this.policies.get(ctor)\n }\n return undefined\n }\n}\n","/**\n * @plinthjs/authorization.\n *\n * A {@link Gate} that registers named abilities and resource {@link Policy} objects, then answers\n * authorization questions: `allows`/`denies`/`check` booleans, `inspect` for the raw {@link Response},\n * `any`/`none` across several abilities, and `authorize` which throws {@link AuthorizationError} on\n * denial. `resource` registers the standard `viewAny`/`view`/`create`/`update`/`delete` abilities for\n * a policy, `getPolicyFor` looks a policy up by model, `has`/`abilities` report what is defined,\n * `allowIf`/`denyIf` authorize ad-hoc conditions, `before`/`after` hooks short-circuit or backfill\n * decisions, `forUser` binds a default user, and guests (`null`/`undefined`) are denied unless a\n * `before` hook allows them. {@link Response} carries an allow/deny verdict plus an optional message,\n * code, and (via `denyWithStatus`/`denyAsNotFound`) an HTTP status for the denial, and its\n * `authorize` throws when denied. {@link AuthorizationError} carries a structural `status` (the\n * response's, defaulting to `403`) so `@plinthjs/http`'s handler renders it correctly.\n */\n\n/** The Plinth version this build of `authorization` ships with. */\nexport const VERSION = '0.1.0'\n\nexport { AuthorizationError } from './authorization-error'\nexport {\n type AbilityCallback,\n type AbilityResult,\n type AfterCallback,\n type BeforeCallback,\n Gate,\n type GateCondition,\n type Policy,\n} from './gate'\nexport { Response } from './response'\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@plinthjs/authorization",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.2",
|
|
4
4
|
"description": "Plinth authorization: Gate + Policies.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"plinth",
|
|
@@ -8,13 +8,13 @@
|
|
|
8
8
|
"typescript",
|
|
9
9
|
"authorization"
|
|
10
10
|
],
|
|
11
|
-
"homepage": "https://github.com/anilkumarthakur60/
|
|
11
|
+
"homepage": "https://github.com/anilkumarthakur60/plinthjs/tree/main/packages/authorization#readme",
|
|
12
12
|
"bugs": {
|
|
13
|
-
"url": "https://github.com/anilkumarthakur60/
|
|
13
|
+
"url": "https://github.com/anilkumarthakur60/plinthjs/issues"
|
|
14
14
|
},
|
|
15
15
|
"repository": {
|
|
16
16
|
"type": "git",
|
|
17
|
-
"url": "git+https://github.com/anilkumarthakur60/
|
|
17
|
+
"url": "git+https://github.com/anilkumarthakur60/plinthjs.git",
|
|
18
18
|
"directory": "packages/authorization"
|
|
19
19
|
},
|
|
20
20
|
"license": "MIT",
|
|
@@ -42,7 +42,7 @@
|
|
|
42
42
|
"access": "public"
|
|
43
43
|
},
|
|
44
44
|
"dependencies": {
|
|
45
|
-
"@plinthjs/support": "^0.1.
|
|
45
|
+
"@plinthjs/support": "^0.1.2"
|
|
46
46
|
},
|
|
47
47
|
"devDependencies": {
|
|
48
48
|
"tsup": "^8.3.5",
|