@vite-hub/auth 0.7.0 → 0.9.0

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.
Files changed (78) hide show
  1. package/README.md +59 -6
  2. package/dist/{abilities-CfvuGrBv.d.ts → abilities-6LE7VSdN.d.ts} +1 -1
  3. package/dist/abilities.d.ts +1 -1
  4. package/dist/{ability-error-OKoyOwPM.js → ability-error-Ccm5Iy4F.js} +1 -1
  5. package/dist/{access-pages-Bej95blM.js → access-pages-lQGfRvfL.js} +1 -4
  6. package/dist/{admin-claim-code-C3X_U43x.js → admin-claim-code-CMa0eRRm.js} +0 -1
  7. package/dist/agent.js +11 -11
  8. package/dist/{application-path-zKi7NrvK.js → application-path-LMc_ptL9.js} +0 -2
  9. package/dist/{auth-instance-5RSiFTDC.js → auth-instance-0PTsOttV.js} +41 -57
  10. package/dist/bun-sqlite.d.ts +0 -2
  11. package/dist/cli.js +2 -2
  12. package/dist/client-extension-BVBVUqa1.d.ts +33 -0
  13. package/dist/client-request-B1DCz3a9.js +29 -0
  14. package/dist/{console-runtime-Bg_PAl7e.js → console-runtime-BlOx9hWC.js} +3 -19
  15. package/dist/{console-runtime-XcplYv4R.d.ts → console-runtime-D2FUATXQ.d.ts} +1 -1
  16. package/dist/console-runtime.d.ts +2 -2
  17. package/dist/console-runtime.js +1 -1
  18. package/dist/console.d.ts +1 -1
  19. package/dist/database-options-CPhnGap9.js +36 -0
  20. package/dist/{database-schema-options-CCQsNhjc.js → database-schema-options-BQyynyhw.js} +1 -1
  21. package/dist/database.d.ts +1 -1
  22. package/dist/database.js +22 -11
  23. package/dist/{definition-DeEeqTLC.js → definition-CvmvHaQT.js} +4 -12
  24. package/dist/{error-diagnostics-DkzL9ltR.js → error-diagnostics-BpQy1iIO.js} +35 -4
  25. package/dist/{events-BUaoHFoC.js → events-aP_Rz_gx.js} +1 -1
  26. package/dist/extension-B35v_o1u.js +133 -0
  27. package/dist/extension-C2giF7w2.d.ts +59 -0
  28. package/dist/forward.d.ts +0 -5
  29. package/dist/forward.js +1 -1
  30. package/dist/index.d.ts +4 -3
  31. package/dist/index.js +4 -3
  32. package/dist/internal/server.d.ts +3 -3
  33. package/dist/internal/server.js +5 -5
  34. package/dist/{mcp-config-C7srUMIZ.js → mcp-config-DYlTXmr6.js} +9 -1
  35. package/dist/{mcp-token-DG1jmw4o.d.ts → mcp-token-CxpopXmK.d.ts} +4 -2
  36. package/dist/{mcp-token-DgveSGEl.js → mcp-token-i-8NMulH.js} +28 -6
  37. package/dist/mcp.d.ts +2 -7
  38. package/dist/mcp.js +26 -7
  39. package/dist/{members-CRlYyxVk.js → members-USm08YwK.js} +4 -6
  40. package/dist/nuxt.d.ts +4 -14
  41. package/dist/nuxt.js +29 -61
  42. package/dist/{own-access-BvVUjaeL.d.ts → own-access-B7VRd92K.d.ts} +1 -1
  43. package/dist/presets.js +1 -1
  44. package/dist/{request-Dpq7GO8B.js → request-CdlcvqVc.js} +0 -1
  45. package/dist/runtime/client-request-plugin.d.ts +2 -1
  46. package/dist/runtime/client-request-plugin.js +8 -5
  47. package/dist/runtime/console.d.ts +1 -1
  48. package/dist/runtime/console.js +2 -2
  49. package/dist/runtime/empty-abilities.d.ts +1 -1
  50. package/dist/runtime/empty-client.d.ts +3 -0
  51. package/dist/runtime/empty-client.js +3 -1
  52. package/dist/runtime/empty-definition.d.ts +1 -1
  53. package/dist/runtime/server.d.ts +4 -3
  54. package/dist/runtime/server.js +5 -4
  55. package/dist/runtime/vue-nuxt.js +2 -18
  56. package/dist/schema.d.ts +32 -17
  57. package/dist/schema.js +39 -16
  58. package/dist/{server-1G_BbfBD.d.ts → server-4_EXgXFn.d.ts} +25 -8
  59. package/dist/{server-iQNOXyfS.js → server-CZR2dVVp.js} +43 -352
  60. package/dist/{server-B8kTFrHP.d.ts → server-DAIBBKbR.d.ts} +3 -2
  61. package/dist/server.d.ts +3 -3
  62. package/dist/server.js +4 -4
  63. package/dist/{session-cookies-DN0svCKj.js → session-cookies-CfXdF1yd.js} +5 -33
  64. package/dist/{set-cookie-CMB3t4NF.js → set-cookie-BYZslovs.js} +1 -1
  65. package/dist/{table-specs-C3-bLOSF.js → table-specs-Cvjc_Ccs.js} +28 -2
  66. package/dist/{table-specs-P4LvbOlX.d.ts → table-specs-VYAy_jJ7.d.ts} +5 -2
  67. package/dist/test.d.ts +1 -1
  68. package/dist/test.js +2 -2
  69. package/dist/{types-BmRGse4l.d.ts → types-DakualFJ.d.ts} +20 -4
  70. package/dist/vite-CZ_Z6IR3.d.ts +28 -0
  71. package/dist/{vite-GRzej8Cs.js → vite-DVvWaN3D.js} +652 -301
  72. package/dist/vite.d.ts +35 -17
  73. package/dist/vite.js +1 -1
  74. package/dist/vue.d.ts +4 -34
  75. package/dist/vue.js +40 -66
  76. package/package.json +9 -8
  77. package/dist/client-request-BzMKtfCY.js +0 -52
  78. package/dist/database-options-DE9lMwu1.js +0 -28
@@ -1,22 +1,22 @@
1
- import { t as createAuthConsole } from "./console-runtime-Bg_PAl7e.js";
1
+ import { t as createAuthConsole } from "./console-runtime-BlOx9hWC.js";
2
2
  import { t as isRecord } from "./object-CAK6UYR5.js";
3
- import { i as resolveAuthMountPath, n as canonicalAccessPath } from "./application-path-zKi7NrvK.js";
4
- import { o as normalizeAuthBasePath } from "./access-pages-Bej95blM.js";
3
+ import { i as resolveAuthMountPath, n as canonicalAccessPath } from "./application-path-LMc_ptL9.js";
4
+ import { o as normalizeAuthBasePath } from "./access-pages-lQGfRvfL.js";
5
5
  import { t as hasRole } from "./roles-BGi8CyBG.js";
6
- import { n as authRequestEvent, r as unwrapAuthRequest } from "./request-Dpq7GO8B.js";
7
- import { n as clientRequestOrigin } from "./client-request-BzMKtfCY.js";
8
- import { _ as setAuthResponseOutcome, a as getAuthForDefinition, c as withSessionMarker, d as withEndpointRateLimits, f as eventClientAddress, g as setAuthOutcome, h as runWithAuthEvent, l as resolveAuthOptions, m as withClientAddress, n as createBetterAuthOptions, o as requestProvider, p as setRequestClientAddress, r as envResolverFor, s as resolveDefaultDefinition, t as authForRequest, u as trustsProxyHeaders } from "./auth-instance-5RSiFTDC.js";
9
- import { a as getAuthenticationSession, i as authenticationRefusalResponse, n as sendSessionCookies, r as authenticationRefusalError, t as prepareSessionCookies } from "./session-cookies-DN0svCKj.js";
6
+ import { n as authRequestEvent, r as unwrapAuthRequest } from "./request-CdlcvqVc.js";
7
+ import { a as clientRequestOrigin, r as mcpOAuthResources, t as isJwsToken } from "./mcp-config-DYlTXmr6.js";
8
+ import { _ as setAuthResponseOutcome, a as getAuthForDefinition, c as withSessionMarker, d as withEndpointRateLimits, f as eventClientAddress, g as setAuthOutcome, h as runWithAuthEvent, l as resolveAuthOptions, m as withClientAddress, n as createBetterAuthOptions, o as requestProvider, p as setRequestClientAddress, r as envResolverFor, s as resolveDefaultDefinition, t as authForRequest, u as trustsProxyHeaders } from "./auth-instance-0PTsOttV.js";
9
+ import { a as getAuthenticationSession, i as authenticationRefusalResponse, n as sendSessionCookies, r as authenticationRefusalError, t as prepareSessionCookies } from "./session-cookies-CfXdF1yd.js";
10
10
  import { t as getAuthRuntimeState } from "./runtime-state-C0Rd1W4m.js";
11
- import { t as readSetCookies } from "./set-cookie-CMB3t4NF.js";
11
+ import { t as readSetCookies } from "./set-cookie-BYZslovs.js";
12
12
  import { createAuthAccessRouteMatcher } from "./runtime/server.js";
13
- import { n as checkAbility, t as AbilityError } from "./ability-error-OKoyOwPM.js";
14
- import { i as parseAuthEventWindow, r as parseAuthEventList } from "./events-BUaoHFoC.js";
15
- import { t as authErrorDiagnostics } from "./error-diagnostics-DkzL9ltR.js";
16
- import { g as findAccessPolicyPlugin, i as notMemberError } from "./members-CRlYyxVk.js";
17
- import { n as mcpOAuthResources, t as isJwsToken } from "./mcp-config-C7srUMIZ.js";
13
+ import { n as checkAbility, t as AbilityError } from "./ability-error-Ccm5Iy4F.js";
14
+ import { i as parseAuthEventWindow, r as parseAuthEventList } from "./events-aP_Rz_gx.js";
15
+ import { t as authErrorDiagnostics } from "./error-diagnostics-BpQy1iIO.js";
16
+ import { g as findAccessPolicyPlugin, i as notMemberError } from "./members-USm08YwK.js";
18
17
  import { defineErrors, toResultError } from "@vite-hub/runtime";
19
18
  import { HTTPError } from "nitro/h3";
19
+ import { isRequest } from "@vite-hub/runtime/internal/response";
20
20
  import { parseUserOutput } from "better-auth/db";
21
21
  import abilities from "#vitehub/auth/abilities";
22
22
  import { isRuntimeResponse } from "@vite-hub/runtime/internal/runtime-type";
@@ -31,170 +31,6 @@ const callerErrors = /*#__PURE__*/ defineErrors({
31
31
  });
32
32
  const signedOutError = () => callerErrors.AUTH_SIGNED_OUT();
33
33
  // src/internal/server.ts
34
- function hasHappyDomRequestState(value) {
35
- const ownSymbols = Object.getOwnPropertySymbols(value);
36
- const prototypeSymbols = Object.getOwnPropertySymbols(Object.getPrototypeOf(value) ?? {});
37
- return [
38
- "method",
39
- "body",
40
- "mode",
41
- "headers",
42
- "redirect",
43
- "referrerPolicy",
44
- "signal",
45
- "bodyUsed",
46
- "credentials",
47
- "aborted",
48
- "error",
49
- "contentLength",
50
- "contentType",
51
- "referrer",
52
- "url",
53
- "bodyBuffer"
54
- ].every((name) => ownSymbols.some((symbol) => symbol.description === name)) && prototypeSymbols.some((symbol) => symbol.description === "window");
55
- }
56
- function isRequestLike$1(value) {
57
- try {
58
- const isBrandCheckError = (error) => {
59
- if (typeof error !== "object" && typeof error !== "function" || error === null) return false;
60
- try {
61
- if (Object.prototype.toString.call(error) !== "[object Error]") return false;
62
- } catch {
63
- return false;
64
- }
65
- let name;
66
- let message;
67
- try {
68
- name = Reflect.get(error, "name");
69
- message = Reflect.get(error, "message");
70
- } catch {
71
- return false;
72
- }
73
- return name === "TypeError" && typeof message === "string" && /illegal invocation|invalid (this|receiver)|brand|cannot read properties of (?:null|undefined)|must be (?:an? )?instance/i.test(message);
74
- };
75
- if (Object.prototype.toString.call(value) !== "[object Request]") return false;
76
- const hasPrototypeTag = (target, tag) => {
77
- let prototype = Object.getPrototypeOf(target);
78
- while (prototype) {
79
- const descriptor = Object.getOwnPropertyDescriptor(prototype, Symbol.toStringTag);
80
- if (descriptor) {
81
- if (typeof descriptor.get === "function") return descriptor.get.call(target) === tag;
82
- return "value" in descriptor && descriptor.value === tag;
83
- }
84
- prototype = Object.getPrototypeOf(prototype);
85
- }
86
- return false;
87
- };
88
- const hasBrandedAccessor = (target, property) => {
89
- let current = Object.getPrototypeOf(target);
90
- while (current) {
91
- const descriptor = Object.getOwnPropertyDescriptor(current, property);
92
- if (descriptor) {
93
- if (typeof descriptor.get !== "function") return false;
94
- try {
95
- descriptor.get.call(Object.create(null));
96
- if (target !== value) return false;
97
- return hasHappyDomRequestState(value);
98
- } catch (error) {
99
- if (!isBrandCheckError(error)) return false;
100
- return true;
101
- }
102
- }
103
- current = Object.getPrototypeOf(current);
104
- }
105
- return false;
106
- };
107
- if (!hasPrototypeTag(value, "Request")) return false;
108
- const hasMethods = (target, methods) => methods.every((method) => {
109
- return typeof Reflect.get(target, method) === "function";
110
- });
111
- if (hasHappyDomRequestState(value)) {
112
- if (!hasMethods(value, [
113
- "clone",
114
- "arrayBuffer",
115
- "blob",
116
- "formData",
117
- "json",
118
- "text"
119
- ])) return false;
120
- if (!value.headers || !hasMethods(value.headers, [
121
- "get",
122
- "has",
123
- "set",
124
- "append",
125
- "delete",
126
- "entries",
127
- "forEach"
128
- ])) return false;
129
- if (!value.signal || typeof value.signal.aborted !== "boolean") return false;
130
- return true;
131
- }
132
- if (![
133
- "body",
134
- "bodyUsed",
135
- "headers",
136
- "method",
137
- "signal",
138
- "url"
139
- ].every((property) => hasBrandedAccessor(value, property))) return false;
140
- if (!hasMethods(value, [
141
- "clone",
142
- "arrayBuffer",
143
- "blob",
144
- "formData",
145
- "json",
146
- "text"
147
- ])) return false;
148
- if (!value.headers || Object.prototype.toString.call(value.headers) !== "[object Headers]" || !hasPrototypeTag(value.headers, "Headers") || !hasMethods(value.headers, [
149
- "get",
150
- "has",
151
- "set",
152
- "append",
153
- "delete",
154
- "entries",
155
- "forEach"
156
- ])) return false;
157
- if ([
158
- "get",
159
- "has",
160
- "set",
161
- "append",
162
- "delete",
163
- "entries",
164
- "forEach"
165
- ].some((method) => Object.prototype.hasOwnProperty.call(value.headers, method))) return false;
166
- const headersGet = Reflect.get(value.headers, "get");
167
- if (typeof headersGet !== "function") return false;
168
- try {
169
- headersGet.call(Object.create(null), "");
170
- return false;
171
- } catch (error) {
172
- if (!isBrandCheckError(error)) return false;
173
- }
174
- if (!value.signal || Object.prototype.toString.call(value.signal) !== "[object AbortSignal]" || !hasPrototypeTag(value.signal, "AbortSignal") || typeof value.signal.aborted !== "boolean") return false;
175
- if (Object.prototype.hasOwnProperty.call(value.signal, "aborted")) return false;
176
- return true;
177
- } catch {
178
- return false;
179
- }
180
- }
181
- function isAbortSignalLike(value) {
182
- if (!value || typeof value !== "object" && typeof value !== "function") return false;
183
- try {
184
- let prototype = Object.getPrototypeOf(value);
185
- const seen = /* @__PURE__ */ new Set();
186
- while (prototype && !seen.has(prototype)) {
187
- seen.add(prototype);
188
- const descriptor = Object.getOwnPropertyDescriptor(prototype, "aborted");
189
- if (descriptor?.get) return typeof Reflect.apply(descriptor.get, value, []) === "boolean";
190
- prototype = Object.getPrototypeOf(prototype);
191
- }
192
- } catch {
193
- return false;
194
- }
195
- return false;
196
- }
197
- /** The provider sign-in of `access`, which returns to `afterSignIn`. A sign-in page has none: the page signs in. */
198
34
  function providerSignIn(options) {
199
35
  const access = options.access;
200
36
  const signIn = access?.signIn;
@@ -203,10 +39,6 @@ function providerSignIn(options) {
203
39
  callbackURL: `${resolveAuthMountPath("/")}${(appPath(access?.afterSignIn ?? "/") ?? "/").slice(1)}`
204
40
  } : void 0;
205
41
  }
206
- /**
207
- * The Headers init of a host request. A Headers-like object without `Symbol.iterator`, from another
208
- * Fetch implementation, gives its fields through `entries()`, not through its own properties.
209
- */
210
42
  function headersInit(headers) {
211
43
  const value = headers;
212
44
  if (typeof value !== "object" || value === null || typeof Reflect.get(value, Symbol.iterator) === "function") return headers;
@@ -215,10 +47,10 @@ function headersInit(headers) {
215
47
  return Array.from(Reflect.apply(entries, value, []));
216
48
  }
217
49
  function toRequest(request) {
218
- if (request instanceof Request || isRequestLike$1(request)) return request;
50
+ if (isRequest(request)) return request;
219
51
  const init = { method: request.method };
220
52
  init.headers = new Headers(headersInit(request.headers));
221
- if (isAbortSignalLike(request.signal)) init.signal = request.signal;
53
+ if (request.signal instanceof AbortSignal) init.signal = request.signal;
222
54
  if (request.body) {
223
55
  init.body = request.body;
224
56
  init.duplex = "half";
@@ -257,10 +89,6 @@ function handleAuthRequest(definition, input, event = authRequestEvent(input)) {
257
89
  return response;
258
90
  });
259
91
  }
260
- /**
261
- * With a provider in `access.signIn`, the Auth route also answers `GET <basePath>/sign-in` and `GET <basePath>/sign-out`, so a link
262
- * can sign in or out and come back to `?redirect=`. Better Auth has no GET endpoint at these paths.
263
- */
264
92
  function handleSignInRoute(auth, options, request, address) {
265
93
  const signIn = providerSignIn(options);
266
94
  if (!signIn || request.method !== "GET") return;
@@ -313,10 +141,6 @@ function textResponse(text, status) {
313
141
  status
314
142
  });
315
143
  }
316
- /**
317
- * A path of this app, such as `/docs?tab=a`, URL-encoded for a `Location` header, or `null` for another value.
318
- * `//host` and `/\\host` open another site, so they are not paths.
319
- */
320
144
  function appPath(value) {
321
145
  if (!value.startsWith("/") || /^\/[/\\]/.test(value) || /[\u0000-\u001F\u007F]/.test(value)) return null;
322
146
  const url = new URL(value, "http://app.invalid");
@@ -415,10 +239,6 @@ function refusal(response, code) {
415
239
  refusalCodes.set(response, code);
416
240
  return response;
417
241
  }
418
- /**
419
- * A refusal in H3's JSON error format, the same body that `requireAuth()` and H3 errors send. The phrase also goes on
420
- * the status line.
421
- */
422
242
  function createRefusalResponse(code) {
423
243
  const status = code === "SIGNED_OUT" ? 401 : 403;
424
244
  const statusText = code === "SIGNED_OUT" ? "Unauthorized" : "Forbidden";
@@ -432,10 +252,6 @@ function createRefusalResponse(code) {
432
252
  statusText
433
253
  }), code);
434
254
  }
435
- /**
436
- * A text 403 for an HTML request. The phrase on the status line is also the `statusText` of the error that the inline
437
- * guards throw.
438
- */
439
255
  function createTextRefusalResponse(text, code) {
440
256
  return refusal(new Response(text, {
441
257
  headers: { "content-type": "text/plain; charset=utf-8" },
@@ -443,7 +259,6 @@ function createTextRefusalResponse(text, code) {
443
259
  statusText: "Forbidden"
444
260
  }), code);
445
261
  }
446
- /** Better Auth's refusal of the credentials of the request, such as an invalid key of the API Key plugin. */
447
262
  function createProviderRefusalResponse(provider) {
448
263
  const response = authenticationRefusalResponse(provider);
449
264
  if (provider.code) refusalCodes.set(response, provider.code);
@@ -548,10 +363,6 @@ function logRefusal(input, response) {
548
363
  });
549
364
  }
550
365
  const nativeResponseClone = Object.getOwnPropertyDescriptor(Response.prototype, "clone")?.value;
551
- /**
552
- * A Response of this runtime with an own `then` would be assimilated as a thenable by the host that awaits it.
553
- * Send a native clone instead, so the rejection still reaches the client as a Response.
554
- */
555
366
  function sendableRuntimeResponse(value, request) {
556
367
  if (!Object.prototype.hasOwnProperty.call(value, "then")) return value;
557
368
  try {
@@ -560,150 +371,10 @@ function sendableRuntimeResponse(value, request) {
560
371
  return createForbiddenResponse(request);
561
372
  }
562
373
  }
563
- const nativePromiseThen = Object.getOwnPropertyDescriptor(Promise.prototype, "then")?.value;
564
- const nativePromiseResolve = Promise.resolve;
565
- function hasNativePromiseBrand(value) {
566
- if (!nativePromiseThen) return false;
567
- try {
568
- let prototype = Object.getPrototypeOf(value);
569
- const seen = /* @__PURE__ */ new Set();
570
- while (prototype && !seen.has(prototype)) {
571
- seen.add(prototype);
572
- if (Object.prototype.hasOwnProperty.call(prototype, "then") && Object.getOwnPropertyDescriptor(prototype, "then")?.value === nativePromiseThen) return true;
573
- prototype = Object.getPrototypeOf(prototype);
574
- }
575
- const valueDescriptor = Object.getOwnPropertyDescriptor(value, "constructor");
576
- let valueOverridden = false;
577
- try {
578
- if (!valueDescriptor || valueDescriptor.configurable) {
579
- Object.defineProperty(value, "constructor", {
580
- configurable: true,
581
- writable: true,
582
- value: Promise
583
- });
584
- valueOverridden = true;
585
- } else if ("value" in valueDescriptor && valueDescriptor.writable) {
586
- Object.defineProperty(value, "constructor", { value: Promise });
587
- valueOverridden = true;
588
- }
589
- } catch {}
590
- let probe;
591
- try {
592
- probe = Reflect.apply(nativePromiseThen, value, [() => void 0, () => void 0]);
593
- } finally {
594
- if (valueOverridden) {
595
- if (valueDescriptor) Object.defineProperty(value, "constructor", valueDescriptor);
596
- else Reflect.deleteProperty(value, "constructor");
597
- }
598
- }
599
- if (probe && (typeof probe === "object" || typeof probe === "function")) {
600
- const descriptor = Object.getOwnPropertyDescriptor(probe, "constructor");
601
- let overridden = false;
602
- try {
603
- if (!descriptor || descriptor.configurable) {
604
- Object.defineProperty(probe, "constructor", {
605
- configurable: true,
606
- writable: true,
607
- value: Promise
608
- });
609
- overridden = true;
610
- } else if ("value" in descriptor && descriptor.writable) {
611
- Object.defineProperty(probe, "constructor", { value: Promise });
612
- overridden = true;
613
- }
614
- const cleanup = Reflect.apply(nativePromiseThen, probe, [() => void 0, () => void 0]);
615
- if (cleanup && (typeof cleanup === "object" || typeof cleanup === "function")) {
616
- const cleanupDescriptor = Object.getOwnPropertyDescriptor(cleanup, "constructor");
617
- let cleanupOverridden = false;
618
- try {
619
- if (!cleanupDescriptor || cleanupDescriptor.configurable) {
620
- Object.defineProperty(cleanup, "constructor", {
621
- configurable: true,
622
- writable: true,
623
- value: Promise
624
- });
625
- cleanupOverridden = true;
626
- } else if ("value" in cleanupDescriptor && cleanupDescriptor.writable) {
627
- Object.defineProperty(cleanup, "constructor", { value: Promise });
628
- cleanupOverridden = true;
629
- }
630
- const cleanupResult = Reflect.apply(nativePromiseThen, cleanup, [() => void 0, () => void 0]);
631
- if (cleanupResult && (typeof cleanupResult === "object" || typeof cleanupResult === "function")) Reflect.apply(nativePromiseThen, cleanupResult, [() => void 0, () => void 0]);
632
- } finally {
633
- if (cleanupOverridden) {
634
- if (cleanupDescriptor) Object.defineProperty(cleanup, "constructor", cleanupDescriptor);
635
- else Reflect.deleteProperty(cleanup, "constructor");
636
- }
637
- }
638
- }
639
- } finally {
640
- if (overridden) {
641
- if (descriptor) Object.defineProperty(probe, "constructor", descriptor);
642
- else Reflect.deleteProperty(probe, "constructor");
643
- }
644
- }
645
- }
646
- return true;
647
- } catch {
648
- return false;
649
- }
650
- }
651
- /**
652
- * Only `true` grants access. A Response of this runtime is sent as the rejection. Every other value gets `deny()`, `403` by default.
653
- */
654
374
  async function runAccessAuthorize(authorize, context, deny = () => createForbiddenResponse(context.request)) {
655
375
  const result = authorize(context);
656
376
  if (isRuntimeResponse(result)) return { response: sendableRuntimeResponse(result, context.request) };
657
- let resolved;
658
- if (result !== null && (typeof result === "object" || typeof result === "function") && hasNativePromiseBrand(result)) {
659
- let nativePromise;
660
- let constructorDescriptor;
661
- let speciesDescriptor;
662
- let speciesOverridden = false;
663
- let constructorOverridden = false;
664
- try {
665
- constructorDescriptor = Object.getOwnPropertyDescriptor(result, "constructor");
666
- if (!constructorDescriptor || constructorDescriptor.configurable) {
667
- Object.defineProperty(result, "constructor", {
668
- configurable: true,
669
- writable: true,
670
- value: Promise
671
- });
672
- constructorOverridden = true;
673
- } else if (typeof constructorDescriptor.value === "function") {
674
- speciesDescriptor = Object.getOwnPropertyDescriptor(constructorDescriptor.value, Symbol.species);
675
- if (!speciesDescriptor || speciesDescriptor.configurable) {
676
- Object.defineProperty(constructorDescriptor.value, Symbol.species, {
677
- configurable: true,
678
- value: Promise
679
- });
680
- speciesOverridden = true;
681
- } else if ("value" in constructorDescriptor && constructorDescriptor.writable) {
682
- Object.defineProperty(result, "constructor", { value: Promise });
683
- constructorOverridden = true;
684
- }
685
- }
686
- nativePromise = new Promise((resolve, reject) => {
687
- Promise.prototype.then.call(result, resolve, reject);
688
- });
689
- } catch (error) {
690
- try {
691
- nativePromise = Reflect.apply(nativePromiseResolve, Promise, [result]);
692
- } catch {
693
- nativePromise = Promise.reject(error);
694
- }
695
- } finally {
696
- if (constructorOverridden) {
697
- if (constructorDescriptor) Object.defineProperty(result, "constructor", constructorDescriptor);
698
- else Reflect.deleteProperty(result, "constructor");
699
- }
700
- if (speciesOverridden && constructorDescriptor && typeof constructorDescriptor.value === "function") {
701
- if (speciesDescriptor) Object.defineProperty(constructorDescriptor.value, Symbol.species, speciesDescriptor);
702
- else Reflect.deleteProperty(constructorDescriptor.value, Symbol.species);
703
- }
704
- }
705
- resolved = nativePromise ? await nativePromise : void 0;
706
- } else resolved = result !== null && (typeof result === "object" || typeof result === "function") ? await result : result;
377
+ const resolved = await result;
707
378
  if (resolved === true) return {};
708
379
  if (isRuntimeResponse(resolved)) return { response: sendableRuntimeResponse(resolved, context.request) };
709
380
  return { response: deny() };
@@ -804,11 +475,6 @@ function withAuthorization(authorize, handler, definition) {
804
475
  return sendSessionCookies(input, await handler(input, authorization));
805
476
  };
806
477
  }
807
- /**
808
- * The `HTTPError` that an inline guard throws for a rejection `Response`. It keeps the status and headers, such as
809
- * `location` and `set-cookie` of a sign-in redirect. JSON object fields stay in the error body; other JSON values
810
- * become `data`. Text becomes the error message, with H3's JSON content type.
811
- */
812
478
  async function rejectionError(response, code = refusalCodes.get(response)) {
813
479
  const headers = new Headers(response.headers);
814
480
  headers.delete("content-length");
@@ -846,6 +512,31 @@ function requireAuthorization(event, authorize, definition) {
846
512
  if (authorize !== true && typeof authorize !== "function") throw authErrorDiagnostics.AUTH_R0014({ message: "[vitehub] `authorize` must be true or a function." });
847
513
  return requireCheck(event, checkAuthorizeRequest(event, authorize, definition ?? resolveDefaultDefinition()));
848
514
  }
515
+ /**
516
+ * Route middleware that checks access before H3 applies `validate.query` and `validate.headers`.
517
+ * Put it in `middleware` of `defineHandler()` or `defineValidatedHandler()`.
518
+ * It returns nothing when the check passes, so the route answers with its handler.
519
+ * Without `authorize`, it rejects like `requireAuth()`. With `authorize`, it rejects like `requireAuthorization()`.
520
+ * For path parameters, call H3's `getValidatedRouterParams(event, schema)` in the handler after checking access.
521
+ *
522
+ * ```ts [server/api/inbox.get.ts]
523
+ * export default defineValidatedHandler({
524
+ * middleware: [authMiddleware()],
525
+ * validate: { query: v.object({ view: v.picklist(["open", "archived"]) }) },
526
+ * handler: async (event) => {
527
+ * const { user } = await requireAuth(event)
528
+ * return listInbox(user.id, event.url.searchParams.get("view"))
529
+ * },
530
+ * })
531
+ * ```
532
+ */
533
+ function authMiddleware(authorize) {
534
+ if (authorize !== void 0 && authorize !== true && typeof authorize !== "function") throw authErrorDiagnostics.AUTH_R0014({ message: "[vitehub] `authorize` must be true or a function." });
535
+ return async (event) => {
536
+ if (authorize === void 0) await requireAuth(event);
537
+ else await requireAuthorization(event, authorize);
538
+ };
539
+ }
849
540
  const callerReads = /* @__PURE__ */ new WeakMap();
850
541
  function requireCaller(event, definition = resolveDefaultDefinition()) {
851
542
  const request = unwrapAuthRequest(event);
@@ -866,7 +557,7 @@ async function readCaller(event, definition) {
866
557
  const auth = authForRequest(request, authRequestEvent(event), definition);
867
558
  const { options } = await auth.$context;
868
559
  if (isJwsToken(token) && mcpOAuthResources(options.plugins).length) {
869
- const { verifyAppAccessToken } = await import("./mcp-token-DgveSGEl.js").then((n) => n.a);
560
+ const { verifyAppAccessToken } = await import("./mcp-token-i-8NMulH.js").then((n) => n.a);
870
561
  const url = new URL(request.url);
871
562
  const [error, caller] = await verifyAppAccessToken(token, clientRequestOrigin(request, trustsProxyHeaders(options)), url, auth);
872
563
  if (error) return [error, void 0];
@@ -1023,4 +714,4 @@ function getAuthConsoleForRequest(request, event, host) {
1023
714
  });
1024
715
  return createAuthConsole(requestProvider(definition, resolved), resolved.options.console, resolved.options.events ? resolved.options.events.store : void 0, host);
1025
716
  }
1026
- export { toAuthRequest as C, withAuthorization as D, withAuth as E, signOut as S, withAnonymousAuthorization as T, requireAbility as _, checkAuthMember as a, requireAuthorization as b, createAuthForRequest as c, getAuth as d, getAuthConsoleForRequest as f, listAuthEvents as g, handleAuthRequest as h, can as i, createAuthHandler as l, handleAuth as m, assertAuthOrigin as n, createAuth as o, getAuthEvents as p, authRoute as r, createAuthAccessHandler as s, aggregateAuthEvents as t, createAuthRequestRuntimeOptions as u, requireAuth as v, useAuth as w, requireCaller as x, requireAuthAccessRoutes as y };
717
+ export { signOut as C, withAuth as D, withAnonymousAuthorization as E, withAuthorization as O, requireCaller as S, useAuth as T, listAuthEvents as _, can as a, requireAuthAccessRoutes as b, createAuthAccessHandler as c, createAuthRequestRuntimeOptions as d, getAuth as f, handleAuthRequest as g, handleAuth as h, authRoute as i, createAuthForRequest as l, getAuthEvents as m, assertAuthOrigin as n, checkAuthMember as o, getAuthConsoleForRequest as p, authMiddleware as r, createAuth as s, aggregateAuthEvents as t, createAuthHandler as u, requireAbility as v, toAuthRequest as w, requireAuthorization as x, requireAuth as y };
@@ -1,5 +1,6 @@
1
- import "./own-access-BvVUjaeL.js";
2
- import { E as AuthRequestInput, H as ResolvedAuthAccessRoute, _ as AuthDefinition } from "./types-BmRGse4l.js";
1
+ import "./extension-C2giF7w2.js";
2
+ import "./own-access-B7VRd92K.js";
3
+ import { E as AuthRequestInput, U as ResolvedAuthAccessRoute, _ as AuthDefinition } from "./types-DakualFJ.js";
3
4
  import { AccessAuthorizationContext, ViteHubContext } from "@vite-hub/runtime";
4
5
  type AuthRuntimeEnvResolver = (event?: ViteHubContext) => Record<string, unknown>;
5
6
  type AuthAccessIdentityResolver = (request: Request, event: AuthRequestInput, hasSession: boolean) => Promise<AccessAuthorizationContext<unknown, false>["user"] | Response | undefined>;
package/dist/server.d.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  /// <reference path="./host-declarations.d.ts" />
2
- import { B as AuthMemberErrorCode, C as requireCaller, D as withAnonymousAuthorization, E as useAuth, F as AuthCaller, I as AuthCallerError, L as AuthCallerErrorCode, O as withAuth, R as AuthCallerResult, S as requireAuthorization, a as authRoute, b as requireAuth, d as createAuthHandler, g as handleAuth, h as getAuthEvents, k as withAuthorization, m as getAuthConsoleForRequest, o as can, r as aggregateAuthEvents, s as checkAuthMember, t as AuthEventReadErrorCode, v as listAuthEvents, w as signOut, y as requireAbility, z as AuthCallerUser } from "./server-1G_BbfBD.js";
3
- import { a as McpTokenInvalidData, o as McpTokenInvalidError, s as McpTokenInvalidReason } from "./mcp-token-DG1jmw4o.js";
2
+ import { A as withAuthorization, B as AuthCallerUser, C as requireAuthorization, D as useAuth, I as AuthCaller, L as AuthCallerError, O as withAnonymousAuthorization, R as AuthCallerErrorCode, T as signOut, V as AuthMemberErrorCode, _ as handleAuth, a as authMiddleware, b as requireAbility, c as checkAuthMember, f as createAuthHandler, g as getAuthEvents, h as getAuthConsoleForRequest, k as withAuth, o as authRoute, r as aggregateAuthEvents, s as can, t as AuthEventReadErrorCode, w as requireCaller, x as requireAuth, y as listAuthEvents, z as AuthCallerResult } from "./server-4_EXgXFn.js";
3
+ import { a as McpTokenInvalidData, o as McpTokenInvalidError, s as McpTokenInvalidReason } from "./mcp-token-CxpopXmK.js";
4
4
  import { n as AbilityErrorData, t as AbilityError } from "./ability-error-C1c30O6E.js";
5
5
  import { AuthContext } from "better-auth";
6
6
  /** Whether the resolved Auth context applies `VITEHUB_MEMBERS`. */
7
7
  export declare function hasAuthMembers(context: Pick<AuthContext, "options">): boolean;
8
- export { AbilityError, type AbilityErrorData, type AuthCaller, type AuthCallerError, type AuthCallerErrorCode, type AuthCallerResult, type AuthCallerUser, type AuthEventReadErrorCode, type AuthMemberErrorCode, type McpTokenInvalidData, type McpTokenInvalidError, type McpTokenInvalidReason, aggregateAuthEvents, can, checkAuthMember, createAuthHandler, authRoute as default, getAuthConsoleForRequest, getAuthEvents, handleAuth, listAuthEvents, requireAbility, requireAuth, requireAuthorization, requireCaller, signOut, useAuth, withAnonymousAuthorization, withAuth, withAuthorization };
8
+ export { AbilityError, type AbilityErrorData, type AuthCaller, type AuthCallerError, type AuthCallerErrorCode, type AuthCallerResult, type AuthCallerUser, type AuthEventReadErrorCode, type AuthMemberErrorCode, type McpTokenInvalidData, type McpTokenInvalidError, type McpTokenInvalidReason, aggregateAuthEvents, authMiddleware, can, checkAuthMember, createAuthHandler, authRoute as default, getAuthConsoleForRequest, getAuthEvents, handleAuth, listAuthEvents, requireAbility, requireAuth, requireAuthorization, requireCaller, signOut, useAuth, withAnonymousAuthorization, withAuth, withAuthorization };
package/dist/server.js CHANGED
@@ -1,9 +1,9 @@
1
- import { g as findAccessPolicyPlugin } from "./members-CRlYyxVk.js";
2
- import { t as AbilityError } from "./ability-error-OKoyOwPM.js";
3
- import { D as withAuthorization, E as withAuth, S as signOut, T as withAnonymousAuthorization, _ as requireAbility, a as checkAuthMember, b as requireAuthorization, f as getAuthConsoleForRequest, g as listAuthEvents, i as can, l as createAuthHandler, m as handleAuth, p as getAuthEvents, r as authRoute, t as aggregateAuthEvents, v as requireAuth, w as useAuth, x as requireCaller } from "./server-iQNOXyfS.js";
1
+ import { g as findAccessPolicyPlugin } from "./members-USm08YwK.js";
2
+ import { t as AbilityError } from "./ability-error-Ccm5Iy4F.js";
3
+ import { C as signOut, D as withAuth, E as withAnonymousAuthorization, O as withAuthorization, S as requireCaller, T as useAuth, _ as listAuthEvents, a as can, h as handleAuth, i as authRoute, m as getAuthEvents, o as checkAuthMember, p as getAuthConsoleForRequest, r as authMiddleware, t as aggregateAuthEvents, u as createAuthHandler, v as requireAbility, x as requireAuthorization, y as requireAuth } from "./server-CZR2dVVp.js";
4
4
  // src/server.ts
5
5
  /** Whether the resolved Auth context applies `VITEHUB_MEMBERS`. */
6
6
  function hasAuthMembers(context) {
7
7
  return Boolean(findAccessPolicyPlugin(context.options.plugins)?.members);
8
8
  }
9
- export { AbilityError, aggregateAuthEvents, can, checkAuthMember, createAuthHandler, authRoute as default, getAuthConsoleForRequest, getAuthEvents, handleAuth, hasAuthMembers, listAuthEvents, requireAbility, requireAuth, requireAuthorization, requireCaller, signOut, useAuth, withAnonymousAuthorization, withAuth, withAuthorization };
9
+ export { AbilityError, aggregateAuthEvents, authMiddleware, can, checkAuthMember, createAuthHandler, authRoute as default, getAuthConsoleForRequest, getAuthEvents, handleAuth, hasAuthMembers, listAuthEvents, requireAbility, requireAuth, requireAuthorization, requireCaller, signOut, useAuth, withAnonymousAuthorization, withAuth, withAuthorization };
@@ -1,8 +1,9 @@
1
- import { t as authErrorDiagnostics } from "./error-diagnostics-DkzL9ltR.js";
2
- import { r as throwAuthenticationProviderError, t as readSetCookies } from "./set-cookie-CMB3t4NF.js";
1
+ import { t as authErrorDiagnostics } from "./error-diagnostics-BpQy1iIO.js";
2
+ import { r as throwAuthenticationProviderError, t as readSetCookies } from "./set-cookie-BYZslovs.js";
3
3
  import { t as isRecord } from "./object-CAK6UYR5.js";
4
- import { n as authRequestEvent } from "./request-Dpq7GO8B.js";
4
+ import { n as authRequestEvent } from "./request-CdlcvqVc.js";
5
5
  import { HTTPError } from "nitro/h3";
6
+ import { isResponse } from "@vite-hub/runtime/internal/response";
6
7
  import { getStandardContext } from "@vite-hub/runtime/internal/h3";
7
8
  // src/session.ts
8
9
  const apiErrorHeaders = Symbol.for("better-call:api-error-headers");
@@ -75,7 +76,6 @@ function readRecordProperty(value, property) {
75
76
  const nested = readProperty(value, property);
76
77
  return isRecord(nested) ? nested : void 0;
77
78
  }
78
- /** Reads the `{ headers, response }` result of `getSession({ returnHeaders: true })`. */
79
79
  function resolveAuthenticationSessionRead(value) {
80
80
  if (!isRecord(value) || !("response" in value)) return;
81
81
  const { headers, response } = value;
@@ -115,10 +115,6 @@ function isUnauthorizedApiError(error) {
115
115
  return false;
116
116
  }
117
117
  }
118
- /**
119
- * The refusal of a Better Auth `APIError` with a 4xx status, and all its headers. A `before` hook can pass headers to
120
- * the error, and better-call keeps the headers that the endpoint set before under its own key. Both reach the client.
121
- */
122
118
  function readClientApiError(error) {
123
119
  if (typeof error !== "object" || error === null) return;
124
120
  try {
@@ -192,7 +188,7 @@ function sendSessionCookies(input, outcome) {
192
188
  const standard = getStandardContext(authRequestEvent(input));
193
189
  const prepared = preparedSessionCookies.get(standard);
194
190
  if (!prepared) return outcome;
195
- const response = isResponseLike(outcome) ? outcome : void 0;
191
+ const response = isResponse(outcome) ? outcome : void 0;
196
192
  const headers = standard.res.headers;
197
193
  if (standard.vendor === "fetch") {
198
194
  if (!response) return outcome;
@@ -230,12 +226,6 @@ function withSessionCookies(response, cookies) {
230
226
  sent.headers.set("cache-control", cacheControl);
231
227
  return sent;
232
228
  }
233
- /**
234
- * Writes the Cache-Control of a response with session cookies in the prepared response. H3 sends the prepared value
235
- * over the one of the route, so the policy starts from the value that the response would have without the guards:
236
- * a prepared value that someone else wrote, else the value of the route. `route` is `undefined` when no guard has
237
- * seen the response yet.
238
- */
239
229
  function writeCacheControl(headers, prepared, route) {
240
230
  const current = headers.get("cache-control");
241
231
  const base = prepared.cacheControl && current === prepared.cacheControl.written ? prepared.cacheControl.replaced : current;
@@ -247,10 +237,6 @@ function writeCacheControl(headers, prepared, route) {
247
237
  written
248
238
  };
249
239
  }
250
- /**
251
- * Adds `private` to Cache-Control unless it already has `private` or `no-store`. The directives for the browser cache
252
- * stay, and `public` and `s-maxage`, which let a shared cache store the response, go.
253
- */
254
240
  function privateCacheControl(value) {
255
241
  const directives = (value ?? "").split(",").map((directive) => directive.trim()).filter(Boolean);
256
242
  if (directives.some((directive) => /^(?:private|no-store)\b/i.test(directive))) return value ?? "";
@@ -260,7 +246,6 @@ function cookieName(setCookie) {
260
246
  const end = setCookie.search(/[=;]/);
261
247
  return (end < 0 ? setCookie : setCookie.slice(0, end)).trim();
262
248
  }
263
- /** Removes these exact `Set-Cookie` values, once each, and keeps the others in their order. */
264
249
  function removeSetCookies(headers, values) {
265
250
  if (values.length === 0) return;
266
251
  const remove = [...values];
@@ -273,17 +258,4 @@ function removeSetCookies(headers, values) {
273
258
  headers.delete("set-cookie");
274
259
  for (const cookie of kept) headers.append("set-cookie", cookie);
275
260
  }
276
- /** A Response of this runtime, or of another Fetch implementation, such as `undici`. */
277
- function isResponseLike(value) {
278
- if (value instanceof Response) return true;
279
- if (value === null || typeof value !== "object") return false;
280
- try {
281
- if (Object.prototype.toString.call(value) !== "[object Response]") return false;
282
- const status = Reflect.get(value, "status");
283
- const headers = Reflect.get(value, "headers");
284
- return typeof status === "number" && typeof Reflect.get(value, "statusText") === "string" && typeof headers === "object" && headers !== null && typeof Reflect.get(headers, "get") === "function";
285
- } catch {
286
- return false;
287
- }
288
- }
289
261
  export { getAuthenticationSession as a, authenticationRefusalResponse as i, sendSessionCookies as n, authenticationRefusalError as r, prepareSessionCookies as t };
@@ -1,4 +1,4 @@
1
- import { t as authErrorDiagnostics } from "./error-diagnostics-DkzL9ltR.js";
1
+ import { t as authErrorDiagnostics } from "./error-diagnostics-BpQy1iIO.js";
2
2
  import { ViteHubError, isViteHubError } from "@vite-hub/runtime";
3
3
  // src/errors.ts
4
4
  function invalidAuthenticationErrorOptions() {