@vite-hub/auth 0.0.4 → 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.
- package/README.md +443 -32
- package/dist/abilities-DfAnFYwG.d.ts +93 -0
- package/dist/abilities.d.ts +2 -0
- package/dist/abilities.js +43 -0
- package/dist/ability-error-CqgBrBfR.js +91 -0
- package/dist/ability-error-DcgChwCN.d.ts +34 -0
- package/dist/admin-claim-code-CDipqeAU.js +22 -0
- package/dist/agent.d.ts +23 -12
- package/dist/agent.js +30 -8
- package/dist/application-path-DuTpfGFj.js +62 -0
- package/dist/auth-instance-CR6b1W80.js +1168 -0
- package/dist/bun-sqlite.d.ts +8 -0
- package/dist/cli-ubYJpAL_.d.ts +163 -0
- package/dist/cli.d.ts +7 -0
- package/dist/cli.js +108 -0
- package/dist/console-runtime-DTopBP-x.d.ts +71 -0
- package/dist/console-runtime-J9_Vx9pT.js +1166 -0
- package/dist/console-runtime.d.ts +3 -0
- package/dist/console-runtime.js +2 -0
- package/dist/console-types-CmmnKGMx.js +38 -0
- package/dist/console.d.ts +219 -0
- package/dist/console.js +15 -0
- package/dist/database-options-BRNef9oy.js +29 -0
- package/dist/database-schema-options-ENuRMduM.js +12 -0
- package/dist/database.d.ts +12 -0
- package/dist/database.js +45 -0
- package/dist/definition-CqQMcDEK.js +280 -0
- package/dist/error-diagnostics-C8XtVz0i.js +138 -0
- package/dist/events-ByzenEVj.js +314 -0
- package/dist/forward.d.ts +50 -0
- package/dist/forward.js +120 -0
- package/dist/host-declarations.d.ts +6 -1
- package/dist/index.d.ts +26 -5
- package/dist/index.js +3 -95
- package/dist/internal/server.d.ts +5 -0
- package/dist/internal/server.js +858 -0
- package/dist/invariant-D8_xBqmZ.js +22 -0
- package/dist/mcp.d.ts +187 -0
- package/dist/mcp.js +353 -0
- package/dist/members-D9lfaEO_.js +533 -0
- package/dist/nuxt-bridge-Cl988STZ.js +44 -0
- package/dist/nuxt.d.ts +36 -7
- package/dist/nuxt.js +116 -7
- package/dist/object-Da1zyPCR.js +11 -0
- package/dist/page-tools-shared-l4eyj53D.js +19 -0
- package/dist/presets-BGZi6Dfu.d.ts +25 -0
- package/dist/presets.d.ts +2 -0
- package/dist/presets.js +32 -0
- package/dist/request-z6DHHmrb.js +47 -0
- package/dist/runtime/console.d.ts +3 -0
- package/dist/runtime/console.js +4 -0
- package/dist/runtime/empty-abilities.d.ts +5 -0
- package/dist/runtime/empty-abilities.js +4 -0
- package/dist/runtime/empty-client.d.ts +6 -0
- package/dist/runtime/empty-client.js +5 -0
- package/dist/runtime/empty-definition.d.ts +1 -2
- package/dist/runtime/nuxt.d.ts +2 -3
- package/dist/runtime/nuxt.js +3 -2
- package/dist/runtime/server.d.ts +2 -0
- package/dist/runtime/server.js +77 -0
- package/dist/runtime/vue-nuxt.d.ts +4 -0
- package/dist/runtime/vue-nuxt.js +160 -0
- package/dist/runtime-state-ojQCzKOc.js +25 -0
- package/dist/schema.d.ts +137 -0
- package/dist/schema.js +147 -0
- package/dist/server-C0qnKN2W.d.ts +143 -0
- package/dist/server-bQGzVQ--.d.ts +41 -0
- package/dist/server.d.ts +3 -22
- package/dist/server.js +3 -2
- package/dist/session-cookies-BbH3UR2m.js +227 -0
- package/dist/set-cookie-C8NOhdRE.js +90 -0
- package/dist/shared-BwcdRGxD.js +12 -0
- package/dist/table-specs-8gq_FCaq.js +771 -0
- package/dist/table-specs-DbXyaXWs.d.ts +842 -0
- package/dist/test.d.ts +26 -0
- package/dist/test.js +25 -0
- package/dist/types-CNaeH2Fd.d.ts +569 -0
- package/dist/vite-CV400XXY.js +1556 -0
- package/dist/vite.d.ts +145 -18
- package/dist/vite.js +2 -2
- package/dist/vue.d.ts +343 -17
- package/dist/vue.js +640 -15
- package/package.json +156 -27
- package/dist/server-BZn8iQrB.js +0 -370
- package/dist/shared-QSYBHaMG.js +0 -12
- package/dist/types-jaRlW3D1.d.ts +0 -117
- package/dist/vite-Cmey8ODS.js +0 -1018
package/dist/nuxt.js
CHANGED
|
@@ -1,18 +1,44 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { t as authErrorDiagnostics } from "./error-diagnostics-C8XtVz0i.js";
|
|
2
|
+
import { c as resolveAuthViteConfig, d as resolveViteHubProjectRoot, l as authAbilitiesCandidates, o as createAuthNitroConfig, s as hubAuth, u as resolveNuxtServerDirs } from "./vite-CV400XXY.js";
|
|
3
|
+
import { realpathSync } from "node:fs";
|
|
4
|
+
import { dirname, resolve } from "node:path";
|
|
3
5
|
import { fileURLToPath } from "node:url";
|
|
4
6
|
import { createEnvImportAliases, hubEnv } from "@vite-hub/env/vite";
|
|
5
7
|
//#region src/nuxt.ts
|
|
6
8
|
const composables = [
|
|
9
|
+
"useAbility",
|
|
7
10
|
"useAuthClient",
|
|
8
11
|
"useSession",
|
|
9
|
-
"useSignIn",
|
|
10
|
-
"useSignUp",
|
|
11
12
|
"useUserSession"
|
|
12
13
|
];
|
|
13
14
|
const nitroRegistered = /* @__PURE__ */ new WeakSet();
|
|
15
|
+
const vueBridgeRegistered = /* @__PURE__ */ new WeakSet();
|
|
16
|
+
const pageMetaRegistered = /* @__PURE__ */ new WeakSet();
|
|
17
|
+
const componentsRegistered = /* @__PURE__ */ new WeakSet();
|
|
18
|
+
const abilitiesWatchRegistered = /* @__PURE__ */ new WeakSet();
|
|
19
|
+
const manifestRegistered = /* @__PURE__ */ new WeakSet();
|
|
20
|
+
/** Better Auth's Vue client file, which `createAuthClient()` imports on first use. */
|
|
21
|
+
function resolveBetterAuthVueClient() {
|
|
22
|
+
try {
|
|
23
|
+
return realpathSync(fileURLToPath(import.meta.resolve("better-auth/vue")));
|
|
24
|
+
} catch {
|
|
25
|
+
return;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
14
28
|
function hubAuthNuxt(options = {}, nuxt) {
|
|
15
29
|
if (!nuxt) return;
|
|
30
|
+
nuxt.options.plugins ??= [];
|
|
31
|
+
const vueRuntimePlugin = fileURLToPath(new URL("./runtime/vue-nuxt.js", import.meta.url));
|
|
32
|
+
const ensureVueRuntimePlugin = () => {
|
|
33
|
+
const index = nuxt.options.plugins.findIndex((plugin) => typeof plugin === "string" ? plugin === vueRuntimePlugin : plugin.src === vueRuntimePlugin);
|
|
34
|
+
if (index === 0) return;
|
|
35
|
+
const bridge = index < 0 ? {
|
|
36
|
+
src: vueRuntimePlugin,
|
|
37
|
+
order: -1
|
|
38
|
+
} : nuxt.options.plugins.splice(index, 1)[0];
|
|
39
|
+
nuxt.options.plugins.unshift(bridge);
|
|
40
|
+
};
|
|
41
|
+
ensureVueRuntimePlugin();
|
|
16
42
|
nuxt.options.vite ??= {};
|
|
17
43
|
nuxt.options.vite.plugins ??= [];
|
|
18
44
|
const vitePlugins = nuxt.options.vite.plugins.flat(Infinity);
|
|
@@ -21,27 +47,110 @@ function hubAuthNuxt(options = {}, nuxt) {
|
|
|
21
47
|
const existingEnvPlugin = vitePlugins.find((plugin) => plugin?.name === "@vite-hub/env/vite");
|
|
22
48
|
const envPlugin = existingEnvPlugin || (options.env === false ? void 0 : hubEnv(options.env));
|
|
23
49
|
const envProjectRoot = envPlugin?.api.resolveProjectRoot(viteRoot) || configuredEnvProjectRoot;
|
|
24
|
-
if (options.env !== false && options.env?.projectRoot && existingEnvPlugin && envProjectRoot !== configuredEnvProjectRoot) throw
|
|
50
|
+
if (options.env !== false && options.env?.projectRoot && existingEnvPlugin && envProjectRoot !== configuredEnvProjectRoot) throw authErrorDiagnostics.AUTH_B0001({ message: "`@vite-hub/auth/nuxt` env.projectRoot must match the installed `@vite-hub/env/vite` plugin." });
|
|
25
51
|
if (options.env !== false && !existingEnvPlugin) nuxt.options.vite.plugins.push(envPlugin);
|
|
52
|
+
nuxt.options.vite.define = {
|
|
53
|
+
...nuxt.options.vite.define,
|
|
54
|
+
__VITEHUB_AUTH_APP_BASE_URL__: JSON.stringify(nuxt.options.app?.baseURL || "/")
|
|
55
|
+
};
|
|
26
56
|
const authPlugin = vitePlugins.find((plugin) => plugin?.name === "@vite-hub/auth/vite") || hubAuth(options.auth);
|
|
27
57
|
if (!vitePlugins.some((plugin) => plugin?.name === "@vite-hub/auth/vite")) nuxt.options.vite.plugins.push(authPlugin);
|
|
58
|
+
const resolveAuthOptions = () => options.auth;
|
|
59
|
+
const resolveAuthConfig = () => {
|
|
60
|
+
const configRoot = resolve(viteRoot);
|
|
61
|
+
const serverDirs = resolveNuxtServerDirs(nuxt.options);
|
|
62
|
+
const authOptions = resolveAuthOptions();
|
|
63
|
+
return resolveAuthViteConfig(authOptions, configRoot, { serverDirs }) ?? resolveAuthViteConfig(authOptions, resolveViteHubProjectRoot(configRoot), { serverDirs });
|
|
64
|
+
};
|
|
28
65
|
if (options.nitro !== false && !nitroRegistered.has(nuxt)) {
|
|
29
66
|
nitroRegistered.add(nuxt);
|
|
30
67
|
nuxt.hook?.("nitro:config", async (nitroConfig) => {
|
|
68
|
+
const authConfig = resolveAuthConfig();
|
|
69
|
+
if (authConfig) nitroConfig.alias = {
|
|
70
|
+
...nitroConfig.alias,
|
|
71
|
+
"#vitehub/auth/definition": authConfig.definition.handler,
|
|
72
|
+
...authConfig.abilities ? { "#vitehub/auth/abilities": authConfig.abilities } : {}
|
|
73
|
+
};
|
|
31
74
|
Object.assign(nitroConfig, createAuthNitroConfig(authPlugin, {
|
|
32
75
|
nitro: nitroConfig,
|
|
33
76
|
projectRoot: viteRoot,
|
|
34
|
-
serverDirs: nuxt.options
|
|
35
|
-
viteAuth: nuxt.options.vite?.auth
|
|
77
|
+
serverDirs: resolveNuxtServerDirs(nuxt.options)
|
|
36
78
|
}));
|
|
37
79
|
});
|
|
38
80
|
}
|
|
81
|
+
if (!vueBridgeRegistered.has(nuxt) && nuxt.hook) {
|
|
82
|
+
vueBridgeRegistered.add(nuxt);
|
|
83
|
+
nuxt.hook("modules:done", async () => {
|
|
84
|
+
ensureVueRuntimePlugin();
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
const authOptions = resolveAuthOptions();
|
|
88
|
+
const redirects = authOptions ? authOptions.redirects : void 0;
|
|
89
|
+
nuxt.options.runtimeConfig ??= {};
|
|
90
|
+
nuxt.options.runtimeConfig.public ??= {};
|
|
91
|
+
nuxt.options.runtimeConfig.public.vitehubAuth = authOptions === false ? false : {
|
|
92
|
+
basePath: resolveAuthConfig()?.basePath ?? "/api/auth",
|
|
93
|
+
redirects: {
|
|
94
|
+
login: redirects?.login ?? "/login",
|
|
95
|
+
guest: redirects?.guest ?? "/"
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
if (!pageMetaRegistered.has(nuxt) && nuxt.hook) {
|
|
99
|
+
pageMetaRegistered.add(nuxt);
|
|
100
|
+
nuxt.hook("prepare:types", ({ declarations }) => {
|
|
101
|
+
declarations.push(`declare module "#app" {\n interface PageMeta {\n /** Who may open the page. See https://vitehub.dev/docs/auth/protect-pages. */\n auth?: import("@vite-hub/auth/nuxt").AuthPageMeta\n }\n}`);
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
if (!componentsRegistered.has(nuxt) && nuxt.hook) {
|
|
105
|
+
componentsRegistered.add(nuxt);
|
|
106
|
+
const filePath = options.importsFrom || "@vite-hub/auth/vue";
|
|
107
|
+
nuxt.hook("components:extend", (components) => {
|
|
108
|
+
for (const name of ["Can", "Cannot"]) {
|
|
109
|
+
if (components.some((component) => component.pascalName === name)) continue;
|
|
110
|
+
components.push({
|
|
111
|
+
chunkName: `components/${name.toLowerCase()}`,
|
|
112
|
+
export: name,
|
|
113
|
+
filePath,
|
|
114
|
+
global: false,
|
|
115
|
+
kebabName: name.toLowerCase(),
|
|
116
|
+
meta: {},
|
|
117
|
+
mode: "all",
|
|
118
|
+
pascalName: name,
|
|
119
|
+
prefetch: false,
|
|
120
|
+
preload: false,
|
|
121
|
+
priority: 0,
|
|
122
|
+
shortPath: filePath
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
if (!manifestRegistered.has(nuxt) && nuxt.hook) {
|
|
128
|
+
manifestRegistered.add(nuxt);
|
|
129
|
+
nuxt.hook("build:manifest", (manifest) => {
|
|
130
|
+
const lazy = /* @__PURE__ */ new Set([resolveBetterAuthVueClient(), fileURLToPath(new URL("./vue.js", import.meta.url))]);
|
|
131
|
+
const root = nuxt.options.vite?.root || nuxt.options.srcDir || nuxt.options.rootDir || process.cwd();
|
|
132
|
+
const keys = new Set(Object.keys(manifest).filter((id) => lazy.has(resolve(root, id))));
|
|
133
|
+
if (!keys.size) return;
|
|
134
|
+
for (const chunk of Object.values(manifest)) chunk.dynamicImports &&= chunk.dynamicImports.filter((id) => !keys.has(id));
|
|
135
|
+
});
|
|
136
|
+
}
|
|
39
137
|
nuxt.options.imports ??= {};
|
|
40
138
|
nuxt.options.imports.imports ??= [];
|
|
41
139
|
for (const name of composables) if (!nuxt.options.imports.imports.some((entry) => entry.name === name)) nuxt.options.imports.imports.push({
|
|
42
140
|
from: options.importsFrom || "@vite-hub/auth/vue",
|
|
43
141
|
name
|
|
44
142
|
});
|
|
143
|
+
if (nuxt.options.dev && options.auth !== false && nuxt.hook && !abilitiesWatchRegistered.has(nuxt)) {
|
|
144
|
+
abilitiesWatchRegistered.add(nuxt);
|
|
145
|
+
const files = authAbilitiesCandidates(viteRoot, { serverDirs: resolveNuxtServerDirs(nuxt.options) });
|
|
146
|
+
nuxt.options.watch ??= [];
|
|
147
|
+
for (const directory of new Set([...files.app, ...files.layers].map(dirname))) if (!nuxt.options.watch.includes(directory)) nuxt.options.watch.push(directory);
|
|
148
|
+
nuxt.hook("builder:watch", async (event, path) => {
|
|
149
|
+
if (event !== "add" && event !== "unlink") return;
|
|
150
|
+
const candidates = authAbilitiesCandidates(viteRoot, { serverDirs: resolveNuxtServerDirs(nuxt.options) });
|
|
151
|
+
if ([...candidates.app, ...candidates.layers].includes(resolve(nuxt.options.rootDir || viteRoot, path))) await nuxt.callHook?.("restart");
|
|
152
|
+
});
|
|
153
|
+
}
|
|
45
154
|
if (options.env === false) return;
|
|
46
155
|
const envAliases = createEnvImportAliases({ projectRoot: envProjectRoot });
|
|
47
156
|
const runtimePlugin = fileURLToPath(new URL("./runtime/nuxt.js", import.meta.url));
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
//#region ../internal/src/object.ts
|
|
2
|
+
/** A non-null object that is not an array. Functions do not pass. */
|
|
3
|
+
function isRecord(value) {
|
|
4
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
5
|
+
}
|
|
6
|
+
/** A non-null object or a function that is not an array. */
|
|
7
|
+
function isRecordOrFunction(value) {
|
|
8
|
+
return Object(value) === value && !Array.isArray(value);
|
|
9
|
+
}
|
|
10
|
+
//#endregion
|
|
11
|
+
export { isRecordOrFunction as n, isRecord as t };
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
//#region ../internal/src/runtime/page-tools-shared.ts
|
|
2
|
+
/**
|
|
3
|
+
* The cookie that remembers the session route's answer for this browser: `1` when a tool allows the person, `0` when
|
|
4
|
+
* none does or the person turned the tools off. It is a hint, never a credential, and it is not HttpOnly, because the
|
|
5
|
+
* page's bootstrap script reads it.
|
|
6
|
+
*/
|
|
7
|
+
const viteHubPageToolsCookie = "vitehub-tools";
|
|
8
|
+
/**
|
|
9
|
+
* The cookie that tells page scripts that an app Auth session exists. `@vite-hub/auth` sets it to `1` next to the
|
|
10
|
+
* session cookie and clears it on sign-out. It is not HttpOnly and holds no secret.
|
|
11
|
+
*/
|
|
12
|
+
const viteHubSessionMarkerCookie = "vitehub_session";
|
|
13
|
+
/**
|
|
14
|
+
* The `Set-Cookie` value that forgets the session route's answer. Auth sends it when a session starts or ends, so the
|
|
15
|
+
* next page asks the session route again for the new person.
|
|
16
|
+
*/
|
|
17
|
+
const viteHubPageToolsResetCookie = `${viteHubPageToolsCookie}=; Path=/; Max-Age=0; SameSite=Lax`;
|
|
18
|
+
//#endregion
|
|
19
|
+
export { viteHubPageToolsResetCookie as n, viteHubSessionMarkerCookie as r, viteHubPageToolsCookie as t };
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
//#region src/presets.d.ts
|
|
2
|
+
/** A duration such as `"30m"`, `"12h"`, `"7d"`, or `"2w"`. */
|
|
3
|
+
type AuthDuration = `${number}${"s" | "m" | "h" | "d" | "w"}`;
|
|
4
|
+
interface AuthStatelessPresetOptions {
|
|
5
|
+
/**
|
|
6
|
+
* How long a session lasts after sign-in, in seconds or as a duration such as `"7d"`.
|
|
7
|
+
* The session cookie and the encrypted session data use the same age. Defaults to 7 days.
|
|
8
|
+
*/
|
|
9
|
+
maxAge?: number | AuthDuration;
|
|
10
|
+
}
|
|
11
|
+
/** Sessions in encrypted cookies, with no database. Create it with `stateless()`. */
|
|
12
|
+
interface AuthStatelessPreset {
|
|
13
|
+
readonly name: "stateless";
|
|
14
|
+
/** Session lifetime in seconds. */
|
|
15
|
+
readonly maxAge: number;
|
|
16
|
+
}
|
|
17
|
+
/** An Auth preset for the `preset` option of `defineAuth()`. */
|
|
18
|
+
type AuthPreset = AuthStatelessPreset;
|
|
19
|
+
/**
|
|
20
|
+
* Keep sessions in encrypted cookies, with no database. Sessions survive restarts and work across
|
|
21
|
+
* replicas and Workers when every instance uses the same secret. Use it with social providers.
|
|
22
|
+
*/
|
|
23
|
+
declare function stateless(options?: AuthStatelessPresetOptions): AuthStatelessPreset;
|
|
24
|
+
//#endregion
|
|
25
|
+
export { stateless as a, AuthStatelessPresetOptions as i, AuthPreset as n, AuthStatelessPreset as r, AuthDuration as t };
|
package/dist/presets.js
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { t as authErrorDiagnostics } from "./error-diagnostics-C8XtVz0i.js";
|
|
2
|
+
//#region src/presets.ts
|
|
3
|
+
const durationUnits = {
|
|
4
|
+
s: 1,
|
|
5
|
+
m: 60,
|
|
6
|
+
h: 3600,
|
|
7
|
+
d: 86400,
|
|
8
|
+
w: 604800
|
|
9
|
+
};
|
|
10
|
+
const defaultStatelessMaxAge = 604800;
|
|
11
|
+
function durationSeconds(value) {
|
|
12
|
+
if (typeof value === "number") return Number.isSafeInteger(value) && value > 0 ? value : void 0;
|
|
13
|
+
if (typeof value !== "string") return;
|
|
14
|
+
const match = /^(\d+(?:\.\d+)?)(s|m|h|d|w)$/.exec(value.trim());
|
|
15
|
+
if (!match) return;
|
|
16
|
+
const seconds = Math.round(Number(match[1]) * durationUnits[match[2]]);
|
|
17
|
+
return Number.isSafeInteger(seconds) && seconds > 0 ? seconds : void 0;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Keep sessions in encrypted cookies, with no database. Sessions survive restarts and work across
|
|
21
|
+
* replicas and Workers when every instance uses the same secret. Use it with social providers.
|
|
22
|
+
*/
|
|
23
|
+
function stateless(options = {}) {
|
|
24
|
+
const maxAge = options.maxAge === void 0 ? defaultStatelessMaxAge : durationSeconds(options.maxAge);
|
|
25
|
+
if (maxAge === void 0) throw authErrorDiagnostics.AUTH_C0049({ message: `\`stateless({ maxAge })\` must be a positive whole number of seconds or a duration such as "7d". Received ${JSON.stringify(options.maxAge)}.` });
|
|
26
|
+
return {
|
|
27
|
+
name: "stateless",
|
|
28
|
+
maxAge
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
//#endregion
|
|
32
|
+
export { stateless };
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { getStandardContext } from "@vite-hub/runtime/internal/h3";
|
|
2
|
+
//#region ../internal/src/runtime/cloudflare-env-lookup.ts
|
|
3
|
+
/** The key of the AsyncLocalStorage store on `globalThis`. Every bundled copy of this module shares the store. */
|
|
4
|
+
const activeEnvStorageKey = Symbol.for("vitehub.cloudflare.env-storage");
|
|
5
|
+
let activeEnv;
|
|
6
|
+
/** The store of the current `runWithActiveCloudflareEnv()` call, or undefined outside one. */
|
|
7
|
+
function getScopedCloudflareEnv() {
|
|
8
|
+
return globalThis[activeEnvStorageKey]?.getStore();
|
|
9
|
+
}
|
|
10
|
+
function getActiveCloudflareEnv() {
|
|
11
|
+
const scoped = getScopedCloudflareEnv();
|
|
12
|
+
if (scoped) return scoped.env;
|
|
13
|
+
const host = globalThis;
|
|
14
|
+
return Object.hasOwn(host, "__env__") && host.__env__ !== void 0 ? host.__env__ : activeEnv;
|
|
15
|
+
}
|
|
16
|
+
//#endregion
|
|
17
|
+
//#region src/request.ts
|
|
18
|
+
function isObjectLike(value) {
|
|
19
|
+
return value !== null && (typeof value === "object" || typeof value === "function");
|
|
20
|
+
}
|
|
21
|
+
/** A Web Request, also from another realm. A request event has no string `url` and `method` of its own. */
|
|
22
|
+
function isAuthRequest(input) {
|
|
23
|
+
if (input instanceof Request) return true;
|
|
24
|
+
if ("~standard" in input) return false;
|
|
25
|
+
const headers = Reflect.get(input, "headers");
|
|
26
|
+
return typeof Reflect.get(input, "url") === "string" && typeof Reflect.get(input, "method") === "string" && isObjectLike(headers) && typeof Reflect.get(headers, "get") === "function";
|
|
27
|
+
}
|
|
28
|
+
/** Return a Web Request itself, or the request in the Standard Context of a request event. */
|
|
29
|
+
function unwrapAuthRequest(input) {
|
|
30
|
+
return isAuthRequest(input) ? input : getStandardContext(input).req;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Return the object that carries the Standard Context of an Auth input: the request event, or the Web Request itself.
|
|
34
|
+
* A Request that no framework wrapped gets a Standard Context that reads the host data on it, such as srvx `ip` and
|
|
35
|
+
* `runtime.cloudflare`.
|
|
36
|
+
*/
|
|
37
|
+
function authRequestEvent(input) {
|
|
38
|
+
const value = input;
|
|
39
|
+
getStandardContext(value);
|
|
40
|
+
return value;
|
|
41
|
+
}
|
|
42
|
+
/** The Cloudflare bindings in the Standard Context of `event`, else the bindings of the active Cloudflare request. */
|
|
43
|
+
function authCloudflareEnv(event) {
|
|
44
|
+
return (event ? getStandardContext(event).runtime?.cloudflare?.env : void 0) ?? getActiveCloudflareEnv();
|
|
45
|
+
}
|
|
46
|
+
//#endregion
|
|
47
|
+
export { authRequestEvent as n, unwrapAuthRequest as r, authCloudflareEnv as t };
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { BetterAuthClientOptions } from "better-auth";
|
|
2
|
+
//#region src/runtime/empty-client.d.ts
|
|
3
|
+
/** The options of the default Auth client when the app has no `auth.client.ts`. */
|
|
4
|
+
declare const options: BetterAuthClientOptions | undefined;
|
|
5
|
+
//#endregion
|
|
6
|
+
export { options as default };
|
package/dist/runtime/nuxt.d.ts
CHANGED
package/dist/runtime/nuxt.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
|
+
import discoveredDefinition from "#vitehub/auth/definition";
|
|
1
2
|
import { useServerEnv } from "#vitehub/env/server";
|
|
2
|
-
import { setAuthRuntimeEnvResolver } from "@vite-hub/auth/server";
|
|
3
|
+
import { setAuthRuntimeEnvResolver } from "@vite-hub/auth/runtime/server";
|
|
3
4
|
//#region src/runtime/nuxt.ts
|
|
4
5
|
function viteHubAuthNuxtRuntime() {
|
|
5
|
-
setAuthRuntimeEnvResolver(useServerEnv);
|
|
6
|
+
setAuthRuntimeEnvResolver(useServerEnv, discoveredDefinition);
|
|
6
7
|
}
|
|
7
8
|
//#endregion
|
|
8
9
|
export { viteHubAuthNuxtRuntime as default };
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { a as setAuthAccessIdentityResolver, i as createLazyAuthAccessHandler, n as authAccessHandlerMeta, o as setAuthRuntimeEnvResolver, r as createAuthAccessRouteMatcher, t as AuthAccessRouteMatch } from "../server-bQGzVQ--.js";
|
|
2
|
+
export { AuthAccessRouteMatch, authAccessHandlerMeta, createAuthAccessRouteMatcher, createLazyAuthAccessHandler, setAuthAccessIdentityResolver, setAuthRuntimeEnvResolver };
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { r as unwrapAuthRequest } from "../request-z6DHHmrb.js";
|
|
2
|
+
import { n as getAuthRuntimeState } from "../runtime-state-ojQCzKOc.js";
|
|
3
|
+
import { n as canonicalAccessPath, r as resolveAccessRoutePath } from "../application-path-DuTpfGFj.js";
|
|
4
|
+
//#region src/runtime/server.ts
|
|
5
|
+
function setAuthRuntimeEnvResolver(resolver, definition) {
|
|
6
|
+
const state = getAuthRuntimeState();
|
|
7
|
+
if (definition) state.envResolvers?.set(definition, resolver);
|
|
8
|
+
else state.envResolver = resolver;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Let a trusted server integration authenticate one exact mounted path without a browser session.
|
|
12
|
+
* Resolved users still pass every matching Auth access route's authorize callback, with an empty session.
|
|
13
|
+
*/
|
|
14
|
+
function setAuthAccessIdentityResolver(path, resolver) {
|
|
15
|
+
const state = getAuthRuntimeState();
|
|
16
|
+
state.accessIdentityResolvers ??= /* @__PURE__ */ new Map();
|
|
17
|
+
if (resolver) state.accessIdentityResolvers.set(path, resolver);
|
|
18
|
+
else state.accessIdentityResolvers.delete(path);
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* The Nitro route `meta` of a handler that checks its own access, such as the ViteHub Console route. The access routes
|
|
22
|
+
* leave a request to the handler that Nitro routed it to when that handler has this meta, whatever its path and method.
|
|
23
|
+
* The exception follows the dispatch, so an app route file on the same path keeps the access routes.
|
|
24
|
+
*/
|
|
25
|
+
const authAccessHandlerMeta = Object.freeze({ vitehubAuthAccess: "handler" });
|
|
26
|
+
/** Whether Nitro routed the request event to a handler with `authAccessHandlerMeta`. A plain Request has no route. */
|
|
27
|
+
function routedToAccessHandler(input) {
|
|
28
|
+
if (!("context" in input) || !(input.context instanceof Object)) return false;
|
|
29
|
+
const route = Reflect.get(input.context, "matchedRoute");
|
|
30
|
+
const meta = route instanceof Object ? Reflect.get(route, "meta") : void 0;
|
|
31
|
+
return meta instanceof Object && Reflect.get(meta, "vitehubAuthAccess") === authAccessHandlerMeta.vitehubAuthAccess;
|
|
32
|
+
}
|
|
33
|
+
function matchesPath(rule, pathname) {
|
|
34
|
+
return pathname === rule.path || rule.recursive && (rule.path === "" || pathname.startsWith(`${rule.path}/`));
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Return a function that lists the access routes that match a request, in Definition order. A request to a path of
|
|
38
|
+
* `publicRoutes` matches no access route.
|
|
39
|
+
*/
|
|
40
|
+
function createAuthAccessRouteMatcher(routes, publicRoutes = []) {
|
|
41
|
+
const rules = routes.map((route, index) => ({
|
|
42
|
+
index,
|
|
43
|
+
authorize: route.authorize === true,
|
|
44
|
+
method: route.method?.toUpperCase(),
|
|
45
|
+
...resolveAccessRoutePath(route.route)
|
|
46
|
+
}));
|
|
47
|
+
const exceptions = publicRoutes.map((route) => resolveAccessRoutePath(route));
|
|
48
|
+
return (input) => {
|
|
49
|
+
if (routedToAccessHandler(input)) return [];
|
|
50
|
+
const request = unwrapAuthRequest(input);
|
|
51
|
+
const pathname = canonicalAccessPath(new URL(request.url).pathname);
|
|
52
|
+
if (exceptions.some((rule) => matchesPath(rule, pathname))) return [];
|
|
53
|
+
const method = request.method.toUpperCase();
|
|
54
|
+
return rules.filter((rule) => (!rule.method || rule.method === method || rule.method === "GET" && method === "HEAD") && matchesPath(rule, pathname)).map((rule) => ({
|
|
55
|
+
index: rule.index,
|
|
56
|
+
authorize: rule.authorize
|
|
57
|
+
}));
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* The access middleware of generated hosts. A request that no access route matches returns without loading `load()`,
|
|
62
|
+
* so the server starts without Better Auth.
|
|
63
|
+
*/
|
|
64
|
+
function createLazyAuthAccessHandler(routes, load, publicRoutes = []) {
|
|
65
|
+
const match = createAuthAccessRouteMatcher(routes, publicRoutes);
|
|
66
|
+
let handler;
|
|
67
|
+
return async (input) => {
|
|
68
|
+
if (match(input).length === 0) return;
|
|
69
|
+
handler ??= load().then((module) => module.createAuthAccessHandler(routes, void 0, publicRoutes)).catch((error) => {
|
|
70
|
+
handler = void 0;
|
|
71
|
+
throw error;
|
|
72
|
+
});
|
|
73
|
+
return await (await handler)(input);
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
//#endregion
|
|
77
|
+
export { authAccessHandlerMeta, createAuthAccessRouteMatcher, createLazyAuthAccessHandler, setAuthAccessIdentityResolver, setAuthRuntimeEnvResolver };
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import { i as resolveAuthMountPath } from "../application-path-DuTpfGFj.js";
|
|
2
|
+
import "../page-tools-shared-l4eyj53D.js";
|
|
3
|
+
import { a as setRequestFetchResolver, i as setNuxtErrorFactory, n as setDefaultAuthBasePath, o as setSessionSeedResolver, r as setNuxtAppResolver, s as setSignOutHandler } from "../nuxt-bridge-Cl988STZ.js";
|
|
4
|
+
import { addRouteMiddleware, createError, defineNuxtPlugin, navigateTo, tryUseNuxtApp, useRequestEvent, useRequestFetch, useRequestURL, useRouter, useRuntimeConfig, useState } from "#app";
|
|
5
|
+
//#region src/runtime/vue-nuxt.ts
|
|
6
|
+
const stateKey = "vitehub:auth:session";
|
|
7
|
+
/**
|
|
8
|
+
* True when the request may have a session: ViteHub's `vitehub_session` marker cookie, which Auth sets next to the
|
|
9
|
+
* session cookie, or Better Auth's own `<prefix>.session_token` and `<prefix>.session_data` cookies.
|
|
10
|
+
*/
|
|
11
|
+
function hasSessionCookie(cookie) {
|
|
12
|
+
if (!cookie) return false;
|
|
13
|
+
return cookie.split(";").map((part) => part.split("=")[0]?.trim() ?? "").some((name) => name === "vitehub_session" || /(?:^|\.)session_(?:token|data)$/.test(name));
|
|
14
|
+
}
|
|
15
|
+
const isoDate = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/;
|
|
16
|
+
/** Better Auth's client returns dates as `Date`. Revive them so the server's session has the same shape. */
|
|
17
|
+
function reviveDates(value) {
|
|
18
|
+
if (typeof value === "string" && isoDate.test(value)) return new Date(value);
|
|
19
|
+
if (Array.isArray(value)) return value.map(reviveDates);
|
|
20
|
+
if (typeof value === "object" && value !== null) return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, reviveDates(entry)]));
|
|
21
|
+
return value;
|
|
22
|
+
}
|
|
23
|
+
/** Forward Better Auth's `Set-Cookie` headers, such as a refreshed session, to the page response. */
|
|
24
|
+
function appendSetCookies(event, response) {
|
|
25
|
+
for (const cookie of response.headers.getSetCookie?.() ?? []) event.res?.headers?.append("set-cookie", cookie);
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* The path and query of a URL that Better Auth's client built. The client can build an absolute URL from a variable
|
|
29
|
+
* such as `VERCEL_URL`, and that URL would leave the process.
|
|
30
|
+
*/
|
|
31
|
+
function pathOf(input) {
|
|
32
|
+
const url = new URL(input instanceof Request ? input.url : String(input), "http://localhost");
|
|
33
|
+
return url.pathname + url.search;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* The fetch of the current page request for Better Auth's client, or `undefined` outside a request. Nuxt's request fetch
|
|
37
|
+
* calls the app in-process with the headers of the page request, such as the cookie, and its `native` form answers with
|
|
38
|
+
* the `Response` that Better Auth reads.
|
|
39
|
+
*/
|
|
40
|
+
function currentRequestFetch() {
|
|
41
|
+
const nuxtApp = tryUseNuxtApp();
|
|
42
|
+
const event = nuxtApp ? useRequestEvent() : void 0;
|
|
43
|
+
if (!nuxtApp || !event) return void 0;
|
|
44
|
+
const { native } = useRequestFetch();
|
|
45
|
+
const requestFetch = async (input, init) => {
|
|
46
|
+
const response = await native(pathOf(input), init);
|
|
47
|
+
appendSetCookies(event, response);
|
|
48
|
+
return response;
|
|
49
|
+
};
|
|
50
|
+
return {
|
|
51
|
+
request: nuxtApp,
|
|
52
|
+
origin: useRequestURL().origin,
|
|
53
|
+
fetch: requestFetch
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Reads the session of the request, so server rendering and hydration start signed in or signed out. Returns `null` at
|
|
58
|
+
* once when the request has no session cookie, else a promise. Call it in a Nuxt context.
|
|
59
|
+
*/
|
|
60
|
+
function readServerSession(basePath) {
|
|
61
|
+
const event = useRequestEvent();
|
|
62
|
+
if (!event) return void 0;
|
|
63
|
+
if (!hasSessionCookie(event.req?.headers?.get("cookie") ?? void 0)) return null;
|
|
64
|
+
return fetchServerSession(event, useRequestFetch(), basePath);
|
|
65
|
+
}
|
|
66
|
+
/** Asks Better Auth for the session with Nuxt's request fetch, which the caller got in a Nuxt context. */
|
|
67
|
+
async function fetchServerSession(event, fetch, basePath) {
|
|
68
|
+
try {
|
|
69
|
+
const data = await fetch(`${basePath}/get-session`, {
|
|
70
|
+
baseURL: "/",
|
|
71
|
+
onResponse: ({ response }) => appendSetCookies(event, response)
|
|
72
|
+
});
|
|
73
|
+
if (typeof data !== "object" || data === null) return null;
|
|
74
|
+
const session = Reflect.get(data, "session");
|
|
75
|
+
const user = Reflect.get(data, "user");
|
|
76
|
+
if (typeof session !== "object" || session === null || !user) return null;
|
|
77
|
+
const { token: _token, ...safeSession } = session;
|
|
78
|
+
return reviveDates({
|
|
79
|
+
session: safeSession,
|
|
80
|
+
user
|
|
81
|
+
});
|
|
82
|
+
} catch {
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
/** The session read of each server request, so the page guard and all components share one read. */
|
|
87
|
+
const serverReads = /* @__PURE__ */ new WeakMap();
|
|
88
|
+
const viteHubAuthPlugin = defineNuxtPlugin({
|
|
89
|
+
name: "vitehub:auth",
|
|
90
|
+
enforce: "pre",
|
|
91
|
+
setup(nuxtApp) {
|
|
92
|
+
setNuxtAppResolver(() => tryUseNuxtApp());
|
|
93
|
+
setNuxtErrorFactory(createError);
|
|
94
|
+
if (!("window" in globalThis)) setRequestFetchResolver(currentRequestFetch);
|
|
95
|
+
const runtimeConfig = useRuntimeConfig();
|
|
96
|
+
const config = runtimeConfig.public?.vitehubAuth;
|
|
97
|
+
const redirects = (config || void 0)?.redirects ?? {};
|
|
98
|
+
/** The page guard of `to`: where a visitor goes, or nothing when the page has no guard. */
|
|
99
|
+
const guardOf = (to) => {
|
|
100
|
+
const meta = to.meta.auth;
|
|
101
|
+
if (config === false || meta === void 0 || meta === false) return;
|
|
102
|
+
const mode = typeof meta === "string" ? meta : meta === true ? "user" : meta.only ?? "user";
|
|
103
|
+
const redirectTo = typeof meta === "object" ? meta.redirectTo : void 0;
|
|
104
|
+
return (loggedIn) => {
|
|
105
|
+
if (mode === "guest") return loggedIn ? navigateTo(redirectTo ?? redirects.guest ?? "/") : void 0;
|
|
106
|
+
if (!loggedIn) return navigateTo({
|
|
107
|
+
path: redirectTo ?? redirects.login ?? "/login",
|
|
108
|
+
query: { redirect: to.fullPath }
|
|
109
|
+
});
|
|
110
|
+
};
|
|
111
|
+
};
|
|
112
|
+
if ("window" in globalThis) setSignOutHandler((redirectTo) => nuxtApp.runWithContext(() => {
|
|
113
|
+
const seed = useState(stateKey, () => void 0);
|
|
114
|
+
seed.value = null;
|
|
115
|
+
if (redirectTo) return navigateTo(redirectTo, { external: /^(?:[\w+.-]{2,}:|[/\\]{2})/.test(redirectTo) });
|
|
116
|
+
return guardOf(useRouter().currentRoute.value)?.(false);
|
|
117
|
+
}));
|
|
118
|
+
if (config === false) return;
|
|
119
|
+
const basePath = resolveAuthMountPath(config?.basePath ?? "/api/auth", "window" in globalThis ? runtimeConfig.app?.baseURL : void 0);
|
|
120
|
+
setDefaultAuthBasePath(basePath);
|
|
121
|
+
let serverSession;
|
|
122
|
+
if (!("window" in globalThis)) {
|
|
123
|
+
let read = false;
|
|
124
|
+
let session;
|
|
125
|
+
serverSession = () => {
|
|
126
|
+
if (read) return session;
|
|
127
|
+
read = true;
|
|
128
|
+
const seed = useState(stateKey);
|
|
129
|
+
session = seed.value !== void 0 ? seed.value : readServerSession(basePath);
|
|
130
|
+
if (session instanceof Promise) session = session.then((value) => session = seed.value = value);
|
|
131
|
+
else seed.value = session;
|
|
132
|
+
return session;
|
|
133
|
+
};
|
|
134
|
+
serverReads.set(nuxtApp, serverSession);
|
|
135
|
+
}
|
|
136
|
+
const stale = "window" in globalThis && Boolean(nuxtApp.payload.prerenderedAt || nuxtApp.payload.isCached);
|
|
137
|
+
setSessionSeedResolver((read) => {
|
|
138
|
+
if (stale) return void 0;
|
|
139
|
+
try {
|
|
140
|
+
const app = read ? tryUseNuxtApp() : void 0;
|
|
141
|
+
const readRequest = app && serverReads.get(app);
|
|
142
|
+
return readRequest ? readRequest() : useState(stateKey).value;
|
|
143
|
+
} catch {
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
});
|
|
147
|
+
addRouteMiddleware("vitehub-auth", (to) => {
|
|
148
|
+
const decide = guardOf(to);
|
|
149
|
+
if (!decide) return;
|
|
150
|
+
const session = serverSession?.();
|
|
151
|
+
const app = tryUseNuxtApp();
|
|
152
|
+
const inApp = (run) => app ? app.runWithContext(run) : run();
|
|
153
|
+
const loggedIn = !serverSession ? import("../vue.js").then(({ useUserSession }) => inApp(() => useUserSession().refresh())).then((current) => Boolean(current?.session && current?.user)) : session instanceof Promise ? session.then(Boolean) : Boolean(session);
|
|
154
|
+
if (typeof loggedIn === "boolean") return decide(loggedIn);
|
|
155
|
+
return loggedIn.then((value) => inApp(() => decide(value)));
|
|
156
|
+
}, { global: true });
|
|
157
|
+
}
|
|
158
|
+
});
|
|
159
|
+
//#endregion
|
|
160
|
+
export { viteHubAuthPlugin as default };
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
//#region src/runtime-state.ts
|
|
2
|
+
const authRuntimeStateKey = Symbol.for("vitehub.auth.runtime");
|
|
3
|
+
/**
|
|
4
|
+
* Marks the database that Auth adds to a Definition without one. It keeps rows in the memory of one process, so a value
|
|
5
|
+
* that another instance must see, such as a one-time ticket, cannot live there.
|
|
6
|
+
*/
|
|
7
|
+
const authProcessMemoryDatabase = Symbol.for("vitehub.auth.processMemoryDatabase");
|
|
8
|
+
/** Whether a Better Auth `database` option is the process memory database that Auth adds. */
|
|
9
|
+
function isAuthProcessMemoryDatabase(database) {
|
|
10
|
+
return database instanceof Object && Reflect.get(database, authProcessMemoryDatabase) === true;
|
|
11
|
+
}
|
|
12
|
+
function getAuthRuntimeState() {
|
|
13
|
+
const globalScope = globalThis;
|
|
14
|
+
globalScope[authRuntimeStateKey] ??= {};
|
|
15
|
+
globalScope[authRuntimeStateKey].envResolvers ??= /* @__PURE__ */ new WeakMap();
|
|
16
|
+
return globalScope[authRuntimeStateKey];
|
|
17
|
+
}
|
|
18
|
+
function resetAuth() {
|
|
19
|
+
const state = getAuthRuntimeState();
|
|
20
|
+
state.auth = void 0;
|
|
21
|
+
state.definition = void 0;
|
|
22
|
+
state.providers = void 0;
|
|
23
|
+
}
|
|
24
|
+
//#endregion
|
|
25
|
+
export { resetAuth as i, getAuthRuntimeState as n, isAuthProcessMemoryDatabase as r, authProcessMemoryDatabase as t };
|