@robelest/convex-auth 0.0.4-preview.22 → 0.0.4-preview.24
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 +10 -11
- package/dist/authorization/index.d.ts +1 -1
- package/dist/authorization/index.js +1 -1
- package/dist/authorization/index.js.map +1 -1
- package/dist/client/index.d.ts +1 -2
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +36 -39
- package/dist/client/index.js.map +1 -1
- package/dist/component/client/index.d.ts +1 -2
- package/dist/component/index.js +2 -2
- package/dist/component/model.d.ts +9 -9
- package/dist/component/model.d.ts.map +1 -1
- package/dist/component/public/enterprise/audit.d.ts.map +1 -1
- package/dist/component/public/enterprise/audit.js.map +1 -1
- package/dist/component/public/enterprise/core.d.ts.map +1 -1
- package/dist/component/public/enterprise/core.js.map +1 -1
- package/dist/component/public/enterprise/domains.d.ts.map +1 -1
- package/dist/component/public/enterprise/domains.js.map +1 -1
- package/dist/component/public/enterprise/scim.d.ts.map +1 -1
- package/dist/component/public/enterprise/scim.js.map +1 -1
- package/dist/component/public/enterprise/secrets.d.ts.map +1 -1
- package/dist/component/public/enterprise/secrets.js.map +1 -1
- package/dist/component/public/enterprise/webhooks.d.ts.map +1 -1
- package/dist/component/public/enterprise/webhooks.js.map +1 -1
- package/dist/component/public/factors/devices.d.ts.map +1 -1
- package/dist/component/public/factors/devices.js.map +1 -1
- package/dist/component/public/factors/passkeys.d.ts.map +1 -1
- package/dist/component/public/factors/passkeys.js.map +1 -1
- package/dist/component/public/factors/totp.d.ts.map +1 -1
- package/dist/component/public/factors/totp.js.map +1 -1
- package/dist/component/public/groups/core.js.map +1 -1
- package/dist/component/public/groups/invites.d.ts.map +1 -1
- package/dist/component/public/groups/invites.js.map +1 -1
- package/dist/component/public/groups/members.d.ts.map +1 -1
- package/dist/component/public/groups/members.js.map +1 -1
- package/dist/component/public/identity/accounts.d.ts.map +1 -1
- package/dist/component/public/identity/accounts.js.map +1 -1
- package/dist/component/public/identity/codes.d.ts.map +1 -1
- package/dist/component/public/identity/codes.js.map +1 -1
- package/dist/component/public/identity/sessions.d.ts.map +1 -1
- package/dist/component/public/identity/sessions.js.map +1 -1
- package/dist/component/public/identity/tokens.d.ts.map +1 -1
- package/dist/component/public/identity/tokens.js.map +1 -1
- package/dist/component/public/identity/users.d.ts.map +1 -1
- package/dist/component/public/identity/users.js.map +1 -1
- package/dist/component/public/identity/verifiers.d.ts.map +1 -1
- package/dist/component/public/identity/verifiers.js.map +1 -1
- package/dist/component/public/security/keys.d.ts.map +1 -1
- package/dist/component/public/security/keys.js.map +1 -1
- package/dist/component/public/security/limits.d.ts.map +1 -1
- package/dist/component/public/security/limits.js.map +1 -1
- package/dist/component/schema.d.ts +41 -41
- package/dist/component/server/auth.d.ts +127 -130
- package/dist/component/server/auth.d.ts.map +1 -1
- package/dist/component/server/auth.js +100 -64
- package/dist/component/server/auth.js.map +1 -1
- package/dist/component/server/context.js +53 -0
- package/dist/component/server/context.js.map +1 -0
- package/dist/component/server/core.js +113 -250
- package/dist/component/server/core.js.map +1 -1
- package/dist/component/server/crypto.js +25 -7
- package/dist/component/server/crypto.js.map +1 -1
- package/dist/component/server/device.js +59 -16
- package/dist/component/server/device.js.map +1 -1
- package/dist/component/server/enterprise/domain.js +148 -59
- package/dist/component/server/enterprise/domain.js.map +1 -1
- package/dist/component/server/enterprise/http.js +36 -15
- package/dist/component/server/enterprise/http.js.map +1 -1
- package/dist/component/server/enterprise/oidc.js +1 -1
- package/dist/component/server/http.d.ts +85 -0
- package/dist/component/server/http.d.ts.map +1 -0
- package/dist/component/server/http.js +85 -22
- package/dist/component/server/http.js.map +1 -1
- package/dist/component/server/identity.js +5 -2
- package/dist/component/server/identity.js.map +1 -1
- package/dist/component/server/limits.js +21 -30
- package/dist/component/server/limits.js.map +1 -1
- package/dist/component/server/mutations/account.js +12 -10
- package/dist/component/server/mutations/account.js.map +1 -1
- package/dist/component/server/mutations/code.js +5 -2
- package/dist/component/server/mutations/code.js.map +1 -1
- package/dist/component/server/mutations/invalidate.js +1 -1
- package/dist/component/server/mutations/invalidate.js.map +1 -1
- package/dist/component/server/mutations/oauth.js +10 -4
- package/dist/component/server/mutations/oauth.js.map +1 -1
- package/dist/component/server/mutations/refresh.js +2 -2
- package/dist/component/server/mutations/refresh.js.map +1 -1
- package/dist/component/server/mutations/register.js +46 -42
- package/dist/component/server/mutations/register.js.map +1 -1
- package/dist/component/server/mutations/retrieve.js +21 -25
- package/dist/component/server/mutations/retrieve.js.map +1 -1
- package/dist/component/server/mutations/signature.js +10 -4
- package/dist/component/server/mutations/signature.js.map +1 -1
- package/dist/component/server/mutations/signout.js.map +1 -1
- package/dist/component/server/mutations/store.js +9 -24
- package/dist/component/server/mutations/store.js.map +1 -1
- package/dist/component/server/mutations/verifier.js.map +1 -1
- package/dist/component/server/mutations/verify.js +1 -1
- package/dist/component/server/mutations/verify.js.map +1 -1
- package/dist/component/server/oauth.js +53 -16
- package/dist/component/server/oauth.js.map +1 -1
- package/dist/component/server/passkey.js +115 -31
- package/dist/component/server/passkey.js.map +1 -1
- package/dist/component/server/redirects.js +9 -3
- package/dist/component/server/redirects.js.map +1 -1
- package/dist/component/server/refresh.js +10 -7
- package/dist/component/server/refresh.js.map +1 -1
- package/dist/component/server/runtime.d.ts +5 -5
- package/dist/component/server/runtime.js +156 -113
- package/dist/component/server/runtime.js.map +1 -1
- package/dist/component/server/signin.js +34 -10
- package/dist/component/server/signin.js.map +1 -1
- package/dist/component/server/totp.js +79 -19
- package/dist/component/server/totp.js.map +1 -1
- package/dist/component/server/types.d.ts +12 -20
- package/dist/component/server/types.d.ts.map +1 -1
- package/dist/component/server/types.js.map +1 -1
- package/dist/component/server/users.js +6 -3
- package/dist/component/server/users.js.map +1 -1
- package/dist/component/server/utils.js +10 -4
- package/dist/component/server/utils.js.map +1 -1
- package/dist/core/types.d.ts +14 -22
- package/dist/core/types.d.ts.map +1 -1
- package/dist/factors/device.js +8 -9
- package/dist/factors/device.js.map +1 -1
- package/dist/factors/passkey.js +18 -21
- package/dist/factors/passkey.js.map +1 -1
- package/dist/providers/password.js +66 -81
- package/dist/providers/password.js.map +1 -1
- package/dist/runtime/invite.js +2 -8
- package/dist/runtime/invite.js.map +1 -1
- package/dist/server/auth.d.ts +127 -130
- package/dist/server/auth.d.ts.map +1 -1
- package/dist/server/auth.js +100 -64
- package/dist/server/auth.js.map +1 -1
- package/dist/server/context.d.ts +1 -0
- package/dist/server/context.js +53 -0
- package/dist/server/context.js.map +1 -0
- package/dist/server/core.d.ts +74 -195
- package/dist/server/core.d.ts.map +1 -1
- package/dist/server/core.js +113 -250
- package/dist/server/core.js.map +1 -1
- package/dist/server/crypto.d.ts.map +1 -1
- package/dist/server/crypto.js +25 -7
- package/dist/server/crypto.js.map +1 -1
- package/dist/server/device.js +59 -16
- package/dist/server/device.js.map +1 -1
- package/dist/server/enterprise/domain.d.ts +0 -8
- package/dist/server/enterprise/domain.d.ts.map +1 -1
- package/dist/server/enterprise/domain.js +148 -59
- package/dist/server/enterprise/domain.js.map +1 -1
- package/dist/server/enterprise/http.d.ts.map +1 -1
- package/dist/server/enterprise/http.js +35 -14
- package/dist/server/enterprise/http.js.map +1 -1
- package/dist/server/http.d.ts +81 -3
- package/dist/server/http.d.ts.map +1 -1
- package/dist/server/http.js +84 -21
- package/dist/server/http.js.map +1 -1
- package/dist/server/identity.js +5 -2
- package/dist/server/identity.js.map +1 -1
- package/dist/server/index.d.ts +3 -2
- package/dist/server/index.js +2 -2
- package/dist/server/limits.js +21 -30
- package/dist/server/limits.js.map +1 -1
- package/dist/server/mounts.d.ts +25 -63
- package/dist/server/mounts.d.ts.map +1 -1
- package/dist/server/mounts.js +46 -107
- package/dist/server/mounts.js.map +1 -1
- package/dist/server/mutations/account.d.ts +8 -9
- package/dist/server/mutations/account.d.ts.map +1 -1
- package/dist/server/mutations/account.js +11 -9
- package/dist/server/mutations/account.js.map +1 -1
- package/dist/server/mutations/code.d.ts +12 -12
- package/dist/server/mutations/code.d.ts.map +1 -1
- package/dist/server/mutations/code.js +5 -2
- package/dist/server/mutations/code.js.map +1 -1
- package/dist/server/mutations/invalidate.d.ts +4 -4
- package/dist/server/mutations/invalidate.d.ts.map +1 -1
- package/dist/server/mutations/invalidate.js.map +1 -1
- package/dist/server/mutations/oauth.d.ts +14 -12
- package/dist/server/mutations/oauth.d.ts.map +1 -1
- package/dist/server/mutations/oauth.js +9 -3
- package/dist/server/mutations/oauth.js.map +1 -1
- package/dist/server/mutations/refresh.d.ts +3 -3
- package/dist/server/mutations/refresh.d.ts.map +1 -1
- package/dist/server/mutations/refresh.js +1 -1
- package/dist/server/mutations/refresh.js.map +1 -1
- package/dist/server/mutations/register.d.ts +11 -11
- package/dist/server/mutations/register.d.ts.map +1 -1
- package/dist/server/mutations/register.js +45 -41
- package/dist/server/mutations/register.js.map +1 -1
- package/dist/server/mutations/retrieve.d.ts +6 -6
- package/dist/server/mutations/retrieve.d.ts.map +1 -1
- package/dist/server/mutations/retrieve.js +20 -24
- package/dist/server/mutations/retrieve.js.map +1 -1
- package/dist/server/mutations/signature.d.ts +6 -7
- package/dist/server/mutations/signature.d.ts.map +1 -1
- package/dist/server/mutations/signature.js +9 -3
- package/dist/server/mutations/signature.js.map +1 -1
- package/dist/server/mutations/signin.d.ts +5 -5
- package/dist/server/mutations/signout.js.map +1 -1
- package/dist/server/mutations/store.d.ts +83 -83
- package/dist/server/mutations/store.js +8 -23
- package/dist/server/mutations/store.js.map +1 -1
- package/dist/server/mutations/verifier.js.map +1 -1
- package/dist/server/mutations/verify.d.ts +7 -7
- package/dist/server/mutations/verify.d.ts.map +1 -1
- package/dist/server/mutations/verify.js.map +1 -1
- package/dist/server/oauth.js +53 -16
- package/dist/server/oauth.js.map +1 -1
- package/dist/server/passkey.d.ts +2 -2
- package/dist/server/passkey.d.ts.map +1 -1
- package/dist/server/passkey.js +114 -30
- package/dist/server/passkey.js.map +1 -1
- package/dist/server/redirects.js +9 -3
- package/dist/server/redirects.js.map +1 -1
- package/dist/server/refresh.js +10 -7
- package/dist/server/refresh.js.map +1 -1
- package/dist/server/runtime.d.ts +11 -11
- package/dist/server/runtime.js +155 -112
- package/dist/server/runtime.js.map +1 -1
- package/dist/server/signin.js +34 -10
- package/dist/server/signin.js.map +1 -1
- package/dist/server/ssr.d.ts.map +1 -1
- package/dist/server/ssr.js +175 -184
- package/dist/server/ssr.js.map +1 -1
- package/dist/server/totp.js +78 -18
- package/dist/server/totp.js.map +1 -1
- package/dist/server/types.d.ts +13 -21
- package/dist/server/types.d.ts.map +1 -1
- package/dist/server/types.js.map +1 -1
- package/dist/server/users.js +6 -3
- package/dist/server/users.js.map +1 -1
- package/dist/server/utils.js +10 -4
- package/dist/server/utils.js.map +1 -1
- package/package.json +1 -5
- package/src/authorization/index.ts +1 -1
- package/src/client/core/types.ts +14 -14
- package/src/client/factors/device.ts +10 -12
- package/src/client/factors/passkey.ts +23 -26
- package/src/client/index.ts +54 -64
- package/src/client/runtime/invite.ts +5 -7
- package/src/component/index.ts +9 -3
- package/src/component/public/enterprise/audit.ts +6 -1
- package/src/component/public/enterprise/core.ts +1 -0
- package/src/component/public/enterprise/domains.ts +5 -1
- package/src/component/public/enterprise/scim.ts +1 -0
- package/src/component/public/enterprise/secrets.ts +1 -0
- package/src/component/public/enterprise/webhooks.ts +1 -0
- package/src/component/public/factors/devices.ts +1 -0
- package/src/component/public/factors/passkeys.ts +1 -0
- package/src/component/public/factors/totp.ts +1 -0
- package/src/component/public/groups/core.ts +1 -1
- package/src/component/public/groups/invites.ts +7 -1
- package/src/component/public/groups/members.ts +1 -0
- package/src/component/public/identity/accounts.ts +1 -0
- package/src/component/public/identity/codes.ts +1 -0
- package/src/component/public/identity/sessions.ts +1 -0
- package/src/component/public/identity/tokens.ts +1 -0
- package/src/component/public/identity/users.ts +1 -0
- package/src/component/public/identity/verifiers.ts +1 -0
- package/src/component/public/security/keys.ts +1 -0
- package/src/component/public/security/limits.ts +1 -0
- package/src/providers/password.ts +89 -110
- package/src/server/auth.ts +240 -182
- package/src/server/context.ts +90 -0
- package/src/server/core.ts +195 -286
- package/src/server/crypto.ts +31 -29
- package/src/server/device.ts +65 -32
- package/src/server/enterprise/domain.ts +158 -170
- package/src/server/enterprise/http.ts +46 -39
- package/src/server/http.ts +289 -30
- package/src/server/identity.ts +5 -5
- package/src/server/index.ts +9 -3
- package/src/server/limits.ts +53 -80
- package/src/server/mounts.ts +56 -80
- package/src/server/mutations/account.ts +22 -36
- package/src/server/mutations/code.ts +6 -6
- package/src/server/mutations/invalidate.ts +1 -1
- package/src/server/mutations/oauth.ts +14 -8
- package/src/server/mutations/refresh.ts +5 -4
- package/src/server/mutations/register.ts +87 -132
- package/src/server/mutations/retrieve.ts +44 -44
- package/src/server/mutations/signature.ts +13 -6
- package/src/server/mutations/signout.ts +1 -1
- package/src/server/mutations/store.ts +16 -31
- package/src/server/mutations/verifier.ts +1 -1
- package/src/server/mutations/verify.ts +3 -5
- package/src/server/oauth.ts +60 -69
- package/src/server/passkey.ts +567 -517
- package/src/server/redirects.ts +10 -6
- package/src/server/refresh.ts +14 -18
- package/src/server/runtime.ts +340 -302
- package/src/server/signin.ts +44 -37
- package/src/server/ssr.ts +390 -407
- package/src/server/totp.ts +85 -35
- package/src/server/types.ts +19 -22
- package/src/server/users.ts +7 -6
- package/src/server/utils.ts +10 -12
- package/dist/component/server/authError.js +0 -34
- package/dist/component/server/authError.js.map +0 -1
- package/dist/component/server/errors.d.ts +0 -1
- package/dist/component/server/errors.js +0 -137
- package/dist/component/server/errors.js.map +0 -1
- package/dist/server/authError.d.ts +0 -46
- package/dist/server/authError.d.ts.map +0 -1
- package/dist/server/authError.js +0 -34
- package/dist/server/authError.js.map +0 -1
- package/dist/server/errors.d.ts +0 -177
- package/dist/server/errors.d.ts.map +0 -1
- package/dist/server/errors.js +0 -212
- package/dist/server/errors.js.map +0 -1
- package/src/server/authError.ts +0 -44
- package/src/server/errors.ts +0 -290
package/dist/server/auth.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth.js","names":["AuthFactory"],"sources":["../../src/server/auth.ts"],"sourcesContent":["/**\n * Auth configuration helpers for Convex Auth.\n *\n * @module\n */\n\nimport type { UserIdentity } from \"convex/server\";\nimport type { GenericId } from \"convex/values\";\n\nimport type { AuthApiRefs } from \"../client/index\";\nimport { Auth as AuthFactory } from \"./runtime\";\nimport { AuthError } from \"./authError\";\nimport type { Doc } from \"./types\";\nimport type {\n AuthAuthorizationConfig,\n AuthGrant,\n AuthProviderConfig,\n AuthRoleDefinition,\n AuthRoleId,\n ConvexAuthConfig,\n HasDeviceProvider,\n HasPasskeyProvider,\n HasSSO,\n HasTotpProvider,\n} from \"./types\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Config for auth setup. Extends the standard auth config\n * minus `component` (which is passed as the first constructor argument).\n */\nexport type AuthConfig = Omit<ConvexAuthConfig, \"component\">;\n\n/** Canonical user document type exposed by Convex Auth. */\nexport type UserDoc = Doc<\"User\">;\n\ntype MemberApiWithAuthorization<\n TAuthorization extends AuthAuthorizationConfig | undefined,\n> = Omit<\n ReturnType<typeof AuthFactory>[\"auth\"][\"member\"],\n \"create\" | \"list\" | \"update\" | \"resolve\"\n> & {\n create: (\n ctx: Parameters<\n ReturnType<typeof AuthFactory>[\"auth\"][\"member\"][\"create\"]\n >[0],\n data: {\n groupId: string;\n userId: string;\n roleIds?: AuthRoleId<TAuthorization>[];\n status?: string;\n extend?: Record<string, unknown>;\n },\n ) => Promise<{ ok: true; memberId: string }>;\n list: (\n ctx: Parameters<\n ReturnType<typeof AuthFactory>[\"auth\"][\"member\"][\"list\"]\n >[0],\n opts?: {\n where?: {\n groupId?: string;\n userId?: string;\n roleId?: AuthRoleId<TAuthorization>;\n status?: string;\n };\n limit?: number;\n cursor?: string | null;\n orderBy?: \"_creationTime\" | \"status\";\n order?: \"asc\" | \"desc\";\n },\n ) => ReturnType<ReturnType<typeof AuthFactory>[\"auth\"][\"member\"][\"list\"]>;\n update: (\n ctx: Parameters<\n ReturnType<typeof AuthFactory>[\"auth\"][\"member\"][\"update\"]\n >[0],\n memberId: string,\n data: Record<string, unknown> & { roleIds?: AuthRoleId<TAuthorization>[] },\n ) => Promise<{ ok: true; memberId: string }>;\n resolve: (\n ctx: Parameters<\n ReturnType<typeof AuthFactory>[\"auth\"][\"member\"][\"resolve\"]\n >[0],\n opts: {\n userId: string;\n groupId: string;\n ancestry?: boolean;\n roleIds?: AuthRoleId<TAuthorization>[];\n grants?: AuthGrant<TAuthorization>[];\n maxDepth?: number;\n },\n ) => ReturnType<ReturnType<typeof AuthFactory>[\"auth\"][\"member\"][\"resolve\"]>;\n};\n\n\n/**\n * The base auth API surface returned by {@link createAuth}.\n *\n * Provides core namespaces — `signIn`, `signOut`, `user`, `session`,\n * `member`, `invite`, `group`, `key`, and `http` — that are\n * always available regardless of which providers are configured.\n * Enterprise namespaces (`sso`, `scim`) are added conditionally by\n * {@link AuthApi} when an SSO provider is present.\n *\n * Use this type when you want to describe code that only depends on the\n * standard auth surface and should not assume enterprise features exist.\n *\n * @typeParam TAuthorization - The authorization config, used to narrow\n * role IDs and grant strings on the `member` API.\n */\nexport type AuthApiBase<\n TAuthorization extends AuthAuthorizationConfig | undefined = undefined,\n> = {\n signIn: ReturnType<typeof AuthFactory>[\"signIn\"];\n signOut: ReturnType<typeof AuthFactory>[\"signOut\"];\n store: ReturnType<typeof AuthFactory>[\"store\"];\n user: ReturnType<typeof AuthFactory>[\"auth\"][\"user\"];\n session: ReturnType<typeof AuthFactory>[\"auth\"][\"session\"];\n provider: ReturnType<typeof AuthFactory>[\"auth\"][\"provider\"];\n account: ReturnType<typeof AuthFactory>[\"auth\"][\"account\"];\n group: ReturnType<typeof AuthFactory>[\"auth\"][\"group\"];\n member: MemberApiWithAuthorization<TAuthorization>;\n invite: ReturnType<typeof AuthFactory>[\"auth\"][\"invite\"];\n key: ReturnType<typeof AuthFactory>[\"auth\"][\"key\"];\n http: ReturnType<typeof AuthFactory>[\"auth\"][\"http\"];\n /**\n * Resolve the current user's auth context. Framework-agnostic — use\n * this in fluent-convex middleware, custom wrappers, or anywhere you\n * need the resolved `{ userId, user, groupId, role, grants }` object.\n *\n * Returns `null` when unauthenticated. Does not throw.\n *\n * @param ctx - Convex query, mutation, or action context.\n * @returns The resolved auth context, or `null`.\n *\n * @example fluent-convex middleware\n * ```ts\n * const withAuth = convex.createMiddleware(async (ctx, next) => {\n * return next({ ...ctx, auth: await auth.resolve(ctx) });\n * });\n * ```\n *\n * @example Direct usage in a handler\n * ```ts\n * const resolved = await auth.resolve(ctx);\n * if (!resolved) return { ok: false, code: \"NOT_SIGNED_IN\" };\n * const { userId, grants } = resolved;\n * ```\n */\n resolve: (ctx: any) => Promise<AuthResolvedContext | null>;\n /**\n * Context enrichment for convex-helpers `customQuery` / `customMutation` /\n * `customAction`.\n *\n * Resolves the current user's identity, active group, membership role,\n * and grants, then attaches them to `ctx.auth`. Returns a `Customization`\n * object compatible with convex-helpers' custom function builders.\n *\n * `ctx.auth` is `{ userId, user, groupId, role, grants }` when\n * authenticated, `null` when unauthenticated. No throwing — your\n * handler decides how to respond.\n *\n * @returns A convex-helpers `Customization` object.\n *\n * @example One-time setup in `convex/functions.ts`\n * ```ts\n * import { query, mutation, action } from \"./_generated/server\";\n * import { customQuery, customMutation, customAction } from \"convex-helpers/server/customFunctions\";\n * import { auth } from \"./auth\";\n *\n * export const authQuery = customQuery(query, auth.ctx());\n * export const authMutation = customMutation(mutation, auth.ctx());\n * export const authAction = customAction(action, auth.ctx());\n * ```\n *\n * @example Per-function usage\n * ```ts\n * import { authQuery } from \"./functions\";\n *\n * export const list = authQuery({\n * args: { workspaceId: v.string() },\n * handler: async (ctx, args) => {\n * if (!ctx.auth) return [];\n * const { userId, groupId, grants } = ctx.auth;\n * // business logic\n * },\n * });\n * ```\n */\n ctx: () => {\n args: Record<string, never>;\n input: (ctx: any) => Promise<{\n ctx: { auth: AuthResolvedContext | null };\n args: Record<string, never>;\n }>;\n };\n};\n\n/**\n * Resolved auth context injected into `ctx.auth` by `auth.ctx()` and\n * {@link AuthCtx}. Also the expected return shape for custom\n * {@link AuthCtxConfig.authResolve | authResolve} hooks.\n *\n * - `null` when unauthenticated.\n * - `groupId` is `null` when the user has no active group set.\n * - `role` / `grants` are `null` / `[]` when no active group or no membership.\n *\n * @example\n * ```ts\n * import type { AuthResolvedContext } from \"@robelest/convex-auth/server\";\n *\n * const mockAuth: AuthResolvedContext = {\n * userId: \"user123\" as Id<\"User\">,\n * user: { _id: \"user123\", email: \"test@example.com\" },\n * groupId: \"group456\",\n * role: \"admin\",\n * grants: [\"read\", \"write\"],\n * };\n * ```\n */\nexport type AuthResolvedContext = {\n /** The authenticated user's document ID. */\n userId: GenericId<\"User\">;\n /** The authenticated user's full document. */\n user: UserDoc;\n /** The user's active group ID, or `null` if none set. */\n groupId: string | null;\n /** The user's primary role in the active group, or `null`. */\n role: string | null;\n /** Resolved grant strings from the user's role definitions. */\n grants: string[];\n};\n\ntype AuthCtxBase = {\n getUserIdentity: () => Promise<UserIdentity | null>;\n};\n\ntype RequiredAuthCtxState = AuthCtxBase & AuthResolvedContext;\n\ntype OptionalAuthCtxState = AuthCtxBase & {\n userId: GenericId<\"User\"> | null;\n user: UserDoc | null;\n groupId: string | null;\n role: string | null;\n grants: string[];\n};\n\ntype InternalSsoApi = ReturnType<typeof AuthFactory>[\"auth\"][\"sso\"];\n\ntype PublicSsoAdminApi = {\n connection: InternalSsoApi[\"connection\"] & {\n domain: {\n list: InternalSsoApi[\"domain\"][\"list\"];\n validate: InternalSsoApi[\"domain\"][\"validate\"];\n set: (\n ctx: Parameters<InternalSsoApi[\"connection\"][\"create\"]>[0],\n enterpriseId: string,\n domains: Array<{\n domain: string;\n isPrimary?: boolean;\n }>,\n ) => Promise<{\n ok: true;\n enterpriseId: string;\n domains: Array<{\n domainId: string;\n domain: string;\n isPrimary: boolean;\n verified: boolean;\n verifiedAt: number | null;\n }>;\n }>;\n verification: {\n request: (\n ctx: Parameters<InternalSsoApi[\"connection\"][\"create\"]>[0],\n args: { enterpriseId: string; domain: string },\n ) => Promise<{\n ok: true;\n enterpriseId: string;\n domain: string;\n requestedAt: number;\n expiresAt: number;\n challenge: {\n recordType: \"TXT\";\n recordName: string;\n recordValue: string;\n };\n }>;\n confirm: (\n ctx: Parameters<InternalSsoApi[\"connection\"][\"create\"]>[0],\n args: { enterpriseId: string; domain: string },\n ) => Promise<{\n ok: boolean;\n enterpriseId: string;\n domain: string;\n verifiedAt?: number;\n checks: Array<{ name: string; ok: boolean; message?: string }>;\n }>;\n };\n };\n };\n oidc: Omit<InternalSsoApi[\"oidc\"], \"signIn\">;\n saml: Omit<InternalSsoApi[\"saml\"], \"metadata\">;\n policy: InternalSsoApi[\"policy\"];\n audit: {\n list: InternalSsoApi[\"audit\"][\"list\"];\n };\n webhook: {\n endpoint: InternalSsoApi[\"webhook\"][\"endpoint\"];\n delivery: {\n list: InternalSsoApi[\"webhook\"][\"delivery\"][\"list\"];\n };\n };\n};\n\ntype PublicSsoClientApi = {\n signIn: InternalSsoApi[\"oidc\"][\"signIn\"];\n metadata: InternalSsoApi[\"saml\"][\"metadata\"];\n};\n\ntype PublicSsoApi = {\n admin: PublicSsoAdminApi;\n client: PublicSsoClientApi;\n};\n\ntype PublicScimApi = {\n admin: Omit<InternalSsoApi[\"scim\"], \"getConfigByToken\" | \"identity\">;\n};\n\n/**\n * Extended auth API that includes enterprise SSO and SCIM namespaces.\n *\n * This type is the union of {@link AuthApiBase} plus `sso` (SSO connection\n * management, OIDC/SAML, domain verification, policies, audit, webhooks)\n * and `scim` (SCIM provisioning configuration). It is returned by\n * {@link createAuth} only when `new SSO()` is included in the providers\n * array; otherwise the narrower {@link AuthApiBase} is returned instead.\n * Attempting to access `auth.sso` or `auth.scim` without an SSO provider\n * produces a compile-time error because the return type narrows back to\n * {@link AuthApiBase}.\n *\n * @typeParam TAuthorization - The authorization config, forwarded to\n * {@link AuthApiBase} for typed role IDs and grant strings.\n */\nexport type AuthApi<\n TAuthorization extends AuthAuthorizationConfig | undefined = undefined,\n> = AuthApiBase<TAuthorization> & {\n sso: PublicSsoApi;\n scim: PublicScimApi;\n};\n\n/**\n * The return type of {@link createAuth}.\n *\n * Resolves to {@link AuthApi} (with `sso` and `scim` namespaces) when\n * `new SSO()` is present in the providers array, or to the narrower\n * {@link AuthApiBase} otherwise. This conditional type ensures that\n * enterprise-only APIs are only accessible when the SSO provider is\n * configured, producing a compile-time error if you try to access\n * `auth.sso` without it.\n * This lets application code keep a single `createAuth()` call while still\n * getting provider-aware typing on the resulting API object.\n *\n * @typeParam P - The tuple of provider configs passed to `createAuth`.\n * @typeParam TAuthorization - Optional authorization config for typed roles/grants.\n */\nexport type ConvexAuthResult<\n P extends AuthProviderConfig[],\n TAuthorization extends AuthAuthorizationConfig | undefined = undefined,\n> =\n HasSSO<P> extends true\n ? AuthApi<TAuthorization>\n : AuthApiBase<TAuthorization>;\n\n/**\n * Infer the typed `AuthApiRefs` for the client SDK from a `createAuth` call.\n *\n * Use this as the generic parameter for `client()` on the frontend:\n *\n * ```ts\n * // convex/auth.ts\n * export const auth = createAuth(components.auth, { providers: [...] });\n *\n * // Frontend\n * import type { auth } from \"../convex/auth\";\n * import type { InferClientApi } from \"@robelest/convex-auth/server\";\n * const c = client<InferClientApi<typeof auth>>({ convex, api: api.auth });\n * ```\n *\n * @typeParam T - A ConvexAuthResult to extract the client API from.\n */\nexport type InferClientApi<T> =\n T extends ConvexAuthResult<infer P>\n ? AuthApiRefs<\n HasPasskeyProvider<P>,\n HasTotpProvider<P>,\n HasDeviceProvider<P>\n >\n : AuthApiRefs;\n\n/** @internal */\nexport type AuthLike = Pick<AuthApiBase, \"user\" | \"member\">;\n\n// ============================================================================\n// Auth setup APIs\n// ============================================================================\n\n/**\n * Create an auth API object.\n *\n * When `new SSO()` is included in providers, `auth.sso` and `auth.scim`\n * are available on the returned object. Without it, those namespaces are\n * absent and accessing them is a TypeScript compile error.\n *\n * @param component - The installed auth component reference from\n * `components.auth` in your Convex app definition.\n * @param config - Auth configuration including `providers` and optional\n * `authorization`. All fields from {@link AuthConfig} are accepted\n * except `component` (passed as the first argument).\n * @returns A {@link ConvexAuthResult} object — either {@link AuthApi}\n * (with `sso`/`scim`) or {@link AuthApiBase}, depending on whether\n * an SSO provider is present.\n *\n * @example\n * ```ts\n * export const auth = createAuth(components.auth, {\n * providers: [password(), google()],\n * authorization: { roles },\n * });\n * ```\n *\n * @see {@link AuthCtx}\n */\n\n// ---------------------------------------------------------------------------\n// Function builders — shared auth resolution logic\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve auth context for the current user. Returns the enriched\n * `ctx.auth` object or `null` when unauthenticated.\n *\n * Resolution flow:\n * 1. `user.id(ctx)` → userId or null (exit early)\n * 2. `user.get(ctx, userId)` → user doc (cached per-execution)\n * 3. `user.getActiveGroup(ctx, { userId })` → groupId or null\n * 4. If groupId → `member.resolve(ctx, { userId, groupId })` → role + grants\n */\nasync function resolveAuthContext(auth: AuthLike, ctx: any) {\n const userId = await auth.user.id(ctx);\n if (!userId) return null;\n const user = await auth.user.get(ctx, userId);\n const groupId = await auth.user.getActiveGroup(ctx, { userId });\n let role: string | null = null;\n let grants: string[] = [];\n if (groupId) {\n const resolved = await auth.member.resolve(ctx, { userId, groupId });\n if (resolved.membership) {\n role = resolved.roleIds[0] ?? null;\n grants = resolved.grants;\n }\n }\n return { userId, user, groupId, role, grants };\n}\n\nexport function createAuth<\n P extends AuthProviderConfig[],\n TAuthorization extends AuthAuthorizationConfig | undefined = undefined,\n>(\n component: ConvexAuthConfig[\"component\"],\n config: Omit<AuthConfig, \"providers\" | \"authorization\"> & {\n providers: P;\n authorization?: TAuthorization;\n },\n): ConvexAuthResult<P, TAuthorization> {\n const authResult = AuthFactory({\n ...config,\n component,\n providers: [...config.providers],\n });\n const {\n domain: domainApi,\n scim: scimApi,\n connection: connectionApi,\n audit: auditApi,\n webhook: webhookApi,\n oidc: oidcApi,\n saml: samlApi,\n ...restSso\n } = authResult.auth.sso as InternalSsoApi;\n\n type SetEnterpriseDomains = PublicSsoAdminApi[\"connection\"][\"domain\"][\"set\"];\n type EnterpriseDomainInput = Array<{\n domain: string;\n isPrimary?: boolean;\n }>;\n const setEnterpriseDomains: PublicSsoAdminApi[\"connection\"][\"domain\"][\"set\"] =\n async (\n ctx: Parameters<SetEnterpriseDomains>[0],\n enterpriseId: Parameters<SetEnterpriseDomains>[1],\n domains: EnterpriseDomainInput,\n ) => {\n const enterprise = await connectionApi.get(ctx, enterpriseId);\n if (enterprise === null) {\n throw new AuthError(\n \"INVALID_PARAMETERS\",\n \"Enterprise not found.\",\n ).toConvexError();\n }\n\n const normalized = domains.map((entry: (typeof domains)[number]) => ({\n ...entry,\n domain: entry.domain.trim().toLowerCase(),\n }));\n const deduped = new Map<string, (typeof normalized)[number]>();\n for (const entry of normalized) {\n if (entry.domain.length === 0) {\n throw new AuthError(\n \"INVALID_PARAMETERS\",\n \"Domain must not be empty.\",\n ).toConvexError();\n }\n if (deduped.has(entry.domain)) {\n throw new AuthError(\n \"INVALID_PARAMETERS\",\n `Duplicate domain: ${entry.domain}`,\n ).toConvexError();\n }\n deduped.set(entry.domain, entry);\n }\n\n const nextDomains = [...deduped.values()];\n const primaryCount = nextDomains.filter(\n (entry) => entry.isPrimary,\n ).length;\n if (primaryCount > 1) {\n throw new AuthError(\n \"INVALID_PARAMETERS\",\n \"Only one primary domain may be set.\",\n ).toConvexError();\n }\n if (nextDomains.length > 0 && primaryCount === 0) {\n nextDomains[0] = { ...nextDomains[0], isPrimary: true };\n }\n\n const currentDomains = await domainApi.list(ctx, enterpriseId);\n const currentByDomain = new Map<string, (typeof currentDomains)[number]>(\n currentDomains.map((entry: (typeof currentDomains)[number]) => [\n entry.domain.toLowerCase(),\n entry,\n ]),\n );\n\n for (const existing of currentDomains) {\n if (!deduped.has(existing.domain.toLowerCase())) {\n await domainApi.remove(ctx, existing._id);\n }\n }\n\n for (const nextDomain of nextDomains) {\n const current = currentByDomain.get(nextDomain.domain);\n if (current && current.isPrimary === Boolean(nextDomain.isPrimary)) {\n continue;\n }\n if (current) {\n await domainApi.remove(ctx, current._id);\n }\n const domainId = await domainApi.add(ctx, {\n enterpriseId: enterprise._id,\n groupId: enterprise.groupId,\n domain: nextDomain.domain,\n isPrimary: nextDomain.isPrimary,\n });\n if (current?.verifiedAt !== undefined) {\n await (ctx as any).runMutation(\n component.public.enterpriseDomainVerify,\n {\n domainId,\n verifiedAt: current.verifiedAt,\n },\n );\n }\n }\n\n const updatedDomains = await domainApi.list(ctx, enterpriseId);\n return {\n ok: true as const,\n enterpriseId,\n domains: updatedDomains.map(\n (domain: (typeof updatedDomains)[number]) => ({\n domainId: domain._id,\n domain: domain.domain,\n isPrimary: domain.isPrimary,\n verified: domain.verifiedAt !== undefined,\n verifiedAt: domain.verifiedAt ?? null,\n }),\n ),\n };\n };\n\n const publicSso: PublicSsoApi = {\n admin: {\n ...restSso,\n oidc: {\n ...oidcApi,\n },\n saml: {\n ...samlApi,\n },\n connection: {\n ...connectionApi,\n domain: {\n list: domainApi.list,\n validate: domainApi.validate,\n set: setEnterpriseDomains,\n verification: {\n request: domainApi.verification.request,\n confirm: domainApi.verification.confirm,\n },\n },\n },\n policy: restSso.policy,\n audit: {\n list: auditApi.list,\n },\n webhook: {\n endpoint: webhookApi.endpoint,\n delivery: {\n list: webhookApi.delivery.list,\n },\n },\n },\n client: {\n signIn: oidcApi.signIn,\n metadata: samlApi.metadata,\n },\n };\n\n return {\n signIn: authResult.signIn,\n signOut: authResult.signOut,\n store: authResult.store,\n user: authResult.auth.user,\n session: authResult.auth.session,\n provider: authResult.auth.provider,\n account: authResult.auth.account,\n group: authResult.auth.group,\n member: authResult.auth.member,\n invite: authResult.auth.invite,\n key: authResult.auth.key,\n sso: publicSso,\n scim: {\n admin: {\n configure: scimApi.configure,\n get: scimApi.get,\n validate: scimApi.validate,\n },\n },\n http: authResult.auth.http,\n\n resolve: (ctx: any) => resolveAuthContext(authResult.auth, ctx),\n\n ctx: () => ({\n args: {},\n input: async (ctx: any) => {\n const authCtx = await resolveAuthContext(authResult.auth, ctx);\n return { ctx: { auth: authCtx }, args: {} };\n },\n }),\n } as unknown as ConvexAuthResult<P, TAuthorization>;\n}\n\n// ============================================================================\n// AuthCtx — ctx enrichment for customQuery / customMutation\n// ============================================================================\n\n/**\n * Configuration for {@link AuthCtx} context enrichment.\n *\n * @typeParam TResolve - Extra fields returned from `resolve()` and merged into\n * the resulting `ctx.auth` object.\n */\nexport type AuthCtxConfig<\n TResolve extends Record<string, unknown> = Record<string, never>,\n> = {\n /** Allow unauthenticated callers and return `userId: null` / `user: null`. */\n optional?: boolean;\n /**\n * Attach additional derived fields to the auth context after the base auth\n * context is resolved.\n */\n resolve?: (\n ctx: any,\n user: UserDoc,\n auth: AuthResolvedContext,\n ) => Promise<TResolve> | TResolve;\n /**\n * Override or wrap the base auth resolution used by {@link AuthCtx}.\n *\n * Return `undefined` to fall back to the built-in resolver,\n * `null` for an explicit unauthenticated state, or an\n * {@link AuthResolvedContext} object to provide a pre-resolved auth state.\n * This is useful for tests, proxy auth, impersonation flows, or any\n * environment that needs to inject auth without depending on the standard\n * Convex auth tables.\n *\n * @param ctx - The Convex function context.\n * @param fallback - The built-in auth resolver used by {@link AuthCtx}.\n * @returns Resolved auth state, `null`, or `undefined` to use the fallback.\n *\n * @example\n * ```ts\n * const authCtx = AuthCtx(auth, {\n * authResolve: async (ctx, fallback) => {\n * const injected = getInjectedAuth(ctx);\n * return injected ?? (await fallback());\n * },\n * });\n * ```\n */\n authResolve?: (\n ctx: any,\n fallback: () => Promise<AuthResolvedContext | null>,\n ) =>\n | Promise<AuthResolvedContext | null | undefined>\n | AuthResolvedContext\n | null\n | undefined;\n};\n\n/**\n * Create a context enrichment for `customQuery` / `customMutation` — optional auth.\n *\n * When `optional: true` is set, unauthenticated requests are allowed.\n * The enriched `ctx.auth` will have `userId: null`, `user: null`,\n * `groupId: null`, `role: null`, and `grants: []` for unauthenticated callers.\n *\n * @param auth - The auth API object returned by {@link createAuth}.\n * @param config - Configuration with `optional: true` and an optional\n * `resolve` callback for attaching extra fields to the auth context.\n * @returns An object with `args` and `input` compatible with Convex\n * custom function builders.\n *\n * @example\n * ```ts\n * const authCtx = AuthCtx(auth, {\n * optional: true,\n * resolve: async (_ctx, user) => ({ plan: user?.extend?.plan ?? null }),\n * });\n * ```\n *\n * @see {@link createAuth}\n */\nexport function AuthCtx<\n TResolve extends Record<string, unknown> = Record<string, never>,\n>(\n auth: AuthLike,\n config: AuthCtxConfig<TResolve> & { optional: true },\n): {\n args: {};\n input: (\n ctx: any,\n _args: any,\n _extra?: any,\n ) => Promise<{\n ctx: {\n auth: OptionalAuthCtxState & TResolve;\n };\n args: {};\n }>;\n};\n/**\n * Create a context enrichment for `customQuery` / `customMutation` — required auth (default).\n *\n * When `optional` is omitted or `false`, the inferred type is the authenticated\n * auth shape. At runtime this helper still resolves instead of throwing, so if\n * no user is signed in the returned `ctx.auth.userId` / `ctx.auth.user` are\n * `null`, `ctx.auth.groupId` / `ctx.auth.role` are `null`, and\n * `ctx.auth.grants` is `[]`.\n *\n * @param auth - The auth API object returned by {@link createAuth}.\n * @param config - Optional configuration with a `resolve` callback\n * for attaching extra fields to the auth context.\n * @returns An object with `args` and `input` compatible with Convex\n * custom function builders.\n *\n * @example\n * ```ts\n * const authCtx = AuthCtx(auth, {\n * resolve: async (_ctx, user) => ({ email: user.email }),\n * });\n * ```\n *\n * @see {@link createAuth}\n */\nexport function AuthCtx<\n TResolve extends Record<string, unknown> = Record<string, never>,\n>(\n auth: AuthLike,\n config?: AuthCtxConfig<TResolve>,\n): {\n args: {};\n input: (\n ctx: any,\n _args: any,\n _extra?: any,\n ) => Promise<{\n ctx: {\n auth: RequiredAuthCtxState & TResolve;\n };\n args: {};\n }>;\n};\n// Implementation\nexport function AuthCtx(auth: AuthLike, config?: AuthCtxConfig<any>) {\n return {\n args: {},\n input: async (ctx: any, _args: any, _extra?: any) => {\n const nativeAuth = ctx.auth;\n const getUserIdentity = nativeAuth.getUserIdentity.bind(nativeAuth);\n const fallback = () => resolveAuthContext(auth, ctx);\n\n const authOverride = config?.authResolve\n ? await config.authResolve(ctx, fallback)\n : undefined;\n const resolved =\n authOverride === undefined ? await fallback() : authOverride;\n\n if (resolved === null) {\n return {\n ctx: {\n auth: {\n getUserIdentity,\n userId: null,\n user: null,\n groupId: null,\n role: null,\n grants: [],\n },\n },\n args: {},\n };\n }\n\n const extra = config?.resolve\n ? await config.resolve(ctx, resolved.user, resolved)\n : {};\n\n return {\n ctx: {\n auth: {\n getUserIdentity,\n ...resolved,\n ...extra,\n },\n },\n args: {},\n };\n },\n };\n}\n\n/**\n * Extract the resolved `auth` context type from an {@link AuthCtx} instance.\n *\n * Use this to type function parameters or variables that receive the\n * enriched auth context produced by `AuthCtx`. The inferred type includes\n * `userId`, `user`, `groupId`, `role`, `grants`, `getUserIdentity`, and any\n * additional fields added by the `resolve` callback. This is the generic\n * utility for reusing the enriched auth shape without manually duplicating\n * conditional auth types.\n *\n * @typeParam T - An `AuthCtx` return value (must have an `input` method\n * that returns `{ ctx: { auth: ... } }`).\n *\n * @example\n * ```ts\n * const authCtx = AuthCtx(auth, {\n * resolve: async (ctx, user) => ({ orgId: user.orgId }),\n * });\n * type Auth = InferAuth<typeof authCtx>;\n * // Auth = { userId: Id<\"User\">; user: UserDoc; getUserIdentity: ...; orgId: string }\n * ```\n *\n * @see {@link createAuth}\n */\nexport type InferAuth<\n T extends { input: (...args: any[]) => Promise<{ ctx: { auth: any } }> },\n> = Awaited<ReturnType<T[\"input\"]>>[\"ctx\"][\"auth\"];\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkcA,eAAe,mBAAmB,MAAgB,KAAU;CAC1D,MAAM,SAAS,MAAM,KAAK,KAAK,GAAG,IAAI;AACtC,KAAI,CAAC,OAAQ,QAAO;CACpB,MAAM,OAAO,MAAM,KAAK,K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AAElD,OAAI,aAAa,KACf,QAAO;IACL,KAAK,EACH,MAAM;KACJ;KACA,QAAQ;KACR,MAAM;KACN,SAAS;KACT,MAAM;KACN,QAAQ,EAAE;KACX,EACF;IACD,MAAM,EAAE;IACT;GAGH,MAAM,QAAQ,QAAQ,UAClB,MAAM,OAAO,QAAQ,KAAK,SAAS,MAAM,SAAS,GAClD,EAAE;AAEN,UAAO;IACL,KAAK,EACH,MAAM;KACJ;KACA,GAAG;KACH,GAAG;KACJ,EACF;IACD,MAAM,EAAE;IACT;;EAEJ"}
|
|
1
|
+
{"version":3,"file":"auth.js","names":["getResolvedAuthContext","AuthFactory","config"],"sources":["../../src/server/auth.ts"],"sourcesContent":["/**\n * Auth configuration helpers for Convex Auth.\n *\n * @module\n */\n\nimport { Cv } from \"@robelest/fx/convex\";\nimport type { UserIdentity } from \"convex/server\";\nimport type { GenericId } from \"convex/values\";\n\nimport type { AuthApiRefs } from \"../client/index\";\nimport {\n createUnauthenticatedAuthContext,\n getAuthContext as getResolvedAuthContext,\n} from \"./context\";\nimport { Auth as AuthFactory } from \"./runtime\";\nimport type { Doc } from \"./types\";\nimport type {\n AuthAuthorizationConfig,\n AuthGrant,\n AuthProviderConfig,\n AuthRoleDefinition,\n AuthRoleId,\n ConvexAuthConfig,\n HasDeviceProvider,\n HasPasskeyProvider,\n HasSSO,\n HasTotpProvider,\n} from \"./types\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Config for auth setup. Extends the standard auth config\n * minus `component` (which is passed as the first constructor argument).\n */\nexport type AuthConfig = Omit<ConvexAuthConfig, \"component\">;\n\n/** Canonical user document type exposed by Convex Auth. */\nexport type UserDoc = Doc<\"User\">;\n\ntype MemberApiWithAuthorization<\n TAuthorization extends AuthAuthorizationConfig | undefined,\n> = Omit<\n ReturnType<typeof AuthFactory>[\"auth\"][\"member\"],\n \"create\" | \"list\" | \"update\" | \"inspect\" | \"require\"\n> & {\n create: (\n ctx: Parameters<\n ReturnType<typeof AuthFactory>[\"auth\"][\"member\"][\"create\"]\n >[0],\n data: {\n groupId: string;\n userId: string;\n roleIds?: AuthRoleId<TAuthorization>[];\n status?: string;\n extend?: Record<string, unknown>;\n },\n ) => Promise<{ memberId: string }>;\n list: (\n ctx: Parameters<\n ReturnType<typeof AuthFactory>[\"auth\"][\"member\"][\"list\"]\n >[0],\n opts?: {\n where?: {\n groupId?: string;\n userId?: string;\n roleId?: AuthRoleId<TAuthorization>;\n status?: string;\n };\n limit?: number;\n cursor?: string | null;\n orderBy?: \"_creationTime\" | \"status\";\n order?: \"asc\" | \"desc\";\n },\n ) => ReturnType<ReturnType<typeof AuthFactory>[\"auth\"][\"member\"][\"list\"]>;\n update: (\n ctx: Parameters<\n ReturnType<typeof AuthFactory>[\"auth\"][\"member\"][\"update\"]\n >[0],\n memberId: string,\n data: Record<string, unknown> & { roleIds?: AuthRoleId<TAuthorization>[] },\n ) => Promise<{ memberId: string }>;\n inspect: (\n ctx: Parameters<\n ReturnType<typeof AuthFactory>[\"auth\"][\"member\"][\"inspect\"]\n >[0],\n opts: {\n userId: string;\n groupId: string;\n ancestry?: boolean;\n maxDepth?: number;\n },\n ) => ReturnType<ReturnType<typeof AuthFactory>[\"auth\"][\"member\"][\"inspect\"]>;\n require: (\n ctx: Parameters<\n ReturnType<typeof AuthFactory>[\"auth\"][\"member\"][\"require\"]\n >[0],\n opts: {\n userId: string;\n groupId: string;\n ancestry?: boolean;\n roleIds?: AuthRoleId<TAuthorization>[];\n grants?: AuthGrant<TAuthorization>[];\n maxDepth?: number;\n },\n ) => ReturnType<ReturnType<typeof AuthFactory>[\"auth\"][\"member\"][\"require\"]>;\n};\n\n/**\n * The base auth API surface returned by {@link createAuth}.\n *\n * Provides core namespaces — `signIn`, `signOut`, `user`, `session`,\n * `member`, `invite`, `group`, `key`, and `http` — that are\n * always available regardless of which providers are configured.\n * Enterprise namespaces (`sso`, `scim`) are added conditionally by\n * {@link AuthApi} when an SSO provider is present.\n *\n * Use this type when you want to describe code that only depends on the\n * standard auth surface and should not assume enterprise features exist.\n *\n * @typeParam TAuthorization - The authorization config, used to narrow\n * role IDs and grant strings on the `member` API.\n */\nexport type AuthApiBase<\n TAuthorization extends AuthAuthorizationConfig | undefined = undefined,\n> = {\n signIn: ReturnType<typeof AuthFactory>[\"signIn\"];\n signOut: ReturnType<typeof AuthFactory>[\"signOut\"];\n store: ReturnType<typeof AuthFactory>[\"store\"];\n user: ReturnType<typeof AuthFactory>[\"auth\"][\"user\"];\n session: ReturnType<typeof AuthFactory>[\"auth\"][\"session\"];\n provider: ReturnType<typeof AuthFactory>[\"auth\"][\"provider\"];\n account: ReturnType<typeof AuthFactory>[\"auth\"][\"account\"];\n group: ReturnType<typeof AuthFactory>[\"auth\"][\"group\"];\n member: MemberApiWithAuthorization<TAuthorization>;\n invite: ReturnType<typeof AuthFactory>[\"auth\"][\"invite\"];\n key: ReturnType<typeof AuthFactory>[\"auth\"][\"key\"];\n http: ReturnType<typeof AuthFactory>[\"auth\"][\"http\"];\n /**\n * Resolve the current request's auth context. Framework-agnostic — use\n * this in fluent-convex middleware, custom wrappers, or anywhere you\n * need the current `{ userId, user, groupId, role, grants }` object.\n *\n * Throws a structured `ConvexError` when unauthenticated by default.\n * Pass `{ optional: true }` to get a null-shaped auth object instead.\n *\n * @param ctx - Convex query, mutation, or action context.\n * @param config - Optional auth resolution config. Supports `optional`,\n * `resolve`, and `authResolve`.\n * @returns The current auth context.\n *\n * @example fluent-convex middleware\n * ```ts\n * const withAuth = convex.createMiddleware(async (ctx, next) => {\n * return next({ ...ctx, auth: await auth.context(ctx) });\n * });\n * ```\n *\n * @example Direct usage in a handler\n * ```ts\n * const authContext = await auth.context(ctx);\n * const { userId, grants } = authContext;\n * ```\n *\n * @example Optional usage\n * ```ts\n * const authContext = await auth.context(ctx, { optional: true });\n * if (authContext.userId === null) {\n * return null;\n * }\n * ```\n */\n context: AuthContextResolver;\n /**\n * Context enrichment for convex-helpers `customQuery` / `customMutation` /\n * `customAction`.\n *\n * Resolves the current user's identity, active group, membership role,\n * and grants, then attaches them to `ctx.auth`. Returns a `Customization`\n * object compatible with convex-helpers' custom function builders.\n *\n * `ctx.auth` is the current request auth context.\n * By default this throws when unauthenticated so handlers can assume\n * `ctx.auth.userId` and `ctx.auth.user` exist.\n *\n * @returns A convex-helpers `Customization` object.\n *\n * @example One-time setup in `convex/functions.ts`\n * ```ts\n * import { query, mutation, action } from \"./_generated/server\";\n * import { customQuery, customMutation, customAction } from \"convex-helpers/server/customFunctions\";\n * import { auth } from \"./auth\";\n *\n * export const authQuery = customQuery(query, auth.ctx());\n * export const authMutation = customMutation(mutation, auth.ctx());\n * export const authAction = customAction(action, auth.ctx());\n * ```\n *\n * @example Per-function usage\n * ```ts\n * import { authQuery } from \"./functions\";\n *\n * export const list = authQuery({\n * args: { workspaceId: v.string() },\n * handler: async (ctx, args) => {\n * const { userId, groupId, grants } = ctx.auth;\n * // business logic\n * },\n * });\n * ```\n */\n ctx: AuthContextFactory;\n};\n\n/**\n * Current request auth context injected into `ctx.auth` by `auth.ctx()`. This\n * is the authenticated auth shape returned by {@link createAuth().context}.\n * Optional context builders may still surface nullable fields when\n * `optional: true` is used.\n *\n * - `groupId` is `null` when the user has no active group set.\n * - `role` is `null` when no active group or no membership is resolved.\n * - `grants` is `[]` when no active group or no membership is resolved.\n *\n * @example\n * ```ts\n * import type { AuthContext } from \"@robelest/convex-auth/server\";\n *\n * const mockAuth: AuthContext = {\n * userId: \"user123\" as Id<\"User\">,\n * user: { _id: \"user123\", email: \"test@example.com\" },\n * groupId: \"group456\",\n * role: \"admin\",\n * grants: [\"read\", \"write\"],\n * };\n * ```\n */\nexport type AuthContext = {\n /** The authenticated user's document ID. */\n userId: GenericId<\"User\">;\n /** The authenticated user's full document. */\n user: UserDoc;\n /** The user's active group ID, or `null` if none set. */\n groupId: string | null;\n /** The user's primary role in the active group, or `null`. */\n role: string | null;\n /** Resolved grant strings from the user's role definitions. */\n grants: string[];\n};\n\n/**\n * Nullable auth context returned by `auth.context(ctx, { optional: true })`\n * and injected by `auth.ctx({ optional: true })`.\n *\n * Use this when callers may be unauthenticated but you still want a stable\n * auth-shaped object.\n *\n * - `userId` and `user` are `null` when unauthenticated.\n * - `groupId` and `role` are `null` when no active group is resolved.\n * - `grants` is `[]` when no membership is resolved.\n *\n * @example\n * ```ts\n * const authContext = await auth.context(ctx, { optional: true });\n * if (authContext.userId === null) {\n * return null;\n * }\n * ```\n */\nexport type OptionalAuthContext = {\n /** The authenticated user's document ID, or `null` when unauthenticated. */\n userId: GenericId<\"User\"> | null;\n /** The authenticated user's full document, or `null` when unauthenticated. */\n user: UserDoc | null;\n /** The user's active group ID, or `null` if none is set. */\n groupId: string | null;\n /** The user's primary role in the active group, or `null`. */\n role: string | null;\n /** Resolved grant strings for the active membership, or `[]`. */\n grants: string[];\n};\n\ntype AuthContextBase = {\n getUserIdentity: () => Promise<UserIdentity | null>;\n};\n\ntype RequiredAuthContextState = AuthContextBase & AuthContext;\n\ntype OptionalAuthContextState = AuthContextBase & OptionalAuthContext;\n\ntype ResolvedAuthContext<TResolve> = AuthContext & TResolve;\n\ntype ResolvedOptionalAuthContext<TResolve> = OptionalAuthContext & TResolve;\n\ntype AuthContextResolver = {\n <TResolve extends Record<string, unknown> = Record<string, never>>(\n ctx: any,\n config: AuthContextConfig<TResolve> & { optional: true },\n ): Promise<ResolvedOptionalAuthContext<TResolve>>;\n <TResolve extends Record<string, unknown> = Record<string, never>>(\n ctx: any,\n config?: AuthContextConfig<TResolve>,\n ): Promise<ResolvedAuthContext<TResolve>>;\n};\n\ntype AuthContextCustomization<TAuth> = {\n args: {};\n input: (\n ctx: any,\n _args: any,\n _extra?: any,\n ) => Promise<{\n ctx: {\n auth: TAuth;\n };\n args: {};\n }>;\n};\n\ntype AuthContextFactory = {\n <TResolve extends Record<string, unknown> = Record<string, never>>(\n config: AuthContextConfig<TResolve> & { optional: true },\n ): AuthContextCustomization<OptionalAuthContextState & TResolve>;\n <TResolve extends Record<string, unknown> = Record<string, never>>(\n config?: AuthContextConfig<TResolve>,\n ): AuthContextCustomization<RequiredAuthContextState & TResolve>;\n};\n\ntype InternalSsoApi = ReturnType<typeof AuthFactory>[\"auth\"][\"sso\"];\n\ntype PublicSsoAdminApi = {\n connection: InternalSsoApi[\"connection\"] & {\n domain: {\n list: InternalSsoApi[\"domain\"][\"list\"];\n validate: InternalSsoApi[\"domain\"][\"validate\"];\n set: (\n ctx: Parameters<InternalSsoApi[\"connection\"][\"create\"]>[0],\n enterpriseId: string,\n domains: Array<{\n domain: string;\n isPrimary?: boolean;\n }>,\n ) => Promise<{\n enterpriseId: string;\n domains: Array<{\n domainId: string;\n domain: string;\n isPrimary: boolean;\n verified: boolean;\n verifiedAt: number | null;\n }>;\n }>;\n verification: {\n request: (\n ctx: Parameters<InternalSsoApi[\"connection\"][\"create\"]>[0],\n args: { enterpriseId: string; domain: string },\n ) => Promise<{\n enterpriseId: string;\n domain: string;\n requestedAt: number;\n expiresAt: number;\n challenge: {\n recordType: \"TXT\";\n recordName: string;\n recordValue: string;\n };\n }>;\n confirm: (\n ctx: Parameters<InternalSsoApi[\"connection\"][\"create\"]>[0],\n args: { enterpriseId: string; domain: string },\n ) => Promise<{\n enterpriseId: string;\n domain: string;\n verifiedAt?: number;\n checks: Array<{ name: string; ok: boolean; message?: string }>;\n }>;\n };\n };\n };\n oidc: Omit<InternalSsoApi[\"oidc\"], \"signIn\">;\n saml: Omit<InternalSsoApi[\"saml\"], \"metadata\">;\n policy: InternalSsoApi[\"policy\"];\n audit: {\n list: InternalSsoApi[\"audit\"][\"list\"];\n };\n webhook: {\n endpoint: InternalSsoApi[\"webhook\"][\"endpoint\"];\n delivery: {\n list: InternalSsoApi[\"webhook\"][\"delivery\"][\"list\"];\n };\n };\n};\n\ntype PublicSsoClientApi = {\n signIn: InternalSsoApi[\"oidc\"][\"signIn\"];\n metadata: InternalSsoApi[\"saml\"][\"metadata\"];\n};\n\ntype PublicSsoApi = {\n admin: PublicSsoAdminApi;\n client: PublicSsoClientApi;\n};\n\ntype PublicScimApi = {\n admin: Omit<InternalSsoApi[\"scim\"], \"getConfigByToken\" | \"identity\">;\n};\n\n/**\n * Extended auth API that includes enterprise SSO and SCIM namespaces.\n *\n * This type is the union of {@link AuthApiBase} plus `sso` (SSO connection\n * management, OIDC/SAML, domain verification, policies, audit, webhooks)\n * and `scim` (SCIM provisioning configuration). It is returned by\n * {@link createAuth} only when `new SSO()` is included in the providers\n * array; otherwise the narrower {@link AuthApiBase} is returned instead.\n * Attempting to access `auth.sso` or `auth.scim` without an SSO provider\n * produces a compile-time error because the return type narrows back to\n * {@link AuthApiBase}.\n *\n * @typeParam TAuthorization - The authorization config, forwarded to\n * {@link AuthApiBase} for typed role IDs and grant strings.\n */\nexport type AuthApi<\n TAuthorization extends AuthAuthorizationConfig | undefined = undefined,\n> = AuthApiBase<TAuthorization> & {\n sso: PublicSsoApi;\n scim: PublicScimApi;\n};\n\n/**\n * The return type of {@link createAuth}.\n *\n * Resolves to {@link AuthApi} (with `sso` and `scim` namespaces) when\n * `new SSO()` is present in the providers array, or to the narrower\n * {@link AuthApiBase} otherwise. This conditional type ensures that\n * enterprise-only APIs are only accessible when the SSO provider is\n * configured, producing a compile-time error if you try to access\n * `auth.sso` without it.\n * This lets application code keep a single `createAuth()` call while still\n * getting provider-aware typing on the resulting API object.\n *\n * @typeParam P - The tuple of provider configs passed to `createAuth`.\n * @typeParam TAuthorization - Optional authorization config for typed roles/grants.\n */\nexport type ConvexAuthResult<\n P extends AuthProviderConfig[],\n TAuthorization extends AuthAuthorizationConfig | undefined = undefined,\n> =\n HasSSO<P> extends true\n ? AuthApi<TAuthorization>\n : AuthApiBase<TAuthorization>;\n\n/**\n * Infer the typed `AuthApiRefs` for the client SDK from a `createAuth` call.\n *\n * Use this as the generic parameter for `client()` on the frontend:\n *\n * ```ts\n * // convex/auth.ts\n * export const auth = createAuth(components.auth, { providers: [...] });\n *\n * // Frontend\n * import type { auth } from \"../convex/auth\";\n * import type { InferClientApi } from \"@robelest/convex-auth/server\";\n * const c = client<InferClientApi<typeof auth>>({ convex, api: api.auth });\n * ```\n *\n * @typeParam T - A ConvexAuthResult to extract the client API from.\n */\nexport type InferClientApi<T> =\n T extends ConvexAuthResult<infer P>\n ? AuthApiRefs<\n HasPasskeyProvider<P>,\n HasTotpProvider<P>,\n HasDeviceProvider<P>\n >\n : AuthApiRefs;\n\n/** @internal */\nexport type AuthLike = Pick<AuthApiBase, \"user\" | \"member\">;\n\n// ============================================================================\n// Auth setup APIs\n// ============================================================================\n\n/**\n * Create an auth API object.\n *\n * When `new SSO()` is included in providers, `auth.sso` and `auth.scim`\n * are available on the returned object. Without it, those namespaces are\n * absent and accessing them is a TypeScript compile error.\n *\n * @param component - The installed auth component reference from\n * `components.auth` in your Convex app definition.\n * @param config - Auth configuration including `providers` and optional\n * `authorization`. All fields from {@link AuthConfig} are accepted\n * except `component` (passed as the first argument).\n * @returns A {@link ConvexAuthResult} object — either {@link AuthApi}\n * (with `sso`/`scim`) or {@link AuthApiBase}, depending on whether\n * an SSO provider is present.\n *\n * @example\n * ```ts\n * export const auth = createAuth(components.auth, {\n * providers: [password(), google()],\n * authorization: { roles },\n * });\n * ```\n *\n * @see {@link AuthContextConfig}\n */\n\n// ---------------------------------------------------------------------------\n// Function builders — shared auth resolution logic\n// ---------------------------------------------------------------------------\n\nasync function resolveConfiguredAuthContext(\n auth: AuthLike,\n ctx: any,\n config?: AuthContextConfig<any>,\n): Promise<AuthContext | null> {\n const fallback = () => getResolvedAuthContext(auth, ctx);\n const authOverride = config?.authResolve\n ? await config.authResolve(ctx, fallback)\n : undefined;\n return authOverride === undefined ? await fallback() : authOverride;\n}\n\nfunction createNotSignedInError() {\n return Cv.error({\n code: \"NOT_SIGNED_IN\",\n message: \"Authentication required.\",\n });\n}\n\nasync function createPublicAuthContext(\n auth: AuthLike,\n ctx: any,\n config?: AuthContextConfig<any>,\n) {\n const resolved = await resolveConfiguredAuthContext(auth, ctx, config);\n\n if (resolved === null) {\n if (config?.optional !== true) {\n throw createNotSignedInError();\n }\n return createUnauthenticatedAuthContext();\n }\n\n const extra = config?.resolve\n ? await config.resolve(ctx, resolved.user, resolved)\n : {};\n\n return {\n ...resolved,\n ...extra,\n };\n}\n\nexport function createAuth<\n P extends AuthProviderConfig[],\n TAuthorization extends AuthAuthorizationConfig | undefined = undefined,\n>(\n component: ConvexAuthConfig[\"component\"],\n config: Omit<AuthConfig, \"providers\" | \"authorization\"> & {\n providers: P;\n authorization?: TAuthorization;\n },\n): ConvexAuthResult<P, TAuthorization> {\n const authResult = AuthFactory({\n ...config,\n component,\n providers: [...config.providers],\n });\n const {\n domain: domainApi,\n scim: scimApi,\n connection: connectionApi,\n audit: auditApi,\n webhook: webhookApi,\n oidc: oidcApi,\n saml: samlApi,\n ...restSso\n } = authResult.auth.sso as InternalSsoApi;\n\n type SetEnterpriseDomains = PublicSsoAdminApi[\"connection\"][\"domain\"][\"set\"];\n type EnterpriseDomainInput = Array<{\n domain: string;\n isPrimary?: boolean;\n }>;\n const setEnterpriseDomains: PublicSsoAdminApi[\"connection\"][\"domain\"][\"set\"] =\n async (\n ctx: Parameters<SetEnterpriseDomains>[0],\n enterpriseId: Parameters<SetEnterpriseDomains>[1],\n domains: EnterpriseDomainInput,\n ) => {\n const enterprise = await connectionApi.get(ctx, enterpriseId);\n if (enterprise === null) {\n throw Cv.error({\n code: \"INVALID_PARAMETERS\",\n message: \"Enterprise not found.\",\n });\n }\n\n const normalized = domains.map((entry: (typeof domains)[number]) => ({\n ...entry,\n domain: entry.domain.trim().toLowerCase(),\n }));\n const deduped = new Map<string, (typeof normalized)[number]>();\n for (const entry of normalized) {\n if (entry.domain.length === 0) {\n throw Cv.error({\n code: \"INVALID_PARAMETERS\",\n message: \"Domain must not be empty.\",\n });\n }\n if (deduped.has(entry.domain)) {\n throw Cv.error({\n code: \"INVALID_PARAMETERS\",\n message: `Duplicate domain: ${entry.domain}`,\n });\n }\n deduped.set(entry.domain, entry);\n }\n\n const nextDomains = [...deduped.values()];\n const primaryCount = nextDomains.filter(\n (entry) => entry.isPrimary,\n ).length;\n if (primaryCount > 1) {\n throw Cv.error({\n code: \"INVALID_PARAMETERS\",\n message: \"Only one primary domain may be set.\",\n });\n }\n if (nextDomains.length > 0 && primaryCount === 0) {\n nextDomains[0] = { ...nextDomains[0], isPrimary: true };\n }\n\n const currentDomains = await domainApi.list(ctx, enterpriseId);\n const currentByDomain = new Map<string, (typeof currentDomains)[number]>(\n currentDomains.map((entry: (typeof currentDomains)[number]) => [\n entry.domain.toLowerCase(),\n entry,\n ]),\n );\n\n for (const existing of currentDomains) {\n if (!deduped.has(existing.domain.toLowerCase())) {\n await domainApi.remove(ctx, existing._id);\n }\n }\n\n for (const nextDomain of nextDomains) {\n const current = currentByDomain.get(nextDomain.domain);\n if (current && current.isPrimary === Boolean(nextDomain.isPrimary)) {\n continue;\n }\n if (current) {\n await domainApi.remove(ctx, current._id);\n }\n const domainId = await domainApi.add(ctx, {\n enterpriseId: enterprise._id,\n groupId: enterprise.groupId,\n domain: nextDomain.domain,\n isPrimary: nextDomain.isPrimary,\n });\n if (current?.verifiedAt !== undefined) {\n await (ctx as any).runMutation(\n component.public.enterpriseDomainVerify,\n {\n domainId,\n verifiedAt: current.verifiedAt,\n },\n );\n }\n }\n\n const updatedDomains = await domainApi.list(ctx, enterpriseId);\n return {\n enterpriseId,\n domains: updatedDomains.map(\n (domain: (typeof updatedDomains)[number]) => ({\n domainId: domain._id,\n domain: domain.domain,\n isPrimary: domain.isPrimary,\n verified: domain.verifiedAt !== undefined,\n verifiedAt: domain.verifiedAt ?? null,\n }),\n ),\n };\n };\n\n const publicSso: PublicSsoApi = {\n admin: {\n ...restSso,\n oidc: {\n ...oidcApi,\n },\n saml: {\n ...samlApi,\n },\n connection: {\n ...connectionApi,\n domain: {\n list: domainApi.list,\n validate: domainApi.validate,\n set: setEnterpriseDomains,\n verification: {\n request: domainApi.verification.request,\n confirm: domainApi.verification.confirm,\n },\n },\n },\n policy: restSso.policy,\n audit: {\n list: auditApi.list,\n },\n webhook: {\n endpoint: webhookApi.endpoint,\n delivery: {\n list: webhookApi.delivery.list,\n },\n },\n },\n client: {\n signIn: oidcApi.signIn,\n metadata: samlApi.metadata,\n },\n };\n\n return {\n signIn: authResult.signIn,\n signOut: authResult.signOut,\n store: authResult.store,\n user: authResult.auth.user,\n session: authResult.auth.session,\n provider: authResult.auth.provider,\n account: authResult.auth.account,\n group: authResult.auth.group,\n member: authResult.auth.member,\n invite: authResult.auth.invite,\n key: authResult.auth.key,\n sso: publicSso,\n scim: {\n admin: {\n configure: scimApi.configure,\n get: scimApi.get,\n validate: scimApi.validate,\n },\n },\n http: authResult.auth.http,\n\n context: ((ctx: any, config?: AuthContextConfig<any>) =>\n createPublicAuthContext(authResult.auth, ctx, config)) as AuthContextResolver,\n\n ctx: ((config?: AuthContextConfig<any>) =>\n createAuthContextCustomization(authResult.auth, config)) as AuthContextFactory,\n } as unknown as ConvexAuthResult<P, TAuthorization>;\n}\n\n// ============================================================================\n// auth.ctx() — ctx enrichment for customQuery / customMutation\n// ============================================================================\n\n/**\n * Configuration for {@link createAuth().ctx} context enrichment.\n *\n * The same config shape is also used by {@link createAuth().context}.\n *\n * @typeParam TResolve - Extra fields returned from `resolve()` and merged into\n * the resulting `ctx.auth` object.\n *\n * @example\n * ```ts\n * const authContext = await auth.context(ctx, {\n * resolve: async (_ctx, user, authState) => ({\n * email: user.email,\n * canWrite: authState.grants.includes(\"posts.write\"),\n * }),\n * });\n * ```\n */\nexport type AuthContextConfig<\n TResolve extends Record<string, unknown> = Record<string, never>,\n> = {\n /**\n * Allow unauthenticated callers and return a null-shaped auth object instead\n * of throwing `NOT_SIGNED_IN`.\n */\n optional?: boolean;\n /**\n * Attach additional derived fields to the auth context after the base auth\n * context is resolved.\n *\n * This callback runs only when a user is authenticated.\n */\n resolve?: (\n ctx: any,\n user: UserDoc,\n auth: AuthContext,\n ) => Promise<TResolve> | TResolve;\n /**\n * Override or wrap the base auth resolution used by {@link createAuth().ctx}.\n *\n * Return `undefined` to fall back to the built-in resolver,\n * `null` for an explicit unauthenticated state, or an\n * {@link AuthContext} object to provide a pre-resolved auth state.\n * This is useful for tests, proxy auth, impersonation flows, or any\n * environment that needs to inject auth without depending on the standard\n * Convex auth tables.\n *\n * @param ctx - The Convex function context.\n * @param fallback - The built-in auth resolver used by {@link createAuth().ctx}.\n * @returns Resolved auth state, `null`, or `undefined` to use the fallback.\n *\n * @example\n * ```ts\n * const authCtx = auth.ctx({\n * authResolve: async (ctx, fallback) => {\n * const injected = getInjectedAuth(ctx);\n * return injected ?? (await fallback());\n * },\n * });\n * ```\n */\n authResolve?: (\n ctx: any,\n fallback: () => Promise<AuthContext | null>,\n ) => Promise<AuthContext | null | undefined> | AuthContext | null | undefined;\n};\n\n/**\n * Create a context enrichment for `customQuery` / `customMutation` — optional auth.\n *\n * When `optional: true` is set, unauthenticated requests are allowed.\n * The enriched `ctx.auth` will have `userId: null`, `user: null`,\n * `groupId: null`, `role: null`, and `grants: []` for unauthenticated callers.\n *\n * @param config - Configuration with `optional: true` and an optional\n * `resolve` callback for attaching extra fields to the auth context.\n * @returns An object with `args` and `input` compatible with Convex\n * custom function builders.\n *\n * @example\n * ```ts\n * const authCtx = auth.ctx({\n * optional: true,\n * resolve: async (_ctx, user) => ({ plan: user.extend?.plan ?? null }),\n * });\n * ```\n *\n * @see {@link createAuth}\n */\n\n/**\n * Create a context enrichment for `customQuery` / `customMutation` — required auth (default).\n *\n * When `optional` is omitted or `false`, unauthenticated requests throw a\n * structured `ConvexError` before your handler runs.\n *\n * @param config - Optional configuration with a `resolve` callback\n * for attaching extra fields to the auth context.\n * @returns An object with `args` and `input` compatible with Convex\n * custom function builders.\n *\n * @example\n * ```ts\n * const authCtx = auth.ctx({\n * resolve: async (_ctx, user) => ({ email: user.email }),\n * });\n * ```\n *\n * @see {@link createAuth}\n */\nfunction createAuthContextCustomization(\n auth: AuthLike,\n config?: AuthContextConfig<any>,\n) {\n return {\n args: {},\n input: async (ctx: any, _args: any, _extra?: any) => {\n const nativeAuth = ctx.auth;\n const getUserIdentity = nativeAuth.getUserIdentity.bind(nativeAuth);\n const resolved = await resolveConfiguredAuthContext(auth, ctx, config);\n\n if (resolved === null) {\n if (config?.optional !== true) {\n throw createNotSignedInError();\n }\n return {\n ctx: {\n auth: {\n getUserIdentity,\n ...createUnauthenticatedAuthContext(),\n },\n },\n args: {},\n };\n }\n\n const extra = config?.resolve\n ? await config.resolve(ctx, resolved.user, resolved)\n : {};\n\n return {\n ctx: {\n auth: {\n getUserIdentity,\n ...resolved,\n ...extra,\n },\n },\n args: {},\n };\n },\n };\n}\n\n/**\n * Extract the resolved `auth` context type from an `auth.ctx()` customization.\n *\n * Use this to type function parameters or variables that receive the\n * enriched auth context produced by `auth.ctx()`. The inferred type includes\n * `userId`, `user`, `groupId`, `role`, `grants`, `getUserIdentity`, and any\n * additional fields added by the `resolve` callback. This is the generic\n * utility for reusing the enriched auth shape without manually duplicating\n * conditional auth types.\n *\n * @typeParam T - An `auth.ctx()` return value (must have an `input` method\n * that returns `{ ctx: { auth: ... } }`).\n *\n * @example\n * ```ts\n * const authCtx = auth.ctx({\n * resolve: async (ctx, user) => ({ orgId: user.orgId }),\n * });\n * type Auth = InferAuth<typeof authCtx>;\n * // Auth = { userId: Id<\"User\">; user: UserDoc; getUserIdentity: ...; orgId: string }\n * ```\n *\n * @see {@link createAuth}\n */\nexport type InferAuth<\n T extends { input: (...args: any[]) => Promise<{ ctx: { auth: any } }> },\n> = Awaited<ReturnType<T[\"input\"]>>[\"ctx\"][\"auth\"];\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAugBA,eAAe,6BACb,MACA,KACA,QAC6B;CAC7B,MAAM,iBAAiBA,eAAuB,MAAM,IAAI;CACxD,MAAM,eAAe,QAAQ,cACzB,MAAM,OAAO,YAAY,KAAK,SAAS,GACvC;AACJ,QAAO,iBAAiB,SAAY,MAAM,UAAU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ACJ;MACA,GAAG,kCAAkC;MACtC,EACF;KACD,MAAM,EAAE;KACT;;GAGH,MAAM,QAAQ,QAAQ,UAClB,MAAM,OAAO,QAAQ,KAAK,SAAS,MAAM,SAAS,GAClD,EAAE;AAEN,UAAO;IACL,KAAK,EACH,MAAM;KACJ;KACA,GAAG;KACH,GAAG;KACJ,EACF;IACD,MAAM,EAAE;IACT;;EAEJ"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { };
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { userIdFromIdentitySubject } from "./identity.js";
|
|
2
|
+
|
|
3
|
+
//#region src/server/context.ts
|
|
4
|
+
/** @internal */
|
|
5
|
+
async function getSessionUserId(ctx) {
|
|
6
|
+
const identity = await ctx.auth.getUserIdentity();
|
|
7
|
+
if (identity === null) return null;
|
|
8
|
+
return userIdFromIdentitySubject(identity.subject);
|
|
9
|
+
}
|
|
10
|
+
/** @internal */
|
|
11
|
+
async function getAuthContextForUser(auth, ctx, userId) {
|
|
12
|
+
const user = await auth.user.get(ctx, userId);
|
|
13
|
+
const groupId = await auth.user.getActiveGroup(ctx, { userId });
|
|
14
|
+
let role = null;
|
|
15
|
+
let grants = [];
|
|
16
|
+
if (groupId) {
|
|
17
|
+
const resolved = await auth.member.inspect(ctx, {
|
|
18
|
+
userId,
|
|
19
|
+
groupId
|
|
20
|
+
});
|
|
21
|
+
if (resolved.membership) {
|
|
22
|
+
role = resolved.roleIds[0] ?? null;
|
|
23
|
+
grants = resolved.grants;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
return {
|
|
27
|
+
userId,
|
|
28
|
+
user,
|
|
29
|
+
groupId,
|
|
30
|
+
role,
|
|
31
|
+
grants
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
/** @internal */
|
|
35
|
+
async function getAuthContext(auth, ctx) {
|
|
36
|
+
const userId = await getSessionUserId(ctx);
|
|
37
|
+
if (userId === null) return null;
|
|
38
|
+
return await getAuthContextForUser(auth, ctx, userId);
|
|
39
|
+
}
|
|
40
|
+
/** @internal */
|
|
41
|
+
function createUnauthenticatedAuthContext() {
|
|
42
|
+
return {
|
|
43
|
+
userId: null,
|
|
44
|
+
user: null,
|
|
45
|
+
groupId: null,
|
|
46
|
+
role: null,
|
|
47
|
+
grants: []
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
//#endregion
|
|
52
|
+
export { createUnauthenticatedAuthContext, getAuthContext, getAuthContextForUser, getSessionUserId };
|
|
53
|
+
//# sourceMappingURL=context.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context.js","names":[],"sources":["../../src/server/context.ts"],"sourcesContent":["import type { UserIdentity } from \"convex/server\";\n\nimport { userIdFromIdentitySubject } from \"./identity\";\nimport type { AuthContext, AuthLike, OptionalAuthContext, UserDoc } from \"./auth\";\n\ntype AuthIdentityCtx = {\n auth: {\n getUserIdentity: () => Promise<UserIdentity | null>;\n };\n};\n\ntype AuthContextResolverLike = {\n user: {\n get: (ctx: any, userId: string) => Promise<UserDoc>;\n getActiveGroup: (\n ctx: any,\n args: { userId: string },\n ) => Promise<string | null>;\n };\n member: {\n inspect: (\n ctx: any,\n args: { userId: string; groupId: string },\n ) => Promise<{\n membership: unknown;\n roleIds: string[];\n grants: string[];\n }>;\n };\n};\n\n/** @internal */\nexport async function getSessionUserId(\n ctx: AuthIdentityCtx,\n): Promise<string | null> {\n const identity = await ctx.auth.getUserIdentity();\n if (identity === null) {\n return null;\n }\n return userIdFromIdentitySubject(identity.subject);\n}\n\n/** @internal */\nexport async function getAuthContextForUser(\n auth: AuthContextResolverLike,\n ctx: any,\n userId: string,\n): Promise<AuthContext> {\n const user = await auth.user.get(ctx, userId);\n const groupId = await auth.user.getActiveGroup(ctx, { userId });\n let role: string | null = null;\n let grants: string[] = [];\n if (groupId) {\n const resolved = await auth.member.inspect(ctx, { userId, groupId });\n if (resolved.membership) {\n role = resolved.roleIds[0] ?? null;\n grants = resolved.grants;\n }\n }\n return {\n userId: userId as AuthContext[\"userId\"],\n user,\n groupId,\n role,\n grants,\n };\n}\n\n/** @internal */\nexport async function getAuthContext(\n auth: AuthLike,\n ctx: AuthIdentityCtx & Record<string, unknown>,\n): Promise<AuthContext | null> {\n const userId = await getSessionUserId(ctx);\n if (userId === null) {\n return null;\n }\n return await getAuthContextForUser(auth, ctx, userId);\n}\n\n/** @internal */\nexport function createUnauthenticatedAuthContext(): OptionalAuthContext {\n return {\n userId: null,\n user: null,\n groupId: null,\n role: null,\n grants: [],\n };\n}\n"],"mappings":";;;;AAgCA,eAAsB,iBACpB,KACwB;CACxB,MAAM,WAAW,MAAM,IAAI,KAAK,iBAAiB;AACjD,KAAI,aAAa,KACf,QAAO;AAET,QAAO,0BAA0B,SAAS,QAAQ;;;AAIpD,eAAsB,sBACpB,MACA,KACA,QACsB;CACtB,MAAM,OAAO,MAAM,KAAK,KAAK,IAAI,KAAK,OAAO;CAC7C,MAAM,UAAU,MAAM,KAAK,KAAK,eAAe,KAAK,EAAE,QAAQ,CAAC;CAC/D,IAAI,OAAsB;CAC1B,IAAI,SAAmB,EAAE;AACzB,KAAI,SAAS;EACX,MAAM,WAAW,MAAM,KAAK,OAAO,QAAQ,KAAK;GAAE;GAAQ;GAAS,CAAC;AACpE,MAAI,SAAS,YAAY;AACvB,UAAO,SAAS,QAAQ,MAAM;AAC9B,YAAS,SAAS;;;AAGtB,QAAO;EACG;EACR;EACA;EACA;EACA;EACD;;;AAIH,eAAsB,eACpB,MACA,KAC6B;CAC7B,MAAM,SAAS,MAAM,iBAAiB,IAAI;AAC1C,KAAI,WAAW,KACb,QAAO;AAET,QAAO,MAAM,sBAAsB,MAAM,KAAK,OAAO;;;AAIvD,SAAgB,mCAAwD;AACtE,QAAO;EACL,QAAQ;EACR,MAAM;EACN,SAAS;EACT,MAAM;EACN,QAAQ,EAAE;EACX"}
|