@vite-hub/auth 0.0.2
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 +186 -0
- package/dist/agent.d.ts +41 -0
- package/dist/agent.js +89 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +90 -0
- package/dist/runtime/empty-definition.d.ts +6 -0
- package/dist/runtime/empty-definition.js +4 -0
- package/dist/server-Diw3mAbX.js +322 -0
- package/dist/server.d.ts +20 -0
- package/dist/server.js +2 -0
- package/dist/shared-QSYBHaMG.js +12 -0
- package/dist/types-B0fg9XFd.d.ts +106 -0
- package/dist/vite.d.ts +22 -0
- package/dist/vite.js +993 -0
- package/package.json +76 -0
package/README.md
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
# @vite-hub/auth
|
|
2
|
+
|
|
3
|
+
<p>
|
|
4
|
+
<a href="https://vitehub.dev"><img alt="ViteHub" src="https://img.shields.io/badge/ViteHub-vitehub.dev-646cff?style=flat-square"></a>
|
|
5
|
+
<img alt="TypeScript" src="https://img.shields.io/badge/TypeScript-ready-3178c6?style=flat-square">
|
|
6
|
+
<img alt="Better Auth" src="https://img.shields.io/badge/Better%20Auth-powered-0f766e?style=flat-square">
|
|
7
|
+
<img alt="Vite" src="https://img.shields.io/badge/Vite-discovery-646cff?style=flat-square">
|
|
8
|
+
</p>
|
|
9
|
+
|
|
10
|
+
`@vite-hub/auth` defines one server-owned Auth Definition and turns it into a Better Auth server for ViteHub apps.
|
|
11
|
+
|
|
12
|
+
## Install
|
|
13
|
+
|
|
14
|
+
```sh
|
|
15
|
+
pnpm add @vite-hub/auth better-auth
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## Minimal API
|
|
19
|
+
|
|
20
|
+
```ts
|
|
21
|
+
// server/auth.ts
|
|
22
|
+
import { defineAuth } from "@vite-hub/auth"
|
|
23
|
+
|
|
24
|
+
export default defineAuth({
|
|
25
|
+
appName: "My app",
|
|
26
|
+
})
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
```ts
|
|
30
|
+
// vite.config.ts
|
|
31
|
+
import { hubAuth } from "@vite-hub/auth/vite"
|
|
32
|
+
import { defineConfig } from "vite"
|
|
33
|
+
|
|
34
|
+
export default defineConfig({
|
|
35
|
+
plugins: [hubAuth()],
|
|
36
|
+
})
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
`hubAuth()` discovers `server/auth.ts`, exposes `/api/auth/**`, and generates the Nitro route handler for production builds.
|
|
40
|
+
|
|
41
|
+
For host routes that need runtime secrets, provider credentials, request-derived origins, or route guarding, keep that policy in the Auth Definition.
|
|
42
|
+
|
|
43
|
+
```ts
|
|
44
|
+
// vite.config.ts
|
|
45
|
+
import { hubAuth } from "@vite-hub/auth/vite"
|
|
46
|
+
import { env, hubEnv } from "@vite-hub/env/vite"
|
|
47
|
+
import { defineConfig } from "vite"
|
|
48
|
+
|
|
49
|
+
export default defineConfig({
|
|
50
|
+
plugins: [
|
|
51
|
+
hubEnv(),
|
|
52
|
+
hubAuth(),
|
|
53
|
+
],
|
|
54
|
+
env: {
|
|
55
|
+
server: {
|
|
56
|
+
auth: {
|
|
57
|
+
github: {
|
|
58
|
+
clientId: env({ source: env.source("GITHUB_CLIENT_ID") }),
|
|
59
|
+
clientSecret: env({ secret: true, source: env.source("GITHUB_CLIENT_SECRET") }),
|
|
60
|
+
},
|
|
61
|
+
secret: env({ secret: true, source: env.source("BETTER_AUTH_SECRET") }),
|
|
62
|
+
},
|
|
63
|
+
},
|
|
64
|
+
},
|
|
65
|
+
})
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
```ts
|
|
69
|
+
// server/auth.ts
|
|
70
|
+
import { defineAuth } from "@vite-hub/auth"
|
|
71
|
+
|
|
72
|
+
export default defineAuth(({ env, requestOrigin }) => ({
|
|
73
|
+
appName: "My app",
|
|
74
|
+
baseURL: requestOrigin,
|
|
75
|
+
secret: env.auth.secret.unseal(),
|
|
76
|
+
access: {
|
|
77
|
+
routes: ["/app", "/app/**"],
|
|
78
|
+
signIn: {
|
|
79
|
+
provider: "github",
|
|
80
|
+
callbackURL: "/app",
|
|
81
|
+
errorCallbackURL: "/app?auth_error=github",
|
|
82
|
+
},
|
|
83
|
+
},
|
|
84
|
+
socialProviders: {
|
|
85
|
+
github: {
|
|
86
|
+
clientId: env.auth.github.clientId,
|
|
87
|
+
clientSecret: env.auth.github.clientSecret.unseal(),
|
|
88
|
+
},
|
|
89
|
+
},
|
|
90
|
+
}))
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
When `@vite-hub/env` is installed, the Auth Definition callback receives the typed server env. It also receives `requestOrigin`, so same-origin apps do not need a separate auth URL environment variable.
|
|
94
|
+
|
|
95
|
+
The generated Nitro middleware uses `access.signIn` when one of the configured `access.routes` needs a browser redirect.
|
|
96
|
+
|
|
97
|
+
## Vite Integration
|
|
98
|
+
|
|
99
|
+
Use `server/auth.ts` for the canonical Auth Definition, or `server.auth.ts` when a flat server file fits the project better. Vite discovers one Auth Definition, exposes it through an internal virtual module, owns `/api/auth/**` in development, and registers the same route with Nitro builds by default.
|
|
100
|
+
|
|
101
|
+
Set `route: false` only when a host integration mounts Auth itself.
|
|
102
|
+
|
|
103
|
+
```ts
|
|
104
|
+
export default defineAuth({
|
|
105
|
+
route: false,
|
|
106
|
+
})
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
Manual hosts can mount the stable `#vitehub/auth/server` handler directly.
|
|
110
|
+
|
|
111
|
+
Better Auth options stay top-level. ViteHub-owned wiring reserves `access`, `database`, `secondaryStorage`, `basePath`, `route`, and `runtime`. The Better Auth fields `baseURL`, `secret`, and `secrets` are runtime-only: return them from the Definition callback or place them under `runtime`. `access.routes` must be static route strings or `{ method, route }` objects so the Vite Integration can register Nitro middleware.
|
|
112
|
+
|
|
113
|
+
```ts
|
|
114
|
+
export default defineAuth({
|
|
115
|
+
basePath: "/auth",
|
|
116
|
+
database: { name: "auth", dedicated: true },
|
|
117
|
+
secondaryStorage: { store: "auth" },
|
|
118
|
+
})
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
`database` and `secondaryStorage` are placement metadata. ViteHub removes metadata-shaped values before calling `betterAuth()`, so they do not create Database or KV adapters. When Better Auth needs persistent storage, return its concrete `database` or `secondaryStorage` adapter from the Definition callback or `runtime`.
|
|
122
|
+
|
|
123
|
+
## Client-side Auth
|
|
124
|
+
|
|
125
|
+
Use Better Auth's client libraries from application code. ViteHub exposes the Auth route in local Vite development and provides the handler for hosts that mount it manually; Better Auth owns framework clients, hooks, client plugins, sign-in actions, and session state.
|
|
126
|
+
|
|
127
|
+
```ts
|
|
128
|
+
// lib/auth-client.ts
|
|
129
|
+
import { createAuthClient } from "better-auth/client"
|
|
130
|
+
|
|
131
|
+
export const authClient = createAuthClient()
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
That default talks to `/api/auth` on the same origin. If the Auth Definition uses a custom `basePath`, pass the same path to the Better Auth client.
|
|
135
|
+
|
|
136
|
+
```ts
|
|
137
|
+
// server/auth.ts
|
|
138
|
+
import { defineAuth } from "@vite-hub/auth"
|
|
139
|
+
|
|
140
|
+
export default defineAuth({
|
|
141
|
+
appName: "My app",
|
|
142
|
+
basePath: "/auth",
|
|
143
|
+
})
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
```ts
|
|
147
|
+
// lib/auth-client.ts
|
|
148
|
+
import { createAuthClient } from "better-auth/client"
|
|
149
|
+
|
|
150
|
+
export const authClient = createAuthClient({
|
|
151
|
+
basePath: "/auth",
|
|
152
|
+
})
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
Use Better Auth's framework entrypoints when you want React, Vue, Svelte, Solid, or other framework-specific client behavior. ViteHub does not provide `@vite-hub/auth/client` or a separate Auth Client Definition.
|
|
156
|
+
|
|
157
|
+
Read [Better Auth's client docs](https://www.better-auth.com/docs/concepts/client) for framework entrypoints and session helpers.
|
|
158
|
+
|
|
159
|
+
## Authenticated Agents
|
|
160
|
+
|
|
161
|
+
Use `authenticated()` when an Agent should derive its Agent Invoker from the current Auth Session.
|
|
162
|
+
|
|
163
|
+
```ts
|
|
164
|
+
// server/support.agent.ts
|
|
165
|
+
import { defineAgent } from "@vite-hub/agent"
|
|
166
|
+
import { authenticated } from "@vite-hub/auth/agent"
|
|
167
|
+
|
|
168
|
+
export default defineAgent({
|
|
169
|
+
invoker: authenticated(),
|
|
170
|
+
driver: {
|
|
171
|
+
run: ({ invoker }) => ({ invoker }),
|
|
172
|
+
},
|
|
173
|
+
})
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
By default, the Auth Package reads the same-app Better Auth session from the request and maps the Auth User to an Agent Invoker with `kind: "authUser"`. Customize `id`, `kind`, `label`, or `meta` for normal identity shaping, and use `source` or `map` when the Agent consumes JWTs, bearer tokens, OAuth/OIDC provider output, or product-specific identity.
|
|
177
|
+
|
|
178
|
+
When authentication is required but unavailable, `authenticated()` throws `ViteHubError` with code `AUTHENTICATION_REQUIRED`. HTTP adapters map that code to `401`; the transport status is not part of the error object.
|
|
179
|
+
|
|
180
|
+
```ts
|
|
181
|
+
import { ViteHubError } from "@vite-hub/runtime"
|
|
182
|
+
|
|
183
|
+
const error = new ViteHubError("AUTHENTICATION_REQUIRED", "Sign in to use this Agent.")
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
`error.toJSON()` includes `name`, `code`, and `message`, while omitting `cause` and stack data. If a default Better Auth request or session operation fails, `authenticated()` and `requireAuth()` throw the same shared error with code `AUTH_PROVIDER_OPERATION_FAILED` and safe operation details; raw provider diagnostics remain available only through `cause`. Existing ViteHub errors and structural `AbortError` objects keep their identity. Missing APIs, malformed responses, invalid Auth configuration, and invalid custom callback results are programmer or provider-contract defects, so ViteHub keeps those `TypeError`s outside the operational provider boundary.
|
package/dist/agent.d.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { AgentInvoker, AgentInvokerOptions, AgentInvokerResolveContext, AgentRuntimeConfig, MaybePromise } from "@vite-hub/agent";
|
|
2
|
+
|
|
3
|
+
//#region src/agent.d.ts
|
|
4
|
+
interface AuthenticatedUser {
|
|
5
|
+
email?: string | null;
|
|
6
|
+
id: string;
|
|
7
|
+
image?: string | null;
|
|
8
|
+
name?: string | null;
|
|
9
|
+
[key: string]: unknown;
|
|
10
|
+
}
|
|
11
|
+
interface AuthenticatedSessionData {
|
|
12
|
+
id?: string;
|
|
13
|
+
token?: string;
|
|
14
|
+
userId?: string;
|
|
15
|
+
[key: string]: unknown;
|
|
16
|
+
}
|
|
17
|
+
interface AuthenticatedSession<TUser extends AuthenticatedUser = AuthenticatedUser, TSession extends AuthenticatedSessionData = AuthenticatedSessionData> {
|
|
18
|
+
session: TSession;
|
|
19
|
+
user: TUser;
|
|
20
|
+
}
|
|
21
|
+
interface AuthenticatedContext<TRuntimeConfig extends AgentRuntimeConfig = AgentRuntimeConfig, CALL_OPTIONS = unknown, TUser extends AuthenticatedUser = AuthenticatedUser, TSession extends AuthenticatedSessionData = AuthenticatedSessionData> extends AgentInvokerResolveContext<TRuntimeConfig, CALL_OPTIONS> {
|
|
22
|
+
auth: AuthenticatedSession<TUser, TSession>;
|
|
23
|
+
session: TSession;
|
|
24
|
+
user: TUser;
|
|
25
|
+
}
|
|
26
|
+
type AuthenticatedSource<TRuntimeConfig extends AgentRuntimeConfig = AgentRuntimeConfig, CALL_OPTIONS = unknown, TUser extends AuthenticatedUser = AuthenticatedUser, TSession extends AuthenticatedSessionData = AuthenticatedSessionData> = (context: AgentInvokerResolveContext<TRuntimeConfig, CALL_OPTIONS>) => MaybePromise<AuthenticatedSession<TUser, TSession> | null | undefined>;
|
|
27
|
+
type AuthenticatedValue<TValue, TRuntimeConfig extends AgentRuntimeConfig = AgentRuntimeConfig, CALL_OPTIONS = unknown, TUser extends AuthenticatedUser = AuthenticatedUser, TSession extends AuthenticatedSessionData = AuthenticatedSessionData> = TValue | ((context: AuthenticatedContext<TRuntimeConfig, CALL_OPTIONS, TUser, TSession>) => MaybePromise<TValue>);
|
|
28
|
+
type AuthenticatedMapper<TRuntimeConfig extends AgentRuntimeConfig = AgentRuntimeConfig, CALL_OPTIONS = unknown, TUser extends AuthenticatedUser = AuthenticatedUser, TSession extends AuthenticatedSessionData = AuthenticatedSessionData> = (context: AuthenticatedContext<TRuntimeConfig, CALL_OPTIONS, TUser, TSession>) => MaybePromise<AgentInvoker>;
|
|
29
|
+
interface AuthenticatedOptions<TRuntimeConfig extends AgentRuntimeConfig = AgentRuntimeConfig, CALL_OPTIONS = unknown, TUser extends AuthenticatedUser = AuthenticatedUser, TSession extends AuthenticatedSessionData = AuthenticatedSessionData> {
|
|
30
|
+
id?: AuthenticatedValue<string | null | undefined, TRuntimeConfig, CALL_OPTIONS, TUser, TSession>;
|
|
31
|
+
kind?: AuthenticatedValue<AgentInvoker["kind"] | null | undefined, TRuntimeConfig, CALL_OPTIONS, TUser, TSession>;
|
|
32
|
+
label?: AuthenticatedValue<string | null | undefined, TRuntimeConfig, CALL_OPTIONS, TUser, TSession>;
|
|
33
|
+
map?: AuthenticatedMapper<TRuntimeConfig, CALL_OPTIONS, TUser, TSession>;
|
|
34
|
+
message?: string;
|
|
35
|
+
meta?: AuthenticatedValue<Record<string, unknown> | null | undefined, TRuntimeConfig, CALL_OPTIONS, TUser, TSession>;
|
|
36
|
+
required?: boolean;
|
|
37
|
+
source?: AuthenticatedSource<TRuntimeConfig, CALL_OPTIONS, TUser, TSession>;
|
|
38
|
+
}
|
|
39
|
+
declare function authenticated<TRuntimeConfig extends AgentRuntimeConfig = AgentRuntimeConfig, CALL_OPTIONS = unknown, TUser extends AuthenticatedUser = AuthenticatedUser, TSession extends AuthenticatedSessionData = AuthenticatedSessionData>(options?: AuthenticatedOptions<TRuntimeConfig, CALL_OPTIONS, TUser, TSession>): AgentInvokerOptions<TRuntimeConfig, CALL_OPTIONS>;
|
|
40
|
+
//#endregion
|
|
41
|
+
export { AuthenticatedContext, AuthenticatedMapper, AuthenticatedOptions, AuthenticatedSession, AuthenticatedSessionData, AuthenticatedSource, AuthenticatedUser, AuthenticatedValue, authenticated };
|
package/dist/agent.js
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { _ as throwAuthenticationProviderError, g as invalidAuthenticationErrorOptions, h as getAuthenticationSession, l as getAuthForRequest } from "./server-Diw3mAbX.js";
|
|
2
|
+
import { ViteHubError } from "@vite-hub/runtime";
|
|
3
|
+
//#region src/agent.ts
|
|
4
|
+
function authenticationRequired(message = "[vitehub] Authentication required.") {
|
|
5
|
+
if (!message || message.length > 16384) invalidAuthenticationErrorOptions();
|
|
6
|
+
return new ViteHubError("AUTHENTICATION_REQUIRED", message);
|
|
7
|
+
}
|
|
8
|
+
function authenticated(options = {}) {
|
|
9
|
+
return { async resolve(context) {
|
|
10
|
+
let auth;
|
|
11
|
+
let providerFields;
|
|
12
|
+
if (options.source) auth = await options.source(context);
|
|
13
|
+
else {
|
|
14
|
+
const resolved = await defaultAuthenticatedSource(context);
|
|
15
|
+
auth = resolved?.auth;
|
|
16
|
+
providerFields = resolved ?? void 0;
|
|
17
|
+
}
|
|
18
|
+
if (!auth) {
|
|
19
|
+
if (options.required === false) return void 0;
|
|
20
|
+
throw authenticationRequired(options.message);
|
|
21
|
+
}
|
|
22
|
+
const authenticatedContext = {
|
|
23
|
+
...context,
|
|
24
|
+
auth,
|
|
25
|
+
session: providerFields?.session ?? auth.session,
|
|
26
|
+
user: providerFields?.user ?? auth.user
|
|
27
|
+
};
|
|
28
|
+
if (options.map) {
|
|
29
|
+
const invoker = await options.map(authenticatedContext);
|
|
30
|
+
if (!invoker) throw new TypeError("[vitehub] authenticated({ map }) must return an Agent Invoker.");
|
|
31
|
+
return invoker;
|
|
32
|
+
}
|
|
33
|
+
return createDefaultInvoker(options, authenticatedContext, providerFields);
|
|
34
|
+
} };
|
|
35
|
+
}
|
|
36
|
+
async function defaultAuthenticatedSource(context) {
|
|
37
|
+
if (!context.request) return void 0;
|
|
38
|
+
return await getAuthenticationSession(getAuthForRequest(context.request), {
|
|
39
|
+
headers: context.request.headers,
|
|
40
|
+
query: {
|
|
41
|
+
disableCookieCache: true,
|
|
42
|
+
disableRefresh: true
|
|
43
|
+
}
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
function readProviderField(read) {
|
|
47
|
+
try {
|
|
48
|
+
return read();
|
|
49
|
+
} catch (cause) {
|
|
50
|
+
throwAuthenticationProviderError(cause, "get-session");
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
async function createDefaultInvoker(options, context, providerFields) {
|
|
54
|
+
const userId = await resolveAuthenticatedValue(options.id, context) ?? providerFields?.userId ?? readString(context.user.id);
|
|
55
|
+
if (!userId) throw authenticationRequired("[vitehub] Authenticated user is missing an id.");
|
|
56
|
+
const kind = await resolveAuthenticatedValue(options.kind, context) ?? "authUser";
|
|
57
|
+
const label = await resolveAuthenticatedValue(options.label, context) ?? (providerFields && readProviderField(() => defaultLabel(providerFields.user, providerFields.userId))) ?? defaultLabel(context.user);
|
|
58
|
+
const sessionId = providerFields ? readProviderField(() => readString(providerFields.session.id)) : readString(context.session.id);
|
|
59
|
+
return {
|
|
60
|
+
id: userId,
|
|
61
|
+
kind,
|
|
62
|
+
label,
|
|
63
|
+
meta: {
|
|
64
|
+
...normalizeMeta(await resolveAuthenticatedValue(options.meta, context)),
|
|
65
|
+
authUserId: providerFields?.userId ?? readString(context.user.id) ?? userId,
|
|
66
|
+
...sessionId ? { authSessionId: sessionId } : {}
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
function resolveAuthenticatedValue(value, context) {
|
|
71
|
+
if (typeof value === "function") return value(context);
|
|
72
|
+
return value;
|
|
73
|
+
}
|
|
74
|
+
function defaultLabel(user, fallbackId = user.id) {
|
|
75
|
+
return readString(user.email) ?? readString(user.name) ?? fallbackId;
|
|
76
|
+
}
|
|
77
|
+
function normalizeMeta(value) {
|
|
78
|
+
if (!value) return {};
|
|
79
|
+
if (!isRecord(value)) throw new TypeError("[vitehub] authenticated({ meta }) must resolve to an object.");
|
|
80
|
+
return value;
|
|
81
|
+
}
|
|
82
|
+
function readString(value) {
|
|
83
|
+
return typeof value === "string" && value.length > 0 ? value : void 0;
|
|
84
|
+
}
|
|
85
|
+
function isRecord(value) {
|
|
86
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
87
|
+
}
|
|
88
|
+
//#endregion
|
|
89
|
+
export { authenticated };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { A as ResolvedAuthSecondaryStorageConfiguration, C as AuthRuntimeOptionsResolver, D as AuthViteHubOptions, E as AuthSignInConfiguration, M as ViteHubAuth, O as DiscoveredAuthDefinition, S as AuthRuntimeOptions, T as AuthSecondaryStorageReference, _ as AuthRuntimeConfiguration, a as AuthBetterAuthRuntimeOptions, b as AuthRuntimeOnlyOptions, c as AuthDefinition, d as AuthDefinitionResolver, f as AuthModuleOptions, g as AuthResolvedDefinitionOptions, h as AuthReservedOption, i as AuthBetterAuthOptions, j as ResolvedAuthViteConfig, k as ResolvedAuthDatabaseConfiguration, l as AuthDefinitionInput, n as AuthAccessRoute, o as AuthDatabaseConfiguration, p as AuthRequest, r as AuthAccessRouteConfiguration, s as AuthDatabaseReference, t as AuthAccessConfiguration, u as AuthDefinitionOptions, v as AuthRuntimeContext, w as AuthSecondaryStorageConfiguration, x as AuthRuntimeOption, y as AuthRuntimeEnv } from "./types-B0fg9XFd.js";
|
|
2
|
+
|
|
3
|
+
//#region src/definition.d.ts
|
|
4
|
+
declare function defineAuth<const TOptions extends AuthBetterAuthOptions>(options: AuthDefinitionOptions<TOptions>): AuthDefinition<AuthDefinitionOptions<TOptions>>;
|
|
5
|
+
declare function defineAuth<const TOptions extends AuthResolvedDefinitionOptions>(options: AuthDefinitionResolver<TOptions>): AuthDefinition<AuthDefinitionResolver<TOptions>>;
|
|
6
|
+
//#endregion
|
|
7
|
+
export { type AuthAccessConfiguration, type AuthAccessRoute, type AuthAccessRouteConfiguration, type AuthBetterAuthOptions, type AuthBetterAuthRuntimeOptions, type AuthDatabaseConfiguration, type AuthDatabaseReference, type AuthDefinition, type AuthDefinitionInput, type AuthDefinitionOptions, type AuthDefinitionResolver, type AuthModuleOptions, type AuthRequest, type AuthReservedOption, type AuthResolvedDefinitionOptions, type AuthRuntimeConfiguration, type AuthRuntimeContext, type AuthRuntimeEnv, type AuthRuntimeOnlyOptions, type AuthRuntimeOption, type AuthRuntimeOptions, type AuthRuntimeOptionsResolver, type AuthSecondaryStorageConfiguration, type AuthSecondaryStorageReference, type AuthSignInConfiguration, type AuthViteHubOptions, type DiscoveredAuthDefinition, type ResolvedAuthDatabaseConfiguration, type ResolvedAuthSecondaryStorageConfiguration, type ResolvedAuthViteConfig, type ViteHubAuth, defineAuth };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { n as normalizeAuthBasePath } from "./shared-QSYBHaMG.js";
|
|
2
|
+
//#region src/definition.ts
|
|
3
|
+
const authRuntimeOptionNames = new Set([
|
|
4
|
+
"baseURL",
|
|
5
|
+
"secret",
|
|
6
|
+
"secrets"
|
|
7
|
+
]);
|
|
8
|
+
const accessRouteKeys = new Set(["method", "route"]);
|
|
9
|
+
const databaseReferenceKeys = new Set(["dedicated", "name"]);
|
|
10
|
+
const secondaryStorageReferenceKeys = new Set(["store"]);
|
|
11
|
+
function isPlainObject(value) {
|
|
12
|
+
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
13
|
+
}
|
|
14
|
+
function validateNamedString(value, label) {
|
|
15
|
+
if (typeof value !== "string" || value.trim().length === 0 || value !== value.trim()) throw new TypeError(`\`defineAuth()\` ${label} must be a non-empty trimmed string.`);
|
|
16
|
+
}
|
|
17
|
+
function validateAuthDatabase(value) {
|
|
18
|
+
if (typeof value === "undefined" || value === true) return;
|
|
19
|
+
if (!isPlainObject(value)) throw new TypeError("`defineAuth()` database must be `true` or an inline object with `name`.");
|
|
20
|
+
const unknownKey = Object.keys(value).find((key) => !databaseReferenceKeys.has(key));
|
|
21
|
+
if (unknownKey) throw new TypeError(`\`defineAuth()\` database does not support the "${unknownKey}" option.`);
|
|
22
|
+
validateNamedString(value.name, "database.name");
|
|
23
|
+
if (typeof value.dedicated !== "undefined" && typeof value.dedicated !== "boolean") throw new TypeError("`defineAuth()` database.dedicated must be a boolean.");
|
|
24
|
+
}
|
|
25
|
+
function validateAuthSecondaryStorage(value) {
|
|
26
|
+
if (typeof value === "undefined" || value === true) return;
|
|
27
|
+
if (!isPlainObject(value)) throw new TypeError("`defineAuth()` secondaryStorage must be `true` or an inline object with `store`.");
|
|
28
|
+
const unknownKey = Object.keys(value).find((key) => !secondaryStorageReferenceKeys.has(key));
|
|
29
|
+
if (unknownKey) throw new TypeError(`\`defineAuth()\` secondaryStorage does not support the "${unknownKey}" option.`);
|
|
30
|
+
validateNamedString(value.store, "secondaryStorage.store");
|
|
31
|
+
}
|
|
32
|
+
function validateStringValue(value, label) {
|
|
33
|
+
if (typeof value !== "string" || value.trim().length === 0) throw new TypeError(`\`defineAuth()\` ${label} must be a non-empty string.`);
|
|
34
|
+
}
|
|
35
|
+
function validateRouteValue(value, label) {
|
|
36
|
+
validateStringValue(value, label);
|
|
37
|
+
if (typeof value === "string" && !value.startsWith("/")) throw new TypeError(`\`defineAuth()\` ${label} must start with \`/\`.`);
|
|
38
|
+
}
|
|
39
|
+
function validateAuthSignIn(value) {
|
|
40
|
+
if (typeof value === "undefined") return;
|
|
41
|
+
if (!isPlainObject(value)) throw new TypeError("`defineAuth()` access.signIn must be an object.");
|
|
42
|
+
validateStringValue(value.provider, "access.signIn.provider");
|
|
43
|
+
if (typeof value.callbackURL !== "undefined") validateStringValue(value.callbackURL, "access.signIn.callbackURL");
|
|
44
|
+
if (typeof value.errorCallbackURL !== "undefined") validateStringValue(value.errorCallbackURL, "access.signIn.errorCallbackURL");
|
|
45
|
+
if (typeof value.requestSignUp !== "undefined" && typeof value.requestSignUp !== "boolean") throw new TypeError("`defineAuth()` access.signIn.requestSignUp must be a boolean.");
|
|
46
|
+
if (typeof value.scopes !== "undefined" && (!Array.isArray(value.scopes) || value.scopes.some((scope) => typeof scope !== "string"))) throw new TypeError("`defineAuth()` access.signIn.scopes must be an array of strings.");
|
|
47
|
+
}
|
|
48
|
+
function validateAuthAccessRoute(value, label) {
|
|
49
|
+
if (typeof value === "string") {
|
|
50
|
+
validateRouteValue(value, label);
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
if (!isPlainObject(value)) throw new TypeError(`\`defineAuth()\` ${label} must be a route string or route object.`);
|
|
54
|
+
const unknownKey = Object.keys(value).find((key) => !accessRouteKeys.has(key));
|
|
55
|
+
if (unknownKey) throw new TypeError(`\`defineAuth()\` ${label} does not support the "${unknownKey}" option.`);
|
|
56
|
+
validateRouteValue(value.route, `${label}.route`);
|
|
57
|
+
if (typeof value.method !== "undefined") validateStringValue(value.method, `${label}.method`);
|
|
58
|
+
}
|
|
59
|
+
function validateAuthAccess(value) {
|
|
60
|
+
if (typeof value === "undefined") return;
|
|
61
|
+
if (!isPlainObject(value)) throw new TypeError("`defineAuth()` access must be an object.");
|
|
62
|
+
const access = value;
|
|
63
|
+
if (typeof access.routes !== "undefined") {
|
|
64
|
+
if (!Array.isArray(access.routes)) throw new TypeError("`defineAuth()` access.routes must be an array.");
|
|
65
|
+
access.routes.forEach((route, index) => validateAuthAccessRoute(route, `access.routes[${index}]`));
|
|
66
|
+
}
|
|
67
|
+
validateAuthSignIn(access.signIn);
|
|
68
|
+
}
|
|
69
|
+
function defineAuth(options) {
|
|
70
|
+
return defineAuthOptions(options);
|
|
71
|
+
}
|
|
72
|
+
function defineAuthOptions(options) {
|
|
73
|
+
if (typeof options === "function") return { options };
|
|
74
|
+
if (!isPlainObject(options)) throw new TypeError("`defineAuth()` expects an object or a callback.");
|
|
75
|
+
const viteHubOptions = options;
|
|
76
|
+
const runtimeOption = Object.keys(options).find((key) => authRuntimeOptionNames.has(key));
|
|
77
|
+
if (runtimeOption) throw new TypeError(`\`defineAuth()\` ${runtimeOption} is resolved at runtime and cannot be defined in the Auth Definition.`);
|
|
78
|
+
if (typeof viteHubOptions.route !== "undefined" && viteHubOptions.route !== false) throw new TypeError("`defineAuth()` route can only be `false` when provided.");
|
|
79
|
+
if (typeof viteHubOptions.runtime !== "undefined" && typeof viteHubOptions.runtime !== "function" && !isPlainObject(viteHubOptions.runtime)) throw new TypeError("`defineAuth()` runtime must be an object or a function.");
|
|
80
|
+
if (typeof viteHubOptions.basePath !== "undefined") {
|
|
81
|
+
if (typeof viteHubOptions.basePath !== "string") throw new TypeError("`defineAuth()` basePath must be a string.");
|
|
82
|
+
normalizeAuthBasePath(viteHubOptions.basePath);
|
|
83
|
+
}
|
|
84
|
+
validateAuthDatabase(viteHubOptions.database);
|
|
85
|
+
validateAuthSecondaryStorage(viteHubOptions.secondaryStorage);
|
|
86
|
+
validateAuthAccess(viteHubOptions.access);
|
|
87
|
+
return { options };
|
|
88
|
+
}
|
|
89
|
+
//#endregion
|
|
90
|
+
export { defineAuth };
|