@plinthjs/authorization 0.1.0 → 0.1.1
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 +1 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +10 -11
- package/dist/index.d.ts +10 -11
- package/dist/index.js +1 -2
- package/dist/index.js.map +1 -1
- package/package.json +4 -5
package/LICENSE
CHANGED
package/README.md
CHANGED
package/dist/index.cjs
CHANGED
|
@@ -133,7 +133,6 @@ var Gate = class _Gate {
|
|
|
133
133
|
/**
|
|
134
134
|
* Whether every given ability has been defined (directly via {@link Gate.define} or
|
|
135
135
|
* {@link Gate.resource}) — the `Gate::has` equivalent. Policy methods are not consulted, matching
|
|
136
|
-
* Laravel.
|
|
137
136
|
*/
|
|
138
137
|
has(ability) {
|
|
139
138
|
const list = typeof ability === "string" ? [ability] : ability;
|
|
@@ -260,7 +259,7 @@ var Gate = class _Gate {
|
|
|
260
259
|
denyIf(condition, message, code) {
|
|
261
260
|
return this.authorizeOnDemand(condition, message, code, false);
|
|
262
261
|
}
|
|
263
|
-
/** Evaluate an ad-hoc condition and authorize it —
|
|
262
|
+
/** Evaluate an ad-hoc condition and authorize it — the conventional `authorizeOnDemand`. */
|
|
264
263
|
authorizeOnDemand(condition, message, code, allowWhenResponseIs) {
|
|
265
264
|
const result = typeof condition === "function" ? condition(this.defaultUser) : condition;
|
|
266
265
|
const response = result instanceof Response ? result : result === allowWhenResponseIs ? Response.allow(message, code) : Response.deny(message, code);
|
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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M,OAAA,GAAU","file":"index.cjs","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;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;AA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,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
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Authorization responses
|
|
2
|
+
* Authorization responses. A
|
|
3
3
|
* {@link Response} is the rich result of an authorization check: it carries an allowed/denied
|
|
4
4
|
* verdict plus an optional human-readable message, an optional error code, and (for denials) an
|
|
5
5
|
* optional HTTP status. Gate check callbacks may return a bare boolean (which the {@link Gate}
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
* the UI can surface or a status the HTTP layer should render (e.g. a `404` that hides existence).
|
|
9
9
|
*/
|
|
10
10
|
/**
|
|
11
|
-
* `Response
|
|
11
|
+
* `Response`. Immutable result of an
|
|
12
12
|
* authorization decision: it is either allowed or denied, optionally with a message, an error
|
|
13
13
|
* code, and (when denied) an HTTP status override. Construct one through the
|
|
14
14
|
* {@link Response.allow}/{@link Response.deny}/{@link Response.denyWithStatus} factories rather
|
|
@@ -72,7 +72,7 @@ declare class Response {
|
|
|
72
72
|
}
|
|
73
73
|
|
|
74
74
|
/**
|
|
75
|
-
* The authorization failure
|
|
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
78
|
* right code — `403` by default, or whatever the denying {@link Response} set via `denyWithStatus`/
|
|
@@ -80,10 +80,10 @@ declare class Response {
|
|
|
80
80
|
*/
|
|
81
81
|
|
|
82
82
|
/**
|
|
83
|
-
* `AuthorizationError
|
|
83
|
+
* `AuthorizationError`. Carries the
|
|
84
84
|
* denying {@link Response} (so callers can read its message/code) and a structural `status` so
|
|
85
85
|
* `@plinthjs/http`'s handler renders it without this package depending on the HTTP layer. The status is
|
|
86
|
-
* the response's own (e.g. `404` from `denyAsNotFound`), falling back to the
|
|
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
89
|
/** The HTTP status this renders as — the denying response's status, or the default `403`. */
|
|
@@ -99,7 +99,7 @@ declare class AuthorizationError extends Error {
|
|
|
99
99
|
}
|
|
100
100
|
|
|
101
101
|
/**
|
|
102
|
-
* The authorization gate
|
|
102
|
+
* The authorization gate. A {@link Gate}
|
|
103
103
|
* holds the registry of named abilities (defined via callbacks) and resource policies, then answers
|
|
104
104
|
* authorization questions about them: `allows`/`denies`/`check` return booleans, `inspect` returns
|
|
105
105
|
* the raw {@link Response} (including any HTTP status a denial set via `denyWithStatus`),
|
|
@@ -143,7 +143,7 @@ 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);
|
|
145
145
|
/**
|
|
146
|
-
* `Gate
|
|
146
|
+
* `Gate`. Registers abilities and policies, then
|
|
147
147
|
* resolves authorization decisions for a user. The user type is generic; pass the application's
|
|
148
148
|
* user shape (it always includes the guest sentinels `null`/`undefined`).
|
|
149
149
|
*
|
|
@@ -167,7 +167,6 @@ declare class Gate<User = unknown> {
|
|
|
167
167
|
/**
|
|
168
168
|
* Whether every given ability has been defined (directly via {@link Gate.define} or
|
|
169
169
|
* {@link Gate.resource}) — the `Gate::has` equivalent. Policy methods are not consulted, matching
|
|
170
|
-
* Laravel.
|
|
171
170
|
*/
|
|
172
171
|
has(ability: string | readonly string[]): boolean;
|
|
173
172
|
/** The names of every defined ability — the `Gate::abilities` listing. */
|
|
@@ -235,7 +234,7 @@ declare class Gate<User = unknown> {
|
|
|
235
234
|
* {@link Gate.allowIf}: a truthy condition throws, a falsy one authorizes.
|
|
236
235
|
*/
|
|
237
236
|
denyIf(condition: GateCondition<User>, message?: string, code?: string | number): Response;
|
|
238
|
-
/** Evaluate an ad-hoc condition and authorize it —
|
|
237
|
+
/** Evaluate an ad-hoc condition and authorize it — the conventional `authorizeOnDemand`. */
|
|
239
238
|
private authorizeOnDemand;
|
|
240
239
|
/**
|
|
241
240
|
* Resolve the callback for an ability: a directly defined one wins, otherwise look for a policy
|
|
@@ -251,7 +250,7 @@ declare class Gate<User = unknown> {
|
|
|
251
250
|
}
|
|
252
251
|
|
|
253
252
|
/**
|
|
254
|
-
* @plinthjs/authorization
|
|
253
|
+
* @plinthjs/authorization.
|
|
255
254
|
*
|
|
256
255
|
* A {@link Gate} that registers named abilities and resource {@link Policy} objects, then answers
|
|
257
256
|
* authorization questions: `allows`/`denies`/`check` booleans, `inspect` for the raw {@link Response},
|
|
@@ -265,7 +264,7 @@ declare class Gate<User = unknown> {
|
|
|
265
264
|
* `authorize` throws when denied. {@link AuthorizationError} carries a structural `status` (the
|
|
266
265
|
* response's, defaulting to `403`) so `@plinthjs/http`'s handler renders it correctly.
|
|
267
266
|
*/
|
|
268
|
-
/** The
|
|
267
|
+
/** The Plinth version this build of `authorization` ships with. */
|
|
269
268
|
declare const VERSION = "0.1.0";
|
|
270
269
|
|
|
271
270
|
export { type AbilityCallback, type AbilityResult, type AfterCallback, AuthorizationError, type BeforeCallback, Gate, type GateCondition, type Policy, Response, VERSION };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Authorization responses
|
|
2
|
+
* Authorization responses. A
|
|
3
3
|
* {@link Response} is the rich result of an authorization check: it carries an allowed/denied
|
|
4
4
|
* verdict plus an optional human-readable message, an optional error code, and (for denials) an
|
|
5
5
|
* optional HTTP status. Gate check callbacks may return a bare boolean (which the {@link Gate}
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
* the UI can surface or a status the HTTP layer should render (e.g. a `404` that hides existence).
|
|
9
9
|
*/
|
|
10
10
|
/**
|
|
11
|
-
* `Response
|
|
11
|
+
* `Response`. Immutable result of an
|
|
12
12
|
* authorization decision: it is either allowed or denied, optionally with a message, an error
|
|
13
13
|
* code, and (when denied) an HTTP status override. Construct one through the
|
|
14
14
|
* {@link Response.allow}/{@link Response.deny}/{@link Response.denyWithStatus} factories rather
|
|
@@ -72,7 +72,7 @@ declare class Response {
|
|
|
72
72
|
}
|
|
73
73
|
|
|
74
74
|
/**
|
|
75
|
-
* The authorization failure
|
|
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
78
|
* right code — `403` by default, or whatever the denying {@link Response} set via `denyWithStatus`/
|
|
@@ -80,10 +80,10 @@ declare class Response {
|
|
|
80
80
|
*/
|
|
81
81
|
|
|
82
82
|
/**
|
|
83
|
-
* `AuthorizationError
|
|
83
|
+
* `AuthorizationError`. Carries the
|
|
84
84
|
* denying {@link Response} (so callers can read its message/code) and a structural `status` so
|
|
85
85
|
* `@plinthjs/http`'s handler renders it without this package depending on the HTTP layer. The status is
|
|
86
|
-
* the response's own (e.g. `404` from `denyAsNotFound`), falling back to the
|
|
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
89
|
/** The HTTP status this renders as — the denying response's status, or the default `403`. */
|
|
@@ -99,7 +99,7 @@ declare class AuthorizationError extends Error {
|
|
|
99
99
|
}
|
|
100
100
|
|
|
101
101
|
/**
|
|
102
|
-
* The authorization gate
|
|
102
|
+
* The authorization gate. A {@link Gate}
|
|
103
103
|
* holds the registry of named abilities (defined via callbacks) and resource policies, then answers
|
|
104
104
|
* authorization questions about them: `allows`/`denies`/`check` return booleans, `inspect` returns
|
|
105
105
|
* the raw {@link Response} (including any HTTP status a denial set via `denyWithStatus`),
|
|
@@ -143,7 +143,7 @@ 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);
|
|
145
145
|
/**
|
|
146
|
-
* `Gate
|
|
146
|
+
* `Gate`. Registers abilities and policies, then
|
|
147
147
|
* resolves authorization decisions for a user. The user type is generic; pass the application's
|
|
148
148
|
* user shape (it always includes the guest sentinels `null`/`undefined`).
|
|
149
149
|
*
|
|
@@ -167,7 +167,6 @@ declare class Gate<User = unknown> {
|
|
|
167
167
|
/**
|
|
168
168
|
* Whether every given ability has been defined (directly via {@link Gate.define} or
|
|
169
169
|
* {@link Gate.resource}) — the `Gate::has` equivalent. Policy methods are not consulted, matching
|
|
170
|
-
* Laravel.
|
|
171
170
|
*/
|
|
172
171
|
has(ability: string | readonly string[]): boolean;
|
|
173
172
|
/** The names of every defined ability — the `Gate::abilities` listing. */
|
|
@@ -235,7 +234,7 @@ declare class Gate<User = unknown> {
|
|
|
235
234
|
* {@link Gate.allowIf}: a truthy condition throws, a falsy one authorizes.
|
|
236
235
|
*/
|
|
237
236
|
denyIf(condition: GateCondition<User>, message?: string, code?: string | number): Response;
|
|
238
|
-
/** Evaluate an ad-hoc condition and authorize it —
|
|
237
|
+
/** Evaluate an ad-hoc condition and authorize it — the conventional `authorizeOnDemand`. */
|
|
239
238
|
private authorizeOnDemand;
|
|
240
239
|
/**
|
|
241
240
|
* Resolve the callback for an ability: a directly defined one wins, otherwise look for a policy
|
|
@@ -251,7 +250,7 @@ declare class Gate<User = unknown> {
|
|
|
251
250
|
}
|
|
252
251
|
|
|
253
252
|
/**
|
|
254
|
-
* @plinthjs/authorization
|
|
253
|
+
* @plinthjs/authorization.
|
|
255
254
|
*
|
|
256
255
|
* A {@link Gate} that registers named abilities and resource {@link Policy} objects, then answers
|
|
257
256
|
* authorization questions: `allows`/`denies`/`check` booleans, `inspect` for the raw {@link Response},
|
|
@@ -265,7 +264,7 @@ declare class Gate<User = unknown> {
|
|
|
265
264
|
* `authorize` throws when denied. {@link AuthorizationError} carries a structural `status` (the
|
|
266
265
|
* response's, defaulting to `403`) so `@plinthjs/http`'s handler renders it correctly.
|
|
267
266
|
*/
|
|
268
|
-
/** The
|
|
267
|
+
/** The Plinth version this build of `authorization` ships with. */
|
|
269
268
|
declare const VERSION = "0.1.0";
|
|
270
269
|
|
|
271
270
|
export { type AbilityCallback, type AbilityResult, type AfterCallback, AuthorizationError, type BeforeCallback, Gate, type GateCondition, type Policy, Response, VERSION };
|
package/dist/index.js
CHANGED
|
@@ -131,7 +131,6 @@ var Gate = class _Gate {
|
|
|
131
131
|
/**
|
|
132
132
|
* Whether every given ability has been defined (directly via {@link Gate.define} or
|
|
133
133
|
* {@link Gate.resource}) — the `Gate::has` equivalent. Policy methods are not consulted, matching
|
|
134
|
-
* Laravel.
|
|
135
134
|
*/
|
|
136
135
|
has(ability) {
|
|
137
136
|
const list = typeof ability === "string" ? [ability] : ability;
|
|
@@ -258,7 +257,7 @@ var Gate = class _Gate {
|
|
|
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);
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/authorization-error.ts","../src/response.ts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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;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;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AAa,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,10 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@plinthjs/authorization",
|
|
3
|
-
"version": "0.1.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Plinth authorization: Gate + Policies.",
|
|
5
5
|
"keywords": [
|
|
6
|
-
"
|
|
7
|
-
"laravel",
|
|
6
|
+
"plinth",
|
|
8
7
|
"framework",
|
|
9
8
|
"typescript",
|
|
10
9
|
"authorization"
|
|
@@ -43,7 +42,7 @@
|
|
|
43
42
|
"access": "public"
|
|
44
43
|
},
|
|
45
44
|
"dependencies": {
|
|
46
|
-
"@plinthjs/support": "^0.1.
|
|
45
|
+
"@plinthjs/support": "^0.1.1"
|
|
47
46
|
},
|
|
48
47
|
"devDependencies": {
|
|
49
48
|
"tsup": "^8.3.5",
|