@plinthjs/authorization 0.1.0 → 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/LICENSE +1 -1
- package/README.md +1 -1
- package/dist/index.cjs +31 -32
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +47 -48
- package/dist/index.d.ts +47 -48
- package/dist/index.js +31 -32
- package/dist/index.js.map +1 -1
- package/package.json +7 -8
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,19 +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})
|
|
134
|
-
* Laravel.
|
|
133
|
+
* {@link Gate.resource}) - the `Gate::has` equivalent. Policy methods are not consulted, matching
|
|
135
134
|
*/
|
|
136
135
|
has(ability) {
|
|
137
136
|
const list = typeof ability === "string" ? [ability] : ability;
|
|
138
137
|
return list.every((name) => this.abilityCallbacks.has(name));
|
|
139
138
|
}
|
|
140
|
-
/** The names of every defined ability
|
|
139
|
+
/** The names of every defined ability - the `Gate::abilities` listing. */
|
|
141
140
|
abilities() {
|
|
142
141
|
return [...this.abilityCallbacks.keys()];
|
|
143
142
|
}
|
|
144
143
|
/**
|
|
145
|
-
* Register a policy for a resource key
|
|
144
|
+
* Register a policy for a resource key - the `Gate::policy` equivalent. `resourceKey` is either a
|
|
146
145
|
* class constructor or a string tag; when an ability is not defined directly, the gate resolves it
|
|
147
146
|
* to `policy[ability](user, resource, ...args)` using the matching policy.
|
|
148
147
|
*/
|
|
@@ -151,7 +150,7 @@ var Gate = class _Gate {
|
|
|
151
150
|
return this;
|
|
152
151
|
}
|
|
153
152
|
/**
|
|
154
|
-
* Register the standard resource abilities for a policy
|
|
153
|
+
* Register the standard resource abilities for a policy - the `Gate::resource` equivalent. Defines
|
|
155
154
|
* `{name}.viewAny`, `{name}.view`, `{name}.create`, `{name}.update`, and `{name}.delete` (override
|
|
156
155
|
* the list via `abilities`), each dispatching to the matching method on `policy`. The policy's
|
|
157
156
|
* method receives the user and the check's extra arguments, e.g. `allows('posts.update', user, post)`
|
|
@@ -166,7 +165,7 @@ var Gate = class _Gate {
|
|
|
166
165
|
return this;
|
|
167
166
|
}
|
|
168
167
|
/**
|
|
169
|
-
* Register a `before` hook
|
|
168
|
+
* Register a `before` hook - the `Gate::before` equivalent. Hooks run in registration order ahead
|
|
170
169
|
* of every check; the first to return a boolean/{@link Response} decides, `undefined` defers.
|
|
171
170
|
*/
|
|
172
171
|
before(callback) {
|
|
@@ -174,7 +173,7 @@ var Gate = class _Gate {
|
|
|
174
173
|
return this;
|
|
175
174
|
}
|
|
176
175
|
/**
|
|
177
|
-
* Register an `after` hook
|
|
176
|
+
* Register an `after` hook - the `Gate::after` equivalent. Hooks run only when nothing else
|
|
178
177
|
* decided; the first to return a boolean/{@link Response} supplies the verdict.
|
|
179
178
|
*/
|
|
180
179
|
after(callback) {
|
|
@@ -182,7 +181,7 @@ var Gate = class _Gate {
|
|
|
182
181
|
return this;
|
|
183
182
|
}
|
|
184
183
|
/**
|
|
185
|
-
* 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
|
|
186
185
|
* shares this gate's abilities, policies, and hooks (by reference) so later registrations are seen.
|
|
187
186
|
*/
|
|
188
187
|
forUser(user) {
|
|
@@ -194,7 +193,7 @@ var Gate = class _Gate {
|
|
|
194
193
|
return gate;
|
|
195
194
|
}
|
|
196
195
|
/**
|
|
197
|
-
* Resolve the raw {@link Response} for an ability
|
|
196
|
+
* Resolve the raw {@link Response} for an ability - the `Gate::inspect` equivalent. Runs `before`
|
|
198
197
|
* hooks (short-circuiting), then the ability or resolved policy method, then `after` hooks. A guest
|
|
199
198
|
* with no allowing decision is denied. When no callback exists at all the result is a denial.
|
|
200
199
|
*/
|
|
@@ -214,28 +213,28 @@ var Gate = class _Gate {
|
|
|
214
213
|
}
|
|
215
214
|
return Response.deny();
|
|
216
215
|
}
|
|
217
|
-
/** Whether the ability is allowed
|
|
216
|
+
/** Whether the ability is allowed - the `Gate::allows` equivalent. */
|
|
218
217
|
allows(ability, user, ...args) {
|
|
219
218
|
return this.inspect(ability, user, ...args).allowed();
|
|
220
219
|
}
|
|
221
|
-
/** Whether the ability is denied
|
|
220
|
+
/** Whether the ability is denied - the `Gate::denies` equivalent. */
|
|
222
221
|
denies(ability, user, ...args) {
|
|
223
222
|
return this.inspect(ability, user, ...args).denied();
|
|
224
223
|
}
|
|
225
|
-
/** Alias of {@link Gate.allows}
|
|
224
|
+
/** Alias of {@link Gate.allows} - the `Gate::check` equivalent. */
|
|
226
225
|
check(ability, user, ...args) {
|
|
227
226
|
return this.allows(ability, user, ...args);
|
|
228
227
|
}
|
|
229
|
-
/** Whether *any* of the abilities is allowed
|
|
228
|
+
/** Whether *any* of the abilities is allowed - the `Gate::any` equivalent. */
|
|
230
229
|
any(abilities, user, ...args) {
|
|
231
230
|
return abilities.some((ability) => this.allows(ability, user, ...args));
|
|
232
231
|
}
|
|
233
|
-
/** Whether *none* of the abilities is allowed
|
|
232
|
+
/** Whether *none* of the abilities is allowed - the `Gate::none` equivalent. */
|
|
234
233
|
none(abilities, user, ...args) {
|
|
235
234
|
return !this.any(abilities, user, ...args);
|
|
236
235
|
}
|
|
237
236
|
/**
|
|
238
|
-
* Assert the ability and return its allowing {@link Response}
|
|
237
|
+
* Assert the ability and return its allowing {@link Response} - the `Gate::authorize` equivalent.
|
|
239
238
|
*
|
|
240
239
|
* @throws {AuthorizationError} when the ability is denied, carrying the denying response.
|
|
241
240
|
*/
|
|
@@ -243,7 +242,7 @@ var Gate = class _Gate {
|
|
|
243
242
|
return this.inspect(ability, user, ...args).authorize();
|
|
244
243
|
}
|
|
245
244
|
/**
|
|
246
|
-
* Authorize when an ad-hoc condition holds
|
|
245
|
+
* Authorize when an ad-hoc condition holds - the `Gate::allowIf` equivalent. `condition` is a
|
|
247
246
|
* boolean, a {@link Response}, or a callback receiving the gate's default user. Returns the
|
|
248
247
|
* allowing {@link Response}; a falsy/denying condition throws an {@link AuthorizationError}
|
|
249
248
|
* carrying `message`/`code`.
|
|
@@ -252,13 +251,13 @@ var Gate = class _Gate {
|
|
|
252
251
|
return this.authorizeOnDemand(condition, message, code, true);
|
|
253
252
|
}
|
|
254
253
|
/**
|
|
255
|
-
* Deny when an ad-hoc condition holds
|
|
254
|
+
* Deny when an ad-hoc condition holds - the `Gate::denyIf` equivalent. The inverse of
|
|
256
255
|
* {@link Gate.allowIf}: a truthy condition throws, a falsy one authorizes.
|
|
257
256
|
*/
|
|
258
257
|
denyIf(condition, message, code) {
|
|
259
258
|
return this.authorizeOnDemand(condition, message, code, false);
|
|
260
259
|
}
|
|
261
|
-
/** Evaluate an ad-hoc condition and authorize it
|
|
260
|
+
/** Evaluate an ad-hoc condition and authorize it - the conventional `authorizeOnDemand`. */
|
|
262
261
|
authorizeOnDemand(condition, message, code, allowWhenResponseIs) {
|
|
263
262
|
const result = typeof condition === "function" ? condition(this.defaultUser) : condition;
|
|
264
263
|
const response = result instanceof Response ? result : result === allowWhenResponseIs ? Response.allow(message, code) : Response.deny(message, code);
|
|
@@ -279,7 +278,7 @@ var Gate = class _Gate {
|
|
|
279
278
|
return method.bind(policy);
|
|
280
279
|
}
|
|
281
280
|
/**
|
|
282
|
-
* Find the policy registered for a model
|
|
281
|
+
* Find the policy registered for a model - the `Gate::getPolicyFor` equivalent. Resolves a string
|
|
283
282
|
* tag, a class constructor, or an instance (by its constructor) to its policy, or `undefined` when
|
|
284
283
|
* none is registered.
|
|
285
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;AAAA;AAAA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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;;;AC/SO,IAAM,OAAA,GAAU","file":"index.js","sourcesContent":["/**\n * The authorization failure — the Laravel `Illuminate\\Auth\\Access\\AuthorizationException` equivalent.\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` — the `Illuminate\\Auth\\Access\\AuthorizationException` equivalent. 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 Laravel `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 — the Laravel `Illuminate\\Auth\\Access\\Response` equivalent. 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` — the `Illuminate\\Auth\\Access\\Response` equivalent. 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 — the Laravel `Illuminate\\Auth\\Access\\Gate` equivalent. 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 Laravel'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` — the `Illuminate\\Auth\\Access\\Gate` equivalent. 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 * Laravel.\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 — Laravel's `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 — the Laravel `Illuminate\\Auth\\Access` equivalent.\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 Mason 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;AA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M,MAAA,GAAS,OAAO,OAAO,CAAA;AAC7B,IAAA,IAAI,OAAO,MAAA,KAAW,UAAA,EAAY,OAAO,MAAA;AAGzC,IAAA,OAAO,MAAA,CAAO,KAAK,MAAM,CAAA;AAAA,EAC3B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,aAAa,KAAA,EAA0C;AACrD,IAAA,IAAI,OAAO,UAAU,QAAA,EAAU;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,21 +1,20 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@plinthjs/authorization",
|
|
3
|
-
"version": "0.1.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "0.1.2",
|
|
4
|
+
"description": "Plinth authorization: Gate + Policies.",
|
|
5
5
|
"keywords": [
|
|
6
|
-
"
|
|
7
|
-
"laravel",
|
|
6
|
+
"plinth",
|
|
8
7
|
"framework",
|
|
9
8
|
"typescript",
|
|
10
9
|
"authorization"
|
|
11
10
|
],
|
|
12
|
-
"homepage": "https://github.com/anilkumarthakur60/
|
|
11
|
+
"homepage": "https://github.com/anilkumarthakur60/plinthjs/tree/main/packages/authorization#readme",
|
|
13
12
|
"bugs": {
|
|
14
|
-
"url": "https://github.com/anilkumarthakur60/
|
|
13
|
+
"url": "https://github.com/anilkumarthakur60/plinthjs/issues"
|
|
15
14
|
},
|
|
16
15
|
"repository": {
|
|
17
16
|
"type": "git",
|
|
18
|
-
"url": "git+https://github.com/anilkumarthakur60/
|
|
17
|
+
"url": "git+https://github.com/anilkumarthakur60/plinthjs.git",
|
|
19
18
|
"directory": "packages/authorization"
|
|
20
19
|
},
|
|
21
20
|
"license": "MIT",
|
|
@@ -43,7 +42,7 @@
|
|
|
43
42
|
"access": "public"
|
|
44
43
|
},
|
|
45
44
|
"dependencies": {
|
|
46
|
-
"@plinthjs/support": "^0.1.
|
|
45
|
+
"@plinthjs/support": "^0.1.2"
|
|
47
46
|
},
|
|
48
47
|
"devDependencies": {
|
|
49
48
|
"tsup": "^8.3.5",
|