@robelest/convex-auth 0.0.4-preview.21 → 0.0.4-preview.23
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/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/convex.config.d.ts +2 -2
- package/dist/component/convex.config.d.ts.map +1 -1
- package/dist/component/model.d.ts +5 -5
- 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 +39 -39
- package/dist/component/server/auth.d.ts +95 -52
- package/dist/component/server/auth.d.ts.map +1 -1
- package/dist/component/server/auth.js +63 -43
- package/dist/component/server/auth.js.map +1 -1
- package/dist/component/server/core.js +116 -235
- 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 +58 -15
- 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.js +26 -21
- 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 +3 -3
- package/dist/component/server/runtime.d.ts.map +1 -1
- package/dist/component/server/runtime.js +62 -20
- 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 +95 -52
- package/dist/server/auth.d.ts.map +1 -1
- package/dist/server/auth.js +63 -43
- package/dist/server/auth.js.map +1 -1
- package/dist/server/core.d.ts +71 -159
- package/dist/server/core.d.ts.map +1 -1
- package/dist/server/core.js +116 -235
- 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 +58 -15
- 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 +2 -2
- package/dist/server/http.d.ts.map +1 -1
- package/dist/server/http.js +25 -20
- 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 +2 -2
- package/dist/server/limits.js +21 -30
- package/dist/server/limits.js.map +1 -1
- package/dist/server/mounts.d.ts +26 -64
- package/dist/server/mounts.d.ts.map +1 -1
- package/dist/server/mounts.js +45 -106
- 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 +13 -13
- 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 +12 -10
- 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/signin.d.ts.map +1 -1
- package/dist/server/mutations/signout.js.map +1 -1
- package/dist/server/mutations/store.d.ts +97 -97
- package/dist/server/mutations/store.d.ts.map +1 -1
- 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 +10 -10
- 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 +14 -14
- package/dist/server/runtime.d.ts.map +1 -1
- package/dist/server/runtime.js +61 -19
- 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 +2 -6
- package/src/authorization/index.ts +1 -1
- package/src/cli/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 +1 -0
- 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 +177 -111
- package/src/server/core.ts +197 -233
- 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 +36 -30
- package/src/server/identity.ts +5 -5
- package/src/server/index.ts +2 -0
- package/src/server/limits.ts +53 -80
- package/src/server/mounts.ts +47 -74
- 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 +70 -55
- 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 { Fx } from \"@robelest/fx\";\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\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()`.\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 */\nexport type AuthResolvedContext = {\n /** The authenticated user's document ID. */\n userId: string;\n /** The authenticated user's full document. */\n user: any;\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 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\">;\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: any, 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/** Canonical user document type exposed by Convex Auth. */\nexport type UserDoc = Doc<\"User\">;\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 user is resolved.\n */\n resolve?: (ctx: any, user: UserDoc) => Promise<TResolve> | TResolve;\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` and `user: null`\n * 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: {\n getUserIdentity: () => Promise<UserIdentity | null>;\n userId: GenericId<\"User\"> | null;\n user: UserDoc | null;\n } & 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` and `ctx.auth.user` are\n * `null`.\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: {\n getUserIdentity: () => Promise<UserIdentity | null>;\n userId: GenericId<\"User\">;\n user: UserDoc;\n } & 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 modeDispatch =\n config?.optional === true\n ? { mode: \"optional\" as const }\n : { mode: \"required\" as const };\n\n const userContext = await Fx.run(\n Fx.match(modeDispatch, modeDispatch.mode, {\n optional: async () => {\n const userId = await auth.user.id(ctx);\n if (!userId) {\n return null;\n }\n const user = await auth.user.get(ctx, userId);\n return { userId, user };\n },\n required: async () => {\n const userId = await auth.user.id(ctx);\n if (!userId) {\n return null;\n }\n const user = await auth.user.get(ctx, userId);\n return { userId, user };\n },\n }),\n );\n\n if (userContext === null) {\n return {\n ctx: {\n auth: {\n getUserIdentity: nativeAuth.getUserIdentity.bind(nativeAuth),\n userId: null,\n user: null,\n },\n },\n args: {},\n };\n }\n\n const extra = config?.resolve\n ? await config.resolve(ctx, userContext.user)\n : {};\n\n return {\n ctx: {\n auth: {\n getUserIdentity: nativeAuth.getUserIdentity.bind(nativeAuth),\n userId: userContext.userId,\n user: userContext.user,\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`, `getUserIdentity`, and any additional fields added\n * by the `resolve` callback. This is the generic utility for reusing the\n * enriched auth shape without manually duplicating 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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmaA,eAAe,mBAAmB,MAAW,KAAU;CACrD,MAAM,SAAS,MAAM,KAAK,KAAK,GAAG,IAAI;AACtC,KAAI,CAAC,OAAQ,QAAO;CACpB,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;EAAE;EAAQ;EAAM;EAAS;EAAM;EAAQ;;AAGhD,SAAgB,WAId,WACA,QAIqC;CACrC,MAAM,aAAaA,KAAY;EAC7B,GAAG;EACH;EACA,WAAW,CAAC,GAAG,OAAO,UAAU;EACjC,CAAC;CACF,MAAM,EACJ,QAAQ,WACR,MAAM,SACN,YAAY,eACZ,OAAO,UACP,SAAS,YACT,MAAM,SACN,MAAM,SACN,GAAG,YACD,WAAW,KAAK;CAOpB,MAAM,uBACJ,OACE,KACA,cACA,YACG;EACH,MAAM,aAAa,MAAM,cAAc,IAAI,KAAK,aAAa;AAC7D,MAAI,eAAe,KACjB,OAAM,IAAI,UACR,sBACA,wBACD,CAAC,eAAe;EAGnB,MAAM,aAAa,QAAQ,KAAK,WAAqC;GACnE,GAAG;GACH,QAAQ,MAAM,OAAO,MAAM,CAAC,aAAa;GAC1C,EAAE;EACH,MAAM,0BAAU,IAAI,KAA0C;AAC9D,OAAK,MA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,SAAgB,QAAQ,MAAgB,QAA6B;AACnE,QAAO;EACL,MAAM,EAAE;EACR,OAAO,OAAO,KAAU,OAAY,WAAiB;GACnD,MAAM,aAAa,IAAI;GACvB,MAAM,eACJ,QAAQ,aAAa,OACjB,EAAE,MAAM,YAAqB,GAC7B,EAAE,MAAM,YAAqB;GAEnC,MAAM,cAAc,MAAM,GAAG,IAC3B,GAAG,MAAM,cAAc,aAAa,MAAM;IACxC,UAAU,YAAY;KACpB,MAAM,SAAS,MAAM,KAAK,KAAK,GAAG,IAAI;AACtC,SAAI,CAAC,OACH,QAAO;AAGT,YAAO;MAAE;MAAQ,MADJ,MAAM,KAAK,KAAK,IAAI,KAAK,OAAO;MACtB;;IAEzB,UAAU,YAAY;KACpB,MAAM,SAAS,MAAM,KAAK,KAAK,GAAG,IAAI;AACtC,SAAI,CAAC,OACH,QAAO;AAGT,YAAO;MAAE;MAAQ,MADJ,MAAM,KAAK,KAAK,IAAI,KAAK,OAAO;MACtB;;IAE1B,CAAC,CACH;AAED,OAAI,gBAAgB,KAClB,QAAO;IACL,KAAK,EACH,MAAM;KACJ,iBAAiB,WAAW,gBAAgB,KAAK,WAAW;KAC5D,QAAQ;KACR,MAAM;KACP,EACF;IACD,MAAM,EAAE;IACT;GAGH,MAAM,QAAQ,QAAQ,UAClB,MAAM,OAAO,QAAQ,KAAK,YAAY,KAAK,GAC3C,EAAE;AAEN,UAAO;IACL,KAAK,EACH,MAAM;KACJ,iBAAiB,WAAW,gBAAgB,KAAK,WAAW;KAC5D,QAAQ,YAAY;KACpB,MAAM,YAAY;KAClB,GAAG;KACJ,EACF;IACD,MAAM,EAAE;IACT;;EAEJ"}
|
|
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 { 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 { 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.\n *\n * @param ctx - Convex query, mutation, or action context.\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 context: (ctx: any) => Promise<AuthContext>;\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: () => {\n args: Record<string, never>;\n input: (ctx: any) => Promise<{\n ctx: { auth: AuthContext };\n args: Record<string, never>;\n }>;\n };\n};\n\n/**\n * Current request auth context injected into `ctx.auth` by `auth.ctx()` and\n * {@link AuthCtx}. This is the authenticated auth shape returned by\n * {@link createAuth().context}. Optional context builders may still surface\n * nullable fields when `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\ntype AuthCtxBase = {\n getUserIdentity: () => Promise<UserIdentity | null>;\n};\n\ntype RequiredAuthCtxState = AuthCtxBase & AuthContext;\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 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 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.inspect(ctx, { userId, groupId })` → role + grants\n */\nasync function getAuthContext(\n auth: AuthLike,\n ctx: any,\n): Promise<AuthContext | null> {\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.inspect(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 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: async (ctx: any) => {\n const authContext = await getAuthContext(authResult.auth, ctx);\n if (authContext === null) {\n throw Cv.error({\n code: \"NOT_SIGNED_IN\",\n message: \"Authentication required.\",\n });\n }\n return authContext;\n },\n\n ctx: () => ({\n args: {},\n input: async (ctx: any) => {\n const authCtx = await getAuthContext(authResult.auth, ctx);\n if (authCtx === null) {\n throw Cv.error({\n code: \"NOT_SIGNED_IN\",\n message: \"Authentication required.\",\n });\n }\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: AuthContext,\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 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 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<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 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`, unauthenticated requests throw a\n * structured `ConvexError` before your handler runs.\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 = () => getAuthContext(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 if (config?.optional !== true) {\n throw Cv.error({\n code: \"NOT_SIGNED_IN\",\n message: \"Authentication required.\",\n });\n }\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwcA,eAAe,eACb,MACA,KAC6B;CAC7B,MAAM,SAAS,MAAM,KAAK,KAAK,GAAG,IAAI;AACtC,KAAI,CAAC,OAAQ,QAAO;CACpB,MAAM,OAAO,MAAM,KAAK,KAAK,IAAI,KAAK,OAAO;CAC7C,MAAM,UAAU,MAAM,KAAK,KAAK,eAAe,KAAK,EA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