@vite-hub/auth 0.1.0 → 0.3.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 (89) hide show
  1. package/README.md +333 -49
  2. package/dist/abilities-DfAnFYwG.d.ts +93 -0
  3. package/dist/abilities.d.ts +2 -0
  4. package/dist/abilities.js +43 -0
  5. package/dist/ability-error-CqgBrBfR.js +91 -0
  6. package/dist/ability-error-DcgChwCN.d.ts +34 -0
  7. package/dist/admin-claim-code-CDipqeAU.js +22 -0
  8. package/dist/agent.d.ts +5 -5
  9. package/dist/agent.js +17 -9
  10. package/dist/application-path-DuTpfGFj.js +62 -0
  11. package/dist/auth-instance-CR6b1W80.js +1168 -0
  12. package/dist/bun-sqlite.d.ts +8 -0
  13. package/dist/cli-ubYJpAL_.d.ts +163 -0
  14. package/dist/cli.d.ts +1 -1
  15. package/dist/cli.js +47 -7
  16. package/dist/console-runtime-DTopBP-x.d.ts +71 -0
  17. package/dist/console-runtime-J9_Vx9pT.js +1166 -0
  18. package/dist/console-runtime.d.ts +3 -3
  19. package/dist/console-runtime.js +2 -819
  20. package/dist/console.d.ts +215 -3
  21. package/dist/console.js +1 -1
  22. package/dist/database-options-BRNef9oy.js +29 -0
  23. package/dist/database-schema-options-ENuRMduM.js +12 -0
  24. package/dist/database.d.ts +12 -0
  25. package/dist/database.js +45 -0
  26. package/dist/definition-CqQMcDEK.js +280 -0
  27. package/dist/error-diagnostics-C8XtVz0i.js +138 -0
  28. package/dist/{events-P7mI4IQb.js → events-ByzenEVj.js} +122 -4
  29. package/dist/forward.d.ts +50 -0
  30. package/dist/forward.js +120 -0
  31. package/dist/host-declarations.d.ts +2 -1
  32. package/dist/index.d.ts +24 -3
  33. package/dist/index.js +3 -102
  34. package/dist/internal/server.d.ts +5 -0
  35. package/dist/internal/server.js +858 -0
  36. package/dist/invariant-D8_xBqmZ.js +22 -0
  37. package/dist/mcp.d.ts +187 -0
  38. package/dist/mcp.js +353 -0
  39. package/dist/members-D9lfaEO_.js +533 -0
  40. package/dist/nuxt-bridge-Cl988STZ.js +44 -0
  41. package/dist/nuxt.d.ts +13 -5
  42. package/dist/nuxt.js +90 -13
  43. package/dist/object-Da1zyPCR.js +11 -0
  44. package/dist/page-tools-shared-l4eyj53D.js +19 -0
  45. package/dist/presets.js +1 -1
  46. package/dist/request-z6DHHmrb.js +47 -0
  47. package/dist/runtime/console.d.ts +3 -7
  48. package/dist/runtime/console.js +4 -42
  49. package/dist/runtime/empty-abilities.d.ts +5 -0
  50. package/dist/runtime/empty-abilities.js +4 -0
  51. package/dist/runtime/empty-client.d.ts +6 -0
  52. package/dist/runtime/empty-client.js +5 -0
  53. package/dist/runtime/empty-definition.d.ts +1 -1
  54. package/dist/runtime/nuxt.js +1 -1
  55. package/dist/runtime/server.d.ts +2 -0
  56. package/dist/runtime/server.js +77 -0
  57. package/dist/runtime/vue-nuxt.d.ts +3 -2
  58. package/dist/runtime/vue-nuxt.js +157 -5
  59. package/dist/runtime-state-ojQCzKOc.js +25 -0
  60. package/dist/schema.d.ts +137 -0
  61. package/dist/schema.js +147 -0
  62. package/dist/server-C0qnKN2W.d.ts +143 -0
  63. package/dist/server-bQGzVQ--.d.ts +41 -0
  64. package/dist/server.d.ts +3 -2
  65. package/dist/server.js +3 -3
  66. package/dist/session-cookies-BbH3UR2m.js +227 -0
  67. package/dist/{set-cookie-2as_DbHe.js → set-cookie-C8NOhdRE.js} +27 -12
  68. package/dist/{shared-DnpgYiLF.js → shared-BwcdRGxD.js} +2 -5
  69. package/dist/table-specs-8gq_FCaq.js +771 -0
  70. package/dist/table-specs-DbXyaXWs.d.ts +842 -0
  71. package/dist/test.d.ts +26 -0
  72. package/dist/test.js +25 -0
  73. package/dist/{events-BkmK2dFY.d.ts → types-CNaeH2Fd.d.ts} +240 -157
  74. package/dist/vite-CV400XXY.js +1556 -0
  75. package/dist/vite.d.ts +138 -20
  76. package/dist/vite.js +2 -2
  77. package/dist/vue.d.ts +330 -21
  78. package/dist/vue.js +583 -36
  79. package/package.json +84 -15
  80. package/dist/application-path-C290OAIs.js +0 -18
  81. package/dist/cli-mgXvsBtA.d.ts +0 -85
  82. package/dist/console-B7eERmGv.d.ts +0 -180
  83. package/dist/console-runtime-bZQtnX2Y.d.ts +0 -39
  84. package/dist/error-diagnostics-CL0yjHiM.js +0 -79
  85. package/dist/events-config-CjcFOhTE.js +0 -177
  86. package/dist/inspect-DPtsW8dB.d.ts +0 -36
  87. package/dist/server-B7LU19dS.js +0 -1730
  88. package/dist/server-CTD_JAww.d.ts +0 -77
  89. package/dist/vite-COWkwxsj.js +0 -990
@@ -0,0 +1,227 @@
1
+ import { t as authErrorDiagnostics } from "./error-diagnostics-C8XtVz0i.js";
2
+ import { r as throwAuthenticationProviderError, t as readSetCookies } from "./set-cookie-C8NOhdRE.js";
3
+ import { t as isRecord } from "./object-Da1zyPCR.js";
4
+ import { n as authRequestEvent } from "./request-z6DHHmrb.js";
5
+ import { getStandardContext } from "@vite-hub/runtime/internal/h3";
6
+ //#region src/session.ts
7
+ const apiErrorHeaders = Symbol.for("better-call:api-error-headers");
8
+ async function getAuthenticationSession(auth, input) {
9
+ const [api, getSession] = await readProvider(() => {
10
+ const api = readRecordProperty(auth, "api");
11
+ return [api, api && readProperty(api, "getSession")];
12
+ });
13
+ if (typeof getSession !== "function") throw authErrorDiagnostics.AUTH_R0011({ message: "Better Auth did not expose api.getSession()." });
14
+ const value = await readProvider(async () => {
15
+ try {
16
+ return await Reflect.apply(getSession, api, [{
17
+ ...input,
18
+ returnHeaders: true
19
+ }]);
20
+ } catch (cause) {
21
+ if (isUnauthorizedApiError(cause)) {
22
+ const headers = Reflect.get(cause, apiErrorHeaders);
23
+ return {
24
+ headers: headers instanceof Headers ? headers : void 0,
25
+ response: null
26
+ };
27
+ }
28
+ throw cause;
29
+ }
30
+ });
31
+ const read = await readProvider(() => resolveAuthenticationSessionRead(value));
32
+ if (!read) throw authErrorDiagnostics.AUTH_R0012({ message: "Better Auth returned an invalid session response." });
33
+ return read;
34
+ }
35
+ async function readProvider(read) {
36
+ try {
37
+ return await read();
38
+ } catch (cause) {
39
+ throwAuthenticationProviderError(cause, "get-session");
40
+ }
41
+ }
42
+ function readRecordProperty(value, property) {
43
+ if (!isRecord(value)) return;
44
+ const nested = readProperty(value, property);
45
+ return isRecord(nested) ? nested : void 0;
46
+ }
47
+ /** Reads the `{ headers, response }` result of `getSession({ returnHeaders: true })`. */
48
+ function resolveAuthenticationSessionRead(value) {
49
+ if (!isRecord(value) || !("response" in value)) return;
50
+ const { headers, response } = value;
51
+ if (headers !== void 0 && headers !== null && !(headers instanceof Headers)) return;
52
+ const setCookies = headers ? readSetCookies(headers) : [];
53
+ if (response === null) return {
54
+ session: null,
55
+ setCookies
56
+ };
57
+ const session = resolveAuthenticationSession(response);
58
+ return session && {
59
+ session,
60
+ setCookies
61
+ };
62
+ }
63
+ function resolveAuthenticationSession(value) {
64
+ if (!isRecord(value)) return;
65
+ const session = value.session;
66
+ const user = value.user;
67
+ if (!isRecord(session) || !isRecord(user)) return;
68
+ const userId = user.id;
69
+ if (typeof userId !== "string" || userId.length === 0) return;
70
+ return {
71
+ auth: value,
72
+ session,
73
+ user,
74
+ userId
75
+ };
76
+ }
77
+ function isUnauthorizedApiError(error) {
78
+ if (typeof error !== "object" || error === null) return false;
79
+ try {
80
+ if (Reflect.get(error, "name") !== "APIError" || Reflect.get(error, "statusCode") !== 401) return false;
81
+ const body = Reflect.get(error, "body");
82
+ return typeof body === "object" && body !== null && Reflect.get(body, "code") === "FAILED_TO_GET_SESSION";
83
+ } catch {
84
+ return false;
85
+ }
86
+ }
87
+ function readProperty(value, property) {
88
+ return value[property];
89
+ }
90
+ //#endregion
91
+ //#region src/session-cookies.ts
92
+ const preparedSessionCookies = /* @__PURE__ */ new WeakMap();
93
+ /**
94
+ * Puts the cookies that Better Auth set while it read the session in the prepared response of the request: the renewed
95
+ * session cookie after `session.updateAge`, a refreshed cookie cache, or the deletion of an ended session. Without them
96
+ * the browser keeps the old cookies and loses the session at their expiry, although the database extended it.
97
+ *
98
+ * Guards call this right after the read, so the cookies also go with a refusal or an error that comes later. H3 adds
99
+ * the prepared response to each response of the request. On a plain Fetch host, `sendSessionCookies()` moves them to
100
+ * the Response of a guard, and a route without one copies `res.headers` of Standard Context.
101
+ *
102
+ * A response with session cookies must stay out of shared caches. The guard cannot see the Cache-Control of the route
103
+ * here, so it asks for `no-store`, which no directive of the route is stricter than. `sendSessionCookies()` asks for
104
+ * `private` when it sees the response.
105
+ */
106
+ function prepareSessionCookies(input, setCookies) {
107
+ if (setCookies.length === 0) return;
108
+ const standard = getStandardContext(authRequestEvent(input));
109
+ let prepared = preparedSessionCookies.get(standard);
110
+ if (!prepared) preparedSessionCookies.set(standard, prepared = { cookies: [] });
111
+ const names = new Set(setCookies.map(cookieName));
112
+ const replaced = prepared.cookies.filter((cookie) => names.has(cookieName(cookie)));
113
+ prepared.cookies = [...prepared.cookies.filter((cookie) => !names.has(cookieName(cookie))), ...setCookies];
114
+ const headers = standard.res.headers;
115
+ if (!headers) return;
116
+ removeSetCookies(headers, replaced);
117
+ for (const cookie of setCookies) headers.append("set-cookie", cookie);
118
+ writeCacheControl(headers, prepared);
119
+ }
120
+ /**
121
+ * The last step of a guard that sees the outcome of the request: a refusal, or the value or Response of the route.
122
+ *
123
+ * A plain Fetch host sends only this Response, so the session cookies move from the prepared response to a copy of
124
+ * it, once, also for a Response of another Fetch implementation, such as `undici`. H3 adds the prepared response to
125
+ * the outcome itself. In both, a cookie that the Response sets itself wins over the session cookie of the same name,
126
+ * and the Cache-Control of the route becomes `private`, unless it already has `private` or `no-store`.
127
+ */
128
+ function sendSessionCookies(input, outcome) {
129
+ const standard = getStandardContext(authRequestEvent(input));
130
+ const prepared = preparedSessionCookies.get(standard);
131
+ if (!prepared) return outcome;
132
+ const response = isResponseLike(outcome) ? outcome : void 0;
133
+ const headers = standard.res.headers;
134
+ if (standard.vendor === "fetch") {
135
+ if (!response) return outcome;
136
+ preparedSessionCookies.delete(standard);
137
+ if (headers) {
138
+ removeSetCookies(headers, prepared.cookies);
139
+ if (prepared.cacheControl && headers.get("cache-control") === prepared.cacheControl.written) {
140
+ const { replaced } = prepared.cacheControl;
141
+ if (replaced === null) headers.delete("cache-control");
142
+ else headers.set("cache-control", replaced);
143
+ }
144
+ }
145
+ return withSessionCookies(response, prepared.cookies);
146
+ }
147
+ if (!headers) return outcome;
148
+ if (response) {
149
+ const own = new Set(readSetCookies(response.headers).map(cookieName));
150
+ removeSetCookies(headers, prepared.cookies.filter((cookie) => own.has(cookieName(cookie))));
151
+ prepared.cookies = prepared.cookies.filter((cookie) => !own.has(cookieName(cookie)));
152
+ }
153
+ writeCacheControl(headers, prepared, response?.headers.get("cache-control") ?? null);
154
+ return outcome;
155
+ }
156
+ function withSessionCookies(response, cookies) {
157
+ const own = new Set(readSetCookies(response.headers).map(cookieName));
158
+ const missing = cookies.filter((cookie) => !own.has(cookieName(cookie)));
159
+ const cacheControl = privateCacheControl(response.headers.get("cache-control"));
160
+ if (missing.length === 0 && cacheControl === response.headers.get("cache-control") && response instanceof Response) return response;
161
+ const sent = new Response(response.body, {
162
+ headers: response.headers,
163
+ status: response.status,
164
+ statusText: response.statusText
165
+ });
166
+ for (const cookie of missing) sent.headers.append("set-cookie", cookie);
167
+ sent.headers.set("cache-control", cacheControl);
168
+ return sent;
169
+ }
170
+ /**
171
+ * Writes the Cache-Control of a response with session cookies in the prepared response. H3 sends the prepared value
172
+ * over the one of the route, so the policy starts from the value that the response would have without the guards:
173
+ * a prepared value that someone else wrote, else the value of the route. `route` is `undefined` when no guard has
174
+ * seen the response yet.
175
+ */
176
+ function writeCacheControl(headers, prepared, route) {
177
+ const current = headers.get("cache-control");
178
+ const base = prepared.cacheControl && current === prepared.cacheControl.written ? prepared.cacheControl.replaced : current;
179
+ const value = base ?? route;
180
+ const written = value === void 0 ? "no-store" : privateCacheControl(value);
181
+ if (written !== current) headers.set("cache-control", written);
182
+ prepared.cacheControl = {
183
+ replaced: base,
184
+ written
185
+ };
186
+ }
187
+ /**
188
+ * Adds `private` to Cache-Control unless it already has `private` or `no-store`. The directives for the browser cache
189
+ * stay, and `public` and `s-maxage`, which let a shared cache store the response, go.
190
+ */
191
+ function privateCacheControl(value) {
192
+ const directives = (value ?? "").split(",").map((directive) => directive.trim()).filter(Boolean);
193
+ if (directives.some((directive) => /^(?:private|no-store)\b/i.test(directive))) return value ?? "";
194
+ return ["private", ...directives.filter((directive) => !/^(?:public|s-maxage)\b/i.test(directive))].join(", ");
195
+ }
196
+ function cookieName(setCookie) {
197
+ const end = setCookie.search(/[=;]/);
198
+ return (end < 0 ? setCookie : setCookie.slice(0, end)).trim();
199
+ }
200
+ /** Removes these exact `Set-Cookie` values, once each, and keeps the others in their order. */
201
+ function removeSetCookies(headers, values) {
202
+ if (values.length === 0) return;
203
+ const remove = [...values];
204
+ const kept = readSetCookies(headers).filter((cookie) => {
205
+ const index = remove.indexOf(cookie);
206
+ if (index < 0) return true;
207
+ remove.splice(index, 1);
208
+ return false;
209
+ });
210
+ headers.delete("set-cookie");
211
+ for (const cookie of kept) headers.append("set-cookie", cookie);
212
+ }
213
+ /** A Response of this runtime, or of another Fetch implementation, such as `undici`. */
214
+ function isResponseLike(value) {
215
+ if (value instanceof Response) return true;
216
+ if (value === null || typeof value !== "object") return false;
217
+ try {
218
+ if (Object.prototype.toString.call(value) !== "[object Response]") return false;
219
+ const status = Reflect.get(value, "status");
220
+ const headers = Reflect.get(value, "headers");
221
+ return typeof status === "number" && typeof Reflect.get(value, "statusText") === "string" && typeof headers === "object" && headers !== null && typeof Reflect.get(headers, "get") === "function";
222
+ } catch {
223
+ return false;
224
+ }
225
+ }
226
+ //#endregion
227
+ export { sendSessionCookies as n, getAuthenticationSession as r, prepareSessionCookies as t };
@@ -1,15 +1,30 @@
1
- //#region src/runtime-state.ts
2
- const authRuntimeStateKey = Symbol.for("vitehub.auth.runtime");
3
- function getAuthRuntimeState() {
4
- const globalScope = globalThis;
5
- globalScope[authRuntimeStateKey] ??= {};
6
- globalScope[authRuntimeStateKey].envResolvers ??= /* @__PURE__ */ new WeakMap();
7
- return globalScope[authRuntimeStateKey];
1
+ import { t as authErrorDiagnostics } from "./error-diagnostics-C8XtVz0i.js";
2
+ import { ViteHubError, isViteHubError } from "@vite-hub/runtime";
3
+ //#region src/errors.ts
4
+ function invalidAuthenticationErrorOptions() {
5
+ throw authErrorDiagnostics.AUTH_R0004({ message: "[vitehub] Invalid authentication error options." });
8
6
  }
9
- function resetAuth() {
10
- const state = getAuthRuntimeState();
11
- state.auth = void 0;
12
- state.definition = void 0;
7
+ function createAuthenticationProviderError(cause, operation) {
8
+ if (operation !== "get-auth-for-request" && operation !== "get-session" && operation !== "get-user") invalidAuthenticationErrorOptions();
9
+ return new ViteHubError("AUTH_PROVIDER_OPERATION_FAILED", "[vitehub] Authentication provider operation failed.", {
10
+ cause,
11
+ details: {
12
+ operation,
13
+ provider: "better-auth"
14
+ }
15
+ });
16
+ }
17
+ function throwAuthenticationProviderError(cause, operation) {
18
+ if (isViteHubError(cause) || isAuthenticationAbortError(cause)) throw cause;
19
+ throw createAuthenticationProviderError(cause, operation);
20
+ }
21
+ function isAuthenticationAbortError(error) {
22
+ if (typeof error !== "object" || error === null) return false;
23
+ try {
24
+ return Reflect.get(error, "name") === "AbortError";
25
+ } catch {
26
+ return false;
27
+ }
13
28
  }
14
29
  //#endregion
15
30
  //#region src/set-cookie.ts
@@ -72,4 +87,4 @@ function isKnownCookieAttribute(cookie, hasBoundaryWhitespace) {
72
87
  return hasBoundaryWhitespace || !lastAttribute.includes("=");
73
88
  }
74
89
  //#endregion
75
- export { getAuthRuntimeState as n, resetAuth as r, readSetCookies as t };
90
+ export { invalidAuthenticationErrorOptions as n, throwAuthenticationProviderError as r, readSetCookies as t };
@@ -1,4 +1,4 @@
1
- import { t as authErrorDiagnostics } from "./error-diagnostics-CL0yjHiM.js";
1
+ import { t as authErrorDiagnostics } from "./error-diagnostics-C8XtVz0i.js";
2
2
  //#region src/shared.ts
3
3
  const defaultAuthBasePath = "/api/auth";
4
4
  function normalizeAuthBasePath(value) {
@@ -8,8 +8,5 @@ function normalizeAuthBasePath(value) {
8
8
  if (!normalized) throw authErrorDiagnostics.AUTH_R0013({ message: "`defineAuth()` basePath must resolve to a non-empty path." });
9
9
  return normalized;
10
10
  }
11
- function isAuthRequestPath(pathname, basePath) {
12
- return basePath === "/" || pathname === basePath || pathname.startsWith(`${basePath}/`);
13
- }
14
11
  //#endregion
15
- export { normalizeAuthBasePath as n, isAuthRequestPath as t };
12
+ export { normalizeAuthBasePath as t };