@vite-hub/auth 0.1.0 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +333 -49
- 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 +5 -5
- package/dist/agent.js +17 -9
- 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 +1 -1
- package/dist/cli.js +47 -7
- 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 -3
- package/dist/console-runtime.js +2 -819
- package/dist/console.d.ts +215 -3
- package/dist/console.js +1 -1
- 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-P7mI4IQb.js → events-ByzenEVj.js} +122 -4
- package/dist/forward.d.ts +50 -0
- package/dist/forward.js +120 -0
- package/dist/host-declarations.d.ts +2 -1
- package/dist/index.d.ts +24 -3
- package/dist/index.js +3 -102
- 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 +13 -5
- package/dist/nuxt.js +90 -13
- package/dist/object-Da1zyPCR.js +11 -0
- package/dist/page-tools-shared-l4eyj53D.js +19 -0
- package/dist/presets.js +1 -1
- package/dist/request-z6DHHmrb.js +47 -0
- package/dist/runtime/console.d.ts +3 -7
- package/dist/runtime/console.js +4 -42
- 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 -1
- package/dist/runtime/nuxt.js +1 -1
- package/dist/runtime/server.d.ts +2 -0
- package/dist/runtime/server.js +77 -0
- package/dist/runtime/vue-nuxt.d.ts +3 -2
- package/dist/runtime/vue-nuxt.js +157 -5
- 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 -2
- package/dist/server.js +3 -3
- package/dist/session-cookies-BbH3UR2m.js +227 -0
- package/dist/{set-cookie-2as_DbHe.js → set-cookie-C8NOhdRE.js} +27 -12
- package/dist/{shared-DnpgYiLF.js → shared-BwcdRGxD.js} +2 -5
- 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/{events-BkmK2dFY.d.ts → types-CNaeH2Fd.d.ts} +240 -157
- package/dist/vite-CV400XXY.js +1556 -0
- package/dist/vite.d.ts +138 -20
- package/dist/vite.js +2 -2
- package/dist/vue.d.ts +330 -21
- package/dist/vue.js +583 -36
- package/package.json +84 -15
- package/dist/application-path-C290OAIs.js +0 -18
- package/dist/cli-mgXvsBtA.d.ts +0 -85
- package/dist/console-B7eERmGv.d.ts +0 -180
- package/dist/console-runtime-bZQtnX2Y.d.ts +0 -39
- package/dist/error-diagnostics-CL0yjHiM.js +0 -79
- package/dist/events-config-CjcFOhTE.js +0 -177
- package/dist/inspect-DPtsW8dB.d.ts +0 -36
- package/dist/server-B7LU19dS.js +0 -1730
- package/dist/server-CTD_JAww.d.ts +0 -77
- package/dist/vite-COWkwxsj.js +0 -990
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import { defineDiagnostics } from "nostics";
|
|
2
|
+
//#region src/error-diagnostics.ts
|
|
3
|
+
const dynamicError = { why: ({ message }) => message === void 0 ? "" : String(message) };
|
|
4
|
+
/** A code whose call site passes the message as `why`, with the fix that the reader applies. */
|
|
5
|
+
const withFix = (fix) => ({
|
|
6
|
+
...dynamicError,
|
|
7
|
+
fix
|
|
8
|
+
});
|
|
9
|
+
const authErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
|
|
10
|
+
docsBase: "https://vitehub.dev/docs/auth/diagnostics",
|
|
11
|
+
codes: {
|
|
12
|
+
AUTH_EVENT_CALLBACK_FAILED: {
|
|
13
|
+
why: ({ type }) => `\`events.onEvent\` failed for the ${JSON.stringify(type)} auth event. Auth kept the change and the stored event.`,
|
|
14
|
+
fix: "Read `error.cause` for the error of your callback. Catch errors inside `events.onEvent`, and retry the outside call there if it can fail."
|
|
15
|
+
},
|
|
16
|
+
AUTH_EVENT_QUERY_INVALID: {
|
|
17
|
+
why: ({ problem }) => problem === "order" ? "Auth event from must be before to." : "Auth event windows must be positive and at most 366 days.",
|
|
18
|
+
fix: "Pass `from` before `to`, as ISO timestamps, and keep an aggregate window at most 366 days long."
|
|
19
|
+
},
|
|
20
|
+
AUTH_EVENT_RETENTION_INVALID: {
|
|
21
|
+
why: "Auth event retention limits must be positive integers.",
|
|
22
|
+
fix: "Pass `retention: { maxAgeMs, maxRecords }` to `createDatabaseAuthEventStore()` with positive whole numbers, or `retention: false` to keep every event."
|
|
23
|
+
},
|
|
24
|
+
AUTH_PASSWORD_HASH_INVALID: {
|
|
25
|
+
why: "Invalid password hash",
|
|
26
|
+
fix: "The stored password hash is not `<salt>:<key>`. Hash new passwords with `hashPasswordWithNoble()` or the Better Auth hasher, and reset the password of the user whose hash is broken."
|
|
27
|
+
},
|
|
28
|
+
AUTH_SIGN_OUT_REDIRECT_INVALID: {
|
|
29
|
+
why: ({ redirectTo }) => `\`signOut()\` redirects only to a path of the app, not to ${JSON.stringify(redirectTo)}.`,
|
|
30
|
+
fix: "Pass a path that starts with one `/`, for example `signOut(event, { redirectTo: '/login' })`. A value from the query string can point to another site, so check it against your own pages first."
|
|
31
|
+
},
|
|
32
|
+
AUTH_TEST_SIGN_IN_STATELESS: {
|
|
33
|
+
why: "`signIn()` writes the user and the session to the Auth database, and a Definition with the `stateless()` preset has none.",
|
|
34
|
+
fix: "Test the routes of a `stateless()` Definition through its social sign-in flow, or give the test app `database: authDatabase()` with `import { authDatabase } from 'vite-hub/auth/database'`."
|
|
35
|
+
},
|
|
36
|
+
AUTH_R0001: withFix("Return an Agent Invoker from the `map` callback of `authenticated()` for each request. Remove `map` to use the default Invoker."),
|
|
37
|
+
AUTH_R0002: withFix("Make `meta` of `authenticated()` return a plain object, `null`, or `undefined`, for example `meta: ({ user }) => ({ plan: user.plan })`."),
|
|
38
|
+
AUTH_C0001: withFix("Write the value as a string literal in `defineAuth()`, for example `basePath: '/auth'`. The Vite plugin reads it at build time, so it cannot use a variable or an expression."),
|
|
39
|
+
AUTH_C0002: withFix("Remove the spaces at the start and end of the value, for example `basePath: '/auth'` or `method: 'POST'`."),
|
|
40
|
+
AUTH_C0003: withFix("Start the path with `/`, for example `/admin/**` or `/auth`."),
|
|
41
|
+
AUTH_C0005: withFix("Write each key as a plain name in the object, for example `{ route: '/admin/**' }`. Do not use computed keys or spreads."),
|
|
42
|
+
AUTH_C0006: withFix("Remove the option. A route object takes only `route`, `method`, and `authorize`."),
|
|
43
|
+
AUTH_C0007: withFix("Write each key as a plain name in the object, for example `{ route: '/admin/**' }`. Do not use computed keys or spreads."),
|
|
44
|
+
AUTH_C0008: withFix("Set `route: false` to stop the automatic `/api/auth/**` route, or remove `route`. Use `basePath` to move the route."),
|
|
45
|
+
AUTH_C0009: withFix("Start the path with `/`, for example `/admin/**` or `/auth`."),
|
|
46
|
+
AUTH_C0010: withFix("Write each entry of `access.routes` inline as a route string or an object, for example `'/admin/**'` or `{ route: '/api/admin/**', method: 'POST' }`."),
|
|
47
|
+
AUTH_C0011: withFix("Add `route` to the route object, for example `{ route: '/admin/**', authorize: isAdmin }`."),
|
|
48
|
+
AUTH_C0012: withFix("Write `access.routes` as an array literal in `defineAuth()`, for example `access: { routes: ['/admin/**'] }`. The Vite plugin reads it at build time."),
|
|
49
|
+
AUTH_C0014: withFix("Set `database: authDatabase()` with `import { authDatabase } from 'vite-hub/auth/database'`, or `authDatabase('auth')` for the Named Database `auth`. Return another Better Auth adapter from the Definition callback. Set `database: \"memory\"` to keep sessions in the memory of one server process."),
|
|
50
|
+
AUTH_C0017: withFix("Remove `secondaryStorage` from the static options. Return a Better Auth `secondaryStorage` adapter, an object with `get`, `set`, and `delete`, from the Definition callback."),
|
|
51
|
+
AUTH_C0019: withFix("Pass an object literal to `defineAuth()` in `server/auth.ts`, or a callback that returns one, for example `export default defineAuth({ basePath: '/auth' })`. Do not pass a variable."),
|
|
52
|
+
AUTH_C0021: withFix("Set `database: authDatabase()` with `import { authDatabase } from 'vite-hub/auth/database'`, or `authDatabase('auth')` for the Named Database `auth`. Return another Better Auth adapter from the Definition callback. Set `database: \"memory\"` to keep sessions in the memory of one server process."),
|
|
53
|
+
AUTH_C0024: withFix("Remove `secondaryStorage` from the static options. Return a Better Auth `secondaryStorage` adapter, an object with `get`, `set`, and `delete`, from the Definition callback."),
|
|
54
|
+
AUTH_C0026: withFix("Set the option to a non-empty string, for example `provider: 'github'` or `method: 'GET'`."),
|
|
55
|
+
AUTH_C0027: withFix("Start the path with `/`, for example `/admin/**` or `/auth`."),
|
|
56
|
+
AUTH_C0028: withFix("Set `access.signIn` to an object, for example `signIn: { provider: 'github' }`."),
|
|
57
|
+
AUTH_C0029: withFix("Set `access.signIn.requestSignUp` to `true` or `false`, or remove it."),
|
|
58
|
+
AUTH_C0030: withFix("Set `access.signIn.scopes` to an array of strings, for example `scopes: ['read:org']`."),
|
|
59
|
+
AUTH_C0031: withFix("Write each entry of `access.routes` as a route string or an object, for example `'/admin/**'` or `{ route: '/api/admin/**', authorize }`."),
|
|
60
|
+
AUTH_C0032: withFix("Remove the option. A route object takes only `route`, `method`, and `authorize`."),
|
|
61
|
+
AUTH_C0033: withFix("Set `authorize` to a function that returns `true`, `false`, or a `Response`, for example `authorize: ({ user }) => user.role === 'admin'`."),
|
|
62
|
+
AUTH_C0034: withFix("Set `access` to an object, for example `access: { routes: ['/admin/**'] }`."),
|
|
63
|
+
AUTH_C0035: withFix("Set `access.routes` to an array, for example `routes: ['/admin/**']`."),
|
|
64
|
+
AUTH_C0036: withFix("Pass an options object or a callback that returns one to `defineAuth()`, for example `defineAuth({ emailAndPassword: { enabled: true } })`."),
|
|
65
|
+
AUTH_C0037: withFix("Return the option from the Definition callback, for example `defineAuth(({ env }) => ({ secret: env.auth.secret.unseal() }))`."),
|
|
66
|
+
AUTH_C0038: withFix("Set `route: false` to stop the automatic `/api/auth/**` route, or remove `route`. Use `basePath` to move the route."),
|
|
67
|
+
AUTH_C0039: withFix("Remove `runtime` and pass one callback that returns all options, for example `defineAuth(({ env }) => ({ advanced: { cookiePrefix: 'acme', trustedProxyHeaders: true }, secret: env.auth.secret.unseal() }))`. Keep `authDatabase()` inline in the returned object."),
|
|
68
|
+
AUTH_C0040: withFix("Set `basePath` to a string that starts with `/`, for example `basePath: '/auth'`."),
|
|
69
|
+
AUTH_C0041: withFix("Set `session.onRefresh` to a function, for example `onRefresh: async ({ session }) => {}`, or remove it."),
|
|
70
|
+
AUTH_C0042: withFix("Set `database: authDatabase()` or return a Better Auth `database` or `secondaryStorage` adapter. Or remove `session.onRefresh`."),
|
|
71
|
+
AUTH_C0043: withFix("Import the preset and call it, for example `preset: stateless()` with `import { stateless } from 'vite-hub/auth/presets'`."),
|
|
72
|
+
AUTH_C0044: withFix("Remove the option from the Auth Definition, or remove `preset: stateless()` and configure a Better Auth database."),
|
|
73
|
+
AUTH_C0045: withFix("Remove the option from the Auth Definition, or remove `preset: stateless()` and configure a Better Auth database."),
|
|
74
|
+
AUTH_C0046: withFix("Remove `emailAndPassword` and use `socialProviders`, or remove `preset: stateless()` and configure a Better Auth database."),
|
|
75
|
+
AUTH_C0047: withFix("Remove the plugin that the message names, or remove `preset: stateless()` and configure a Better Auth database."),
|
|
76
|
+
AUTH_C0048: withFix("Remove the option that the message names. Pass `maxAge` to `stateless()` to change the session lifetime, for example `stateless({ maxAge: '12h' })`."),
|
|
77
|
+
AUTH_C0049: withFix("Pass a positive whole number of seconds or a duration, for example `stateless({ maxAge: '7d' })` or `stateless({ maxAge: 3600 })`."),
|
|
78
|
+
AUTH_C0050: withFix("Set `events: { store: createDatabaseAuthEventStore({ db }) }`, or `events: false` to disable the log. `events.authorize` and `events.onEvent` must be functions."),
|
|
79
|
+
AUTH_C0051: withFix("Add `admin()` from `better-auth/plugins` to the `plugins` of `defineAuth()`, or unset the variable that the message names."),
|
|
80
|
+
AUTH_C0052: withFix("Pass the Database name as one string literal, for example `authDatabase('content')`, or no argument for the `default` Database."),
|
|
81
|
+
AUTH_C0053: withFix("Remove `advanced.database.generateId`, or set it to a function that returns strings. Use another Better Auth adapter for numeric or UUID IDs."),
|
|
82
|
+
AUTH_C0054: withFix("Call `authDatabase()` inline as `database` in the object of `defineAuth()`, or in the one object that its callback returns. Do not select it in a branch."),
|
|
83
|
+
AUTH_C0055: withFix("Write `additionalFields` inline in `server/auth.ts`, with a literal `type` for each field, for example `user: { additionalFields: { login: { type: 'string', required: false } } }`."),
|
|
84
|
+
AUTH_C0056: withFix("Remove the `modelName` or `fieldName` change. For a plugin that adds a table or a column, call it in `server/auth.ts` so that the Auth Vite plugin adds its tables, or add its tables to the Database Definition. Then run `vitehub database generate`."),
|
|
85
|
+
AUTH_C0057: withFix("Unset `VITEHUB_ADMIN_EMAILS`. List each admin's social account in `VITEHUB_ADMINS`, for example `VITEHUB_ADMINS=github:22072217`."),
|
|
86
|
+
AUTH_C0058: withFix("Write each `VITEHUB_ADMINS` entry as `<provider>:<account id>`, for example `github:22072217`. Run `gh api users/<login> --jq .id` to get a GitHub account id. For an app with only email sign-in, remove `VITEHUB_ADMINS`, then run `vitehub auth claim`."),
|
|
87
|
+
AUTH_C0059: withFix("Run `vitehub auth claim` and set `VITEHUB_ADMIN_CLAIM` to the `sha256:` value that it prints. Do not set the code itself."),
|
|
88
|
+
AUTH_R0018: withFix("Set `events: { store: createDatabaseAuthEventStore({ db }) }` in `defineAuth()`."),
|
|
89
|
+
AUTH_R0003: withFix("Keep one of `server/auth.ts` and `server.auth.ts` and delete the others that the message lists. For Nuxt layers, add `server/auth.ts` to the app to select the Definition."),
|
|
90
|
+
AUTH_R0004: withFix("Pass a non-empty `message` of at most 16,384 characters to `authenticated()`, or remove `message`."),
|
|
91
|
+
AUTH_C0060: withFix("Keep one abilities file at `shared/abilities.ts`. Remove the other files listed in the message, or add the app file to replace layer rules."),
|
|
92
|
+
AUTH_C0061: withFix("Return `database: authDatabase()` with `import { authDatabase } from 'vite-hub/auth/database'`, or `authDatabase('auth')` for the Named Database `auth`. Or return another Better Auth adapter."),
|
|
93
|
+
AUTH_C0062: withFix("Return a Better Auth `secondaryStorage` adapter, an object with `get`, `set`, and `delete`, or remove `secondaryStorage`."),
|
|
94
|
+
AUTH_C0063: withFix("Set `database: authDatabase()` with `import { authDatabase } from 'vite-hub/auth/database'` to keep users in the app Database. Use `preset: stateless()` for social sign-in without a database. Set `database: \"memory\"` only when one server process may keep users until it restarts."),
|
|
95
|
+
AUTH_C0064: withFix("Write `access.public` as an inline array of route strings, for example `public: ['/', '/login', '/api/health']`. The Vite plugin reads it at build time."),
|
|
96
|
+
AUTH_C0065: withFix("Set `access.policy` to an object with an `allow` function, for example `policy: { allow: ({ user }) => user.emailVerified === true, recheck: 300_000 }`. `recheck` is a number of milliseconds, 0 or more."),
|
|
97
|
+
AUTH_C0066: withFix("Return `database: authDatabase()` or another Better Auth adapter, or a `secondaryStorage` adapter. `access.policy` ends sessions, so Auth must store them."),
|
|
98
|
+
AUTH_C0067: withFix("Pass both options, for example `forwardAuth({ header: 'x-auth-request-access-token', verify: async ({ value }) => lookUpIdentity(value) })`. `verify` must prove the header, for example with the provider or a secret that only the proxy sends."),
|
|
99
|
+
AUTH_C0068: withFix("Write each access route as a literal path, without percent-encoded pattern syntax or `.` and `..` segments. To guard a path and every path below it, end the route with `/**`, for example `/api/users/**` in place of `/api/users/:id` or `/api/admin/*`. Check the parameter in the handler."),
|
|
100
|
+
AUTH_B0001: withFix("Set `env.projectRoot` of `@vite-hub/auth/nuxt` to the `projectRoot` of the `hubEnv()` plugin, or remove `env.projectRoot`."),
|
|
101
|
+
AUTH_B0002: withFix("Remove `swr`, `cache`, `isr`, `prerender`, or `static` from the route rule that the message names. Or add a rule for the guarded path that turns the cache off, for example `routeRules: { '/dashboard/**': { cache: false, prerender: false } }`. If the page is public, remove the route from `access.routes`."),
|
|
102
|
+
AUTH_R0005: withFix("Add `server/auth.ts` with `export default defineAuth({})`. For a Nuxt layer, add it to the app."),
|
|
103
|
+
AUTH_R0006: withFix("Send the `Origin` header with the request. Browsers send it. A server-side caller must set it, for example `headers: { origin: 'https://app.example.com' }`."),
|
|
104
|
+
AUTH_R0007: withFix("Add the origin to Better Auth's `trustedOrigins` in the Auth Definition, for example `trustedOrigins: ['https://app.example.com']`. Or send the request from the app origin."),
|
|
105
|
+
AUTH_R0008: withFix("Restart the dev server or rebuild the app after you change `access.routes`, so that the generated middleware and the Auth Definition list the same routes. With `createAuthAccessHandler()`, list the routes in the order of `access.routes`."),
|
|
106
|
+
AUTH_R0009: withFix("Pass the indexes of the matched `access.routes`, for example `requireAuthAccessRoutes(event, [0])`. Or use `createAuthAccessHandler()`, which finds them."),
|
|
107
|
+
AUTH_R0010: withFix("Pass the indexes of the matched routes that have `authorize` as the fourth argument of `requireAuthAccessRoutes()`, for example `[0]`, or `[]` for none."),
|
|
108
|
+
AUTH_R0011: withFix("Install the `better-auth` version that `@vite-hub/auth` depends on. If the versions match, this is a ViteHub bug. Report it at https://github.com/vite-hub/vitehub/issues with the message."),
|
|
109
|
+
AUTH_R0012: withFix("Install the `better-auth` version that `@vite-hub/auth` depends on. If the versions match, this is a ViteHub bug. Report it at https://github.com/vite-hub/vitehub/issues with the message."),
|
|
110
|
+
AUTH_R0013: withFix("Set `basePath` to a path that starts with `/` and is not only `/`, for example `basePath: '/auth'`."),
|
|
111
|
+
AUTH_R0014: withFix("Pass a function that returns `true`, `false`, or a `Response`, for example `withAuthorization(({ user }) => user.role === 'admin', handler)`. `withAuthorization()` and `requireAuthorization()` also take `true` for any signed-in user. `withAnonymousAuthorization()` takes only a function."),
|
|
112
|
+
AUTH_R0015: withFix("Pass your handler function, for example `withAuth((event, { user }) => ({ id: user.id }))`."),
|
|
113
|
+
AUTH_R0016: withFix("Set `VITEHUB_SECRET` to at least 32 random characters. Run `openssl rand -base64 32` to make one."),
|
|
114
|
+
AUTH_R0019: withFix("Pass `authDatabase()` inline as `database` of `defineAuth()`, enable the Database integration, and run `vitehub database generate`. Run `vitehub inspect definitions --kind database` to list the tables."),
|
|
115
|
+
AUTH_R0020: withFix("Add the named rule to `shared/abilities.ts` with `defineAbilities()`, or use an existing ability name."),
|
|
116
|
+
AUTH_R0021: withFix("Return the result at once. Load data before the ability check and pass it as a rule argument; remove `async` from the rule."),
|
|
117
|
+
AUTH_R0022: withFix("Send the request to an origin that `vitehub({ publicUrl })` returns for one of your Agents, or set `baseURL` in the Auth Definition. The request Host cannot choose the Auth origin."),
|
|
118
|
+
AUTH_R0023: withFix("Return `null` from `verify` to ignore the header, or an object with `providerId`, `accountId`, `email`, `name`, and `emailVerified`, for example `{ providerId: 'github', accountId: String(user.id), email, name: user.login, emailVerified: true }`."),
|
|
119
|
+
AUTH_EVENTS_OPTION_INVALID: {
|
|
120
|
+
why: ({ option, problem }) => problem === "unknown" ? `[vitehub] Unknown auth events option: ${option}` : `[vitehub] Missing value for ${option}.`,
|
|
121
|
+
fix: "Pass only the options that `vitehub auth events --help` lists, each followed by its value."
|
|
122
|
+
},
|
|
123
|
+
AUTH_EVENTS_REQUEST_FAILED: {
|
|
124
|
+
why: ({ status }) => `[vitehub] Auth events returned HTTP ${status}.`,
|
|
125
|
+
fix: "Return true from `events.authorize` in `defineAuth()` for your user, and set VITEHUB_AUTH_COOKIE to the cookie of a session of that user."
|
|
126
|
+
},
|
|
127
|
+
AUTH_EVENTS_URL_INSECURE: {
|
|
128
|
+
why: "[vitehub] Auth events requires HTTPS or a loopback HTTP URL.",
|
|
129
|
+
fix: "Pass an `https://` Auth base URL to `--url`, or `http://localhost` for a dev server."
|
|
130
|
+
},
|
|
131
|
+
AUTH_EVENTS_URL_MISSING: {
|
|
132
|
+
why: "[vitehub] `vitehub auth events` has no Auth base URL.",
|
|
133
|
+
fix: "Pass `--url` with the Auth base URL, such as `--url http://localhost:5173/api/auth`, or set VITEHUB_AUTH_URL."
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
});
|
|
137
|
+
//#endregion
|
|
138
|
+
export { authErrorDiagnostics as t };
|
|
@@ -1,5 +1,123 @@
|
|
|
1
|
+
import { t as authErrorDiagnostics } from "./error-diagnostics-C8XtVz0i.js";
|
|
2
|
+
import { t as isRecord } from "./object-Da1zyPCR.js";
|
|
3
|
+
import { defineErrors } from "@vite-hub/runtime";
|
|
1
4
|
import { sql } from "drizzle-orm";
|
|
2
5
|
import * as v from "valibot";
|
|
6
|
+
//#region src/github.ts
|
|
7
|
+
const githubErrors = /*#__PURE__*/ defineErrors({
|
|
8
|
+
docs: "https://vitehub.dev/docs/auth/diagnostics",
|
|
9
|
+
codes: {
|
|
10
|
+
AUTH_GITHUB_ORG_REQUIRED: {
|
|
11
|
+
why: "`checkGitHubOrgMember()` got an empty organization login.",
|
|
12
|
+
fix: "Pass the login of the organization, for example `checkGitHubOrgMember(token, \"acme\")`."
|
|
13
|
+
},
|
|
14
|
+
AUTH_GITHUB_NOT_ORG_MEMBER: {
|
|
15
|
+
why: ({ org }) => `The GitHub user is not an active member of \`${org}\`, or the invitation is still pending.`,
|
|
16
|
+
fix: "Deny access. Invite the user to the organization, or ask them to accept the pending invitation."
|
|
17
|
+
},
|
|
18
|
+
AUTH_GITHUB_ORG_ACCESS_DENIED: {
|
|
19
|
+
why: ({ org, sso }) => sso ? `\`${org}\` uses SAML single sign-on, and the token is not authorized for it.` : `The token cannot read the memberships of \`${org}\`. It needs the \`read:org\` scope, and the organization must allow the OAuth app.`,
|
|
20
|
+
fix: "Ask the user to sign in with GitHub again with the `read:org` scope, and to authorize the organization's single sign-on when GitHub asks."
|
|
21
|
+
},
|
|
22
|
+
AUTH_GITHUB_TOKEN_INVALID: {
|
|
23
|
+
why: "GitHub rejected the access token, or there is none. It expired or was revoked.",
|
|
24
|
+
fix: "Ask the user to sign in with GitHub again."
|
|
25
|
+
},
|
|
26
|
+
AUTH_GITHUB_UNAVAILABLE: {
|
|
27
|
+
why: ({ status }) => status === void 0 ? "GitHub did not answer the membership check in time, or the request failed." : `GitHub answered the membership check with HTTP ${status}. It is down or rate limited the token.`,
|
|
28
|
+
fix: "Deny access for now and ask the user to try again later. Read `error.cause` for a network error."
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
});
|
|
32
|
+
const activeMemberships = /* @__PURE__ */ new Map();
|
|
33
|
+
async function cacheKey(accessToken, org) {
|
|
34
|
+
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(`${org.toLowerCase()}\n${accessToken}`));
|
|
35
|
+
return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
36
|
+
}
|
|
37
|
+
const orgScopes = /* @__PURE__ */ new Set([
|
|
38
|
+
"admin:org",
|
|
39
|
+
"read:org",
|
|
40
|
+
"write:org"
|
|
41
|
+
]);
|
|
42
|
+
async function fetchActiveMembership(accessToken, org, timeoutMs) {
|
|
43
|
+
let response;
|
|
44
|
+
try {
|
|
45
|
+
response = await fetch(`https://api.github.com/user/memberships/orgs/${encodeURIComponent(org)}`, {
|
|
46
|
+
headers: {
|
|
47
|
+
accept: "application/vnd.github+json",
|
|
48
|
+
authorization: `Bearer ${accessToken}`,
|
|
49
|
+
"user-agent": "vitehub",
|
|
50
|
+
"x-github-api-version": "2022-11-28"
|
|
51
|
+
},
|
|
52
|
+
signal: AbortSignal.timeout(timeoutMs)
|
|
53
|
+
});
|
|
54
|
+
} catch (cause) {
|
|
55
|
+
return [githubErrors.AUTH_GITHUB_UNAVAILABLE({ cause }), void 0];
|
|
56
|
+
}
|
|
57
|
+
const { headers, status } = response;
|
|
58
|
+
if (status === 401) return [githubErrors.AUTH_GITHUB_TOKEN_INVALID(), void 0];
|
|
59
|
+
if (status === 429 || status >= 500 || !response.ok && (headers.get("x-ratelimit-remaining") === "0" || headers.has("retry-after"))) return [githubErrors.AUTH_GITHUB_UNAVAILABLE({ status }), void 0];
|
|
60
|
+
if (status === 403) {
|
|
61
|
+
const body = await response.json().catch(() => void 0);
|
|
62
|
+
if (isRecord(body) && /rate.limit/i.test(`${body.message} ${body.documentation_url}`)) return [githubErrors.AUTH_GITHUB_UNAVAILABLE({ status }), void 0];
|
|
63
|
+
return [githubErrors.AUTH_GITHUB_ORG_ACCESS_DENIED({
|
|
64
|
+
org,
|
|
65
|
+
sso: headers.has("x-github-sso")
|
|
66
|
+
}), void 0];
|
|
67
|
+
}
|
|
68
|
+
if (status === 404) {
|
|
69
|
+
const scopes = headers.get("x-oauth-scopes")?.split(/[\s,]+/);
|
|
70
|
+
return scopes && !scopes.some((scope) => orgScopes.has(scope)) ? [githubErrors.AUTH_GITHUB_ORG_ACCESS_DENIED({
|
|
71
|
+
org,
|
|
72
|
+
sso: false
|
|
73
|
+
}), void 0] : [githubErrors.AUTH_GITHUB_NOT_ORG_MEMBER({ org }), void 0];
|
|
74
|
+
}
|
|
75
|
+
if (!response.ok) return [githubErrors.AUTH_GITHUB_UNAVAILABLE({ status }), void 0];
|
|
76
|
+
let membership;
|
|
77
|
+
try {
|
|
78
|
+
membership = await response.json();
|
|
79
|
+
} catch (cause) {
|
|
80
|
+
return [githubErrors.AUTH_GITHUB_UNAVAILABLE({
|
|
81
|
+
cause,
|
|
82
|
+
status
|
|
83
|
+
}), void 0];
|
|
84
|
+
}
|
|
85
|
+
if (typeof membership !== "object" || membership === null || !("state" in membership)) return [githubErrors.AUTH_GITHUB_UNAVAILABLE({ status }), void 0];
|
|
86
|
+
return membership.state === "active" ? [void 0, void 0] : [githubErrors.AUTH_GITHUB_NOT_ORG_MEMBER({ org }), void 0];
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Checks that the GitHub user of `accessToken` is an active member of `org`. The token needs the `read:org` scope.
|
|
90
|
+
* Returns `[undefined, undefined]` for an active membership, else the error that says why it could not confirm one.
|
|
91
|
+
*/
|
|
92
|
+
async function checkGitHubOrgMember(accessToken, org, options = {}) {
|
|
93
|
+
if (!org) throw githubErrors.AUTH_GITHUB_ORG_REQUIRED();
|
|
94
|
+
if (!accessToken) return [githubErrors.AUTH_GITHUB_TOKEN_INVALID(), void 0];
|
|
95
|
+
const cacheMs = options.cacheMs ?? 0;
|
|
96
|
+
if (cacheMs <= 0) return await fetchActiveMembership(accessToken, org, options.timeoutMs ?? 5e3);
|
|
97
|
+
const key = await cacheKey(accessToken, org);
|
|
98
|
+
const cached = activeMemberships.get(key);
|
|
99
|
+
if (cached && cached.checkedAt + cacheMs > Date.now()) return [void 0, void 0];
|
|
100
|
+
const result = await fetchActiveMembership(accessToken, org, options.timeoutMs ?? 5e3);
|
|
101
|
+
if (!result[0]) {
|
|
102
|
+
const now = Date.now();
|
|
103
|
+
for (const [entry, membership] of activeMemberships) if (membership.expiresAt <= now) activeMemberships.delete(entry);
|
|
104
|
+
activeMemberships.set(key, {
|
|
105
|
+
checkedAt: now,
|
|
106
|
+
expiresAt: now + cacheMs
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
return result;
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Returns `true` when the GitHub user of `accessToken` is an active member of `org`. The token needs the `read:org` scope.
|
|
113
|
+
* Every failure returns `false`. Use `checkGitHubOrgMember()` to know why.
|
|
114
|
+
*/
|
|
115
|
+
async function isGitHubOrgMember(accessToken, org, options = {}) {
|
|
116
|
+
if (!org) return false;
|
|
117
|
+
const [error] = await checkGitHubOrgMember(accessToken, org, options);
|
|
118
|
+
return !error;
|
|
119
|
+
}
|
|
120
|
+
//#endregion
|
|
3
121
|
//#region src/events.ts
|
|
4
122
|
const authEventTypes = [
|
|
5
123
|
"user.signed_up",
|
|
@@ -61,7 +179,7 @@ const listSchema = v.object({
|
|
|
61
179
|
function parseAuthEventList(input) {
|
|
62
180
|
const query = v.parse(listSchema, input);
|
|
63
181
|
const before = query.cursor ? v.parse(cursorSchema, JSON.parse(decodeURIComponent(query.cursor))) : void 0;
|
|
64
|
-
if (query.from && query.to && Date.parse(query.from) >= Date.parse(query.to)) throw
|
|
182
|
+
if (query.from && query.to && Date.parse(query.from) >= Date.parse(query.to)) throw authErrorDiagnostics.AUTH_EVENT_QUERY_INVALID({ problem: "order" });
|
|
65
183
|
return {
|
|
66
184
|
query,
|
|
67
185
|
before
|
|
@@ -70,7 +188,7 @@ function parseAuthEventList(input) {
|
|
|
70
188
|
function parseAuthEventWindow(window) {
|
|
71
189
|
const from = new Date(v.parse(timestamp, window.from)).toISOString();
|
|
72
190
|
const to = new Date(v.parse(timestamp, window.to)).toISOString();
|
|
73
|
-
if (from >= to || Date.parse(to) - Date.parse(from) > 316224e5) throw
|
|
191
|
+
if (from >= to || Date.parse(to) - Date.parse(from) > 316224e5) throw authErrorDiagnostics.AUTH_EVENT_QUERY_INVALID({ problem: "window" });
|
|
74
192
|
return {
|
|
75
193
|
from,
|
|
76
194
|
to
|
|
@@ -87,7 +205,7 @@ function createDatabaseAuthEventStore(options) {
|
|
|
87
205
|
...defaultAuthEventRetention,
|
|
88
206
|
...options.retention
|
|
89
207
|
};
|
|
90
|
-
if (retention && Object.values(retention).some((value) => !Number.isSafeInteger(value) || value < 1)) throw
|
|
208
|
+
if (retention && Object.values(retention).some((value) => !Number.isSafeInteger(value) || value < 1)) throw authErrorDiagnostics.AUTH_EVENT_RETENTION_INVALID();
|
|
91
209
|
let ready;
|
|
92
210
|
const initialize = () => ready ??= (async () => {
|
|
93
211
|
await db.run(sql`CREATE TABLE IF NOT EXISTS vitehub_auth_events (id TEXT PRIMARY KEY, type TEXT NOT NULL, time TEXT NOT NULL, actor TEXT NOT NULL, user_id TEXT, method TEXT, payload TEXT NOT NULL)`);
|
|
@@ -193,4 +311,4 @@ function createDatabaseAuthEventStore(options) {
|
|
|
193
311
|
};
|
|
194
312
|
}
|
|
195
313
|
//#endregion
|
|
196
|
-
export {
|
|
314
|
+
export { checkGitHubOrgMember as a, parseAuthEventWindow as i, defaultAuthEventRetention as n, isGitHubOrgMember as o, parseAuthEventList as r, createDatabaseAuthEventStore as t };
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { BetterAuthPlugin } from "better-auth";
|
|
2
|
+
//#region src/forward.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* Sign-in through a trusted reverse proxy, such as oauth2-proxy, Cloudflare Access, or Tailscale Serve. The proxy
|
|
5
|
+
* sends the person's identity, or a credential for it, in a request header. Auth trusts the header only when `verify`
|
|
6
|
+
* returns an identity, and then signs that identity in as a Better Auth account.
|
|
7
|
+
*/
|
|
8
|
+
/** The person that `verify` found in the header. Auth links it to a user as a Better Auth account. */
|
|
9
|
+
export interface ForwardedIdentity {
|
|
10
|
+
/** The provider of the account, such as `github` or `cloudflare-access`. */
|
|
11
|
+
providerId: string;
|
|
12
|
+
/** The person's stable id at the provider, such as the numeric GitHub user id. Never a value that can change, such as a login. */
|
|
13
|
+
accountId: string;
|
|
14
|
+
email: string;
|
|
15
|
+
name: string;
|
|
16
|
+
image?: string | null;
|
|
17
|
+
/** Whether the provider proved that the person owns `email`. Better Auth links an existing user by email only then. */
|
|
18
|
+
emailVerified: boolean;
|
|
19
|
+
/** A provider access token to store on the account, such as the GitHub token that oauth2-proxy forwards. */
|
|
20
|
+
accessToken?: string;
|
|
21
|
+
}
|
|
22
|
+
export interface ForwardAuthVerifyContext {
|
|
23
|
+
/** The value of the header. */
|
|
24
|
+
value: string;
|
|
25
|
+
/** All headers of the request, for a check such as a shared secret that the proxy adds. */
|
|
26
|
+
headers: Headers;
|
|
27
|
+
/** The request, when Better Auth has one. A direct `auth.api` call has only headers. */
|
|
28
|
+
request?: Request;
|
|
29
|
+
}
|
|
30
|
+
export interface ForwardAuthOptions {
|
|
31
|
+
/** The request header that the proxy sets, such as `x-auth-request-access-token` or `cf-access-jwt-assertion`. */
|
|
32
|
+
header: string;
|
|
33
|
+
/**
|
|
34
|
+
* Proves the header and returns the identity, or `null` to ignore the header. Anyone can send any header to a server
|
|
35
|
+
* that is reachable without the proxy, so check a credential: call the provider with the token, check the signature
|
|
36
|
+
* of a JWT, or compare a secret that only the proxy sends. Auth calls it on each Better Auth request with the header,
|
|
37
|
+
* so cache slow checks in it.
|
|
38
|
+
*/
|
|
39
|
+
verify: (context: ForwardAuthVerifyContext) => ForwardedIdentity | null | Promise<ForwardedIdentity | null>;
|
|
40
|
+
}
|
|
41
|
+
export declare const forwardAuthPluginId = "vitehub-forward-auth";
|
|
42
|
+
/**
|
|
43
|
+
* A Better Auth plugin that signs in the identity of a trusted proxy header. On each Better Auth request with the
|
|
44
|
+
* header, which includes every `getSession()` call and so every ViteHub guard, it asks `verify`. When `verify` returns
|
|
45
|
+
* an identity, the request uses a session of that identity: the session of its cookie, a session that this process
|
|
46
|
+
* made for the identity before, or a new one, which also sets the session cookie on the response. When `verify` returns
|
|
47
|
+
* `null`, the request keeps its own session cookie, if any.
|
|
48
|
+
*/
|
|
49
|
+
export declare function forwardAuth(options: ForwardAuthOptions): BetterAuthPlugin;
|
|
50
|
+
//#endregion
|
package/dist/forward.js
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { t as authErrorDiagnostics } from "./error-diagnostics-C8XtVz0i.js";
|
|
2
|
+
import { createAuthMiddleware } from "better-auth/api";
|
|
3
|
+
import { applySetCookies, deleteSessionCookie, setSessionCookie } from "better-auth/cookies";
|
|
4
|
+
import { handleOAuthUserInfo, setTokenUtil } from "better-auth/oauth2";
|
|
5
|
+
//#region src/forward.ts
|
|
6
|
+
const forwardAuthPluginId = "vitehub-forward-auth";
|
|
7
|
+
const nonEmpty = (value) => typeof value === "string" && value.trim().length > 0;
|
|
8
|
+
function assertIdentity(value) {
|
|
9
|
+
const field = (name) => value instanceof Object ? Reflect.get(value, name) : void 0;
|
|
10
|
+
if (!nonEmpty(field("providerId")) || !nonEmpty(field("accountId")) || !nonEmpty(field("email")) || typeof field("name") !== "string" || typeof field("emailVerified") !== "boolean") throw authErrorDiagnostics.AUTH_R0023({ message: "`forwardAuth()` verify returned a value that is not an identity. Return `null`, or an object with `providerId`, `accountId`, `email`, `name`, and `emailVerified`." });
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* A Better Auth plugin that signs in the identity of a trusted proxy header. On each Better Auth request with the
|
|
14
|
+
* header, which includes every `getSession()` call and so every ViteHub guard, it asks `verify`. When `verify` returns
|
|
15
|
+
* an identity, the request uses a session of that identity: the session of its cookie, a session that this process
|
|
16
|
+
* made for the identity before, or a new one, which also sets the session cookie on the response. When `verify` returns
|
|
17
|
+
* `null`, the request keeps its own session cookie, if any.
|
|
18
|
+
*/
|
|
19
|
+
function forwardAuth(options) {
|
|
20
|
+
const header = options?.header;
|
|
21
|
+
if (!nonEmpty(header) || typeof options.verify !== "function") throw authErrorDiagnostics.AUTH_C0067({ message: "`forwardAuth()` needs a `header` name and a `verify` function. Auth never trusts a forwarded header without `verify`." });
|
|
22
|
+
const verify = options.verify;
|
|
23
|
+
const sessions = /* @__PURE__ */ new Map();
|
|
24
|
+
const signIns = /* @__PURE__ */ new Map();
|
|
25
|
+
return {
|
|
26
|
+
id: forwardAuthPluginId,
|
|
27
|
+
hooks: { before: [{
|
|
28
|
+
matcher: (context) => context.path !== "/sign-out" && nonEmpty(context.headers?.get(header)),
|
|
29
|
+
handler: createAuthMiddleware(async (ctx) => {
|
|
30
|
+
const headers = ctx.headers;
|
|
31
|
+
const value = headers?.get(header);
|
|
32
|
+
if (!headers || !value) return;
|
|
33
|
+
const identity = await verify({
|
|
34
|
+
value,
|
|
35
|
+
headers,
|
|
36
|
+
...ctx.request ? { request: ctx.request } : {}
|
|
37
|
+
});
|
|
38
|
+
if (identity === null) return;
|
|
39
|
+
assertIdentity(identity);
|
|
40
|
+
const { internalAdapter } = ctx.context;
|
|
41
|
+
const { sessionToken } = ctx.context.authCookies;
|
|
42
|
+
const key = `${identity.providerId}\n${identity.accountId}`;
|
|
43
|
+
const owns = async (userId) => (await internalAdapter.findAccounts(userId)).some((account) => account.providerId === identity.providerId && account.accountId === identity.accountId);
|
|
44
|
+
const live = async (token) => {
|
|
45
|
+
const stored = await internalAdapter.findSession(token);
|
|
46
|
+
return stored && new Date(stored.session.expiresAt).getTime() > Date.now() ? stored : null;
|
|
47
|
+
};
|
|
48
|
+
const refreshToken = async (userId) => {
|
|
49
|
+
if (!identity.accessToken || ctx.context.options.account?.updateAccountOnSignIn === false) return;
|
|
50
|
+
const account = (await internalAdapter.findAccounts(userId)).find((account) => account.providerId === identity.providerId && account.accountId === identity.accountId);
|
|
51
|
+
if (account) await internalAdapter.updateAccount(account.id, { accessToken: await setTokenUtil(identity.accessToken, ctx.context) });
|
|
52
|
+
};
|
|
53
|
+
const cookieToken = await ctx.getSignedCookie(sessionToken.name, ctx.context.secret);
|
|
54
|
+
if (cookieToken) {
|
|
55
|
+
const current = await live(cookieToken);
|
|
56
|
+
if (current && await owns(current.session.userId)) {
|
|
57
|
+
await refreshToken(current.session.userId);
|
|
58
|
+
sessions.set(key, {
|
|
59
|
+
token: cookieToken,
|
|
60
|
+
userId: current.session.userId,
|
|
61
|
+
expiresAt: new Date(current.session.expiresAt).getTime()
|
|
62
|
+
});
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
const previous = signIns.get(key);
|
|
67
|
+
let release = () => {};
|
|
68
|
+
const turn = new Promise((resolve) => {
|
|
69
|
+
release = resolve;
|
|
70
|
+
});
|
|
71
|
+
signIns.set(key, turn);
|
|
72
|
+
await previous;
|
|
73
|
+
try {
|
|
74
|
+
const reusable = sessions.get(key);
|
|
75
|
+
let session = reusable ? await live(reusable.token) : null;
|
|
76
|
+
if (!session || session.session.userId !== reusable?.userId) {
|
|
77
|
+
sessions.delete(key);
|
|
78
|
+
const { data } = await handleOAuthUserInfo(ctx, {
|
|
79
|
+
userInfo: {
|
|
80
|
+
id: identity.accountId,
|
|
81
|
+
email: identity.email,
|
|
82
|
+
emailVerified: identity.emailVerified,
|
|
83
|
+
image: identity.image ?? void 0,
|
|
84
|
+
name: identity.name
|
|
85
|
+
},
|
|
86
|
+
account: {
|
|
87
|
+
providerId: identity.providerId,
|
|
88
|
+
accountId: identity.accountId,
|
|
89
|
+
...identity.accessToken ? { accessToken: identity.accessToken } : {}
|
|
90
|
+
},
|
|
91
|
+
overrideUserInfo: true
|
|
92
|
+
});
|
|
93
|
+
if (!data) {
|
|
94
|
+
deleteSessionCookie(ctx);
|
|
95
|
+
applySetCookies(headers, ctx.responseHeaders?.getSetCookie() ?? []);
|
|
96
|
+
ctx.context.session = null;
|
|
97
|
+
return { context: { headers } };
|
|
98
|
+
}
|
|
99
|
+
session = data;
|
|
100
|
+
} else await refreshToken(session.session.userId);
|
|
101
|
+
const now = Date.now();
|
|
102
|
+
for (const [entry, stored] of sessions) if (stored.expiresAt <= now) sessions.delete(entry);
|
|
103
|
+
sessions.set(key, {
|
|
104
|
+
token: session.session.token,
|
|
105
|
+
userId: session.session.userId,
|
|
106
|
+
expiresAt: new Date(session.session.expiresAt).getTime()
|
|
107
|
+
});
|
|
108
|
+
await setSessionCookie(ctx, session);
|
|
109
|
+
applySetCookies(headers, ctx.responseHeaders?.getSetCookie() ?? []);
|
|
110
|
+
} finally {
|
|
111
|
+
release();
|
|
112
|
+
if (signIns.get(key) === turn) signIns.delete(key);
|
|
113
|
+
}
|
|
114
|
+
return { context: { headers } };
|
|
115
|
+
})
|
|
116
|
+
}] }
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
//#endregion
|
|
120
|
+
export { forwardAuth, forwardAuthPluginId };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,8 +1,29 @@
|
|
|
1
1
|
/// <reference path="./host-declarations.d.ts" />
|
|
2
|
-
import {
|
|
2
|
+
import { A as AuthRuntimeOption, At as AuthEventCounts, Bt as defaultAuthEventRetention, C as AuthRequest, D as AuthRuntimeContext, Dt as AuthEvent, E as AuthResolvedDefinitionOptions, Et as AuthDevice, F as AuthSessionRefreshFields, Ft as AuthEventStore, H as ViteHubAuth, I as AuthSignInConfiguration, It as AuthEventType, J as AuthConsoleColumn, L as AuthViteHubOptions, Lt as AuthEventWindow, M as AuthSessionOptions, Mt as AuthEventMetadata, N as AuthSessionRefresh, Nt as AuthEventPage, O as AuthRuntimeEnv, Ot as AuthEventActor, P as AuthSessionRefreshContext, Pt as AuthEventRetention, R as DiscoveredAuthDefinition, Rt as AuthEventsConfiguration, S as AuthOptions, T as AuthReservedOption, V as ResolvedAuthViteConfig, _ as AuthDefinitionInput, a as AuthAccessPolicy, b as AuthFor, c as AuthAccessRouteConfiguration, ct as AuthConsoleOptions, d as AuthAnonymousGuardedHandler, et as AuthConsoleFieldPolicy, g as AuthDefinition, h as AuthBetterAuthRuntimeOptions, ht as AuthConsoleRoles, i as AuthAccessConfiguration, j as AuthRuntimeOptions, jt as AuthEventListInput, k as AuthRuntimeOnlyOptions, kt as AuthEventAggregates, l as AuthAnonymousAuthorization, m as AuthBetterAuthOptions, n as AuthAccessAuthorize, o as AuthAccessPolicyContext, p as AuthAuthorization, pt as AuthConsolePolicy, r as AuthAccessAuthorizeResult, s as AuthAccessRoute, t as AuthAccessAuthorizationContext, u as AuthAnonymousAuthorize, v as AuthDefinitionOptions, x as AuthGuardedHandler, y as AuthDefinitionResolver, z as RegisteredAuth, zt as createDatabaseAuthEventStore } from "./types-CNaeH2Fd.js";
|
|
3
3
|
import { i as AuthStatelessPresetOptions, n as AuthPreset, r as AuthStatelessPreset, t as AuthDuration } from "./presets-BGZi6Dfu.js";
|
|
4
|
+
import { Result } from "@vite-hub/runtime";
|
|
4
5
|
//#region src/definition.d.ts
|
|
5
6
|
export declare function defineAuth<const TOptions extends AuthResolvedDefinitionOptions>(options: AuthDefinitionResolver<TOptions>): AuthDefinition<AuthDefinitionResolver<TOptions>>;
|
|
6
|
-
export declare function defineAuth<const TOptions extends AuthBetterAuthOptions & Pick<AuthViteHubOptions, "runtime">>(options: AuthDefinitionOptions<TOptions>): AuthDefinition<AuthDefinitionOptions<TOptions>>;
|
|
7
|
+
export declare function defineAuth<const TOptions extends AuthBetterAuthOptions & Pick<AuthViteHubOptions, "database" | "runtime">>(options: AuthDefinitionOptions<TOptions>): AuthDefinition<AuthDefinitionOptions<TOptions>>;
|
|
7
8
|
//#endregion
|
|
8
|
-
|
|
9
|
+
//#region src/github.d.ts
|
|
10
|
+
interface GitHubOrgMemberOptions {
|
|
11
|
+
/** Reuse a successful check no older than this many milliseconds per token and organization. Default: no cache. */
|
|
12
|
+
cacheMs?: number;
|
|
13
|
+
/** Give up on the GitHub request after this many milliseconds. Default: 5000. */
|
|
14
|
+
timeoutMs?: number;
|
|
15
|
+
}
|
|
16
|
+
/** Why `checkGitHubOrgMember()` could not confirm an active membership. */
|
|
17
|
+
type GitHubOrgMemberErrorCode = "AUTH_GITHUB_NOT_ORG_MEMBER" | "AUTH_GITHUB_ORG_ACCESS_DENIED" | "AUTH_GITHUB_TOKEN_INVALID" | "AUTH_GITHUB_UNAVAILABLE";
|
|
18
|
+
/**
|
|
19
|
+
* Checks that the GitHub user of `accessToken` is an active member of `org`. The token needs the `read:org` scope.
|
|
20
|
+
* Returns `[undefined, undefined]` for an active membership, else the error that says why it could not confirm one.
|
|
21
|
+
*/
|
|
22
|
+
export declare function checkGitHubOrgMember(accessToken: string | null | undefined, org: string, options?: GitHubOrgMemberOptions): Promise<Result<void, GitHubOrgMemberErrorCode>>;
|
|
23
|
+
/**
|
|
24
|
+
* Returns `true` when the GitHub user of `accessToken` is an active member of `org`. The token needs the `read:org` scope.
|
|
25
|
+
* Every failure returns `false`. Use `checkGitHubOrgMember()` to know why.
|
|
26
|
+
*/
|
|
27
|
+
export declare function isGitHubOrgMember(accessToken: string | null | undefined, org: string, options?: GitHubOrgMemberOptions): Promise<boolean>;
|
|
28
|
+
//#endregion
|
|
29
|
+
export { type AuthAccessAuthorizationContext, type AuthAccessAuthorize, type AuthAccessAuthorizeResult, type AuthAccessConfiguration, type AuthAccessPolicy, type AuthAccessPolicyContext, type AuthAccessRoute, type AuthAccessRouteConfiguration, type AuthAnonymousAuthorization, type AuthAnonymousAuthorize, type AuthAnonymousGuardedHandler, type AuthAuthorization, type AuthBetterAuthOptions, type AuthBetterAuthRuntimeOptions, type AuthConsoleColumn, type AuthConsoleFieldPolicy, type AuthConsoleOptions, type AuthConsolePolicy, type AuthConsoleRoles, type AuthDefinition, type AuthDefinitionInput, type AuthDefinitionOptions, type AuthDefinitionResolver, type AuthDevice, type AuthDuration, type AuthEvent, type AuthEventActor, type AuthEventAggregates, type AuthEventCounts, type AuthEventListInput, type AuthEventMetadata, type AuthEventPage, type AuthEventRetention, type AuthEventStore, type AuthEventType, type AuthEventWindow, type AuthEventsConfiguration, type AuthFor, type AuthGuardedHandler, type AuthOptions, type AuthPreset, type AuthRequest, type AuthReservedOption, type AuthResolvedDefinitionOptions, type AuthRuntimeContext, type AuthRuntimeEnv, type AuthRuntimeOnlyOptions, type AuthRuntimeOption, type AuthRuntimeOptions, type AuthSessionOptions, type AuthSessionRefresh, type AuthSessionRefreshContext, type AuthSessionRefreshFields, type AuthSignInConfiguration, type AuthStatelessPreset, type AuthStatelessPresetOptions, type AuthViteHubOptions, type DiscoveredAuthDefinition, type GitHubOrgMemberErrorCode, type GitHubOrgMemberOptions, type RegisteredAuth, type ResolvedAuthViteConfig, type ViteHubAuth, createDatabaseAuthEventStore, defaultAuthEventRetention };
|