@guren/server 2.27.0 → 2.28.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.
@@ -89,6 +89,15 @@ function toAuthorizationResponse(value) {
89
89
  if (isAuthorizationResponse(value)) return value;
90
90
  return value === true ? Response.allow() : Response.deny();
91
91
  }
92
+ /**
93
+ * An object literal or null-prototype object, the shape of an ORM record. A class
94
+ * instance or a tuple is not one, so an unresolved one still denies.
95
+ */
96
+ function isPlainRecord(value) {
97
+ if (typeof value !== "object" || value === null) return false;
98
+ const prototype = Object.getPrototypeOf(value);
99
+ return prototype === Object.prototype || prototype === null;
100
+ }
92
101
  /** Honours `denyWithStatus()` / `denyAsNotFound()` so a policy can hide a record as a 404. */
93
102
  function denialToException(response) {
94
103
  const message = response.message ?? "This action is unauthorized.";
@@ -180,6 +189,7 @@ var Gate = class {
180
189
  const result = await gate.callback(user, ...args);
181
190
  return this.settle(user, ability, toAuthorizationResponse(result), args);
182
191
  }
192
+ if (isPlainRecord(model)) throw new Error(`No policy resolved for a plain record in the "${ability}" check; pass [Model, record] so the gate can find the model's policy, or define a gate for "${ability}".`);
183
193
  return this.settle(user, ability, Response.deny(), args);
184
194
  }
185
195
  async settle(user, ability, response, args) {
@@ -188,8 +198,9 @@ var Gate = class {
188
198
  }
189
199
  /**
190
200
  * The subject may be a class instance (policy resolved via its constructor)
191
- * or a `[ModelClass, record]` / `['key', record]` tuple — the tuple form is
192
- * required for plain ORM records, which carry no constructor information.
201
+ * or a `[ModelClass, record]` / `['key', record]` tuple. ORM records are plain
202
+ * objects with no constructor information, so they need the tuple: a plain
203
+ * record reaching no policy and no gate throws in `checkResponse()`.
193
204
  */
194
205
  async checkPolicy(ability, user, model, additionalArgs) {
195
206
  let policyKey;
@@ -8,7 +8,7 @@ import { n as ServiceProvider } from "./ServiceProvider-G0YclITd.js";
8
8
  import { r as getAuthContext } from "./context-af2n5abO.js";
9
9
  import { o as getApiTokenOrFail } from "./api-token-BbgDEd6j.js";
10
10
  import { a as resolveI18n } from "./i18n-DmMKcbqj.js";
11
- import { d as resolveGate, g as tryGetRequestContainer } from "./Gate-BL_zW82W.js";
11
+ import { d as resolveGate, g as tryGetRequestContainer } from "./Gate-CYfoGQqh.js";
12
12
  import { t as jsx_runtime_exports } from "./jsx-runtime.js";
13
13
  import { getCookie } from "hono/cookie";
14
14
  import { isAbsolute, resolve } from "node:path";
@@ -866,12 +866,13 @@ var Controller = class {
866
866
  * Authorize the current user (or guest) for an ability; throws
867
867
  * AuthorizationException (403) when denied. ORM records are plain objects
868
868
  * with no constructor information, so pass the model class alongside the
869
- * record: `await this.authorize('update', [Post, post])`.
869
+ * record: `await this.authorize('update', [Post, post])`. A bare record that
870
+ * resolves no policy and no gate throws an Error rather than denying.
870
871
  */
871
872
  async authorize(ability, ...args) {
872
873
  await this.#resolveGate().forUser(await this.gateUser()).authorize(ability, ...args);
873
874
  }
874
- /** Check an ability without throwing: `await this.can('update', [Post, post])`. */
875
+ /** Check an ability, answering a denial with `false` rather than a 403: `await this.can('update', [Post, post])`. */
875
876
  async can(ability, ...args) {
876
877
  return this.#resolveGate().forUser(await this.gateUser()).allows(ability, ...args);
877
878
  }
@@ -36,8 +36,9 @@ export declare class Gate {
36
36
  protected settle(user: AuthUser | null, ability: string, response: AuthorizationResponse, args: unknown[]): Promise<AuthorizationResponse>;
37
37
  /**
38
38
  * The subject may be a class instance (policy resolved via its constructor)
39
- * or a `[ModelClass, record]` / `['key', record]` tuple — the tuple form is
40
- * required for plain ORM records, which carry no constructor information.
39
+ * or a `[ModelClass, record]` / `['key', record]` tuple. ORM records are plain
40
+ * objects with no constructor information, so they need the tuple: a plain
41
+ * record reaching no policy and no gate throws in `checkResponse()`.
41
42
  */
42
43
  protected checkPolicy(ability: string, user: AuthUser | null, model: unknown, additionalArgs: unknown[]): Promise<boolean | AuthorizationResponse | undefined>;
43
44
  protected getPolicyInstance(policyClass: PolicyClass): Policy;
@@ -1,3 +1,3 @@
1
- import { a as withAuthorization, n as authorizeMiddleware, o as Policy, r as authorizeResourceMiddleware, s as definePolicy, t as authorizeAllMiddleware } from "../authorization-Daa6CxCg.js";
2
- import { a as cannot, f as setGate, i as can, l as getGate, n as Response, o as createGate, r as authorize, s as defineGate, t as Gate, u as isAuthorizationResponse } from "../Gate-BL_zW82W.js";
1
+ import { a as withAuthorization, n as authorizeMiddleware, o as Policy, r as authorizeResourceMiddleware, s as definePolicy, t as authorizeAllMiddleware } from "../authorization-CKOLYWvi.js";
2
+ import { a as cannot, f as setGate, i as can, l as getGate, n as Response, o as createGate, r as authorize, s as defineGate, t as Gate, u as isAuthorizationResponse } from "../Gate-CYfoGQqh.js";
3
3
  export { Gate, Policy, Response, authorize, authorizeAllMiddleware, authorizeMiddleware, authorizeResourceMiddleware, can, cannot, createGate, defineGate, definePolicy, getGate, isAuthorizationResponse, setGate, withAuthorization };
@@ -1,4 +1,4 @@
1
- import { c as denialToException, d as resolveGate, g as tryGetRequestContainer, n as Response, p as AuthorizationException } from "./Gate-BL_zW82W.js";
1
+ import { c as denialToException, d as resolveGate, g as tryGetRequestContainer, n as Response, p as AuthorizationException } from "./Gate-CYfoGQqh.js";
2
2
  //#region src/http/middleware/capabilities.ts
3
3
  /**
4
4
  * Internal security-capability marker (RFC 0007): built-in middleware
@@ -1,2 +1,2 @@
1
- import { a as RedisStore, i as FileStore, n as createCacheManager, o as MemoryStore, r as TaggedCache, t as CacheManager } from "../cache-BlXopnH1.js";
1
+ import { a as RedisStore, i as FileStore, n as createCacheManager, o as MemoryStore, r as TaggedCache, t as CacheManager } from "../cache-C2Im3l7t.js";
2
2
  export { CacheManager, FileStore, MemoryStore, RedisStore, TaggedCache, createCacheManager };
@@ -28,5 +28,7 @@ export declare class FileStore implements CacheStore {
28
28
  ttl(key: string): Promise<number>;
29
29
  /** Delete expired cache files; call periodically to free disk space. */
30
30
  cleanup(): Promise<number>;
31
+ private removeIfExpired;
32
+ private restore;
31
33
  getBasePath(): string;
32
34
  }
@@ -3,8 +3,8 @@ import { n as isHotReloadRuntime, t as claimHotDisposable } from "./hot-disposab
3
3
  import { t as describeDriverMap } from "./driver-map-CkQc52j-.js";
4
4
  import { createHash, randomUUID } from "node:crypto";
5
5
  import { dirname, join } from "node:path";
6
- import { mkdir, readFile, readdir, rename, rm, rmdir, unlink, writeFile } from "node:fs/promises";
7
- import { existsSync } from "node:fs";
6
+ import { copyFile, link, mkdir, readFile, readdir, rename, rm, rmdir, unlink, writeFile } from "node:fs/promises";
7
+ import { constants, existsSync } from "node:fs";
8
8
  //#region src/redis/lazy-client.ts
9
9
  /**
10
10
  * The one rule for a `client` option that may be an ioredis instance or a
@@ -384,10 +384,7 @@ var FileStore = class {
384
384
  const filePath = this.getFilePath(key);
385
385
  const item = await this.readCacheFile(filePath);
386
386
  if (!item) return null;
387
- if (this.isExpired(item)) {
388
- await this.deleteCacheFile(filePath);
389
- return null;
390
- }
387
+ if (this.isExpired(item)) return null;
391
388
  return item.value;
392
389
  }
393
390
  async set(key, value, ttl) {
@@ -415,7 +412,7 @@ var FileStore = class {
415
412
  }
416
413
  async delete(key) {
417
414
  const filePath = this.getFilePath(key);
418
- return this.deleteCacheFile(filePath);
415
+ return this.locked(filePath, () => this.deleteCacheFile(filePath));
419
416
  }
420
417
  async clear() {
421
418
  if (!existsSync(this.basePath)) return;
@@ -474,10 +471,7 @@ var FileStore = class {
474
471
  const filePath = this.getFilePath(key);
475
472
  const item = await this.readCacheFile(filePath);
476
473
  if (!item) return -2;
477
- if (this.isExpired(item)) {
478
- await this.deleteCacheFile(filePath);
479
- return -2;
480
- }
474
+ if (this.isExpired(item)) return -2;
481
475
  if (item.expiresAt === null) return -1;
482
476
  return Math.max(0, Math.ceil((item.expiresAt - this.now()) / 1e3));
483
477
  }
@@ -498,11 +492,32 @@ var FileStore = class {
498
492
  if (!file.endsWith(this.extension)) continue;
499
493
  const filePath = join(subdirPath, file);
500
494
  const item = await this.readCacheFile(filePath);
501
- if (item && this.isExpired(item) && await this.deleteCacheFile(filePath)) cleaned++;
495
+ if (item && this.isExpired(item) && await this.locked(filePath, () => this.removeIfExpired(filePath))) cleaned++;
502
496
  }
503
497
  }
504
498
  return cleaned;
505
499
  }
500
+ async removeIfExpired(filePath) {
501
+ const grave = `${filePath}.${randomUUID()}.grave`;
502
+ try {
503
+ await rename(filePath, grave);
504
+ } catch {
505
+ return false;
506
+ }
507
+ const item = await this.readCacheFile(grave);
508
+ const expired = item !== null && this.isExpired(item);
509
+ if (expired || await this.restore(grave, filePath)) await unlink(grave).catch(() => void 0);
510
+ return expired;
511
+ }
512
+ async restore(grave, filePath) {
513
+ for (const put of [() => link(grave, filePath), () => copyFile(grave, filePath, constants.COPYFILE_EXCL)]) try {
514
+ await put();
515
+ return true;
516
+ } catch (error) {
517
+ if (error.code === "EEXIST") return true;
518
+ }
519
+ return false;
520
+ }
506
521
  getBasePath() {
507
522
  return this.basePath;
508
523
  }
@@ -4,7 +4,7 @@ import chalk from "chalk";
4
4
  import figlet from "figlet";
5
5
  import standard from "figlet/importable-fonts/Standard.js";
6
6
  //#region package.json
7
- var version = "2.27.0";
7
+ var version = "2.28.1";
8
8
  //#endregion
9
9
  //#region src/http/dev-banner.ts
10
10
  var dev_banner_exports = /* @__PURE__ */ __exportAll({
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
- import { C as setInertiaSsrRenderer, D as isDeferredProp, E as isAlwaysProp, O as ensureErrorStackTracePolyfill, S as setInertiaDocument, T as defer, a as renderDocument, b as inertia, c as getRequestLocale, d as mountModuleRoutes, f as definePlugin, g as shareInertiaProps, h as setInertiaSharedProps, i as Controller, l as getRequestTranslator, m as resolveSharedInertiaProps, n as Resource, o as LOCALE_CONTEXT_KEY, p as getInertiaSharedPropsResolver, r as collect, s as detectLocaleMiddleware, t as JsonResource, u as defineModule, w as always } from "./Resource-q3tJpJ0K.js";
1
+ import { C as setInertiaSsrRenderer, D as isDeferredProp, E as isAlwaysProp, O as ensureErrorStackTracePolyfill, S as setInertiaDocument, T as defer, a as renderDocument, b as inertia, c as getRequestLocale, d as mountModuleRoutes, f as definePlugin, g as shareInertiaProps, h as setInertiaSharedProps, i as Controller, l as getRequestTranslator, m as resolveSharedInertiaProps, n as Resource, o as LOCALE_CONTEXT_KEY, p as getInertiaSharedPropsResolver, r as collect, s as detectLocaleMiddleware, t as JsonResource, u as defineModule, w as always } from "./Resource-BhOua2OB.js";
2
2
  import { a as parseRequestPayload, i as parseRequestBody, n as flattenRequestQueries, r as formatValidationErrors } from "./request-CLOYytGP.js";
3
3
  import { i as setValidatedInput, n as getValidatedInput } from "./validated-input-D84J8wcC.js";
4
4
  import { t as HttpException } from "./HttpException-BlQ2yEmT.js";
5
5
  import { n as ValidationException } from "./errors-JpkcCjjn.js";
6
- import { a as withAuthorization, c as capabilitiesOf, i as derivableAbility, l as mergeCapabilities, n as authorizeMiddleware, o as Policy, r as authorizeResourceMiddleware, s as definePolicy, t as authorizeAllMiddleware, u as stampCapabilities } from "./authorization-Daa6CxCg.js";
6
+ import { a as withAuthorization, c as capabilitiesOf, i as derivableAbility, l as mergeCapabilities, n as authorizeMiddleware, o as Policy, r as authorizeResourceMiddleware, s as definePolicy, t as authorizeAllMiddleware, u as stampCapabilities } from "./authorization-CKOLYWvi.js";
7
7
  import { a as mapToolResponse, c as AGENT_PREFLIGHT_VERDICT_HEADER, i as describeBuildFailure, n as advertisesStructuredOutput, o as isDispatchedToolRequest, r as buildToolRequest, t as PREFLIGHT_ARGUMENT } from "./dispatch-ENWpBxbE.js";
8
8
  import { i as trimSlashes } from "./contained-path-BkNSBljW.js";
9
9
  import { PATH_PARAM_PATTERN, extractPathParamNames } from "./internal/route-path.js";
@@ -18,13 +18,13 @@ import { o as AuthenticationException, r as getAuthContext, t as AUTH_CONTEXT_KE
18
18
  import { a as md5, c as sha256, d as verifyPassword, i as hmac, l as sha512, n as hash, o as needsRehash, r as hashPassword, s as secureCompare, t as check, u as verifyHmac } from "./Hash-D2DFd8xX.js";
19
19
  import { _ as verifyApiToken, a as getApiToken, c as hasBearerHeader, d as revokeAllApiTokens, f as revokeApiToken, g as tokenCanAny, h as tokenCanAll, i as createBearerTokenMiddleware, l as parseApiToken, m as tokenCan, n as MemoryApiTokenStore, o as getApiTokenOrFail, r as createApiToken, s as getUserApiTokens, t as API_TOKEN_KEY, u as readBearerToken } from "./api-token-BbgDEd6j.js";
20
20
  import { a as runInRequestScope, i as keepAlive, n as filterSensitiveData, t as Logger } from "./Logger-DWXdtLSJ.js";
21
- import { a as RedisStore, i as FileStore, n as createCacheManager, o as MemoryStore, r as TaggedCache, s as resolveLazyRedisClient, t as CacheManager } from "./cache-BlXopnH1.js";
21
+ import { a as RedisStore, i as FileStore, n as createCacheManager, o as MemoryStore, r as TaggedCache, s as resolveLazyRedisClient, t as CacheManager } from "./cache-C2Im3l7t.js";
22
22
  import { n as createRedisClient, r as RedisSessionStore } from "./client-C5Wj9P9o.js";
23
23
  import { r as isMcpEndpointEnabled } from "./endpoint-Coq0K_6I.js";
24
24
  import { n as isHotReloadRuntime, r as matchingOpenParen, t as claimHotDisposable } from "./hot-disposables-W2fH-GID.js";
25
25
  import { a as setBroadcastManager, c as PresenceChannel, d as createWebSocketOriginGuard, i as getBroadcastManager, l as PrivateChannel, n as BroadcastManager, o as RedisDriver, r as createBroadcastManager, s as MemoryDriver, t as createTypedBroadcaster, u as Channel } from "./broadcasting-N4cRV42s.js";
26
26
  import { c as tc, d as Translator, f as getPluralizationRule, i as getI18n, l as tryGetI18n, m as selectPluralForm, n as I18nManager, o as setI18n, p as pluralizationRules, r as createI18n, s as t, t as MemoryLoader, u as JsonLoader } from "./i18n-DmMKcbqj.js";
27
- import { a as cannot, f as setGate, g as tryGetRequestContainer, h as getRequestContainer, i as can, l as getGate, m as CONTAINER_CONTEXT_KEY, n as Response$1, o as createGate, p as AuthorizationException, r as authorize, s as defineGate, t as Gate } from "./Gate-BL_zW82W.js";
27
+ import { a as cannot, f as setGate, g as tryGetRequestContainer, h as getRequestContainer, i as can, l as getGate, m as CONTAINER_CONTEXT_KEY, n as Response$1, o as createGate, p as AuthorizationException, r as authorize, s as defineGate, t as Gate } from "./Gate-CYfoGQqh.js";
28
28
  import { n as isAgentToolRequest } from "./agent-request-Caj6bnbj.js";
29
29
  import { r as isDocsViewerEnabled } from "./endpoint-CTIzcagh.js";
30
30
  import { n as isWildcardHost, t as formatHostPort } from "./host-port-t6wQFaRu.js";
@@ -3221,7 +3221,7 @@ let devBanner;
3221
3221
  */
3222
3222
  async function loadDevBanner() {
3223
3223
  if (typeof process === "undefined") return devBanner;
3224
- if (process.env.NODE_ENV !== "production") devBanner ??= await import("./dev-banner-CfQDnkfQ.js").then((n) => n.n);
3224
+ if (process.env.NODE_ENV !== "production") devBanner ??= await import("./dev-banner-DnaL8Ku6.js").then((n) => n.n);
3225
3225
  return devBanner;
3226
3226
  }
3227
3227
  function clearManagedViteEnv() {
@@ -1,4 +1,4 @@
1
- import { _ as INERTIA_VARY, f as definePlugin, i as Controller, n as Resource, r as collect, t as JsonResource, u as defineModule, v as acceptsJson, x as serializePage, y as buildInertiaPage } from "../Resource-q3tJpJ0K.js";
1
+ import { _ as INERTIA_VARY, f as definePlugin, i as Controller, n as Resource, r as collect, t as JsonResource, u as defineModule, v as acceptsJson, x as serializePage, y as buildInertiaPage } from "../Resource-BhOua2OB.js";
2
2
  import { r as formatValidationErrors } from "../request-CLOYytGP.js";
3
3
  import { n as ValidationException } from "../errors-JpkcCjjn.js";
4
4
  import { n as ServiceProvider } from "../ServiceProvider-G0YclITd.js";
@@ -135,10 +135,11 @@ export declare class Controller {
135
135
  * Authorize the current user (or guest) for an ability; throws
136
136
  * AuthorizationException (403) when denied. ORM records are plain objects
137
137
  * with no constructor information, so pass the model class alongside the
138
- * record: `await this.authorize('update', [Post, post])`.
138
+ * record: `await this.authorize('update', [Post, post])`. A bare record that
139
+ * resolves no policy and no gate throws an Error rather than denying.
139
140
  */
140
141
  protected authorize(ability: string, ...args: unknown[]): Promise<void>;
141
- /** Check an ability without throwing: `await this.can('update', [Post, post])`. */
142
+ /** Check an ability, answering a denial with `false` rather than a 403: `await this.can('update', [Post, post])`. */
142
143
  protected can(ability: string, ...args: unknown[]): Promise<boolean>;
143
144
  private gateUser;
144
145
  /**
@@ -2,7 +2,7 @@ import { a as trimTrailingSlashes, n as isRealPathWithin, t as isPathWithin } fr
2
2
  import { n as parseImportMap } from "../inertia-defaults-BjrcT7za.js";
3
3
  import { n as hash } from "../Hash-D2DFd8xX.js";
4
4
  import { a as getManifestCss, c as isViteProduction, d as startViteDevServer, i as clientManifestCandidates, l as loadViteManifest, o as getManifestFile, r as PUBLIC_ASSETS_URL_PREFIX, u as normalizeDevServerUrl } from "../vite-manifest-wPxfAzjW.js";
5
- import { r as logDevServerBanner, t as GUREN_ASCII_ART } from "../dev-banner-CfQDnkfQ.js";
5
+ import { r as logDevServerBanner, t as GUREN_ASCII_ART } from "../dev-banner-DnaL8Ku6.js";
6
6
  import { createRequire } from "node:module";
7
7
  import { dirname, extname, join, resolve } from "node:path";
8
8
  import { fileURLToPath } from "node:url";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@guren/server",
3
- "version": "2.27.0",
3
+ "version": "2.28.1",
4
4
  "description": "HTTP layer of the Guren framework, on Hono: routing, controllers, middleware, auth, sessions, queues and the AWS Lambda adapter. Applications import it through @guren/core.",
5
5
  "keywords": [
6
6
  "guren",