@ai-development-environment/server 0.0.145 → 0.0.146
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/package.json +1 -1
- package/standalone/.next/BUILD_ID +1 -1
- package/standalone/.next/app-path-routes-manifest.json +2 -0
- package/standalone/.next/build-manifest.json +3 -3
- package/standalone/.next/prerender-manifest.json +3 -3
- package/standalone/.next/routes-manifest.json +12 -0
- package/standalone/.next/server/app/.well-known/[...path]/route.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(auth)/register/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(auth)/register/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(auth)/sign-in/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(auth)/sign-in/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/ai/costs/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/ai/costs/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/ai/drafts/new/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/ai/drafts/new/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/ai/drafts/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/ai/drafts/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/ai/plans/[runId]/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/ai/plans/[runId]/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/ai/plans/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/ai/plans/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/ai/sessions/[runId]/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/ai/sessions/[runId]/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/ai/sessions/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/ai/sessions/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/ai/skills/[skillId]/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/ai/skills/[skillId]/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/ai/skills/groups/[groupId]/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/ai/skills/groups/[groupId]/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/ai/skills/groups/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/ai/skills/groups/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/ai/skills/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/ai/skills/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/ai/skills/sync/[runId]/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/ai/skills/sync/[runId]/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/ai/usage/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/ai/usage/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/action-center/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/action-center/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/agents/[id]/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/agents/[id]/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/agents/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/agents/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/apps/[appId]/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/apps/[appId]/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/apps/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/apps/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/builds/[buildId]/coverage/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/builds/[buildId]/coverage/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/builds/[buildId]/output/route.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/builds/[buildId]/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/builds/[buildId]/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/builds/configurations/[configurationId]/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/builds/configurations/[configurationId]/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/builds/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/builds/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/changes/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/changes/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/codebases/[codebaseId]/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/codebases/[codebaseId]/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/codebases/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/codebases/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/codebases/repositories/[repositoryId]/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/codebases/repositories/[repositoryId]/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/commands/[commandId]/edit/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/commands/[commandId]/edit/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/commands/new/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/commands/new/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/commands/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/commands/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/commands/runs/[runId]/output/route.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/commands/runs/[runId]/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/commands/runs/[runId]/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/jobs/[jobId]/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/jobs/[jobId]/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/notifications/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/notifications/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/workflows/[workflowId]/edit/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/workflows/[workflowId]/edit/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/workflows/[workflowId]/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/workflows/[workflowId]/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/workflows/new/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/workflows/new/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/workflows/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/workflows/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/workflows/runs/[runId]/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/workflows/runs/[runId]/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/worktrees/[worktreeId]/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/worktrees/[worktreeId]/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/worktrees/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/worktrees/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/debugging/analytics-events/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/debugging/analytics-events/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/debugging/console-logs/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/debugging/console-logs/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/debugging/crashes/[crashId]/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/debugging/crashes/[crashId]/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/debugging/crashes/dsyms/[dsymId]/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/debugging/crashes/dsyms/[dsymId]/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/debugging/crashes/dsyms/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/debugging/crashes/dsyms/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/debugging/crashes/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/debugging/crashes/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/debugging/push-notifications/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/debugging/push-notifications/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/debugging/sse/[endpointId]/mocks/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/debugging/sse/[endpointId]/mocks/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/debugging/sse/[endpointId]/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/debugging/sse/[endpointId]/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/debugging/sse/breakpoints/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/debugging/sse/breakpoints/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/debugging/sse/history/[requestId]/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/debugging/sse/history/[requestId]/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/debugging/sse/history/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/debugging/sse/history/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/debugging/sse/new/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/debugging/sse/new/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/debugging/sse/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/debugging/sse/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/debugging/sse/storage/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/debugging/sse/storage/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/debugging/unified-events/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/debugging/unified-events/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/github/actions/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/github/actions/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/github/actions-cache/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/github/actions-cache/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/github/cache/entries/[id]/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/github/cache/entries/[id]/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/github/cache/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/github/cache/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/github/comments/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/github/comments/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/github/pull-requests/[owner]/[repository]/[number]/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/github/pull-requests/[owner]/[repository]/[number]/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/github/pull-requests/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/github/pull-requests/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/github/webhooks/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/github/webhooks/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/gitlab/cache/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/gitlab/cache/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/gitlab/comments/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/gitlab/comments/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/gitlab/merge-requests/[projectId]/[iid]/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/gitlab/merge-requests/[projectId]/[iid]/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/gitlab/merge-requests/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/gitlab/merge-requests/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/gitlab/pipelines/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/gitlab/pipelines/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/gitlab/webhooks/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/gitlab/webhooks/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/jira/cache/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/jira/cache/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/jira/cache/tickets/[issueKey]/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/jira/cache/tickets/[issueKey]/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/jira/tickets/[issueKey]/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/jira/tickets/[issueKey]/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/jira/tickets/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/jira/tickets/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/jira/webhooks/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/jira/webhooks/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/system/api-keys/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/system/api-keys/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/system/build-data/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/system/build-data/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/system/connected-applications/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/system/connected-applications/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/system/credentials/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/system/credentials/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/system/devices/[id]/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/system/devices/[id]/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/system/devices/enroll/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/system/devices/enroll/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/system/devices/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/system/devices/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/system/polling/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/system/polling/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/system/prepare/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/system/prepare/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/system/provisioning-profiles/[profileId]/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/system/provisioning-profiles/[profileId]/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/system/provisioning-profiles/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/system/provisioning-profiles/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/system/settings/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/system/settings/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/system/status/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/system/status/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/system/tailscale/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/system/tailscale/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/system/tools/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/system/tools/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/system/users/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/system/users/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(mcp)/mcp/consent/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(mcp)/mcp/consent/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/(mcp)/mcp/sign-in/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(mcp)/mcp/sign-in/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/_global-error.html +1 -1
- package/standalone/.next/server/app/_global-error.rsc +1 -1
- package/standalone/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
- package/standalone/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
- package/standalone/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
- package/standalone/.next/server/app/_not-found.html +1 -1
- package/standalone/.next/server/app/_not-found.rsc +1 -1
- package/standalone/.next/server/app/_not-found.segments/_full.segment.rsc +1 -1
- package/standalone/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
- package/standalone/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
- package/standalone/.next/server/app/api/agent/build-artifact-transfers/[transferId]/complete/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/agent/build-artifact-transfers/[transferId]/download/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/agent/build-artifact-transfers/[transferId]/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/agent/build-artifact-transfers/[transferId]/upload/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/agent/dsyms/[dsymId]/dwarf/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/agent/run-attachments/[attachmentId]/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/auth/[...all]/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/auth/config/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/auth/management/api-keys/[keyId]/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/auth/management/api-keys/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/auth/management/registration/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/auth/management/sessions/[sessionId]/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/auth/management/users/[userId]/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/auth/management/users/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/auth/mcp-connections/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/auth/mobile/complete/route/app-paths-manifest.json +3 -0
- package/standalone/.next/server/app/api/auth/mobile/complete/route/build-manifest.json +12 -0
- package/standalone/.next/server/app/api/auth/mobile/complete/route/server-reference-manifest.json +4 -0
- package/standalone/.next/server/app/api/auth/mobile/complete/route.js +27 -0
- package/standalone/.next/server/app/api/auth/mobile/complete/route.js.map +5 -0
- package/standalone/.next/server/app/api/auth/mobile/complete/route.js.nft.json +1 -0
- package/standalone/.next/server/app/api/auth/mobile/complete/route_client-reference-manifest.js +3 -0
- package/standalone/.next/server/app/api/auth/mobile/oauth/complete/route.js +7 -7
- package/standalone/.next/server/app/api/auth/mobile/oauth/complete/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/auth/mobile/oauth/start/route.js +7 -7
- package/standalone/.next/server/app/api/auth/mobile/oauth/start/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/auth/mobile/redeem/route.js +8 -8
- package/standalone/.next/server/app/api/auth/mobile/redeem/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/auth/mobile/start/route/app-paths-manifest.json +3 -0
- package/standalone/.next/server/app/api/auth/mobile/start/route/build-manifest.json +12 -0
- package/standalone/.next/server/app/api/auth/mobile/start/route/server-reference-manifest.json +4 -0
- package/standalone/.next/server/app/api/auth/mobile/start/route.js +27 -0
- package/standalone/.next/server/app/api/auth/mobile/start/route.js.map +5 -0
- package/standalone/.next/server/app/api/auth/mobile/start/route.js.nft.json +1 -0
- package/standalone/.next/server/app/api/auth/mobile/start/route_client-reference-manifest.js +3 -0
- package/standalone/.next/server/app/api/build-artifact-uploads/[uploadId]/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/codebases/by-path/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/codebases/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/crash-files/dsyms/[dsymId]/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/crash-files/reports/[crashId]/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/dsyms/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/dsyms/uploads/[uploadId]/complete/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/dsyms/uploads/[uploadId]/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/dsyms/uploads/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/graphql/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/ios/apns-devices/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/ios/devices/export.tsv/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/ios/enrollment/start/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/ios/notification-devices/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/mcp/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/public/builds/[buildId]/artifacts/[artifactId]/manifest.plist/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/public/builds/[buildId]/artifacts/[artifactId]/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/public/crashes/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/public/github/webhook/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/public/gitlab/webhook/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/public/ios/enrollment-profile/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/public/ios/profile-response/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/public/jira/webhook/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/public/sse/[token]/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/run-attachments/[attachmentId]/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/run-attachments/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/sse/history/export/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/telemetry/analytics-events/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/telemetry/console-logs/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/telemetry/export/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/tools/call/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/tools/catalog/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/worktrees/[worktreeId]/diff-image/route.js.nft.json +1 -1
- package/standalone/.next/server/app-paths-manifest.json +2 -0
- package/standalone/.next/server/chunks/[root-of-the-server]__08_7puebrvq1u._.js +3 -0
- package/standalone/.next/server/chunks/[root-of-the-server]__0q53u1lz9zcel._.js +3 -0
- package/standalone/.next/server/chunks/[root-of-the-server]__0w_fiath2ph0r._.js +3 -0
- package/standalone/.next/server/chunks/{[root-of-the-server]__0ju8rf-41j6tg._.js → [root-of-the-server]__0wklpoczsamtz._.js} +1 -1
- package/standalone/.next/server/chunks/[root-of-the-server]__1p6yaef-nnj9f._.js +3 -0
- package/standalone/.next/server/chunks/[root-of-the-server]__1yi2awtahh06l._.js +3 -0
- package/standalone/.next/server/chunks/_00gwh-xp3pnpi._.js +1 -1
- package/standalone/.next/server/chunks/_01xn06357g7fo._.js +1 -1
- package/standalone/.next/server/chunks/_02howx6vajt3x._.js +1 -1
- package/standalone/.next/server/chunks/_07bdynyr-ww6v._.js +1 -1
- package/standalone/.next/server/chunks/_0_6e6kxry26k1._.js +1 -1
- package/standalone/.next/server/chunks/_0a8wo5-9_cv91._.js +1 -1
- package/standalone/.next/server/chunks/_0c6k8a0d2f3tn._.js +3 -0
- package/standalone/.next/server/chunks/_0gaxgdz7o4e15._.js +1 -1
- package/standalone/.next/server/chunks/_0m2wnzdzbny6g._.js +1 -1
- package/standalone/.next/server/chunks/_0naxf7ngn48-a._.js +1 -1
- package/standalone/.next/server/chunks/_0vlhouch-s4pc._.js +1 -1
- package/standalone/.next/server/chunks/_0yuq4ngrjch9x._.js +12 -12
- package/standalone/.next/server/chunks/_13lj4necdms38._.js +3 -0
- package/standalone/.next/server/chunks/_15xfyrp3ns4se._.js +1 -1
- package/standalone/.next/server/chunks/_1cexgfaro_78_._.js +1 -1
- package/standalone/.next/server/chunks/_1ftldg0qwxhfp._.js +12 -12
- package/standalone/.next/server/chunks/_1rfrstxzen60k._.js +12 -12
- package/standalone/.next/server/chunks/_1x3jv-sohpxg7._.js +12 -12
- package/standalone/.next/server/chunks/_1yawotm_tvy7h._.js +12 -12
- package/standalone/.next/server/chunks/_next-internal_server_app_api_auth_mobile_complete_route_actions_1iv1ncqhts5t2.js +3 -0
- package/standalone/.next/server/chunks/_next-internal_server_app_api_auth_mobile_start_route_actions_1n1uwu0lm0vgh.js +3 -0
- package/standalone/.next/server/chunks/src_app_api_auth_mobile_pkce_ts_0yvx0rhy5xij_._.js +3 -0
- package/standalone/.next/server/chunks/src_services_auth_054qv1_ze5hs6._.js +1 -1
- package/standalone/.next/server/chunks/src_services_auth_mcp-oauth_ts_0u9lgdhxzq5oy._.js +1 -1
- package/standalone/.next/server/chunks/ssr/{_0i3_5985sl3t6._.js → _0i28drefwqlu4._.js} +1 -1
- package/standalone/.next/server/chunks/ssr/{_20vs1czk-ajfp._.js → _0xvm24-eb9_vn._.js} +1 -1
- package/standalone/.next/server/chunks/ssr/{node_modules_@xterm_1gr72n7t9__g9._.js → node_modules_@xterm_15gm8vmx8nfth._.js} +1 -1
- package/standalone/.next/server/chunks/ssr/src_components_app-shell_tsx_0e1q-gvlrd7c8._.js +10 -10
- package/standalone/.next/server/chunks/ssr/src_components_auth_auth-form_tsx_1qbcqfp1650nl._.js +1 -1
- package/standalone/.next/server/chunks/ssr/src_services_auth_auth_ts_1zu3fo64zql9-._.js +2 -2
- package/standalone/.next/server/middleware-build-manifest.js +3 -3
- package/standalone/.next/server/pages/404.html +1 -1
- package/standalone/.next/server/pages/500.html +1 -1
- package/standalone/.next/server/preview-props.json +3 -3
- package/standalone/.next/server/server-reference-manifest.js +1 -1
- package/standalone/.next/server/server-reference-manifest.json +1 -1
- package/standalone/.next/static/chunks/{2aosjxs--k-i6.js → 07vm24tcai0yl.js} +10 -10
- package/standalone/.next/static/chunks/27ctd15f1bo-u.js +1 -0
- package/standalone/.next/static/chunks/{0nyv6hb43lli8.css → 2mh1ywtaqbgzw.css} +1 -1
- package/standalone/.next/server/chunks/[root-of-the-server]__0mh8vw5y7dcse._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__0sz_ys90gtn-r._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__1wa8r7gv5fbny._.js +0 -3
- package/standalone/.next/static/chunks/2qfttxgi_zspw.js +0 -1
- /package/standalone/.next/static/{dabvyPp7MJv8L1G5zvDel → gBLSSraJl0DtgK3pbYety}/_buildManifest.js +0 -0
- /package/standalone/.next/static/{dabvyPp7MJv8L1G5zvDel → gBLSSraJl0DtgK3pbYety}/_clientMiddlewareManifest.js +0 -0
- /package/standalone/.next/static/{dabvyPp7MJv8L1G5zvDel → gBLSSraJl0DtgK3pbYety}/_ssgManifest.js +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
module.exports=[363004,931129,950551,342e3,729522,100762,661372,374091,339507,204721,e=>{"use strict";let t,r,i,a,o=(0,e.i(672823).f)({INVALID_METADATA_TYPE:"metadata must be an object or undefined",REFILL_AMOUNT_AND_INTERVAL_REQUIRED:"refillAmount is required when refillInterval is provided",REFILL_INTERVAL_AND_AMOUNT_REQUIRED:"refillInterval is required when refillAmount is provided",USER_BANNED:"User is banned",UNAUTHORIZED_SESSION:"Unauthorized or invalid session",KEY_NOT_FOUND:"API Key not found",KEY_DISABLED:"API Key is disabled",KEY_EXPIRED:"API Key has expired",USAGE_EXCEEDED:"API Key has reached its usage limit",KEY_NOT_RECOVERABLE:"API Key is not recoverable",EXPIRES_IN_IS_TOO_SMALL:"The expiresIn is smaller than the predefined minimum value.",EXPIRES_IN_IS_TOO_LARGE:"The expiresIn is larger than the predefined maximum value.",INVALID_REMAINING:"The remaining count is either too large or too small.",INVALID_PREFIX_LENGTH:"The prefix length is either too large or too small.",INVALID_NAME_LENGTH:"The name length is either too large or too small.",METADATA_DISABLED:"Metadata is disabled.",RATE_LIMIT_EXCEEDED:"Rate limit exceeded.",NO_VALUES_TO_UPDATE:"No values to update.",KEY_DISABLED_EXPIRATION:"Custom key expiration values are disabled.",INVALID_API_KEY:"Invalid API key.",INVALID_USER_ID_FROM_API_KEY:"The user id from the API key is invalid.",INVALID_REFERENCE_ID_FROM_API_KEY:"The reference id from the API key is invalid.",INVALID_API_KEY_GETTER_RETURN_TYPE:"API Key getter returned an invalid key type. Expected string.",SERVER_ONLY_PROPERTY:"The property you're trying to set can only be set from the server auth instance only.",FAILED_TO_UPDATE_API_KEY:"Failed to update API key",NAME_REQUIRED:"API Key name is required.",ORGANIZATION_ID_REQUIRED:"Organization ID is required for organization-owned API keys.",USER_NOT_MEMBER_OF_ORGANIZATION:"You are not a member of the organization that owns this API key.",INSUFFICIENT_API_KEY_PERMISSIONS:"You do not have permission to perform this action on organization API keys.",NO_DEFAULT_API_KEY_CONFIGURATION_FOUND:"No default api-key configuration found.",ORGANIZATION_PLUGIN_REQUIRED:"Organization plugin is required for organization-owned API keys. Please install and configure the organization plugin."});var n,s=e.i(890659),l=e.i(835860),c=e.i(530501),d=e.i(282318),u=e.i(71616),p=e.i(112996),f=e.i(824374);let{get:m}=(0,f.z)(()=>new Set);async function h(e){(await m()).add(e)}var g=e.i(51144),w=e.i(756023),y=e.i(818195),b=e.i(630283),E=e.i(907855),A=e.i(754257);async function I(e,t,r){let i=e.length;if(0===i)return[];let{signal:a}=r;if(a?.aborted)throw a.reason;let o=Math.floor(r.concurrency),n=Math.min(i,o>=1?o:1),s=Array(i),l=0,c=!1,d=async()=>{for(;!c&&l<i;){if(a?.aborted)throw a.reason;let r=l++;try{s[r]=await t(e[r],r)}catch(e){throw c=!0,e}}};return await Promise.all(Array.from({length:n},d)),s}var _=e.i(483319),k=e.i(174311);function T(e){return null==e?null:"object"==typeof e?e:(0,b.f)(e)}function v(e){return null!=e&&"string"==typeof e}async function U(e,t,r){if("database"!==r.storage&&!r.fallbackToDatabase)return;let i=t.filter(e=>v(e.metadata));if(0===i.length)return;let a=i.map(async t=>{let r=T(t.metadata);try{await e.context.adapter.update({model:"apikey",where:[{field:"id",value:t.id}],update:{metadata:r}})}catch(r){e.context.logger.warn(`Failed to migrate double-stringified metadata for API key ${t.id}:`,r)}});await Promise.all(a)}async function R(e,t,r){let i=T(t.metadata);if(v(t.metadata)&&("database"===r.storage||r.fallbackToDatabase))try{await e.context.adapter.update({model:"apikey",where:[{field:"id",value:t.id}],update:{metadata:i}})}catch(r){e.context.logger.warn(`Failed to migrate double-stringified metadata for API key ${t.id}:`,r)}return i}function x(e){return`api-key:${e}`}function S(e){return`api-key:by-id:${e}`}function O(e){return`api-key:by-ref:${e}`}function D(e){if(!e)return null;try{let t="string"==typeof e?JSON.parse(e):e;return{...t,createdAt:new Date(t.createdAt),updatedAt:new Date(t.updatedAt),expiresAt:t.expiresAt?new Date(t.expiresAt):null,lastRefillAt:t.lastRefillAt?new Date(t.lastRefillAt):null,lastRequest:t.lastRequest?new Date(t.lastRequest):null}}catch{return null}}function N(e,t){return t.customStorage?t.customStorage:e.context.secondaryStorage||null}function L(e){if(e.expiresAt){let t=Date.now(),r=Math.floor((new Date(e.expiresAt).getTime()-t)/1e3);if(r>0)return r}}async function P(e,t,r){let i=x(t);return D(await r.get(i))}async function C(e,t,r){let i=S(t);return D(await r.get(i))}let q=new Map;async function j(e,t,r){var i;let a;await (i=async()=>{let i=await e.get(t),a=[];if(i&&"string"==typeof i)try{a=JSON.parse(i)}catch{a=[]}else Array.isArray(i)&&(a=i);let o=r(a);0===o.length?await e.delete(t):await e.set(t,JSON.stringify(o))},a=(q.get(t)??Promise.resolve()).then(i,i).finally(()=>{q.get(t)===a&&q.delete(t)}),q.set(t,a),a)}async function $(e,t,r,i,a){let o=JSON.stringify({...t,createdAt:t.createdAt.toISOString(),updatedAt:t.updatedAt.toISOString(),expiresAt:t.expiresAt?.toISOString()??null,lastRefillAt:t.lastRefillAt?.toISOString()??null,lastRequest:t.lastRequest?.toISOString()??null}),n=O(t.referenceId);a.fallbackToDatabase?await Promise.all([r.set(x(t.key),o,i),r.set(S(t.id),o,i),r.delete(n)]):(await Promise.all([r.set(x(t.key),o,i),r.set(S(t.id),o,i)]),await j(r,n,e=>e.includes(t.id)?e:[...e,t.id]))}async function B(e,t,r,i){let a=O(t.referenceId);i.fallbackToDatabase?await Promise.all([r.delete(x(t.key)),r.delete(S(t.id)),r.delete(a)]):await Promise.all([r.delete(x(t.key)),r.delete(S(t.id)),j(r,a,e=>e.filter(e=>e!==t.id))])}async function V(e,t,r){let i=N(e,r);if("database"===r.storage)return await e.context.adapter.findOne({model:"apikey",where:[{field:"key",value:t}]});if("secondary-storage"===r.storage&&r.fallbackToDatabase){if(i){let r=await P(e,t,i);if(r)return r}let a=await e.context.adapter.findOne({model:"apikey",where:[{field:"key",value:t}]});return a&&i&&await $(e,a,i,L(a),r),a}return"secondary-storage"===r.storage?i?await P(e,t,i):null:await e.context.adapter.findOne({model:"apikey",where:[{field:"key",value:t}]})}async function M(e,t,r){let i=N(e,r);if("database"===r.storage)return await e.context.adapter.findOne({model:"apikey",where:[{field:"id",value:t}]});if("secondary-storage"===r.storage&&r.fallbackToDatabase){if(i){let r=await C(e,t,i);if(r)return r}let a=await e.context.adapter.findOne({model:"apikey",where:[{field:"id",value:t}]});return a&&i&&await $(e,a,i,L(a),r),a}return"secondary-storage"===r.storage?i?await C(e,t,i):null:await e.context.adapter.findOne({model:"apikey",where:[{field:"id",value:t}]})}async function F(e,t,r){let i=N(e,r),a=L(t);if("database"!==r.storage&&"secondary-storage"===r.storage){if(!i)throw Error("Secondary storage is required when storage mode is 'secondary-storage'");await $(e,t,i,a,r);return}}async function K(e,t,r){let i=N(e,r);if("database"!==r.storage&&"secondary-storage"===r.storage){if(!i)throw Error("Secondary storage is required when storage mode is 'secondary-storage'");await B(e,t,i,r);return}}function z(e,t,r,i,a){let o=[...e];if(t){let e=r||"asc";o.sort((r,i)=>{let a=r[t],o=i[t];return null==a&&null==o?0:null==a?"asc"===e?-1:1:null==o?"asc"===e?1:-1:a<o?"asc"===e?-1:1:a>o?"asc"===e?1:-1:0})}return void 0!==a&&(o=o.slice(a)),void 0!==i&&(o=o.slice(0,i)),o}async function H(e,t,r,i){let a=N(e,r),{limit:o,offset:n,sortBy:s,sortDirection:l}=i||{};if("database"===r.storage){let[r,i]=await Promise.all([e.context.adapter.findMany({model:"apikey",where:[{field:"referenceId",value:t}],limit:o,offset:n,sortBy:s?{field:s,direction:l||"asc"}:void 0}),e.context.adapter.count({model:"apikey",where:[{field:"referenceId",value:t}]})]);return{apiKeys:r,total:i}}if("secondary-storage"===r.storage&&r.fallbackToDatabase){let i=O(t);if(a){let t=await a.get(i),r=[];if(t&&"string"==typeof t)try{r=JSON.parse(t)}catch{r=[]}else Array.isArray(t)&&(r=t);if(r.length>0){let t=(await I(r,t=>C(e,t,a),{concurrency:10})).filter(e=>null!=e);return{apiKeys:z(t,s,l,o,n),total:t.length}}}let[c,d]=await Promise.all([e.context.adapter.findMany({model:"apikey",where:[{field:"referenceId",value:t}],limit:o,offset:n,sortBy:s?{field:s,direction:l||"asc"}:void 0}),e.context.adapter.count({model:"apikey",where:[{field:"referenceId",value:t}]})]);if(a&&c.length>0){await I(c,t=>$(e,t,a,L(t),r),{concurrency:10});let t=c.map(e=>e.id);await a.set(i,JSON.stringify(t))}return{apiKeys:c,total:d}}if("secondary-storage"===r.storage){if(!a)return{apiKeys:[],total:0};let r=O(t),i=await a.get(r),c=[];if(i&&"string"==typeof i)try{c=JSON.parse(i)}catch{return{apiKeys:[],total:0}}else{if(!Array.isArray(i))return{apiKeys:[],total:0};c=i}let d=(await I(c,t=>C(e,t,a),{concurrency:10})).filter(e=>null!=e);return{apiKeys:z(d,s,l,o,n),total:d.length}}let[c,d]=await Promise.all([e.context.adapter.findMany({model:"apikey",where:[{field:"referenceId",value:t}],limit:o,offset:n,sortBy:s?{field:s,direction:l||"asc"}:void 0}),e.context.adapter.count({model:"apikey",where:[{field:"referenceId",value:t}]})]);return{apiKeys:c,total:d}}async function W(e,t,r,i){let a=function(e){let t=e.context;if("orgOptions"in t&&t.orgOptions)return t.orgOptions;let r=t.getPlugin?.("organization");return r&&"options"in r?r.options:null}(e);if(!a){let e=o.ORGANIZATION_PLUGIN_REQUIRED;throw u.E.from("INTERNAL_SERVER_ERROR",e)}let n=await e.context.adapter.findOne({model:"member",where:[{field:"userId",value:t},{field:"organizationId",value:r}]});if(!n){let e=o.USER_NOT_MEMBER_OF_ORGANIZATION;throw u.E.from("FORBIDDEN",e)}if(!await Y(e,n.role,r,i,a)){let e=o.INSUFFICIENT_API_KEY_PERMISSIONS;throw u.E.from("FORBIDDEN",e)}return n}async function Y(t,r,i,a,o){let{hasPermission:n}=await e.A(450257);try{return await n({role:r,options:o,permissions:{apiKey:[a]},organizationId:i,allowCreatorAllPermissions:!0},t)}catch{return!1}}let Q=(e,t="ms")=>new Date(Date.now()+("sec"===t?1e3*e:e)),G=E.object({configId:E.string().meta({description:"The configuration ID to use for the API key. If not provided, the default configuration will be used."}).optional(),name:E.string().meta({description:"Name of the Api Key"}).optional(),expiresIn:E.number().meta({description:"Expiration time of the Api Key in seconds"}).min(1).optional().nullable().default(null),prefix:E.string().meta({description:"Prefix of the Api Key"}).regex(/^[a-zA-Z0-9_-]+$/,{message:"Invalid prefix format, must be alphanumeric and contain only underscores and hyphens."}).optional(),remaining:E.number().meta({description:"Remaining number of requests. Server side only"}).min(0).optional().nullable().default(null),metadata:E.any().optional(),refillAmount:E.number().meta({description:"Amount to refill the remaining count of the Api Key. server-only. Eg: 100"}).min(1).optional(),refillInterval:E.number().meta({description:"Interval to refill the Api Key in milliseconds. server-only. Eg: 1000"}).optional(),rateLimitTimeWindow:E.number().meta({description:"The duration in milliseconds where each request is counted. Once the `maxRequests` is reached, the request will be rejected until the `timeWindow` has passed, at which point the `timeWindow` will be reset. server-only. Eg: 1000"}).optional(),rateLimitMax:E.number().meta({description:"Maximum amount of requests allowed within a window. Once the `maxRequests` is reached, the request will be rejected until the `timeWindow` has passed, at which point the `timeWindow` will be reset. server-only. Eg: 100"}).optional(),rateLimitEnabled:E.boolean().meta({description:"Whether the key has rate limiting enabled. server-only. Eg: true"}).optional(),permissions:E.record(E.string(),E.array(E.string())).meta({description:"Permissions of the Api Key."}).optional(),userId:A.f.string().meta({description:'User Id of the user that the Api Key belongs to. server-only. Eg: "user-id"'}).optional(),organizationId:A.f.string().meta({description:"Organization Id of the organization that the Api Key belongs to. Eg: 'org-id'"}).optional()}),J=E.object({configId:E.string().meta({description:"The configuration ID to use for the API key lookup. If not provided, the default configuration will be used."}).optional(),keyId:E.string().meta({description:"The id of the Api Key"})}),Z=E.object({configId:E.string().meta({description:"The configuration ID to use for the API key lookup. If not provided, the default configuration will be used."}).optional(),id:E.string().meta({description:"The id of the Api Key"})}),X=E.object({configId:E.string().meta({description:"Filter by configuration ID. If not provided, returns keys from all configurations."}).optional(),organizationId:E.string().meta({description:"Organization ID to list keys for. If provided, returns organization-owned keys. If not provided, returns user-owned keys."}).optional(),limit:A.f.number().int().nonnegative().meta({description:"The number of API keys to return"}).optional(),offset:A.f.number().int().nonnegative().meta({description:"The offset to start from"}).optional(),sortBy:E.string().meta({description:"The field to sort by (e.g., createdAt, name, expiresAt)"}).optional(),sortDirection:E.enum(["asc","desc"]).meta({description:"The direction to sort by"}).optional()}).optional(),ee=E.object({configId:E.string().meta({description:"The configuration ID to use for the API key lookup. If not provided, the default configuration will be used."}).optional(),keyId:E.string().meta({description:"The id of the Api Key"}),userId:A.f.string().meta({description:'The id of the user which the api key belongs to. server-only. Eg: "some-user-id"'}).optional(),name:E.string().meta({description:"The name of the key"}).optional(),enabled:E.boolean().meta({description:"Whether the Api Key is enabled or not"}).optional(),remaining:E.number().meta({description:"The number of remaining requests"}).min(1).optional(),refillAmount:E.number().meta({description:"The refill amount"}).optional(),refillInterval:E.number().meta({description:"The refill interval"}).optional(),metadata:E.any().optional(),expiresIn:E.number().meta({description:"Expiration time of the Api Key in seconds"}).min(1).optional().nullable(),rateLimitEnabled:E.boolean().meta({description:"Whether the key has rate limiting enabled."}).optional(),rateLimitTimeWindow:E.number().meta({description:"The duration in milliseconds where each request is counted. server-only. Eg: 1000"}).optional(),rateLimitMax:E.number().meta({description:"Maximum amount of requests allowed within a window. Once the `maxRequests` is reached, the request will be rejected until the `timeWindow` has passed, at which point the `timeWindow` will be reset. server-only. Eg: 100"}).optional(),permissions:E.record(E.string(),E.array(E.string())).meta({description:"Update the permissions on the API Key. server-only."}).optional().nullable()});function et(e,t){let r=new Date,i=e.lastRequest,a=e.rateLimitTimeWindow,n=e.rateLimitMax;if(!1===t.rateLimit.enabled||!1===e.rateLimitEnabled)return{type:"skip",lastRequest:r};if(null===a||null===n)return{type:"skip",lastRequest:null};if(null===i)return{type:"start",now:r};let s=r.getTime()-new Date(i).getTime();return s>a?{type:"reset",now:r,windowStart:new Date(r.getTime()-a)}:e.requestCount>=n?{type:"deny",message:o.RATE_LIMIT_EXCEEDED.message,tryAgainIn:Math.ceil(a-s)}:{type:"increment",now:r,max:n,windowStart:new Date(r.getTime()-a)}}async function er({key:e,ctx:t,lookupOpts:r,configurations:i,schema:a,permissions:n,expectedConfigId:s,runCustomValidator:l}){let c=r.disableKeyHashing?e:await ef(e),d=await V(t,c,r);if(!d||void 0!==s&&!ed(d.configId,s))throw u.E.from("UNAUTHORIZED",o.INVALID_API_KEY);let p=el(t.context,i,d.configId);if(l&&p.customAPIKeyValidator&&!await p.customAPIKeyValidator({ctx:t,key:e}))throw u.E.from("UNAUTHORIZED",o.KEY_NOT_FOUND);if(!1===d.enabled)throw u.E.from("UNAUTHORIZED",o.KEY_DISABLED);if(d.expiresAt&&Date.now()>new Date(d.expiresAt).getTime()){let e=async()=>{"secondary-storage"===p.storage&&p.fallbackToDatabase?(await K(t,d,p),await t.context.adapter.delete({model:em,where:[{field:"id",value:d.id}]})):"secondary-storage"===p.storage?await K(t,d,p):await t.context.adapter.delete({model:em,where:[{field:"id",value:d.id}]})};throw p.deferUpdates?t.context.runInBackground(e().catch(e=>{t.context.logger.error("Deferred update failed:",e)})):await e(),u.E.from("UNAUTHORIZED",o.KEY_EXPIRED)}if(n){let e=d.permissions?(0,b.f)(d.permissions):null;if(!e||!(0,_.Y)(e).authorize(n).success)throw u.E.from("UNAUTHORIZED",o.KEY_NOT_FOUND)}if(0===d.remaining&&null===d.refillAmount){let e=async()=>{"secondary-storage"===p.storage&&p.fallbackToDatabase?(await K(t,d,p),await t.context.adapter.delete({model:em,where:[{field:"id",value:d.id}]})):"secondary-storage"===p.storage?await K(t,d,p):await t.context.adapter.delete({model:em,where:[{field:"id",value:d.id}]})};throw p.deferUpdates?t.context.runInBackground(e().catch(e=>{t.context.logger.error("Deferred update failed:",e)})):await e(),u.E.from("TOO_MANY_REQUESTS",o.USAGE_EXCEEDED)}return{apiKey:"database"===p.storage||"secondary-storage"===p.storage&&p.fallbackToDatabase?await ei({ctx:t,apiKey:d,opts:p,hashedKey:c}):await en({ctx:t,apiKey:d,opts:p,hashedKey:c}),opts:p}}async function ei({ctx:e,apiKey:t,opts:r,hashedKey:i}){let a=t;null!==t.remaining&&(a=await ea(e,t)),a=await eo(e,a,r);let n=await e.context.adapter.update({model:em,where:[{field:"id",value:a.id}],update:{updatedAt:new Date}});if(!n)throw u.E.from("UNAUTHORIZED",o.INVALID_API_KEY);return"secondary-storage"===r.storage&&r.fallbackToDatabase&&await F(e,n,r),n}async function ea(e,t){let r=new Date,{refillInterval:i,refillAmount:a}=t;if(i&&a){let o=new Date(t.lastRefillAt??t.createdAt).getTime();if(r.getTime()-o>i){let i=await e.context.adapter.incrementOne({model:em,where:[{field:"id",value:t.id},{field:"lastRefillAt",value:t.lastRefillAt}],increment:{},set:{remaining:a-1,lastRefillAt:r}});if(i)return i}}let n=await e.context.adapter.incrementOne({model:em,where:[{field:"id",value:t.id},{field:"remaining",operator:"gt",value:0}],increment:{remaining:-1}});if(!n)throw u.E.from("TOO_MANY_REQUESTS",o.USAGE_EXCEEDED);return n}async function eo(e,t,r){let i=et(t,r);if("deny"===i.type)throw new u.E("TOO_MANY_REQUESTS",{message:i.message,code:"RATE_LIMITED",details:{tryAgainIn:i.tryAgainIn}});if("skip"===i.type)return null===i.lastRequest?t:await e.context.adapter.update({model:"apikey",where:[{field:"id",value:t.id}],update:{lastRequest:i.lastRequest}})??t;if("increment"===i.type){let a=await e.context.adapter.incrementOne({model:em,where:[{field:"id",value:t.id},{field:"lastRequest",operator:"gt",value:i.windowStart},{field:"requestCount",operator:"lt",value:i.max}],increment:{requestCount:1},set:{lastRequest:i.now}});if(a)return a;let n=await e.context.adapter.findOne({model:em,where:[{field:"id",value:t.id}]});if(!n)throw u.E.from("UNAUTHORIZED",o.INVALID_API_KEY);return eo(e,n,r)}let a="reset"===i.type?{field:"lastRequest",operator:"lte",value:i.windowStart}:{field:"lastRequest",operator:"eq",value:null},n=await e.context.adapter.incrementOne({model:em,where:[{field:"id",value:t.id},a],increment:{},set:{requestCount:1,lastRequest:i.now}});if(n)return n;let s=await e.context.adapter.findOne({model:em,where:[{field:"id",value:t.id}]});if(!s)throw u.E.from("UNAUTHORIZED",o.INVALID_API_KEY);return eo(e,s,r)}async function en({ctx:e,apiKey:t,opts:r,hashedKey:i}){let a=t.remaining,n=t.lastRefillAt;if(null!==a){let e=Date.now(),{refillInterval:r,refillAmount:i}=t,s=new Date(n??t.createdAt).getTime();if(r&&i&&e-s>r&&(a=i,n=new Date),0===a)throw u.E.from("TOO_MANY_REQUESTS",o.USAGE_EXCEEDED);a--}let s={...function(e,t){let r=et(e,t);switch(r.type){case"deny":throw new u.E("TOO_MANY_REQUESTS",{message:r.message,code:"RATE_LIMITED",details:{tryAgainIn:r.tryAgainIn}});case"skip":return null===r.lastRequest?{}:{lastRequest:r.lastRequest};case"start":case"reset":return{lastRequest:r.now,requestCount:1};case"increment":return{lastRequest:r.now,requestCount:e.requestCount+1}}}(t,r),remaining:a,lastRefillAt:n,updatedAt:new Date},l=async()=>{let t=await V(e,i,r);if(!t)return null;let a={...t,...s};return await F(e,a,r),a};if(r.deferUpdates)return e.context.runInBackground(l().catch(t=>{e.context.logger.error("Failed to update API key:",t)})),{...t,...s};let c=await l();if(!c)throw u.E.from("INTERNAL_SERVER_ERROR",o.FAILED_TO_UPDATE_API_KEY);return c}let es=E.object({configId:E.string().meta({description:"Configuration ID to scope verification to. When omitted, the key is validated against its own configuration."}).optional(),key:E.string().meta({description:"The key to verify"}),permissions:E.record(E.string(),E.array(E.string())).meta({description:"The permissions to verify."}).optional()});function el(e,t,r){let i=()=>{let r=t.find(e=>!e.configId||"default"===e.configId);if(!r){e.logger.error("No default api-key configuration found. Either provide an api-key configuration with configId 'default' or provide a configuration with no `configId` set.");let t=o.NO_DEFAULT_API_KEY_CONFIGURATION_FOUND;throw u.E.from("BAD_REQUEST",t)}return{...r,configId:"default"}};return r?t.find(e=>e.configId===r)??i():i()}function ec(e){return!e||"default"===e}function ed(e,t){return!!(ec(e)&&ec(t))||e===t}let eu=null;async function ep(e,t=!1){eu&&!t&&(new Date).getTime()-eu.getTime()<1e4||(eu=new Date,await e.adapter.deleteMany({model:em,where:[{field:"expiresAt",operator:"lt",value:new Date},{field:"expiresAt",operator:"ne",value:null}]}).catch(t=>{e.logger.error("Failed to delete expired API keys:",t)}))}let ef=async e=>{let t=await (0,d.f)("SHA-256").digest(new TextEncoder().encode(e));return c.W.encode(new Uint8Array(t),{padding:!1})},em="apikey";e.s(["f",0,function(e,t){if(Array.isArray(e)&&e.length>0){if(!e.every(e=>e.configId))throw new u.p("configId is required for each API key configuration in the api-key plugin.");let t=e.map(e=>e.configId);if(new Set(t).size!==t.length)throw new u.p("configId must be unique for each API key configuration in the api-key plugin.")}let r=t??{schema:Array.isArray(e)?void 0:e?.schema},i=[...(Array.isArray(e)?e:[e]).map(e=>({...e,apiKeyHeaders:e?.apiKeyHeaders??"x-api-key",defaultKeyLength:e?.defaultKeyLength||64,maximumPrefixLength:e?.maximumPrefixLength??32,minimumPrefixLength:e?.minimumPrefixLength??1,maximumNameLength:e?.maximumNameLength??32,minimumNameLength:e?.minimumNameLength??1,enableMetadata:e?.enableMetadata??!1,disableKeyHashing:e?.disableKeyHashing??!1,requireName:e?.requireName??!1,storage:e?.storage??"database",rateLimit:{enabled:e?.rateLimit?.enabled===void 0||e?.rateLimit?.enabled,timeWindow:e?.rateLimit?.timeWindow??864e5,maxRequests:e?.rateLimit?.maxRequests??10},keyExpiration:{defaultExpiresIn:e?.keyExpiration?.defaultExpiresIn??null,disableCustomExpiresTime:e?.keyExpiration?.disableCustomExpiresTime??!1,maxExpiresIn:e?.keyExpiration?.maxExpiresIn??365,minExpiresIn:e?.keyExpiration?.minExpiresIn??1},startingCharactersConfig:{shouldStore:e?.startingCharactersConfig?.shouldStore??!0,charactersLength:e?.startingCharactersConfig?.charactersLength??6},enableSessionForAPIKeys:e?.enableSessionForAPIKeys??!1,fallbackToDatabase:e?.fallbackToDatabase??!1,customStorage:e?.customStorage,deferUpdates:e?.deferUpdates??!1}))],a=(0,w.C)((({defaultRateLimitMax:e,defaultTimeWindow:t})=>({apikey:{fields:{configId:{type:"string",required:!0,defaultValue:"default",input:!1,index:!0},name:{type:"string",required:!1,input:!1},start:{type:"string",required:!1,input:!1},referenceId:{type:"string",required:!0,input:!1,index:!0},prefix:{type:"string",required:!1,input:!1},key:{type:"string",required:!0,input:!1,index:!0},refillInterval:{type:"number",required:!1,input:!1},refillAmount:{type:"number",required:!1,input:!1},lastRefillAt:{type:"date",required:!1,input:!1},enabled:{type:"boolean",required:!1,input:!1,defaultValue:!0},rateLimitEnabled:{type:"boolean",required:!1,input:!1,defaultValue:!0},rateLimitTimeWindow:{type:"number",required:!1,input:!1,defaultValue:t},rateLimitMax:{type:"number",required:!1,input:!1,defaultValue:e},requestCount:{type:"number",required:!1,input:!1,defaultValue:0},remaining:{type:"number",required:!1,input:!1},lastRequest:{type:"date",required:!1,input:!1},expiresAt:{type:"date",required:!1,input:!1},createdAt:{type:"date",required:!0,input:!1},updatedAt:{type:"date",required:!0,input:!1},permissions:{type:"string",required:!1,input:!1},metadata:{type:"string",required:!1,input:!0,transform:{input:e=>JSON.stringify(e),output:e=>e?(0,k.f)(e):null}}}}}))({defaultRateLimitMax:(1===i.length?i[0]?.rateLimit.maxRequests:void 0)??10,defaultTimeWindow:(1===i.length?i[0]?.rateLimit.timeWindow:void 0)??864e5}),r.schema);function n(e){for(let t of i){if(!t.enableSessionForAPIKeys)continue;let r=function(e,t){if(t.customAPIKeyGetter)return t.customAPIKeyGetter(e);if(Array.isArray(t.apiKeyHeaders)){for(let r of t.apiKeyHeaders){let t=e.headers?.get(r);if(t)return t}return null}return e.headers?.get(t.apiKeyHeaders)??null}(e,t);if(r)return{key:r,config:t}}return null}let c=function({defaultKeyGenerator:e,configurations:t,schema:r}){return{createApiKey:function({defaultKeyGenerator:e,configurations:t,schema:r,deleteAllExpiredApiKeys:i}){return(0,s.g)("/api-key/create",{method:"POST",body:G,metadata:{openapi:{description:"Create a new API key for a user",responses:{200:{description:"API key created successfully",content:{"application/json":{schema:{type:"object",properties:{id:{type:"string",description:"Unique identifier of the API key"},createdAt:{type:"string",format:"date-time",description:"Creation timestamp"},updatedAt:{type:"string",format:"date-time",description:"Last update timestamp"},name:{type:"string",nullable:!0,description:"Name of the API key"},prefix:{type:"string",nullable:!0,description:"Prefix of the API key"},start:{type:"string",nullable:!0,description:"Starting characters of the key (if configured)"},key:{type:"string",description:"The full API key (only returned on creation)"},enabled:{type:"boolean",description:"Whether the key is enabled"},expiresAt:{type:"string",format:"date-time",nullable:!0,description:"Expiration timestamp"},referenceId:{type:"string",description:"ID of the reference owning the key"},lastRefillAt:{type:"string",format:"date-time",nullable:!0,description:"Last refill timestamp"},lastRequest:{type:"string",format:"date-time",nullable:!0,description:"Last request timestamp"},metadata:{type:"object",nullable:!0,additionalProperties:!0,description:"Metadata associated with the key"},rateLimitMax:{type:"number",nullable:!0,description:"Maximum requests in time window"},rateLimitTimeWindow:{type:"number",nullable:!0,description:"Rate limit time window in milliseconds"},remaining:{type:"number",nullable:!0,description:"Remaining requests"},refillAmount:{type:"number",nullable:!0,description:"Amount to refill"},refillInterval:{type:"number",nullable:!0,description:"Refill interval in milliseconds"},rateLimitEnabled:{type:"boolean",description:"Whether rate limiting is enabled"},requestCount:{type:"number",description:"Current request count in window"},permissions:{type:"object",nullable:!0,additionalProperties:{type:"array",items:{type:"string"}},description:"Permissions associated with the key"}},required:["id","createdAt","updatedAt","key","enabled","referenceId","rateLimitEnabled","requestCount"]}}}}}}}},async r=>{let a,n,{configId:s,name:l,expiresIn:c,prefix:d,remaining:f,metadata:m,refillAmount:h,refillInterval:g,permissions:w,rateLimitMax:E,rateLimitTimeWindow:A,rateLimitEnabled:I}=r.body,_=el(r.context,t,s),k=_.customKeyGenerator||e,T=await (0,p.D)(r,{disableCookieCache:!0}),v=r.request||r.headers;if(v&&(void 0!==h||void 0!==g||void 0!==E||void 0!==A||void 0!==I||void 0!==w||null!==f))throw u.E.from("BAD_REQUEST",o.SERVER_ONLY_PROPERTY);if(r.request&&void 0!==r.body.userId)throw u.E.from("UNAUTHORIZED",o.UNAUTHORIZED_SESSION);if("organization"===(_.references??"user")){let e=r.body.organizationId;if(!e){let e=o.ORGANIZATION_ID_REQUIRED;throw u.E.from("BAD_REQUEST",e)}let t=T?.user.id||r.body.userId;if(!t)throw u.E.from("UNAUTHORIZED",o.UNAUTHORIZED_SESSION);await W(r,t,e,"create"),a=e}else if(v){if(!T?.user.id){let e=o.UNAUTHORIZED_SESSION;throw u.E.from("UNAUTHORIZED",e)}a=T.user.id}else{let e=r.body.userId,t=T?.user.id;if(!t&&!e||T&&e&&t!==e){let e=o.UNAUTHORIZED_SESSION;throw u.E.from("UNAUTHORIZED",e)}a=t||e}if(m){if(!1===_.enableMetadata)throw u.E.from("BAD_REQUEST",o.METADATA_DISABLED);if("object"!=typeof m)throw u.E.from("BAD_REQUEST",o.INVALID_METADATA_TYPE)}if(h&&!g){let e=o.REFILL_AMOUNT_AND_INTERVAL_REQUIRED;throw u.E.from("BAD_REQUEST",e)}if(g&&!h){let e=o.REFILL_INTERVAL_AND_AMOUNT_REQUIRED;throw u.E.from("BAD_REQUEST",e)}if(c){if(!0===_.keyExpiration.disableCustomExpiresTime){let e=o.KEY_DISABLED_EXPIRATION;throw u.E.from("BAD_REQUEST",e)}let e=c/86400;if(_.keyExpiration.minExpiresIn>e){let e=o.EXPIRES_IN_IS_TOO_SMALL;throw u.E.from("BAD_REQUEST",e)}if(_.keyExpiration.maxExpiresIn<e){let e=o.EXPIRES_IN_IS_TOO_LARGE;throw u.E.from("BAD_REQUEST",e)}}if(d&&(d.length<_.minimumPrefixLength||d.length>_.maximumPrefixLength))throw u.E.from("BAD_REQUEST",o.INVALID_PREFIX_LENGTH);if(l){if(l.length<_.minimumNameLength||l.length>_.maximumNameLength)throw u.E.from("BAD_REQUEST",o.INVALID_NAME_LENGTH)}else if(_.requireName)throw u.E.from("BAD_REQUEST",o.NAME_REQUIRED);i(r.context);let U=await k({length:_.defaultKeyLength,prefix:d||_.defaultPrefix}),R=_.disableKeyHashing?U:await ef(U),x=null;_.startingCharactersConfig.shouldStore&&(x=U.substring(0,_.startingCharactersConfig.charactersLength));let S=_.permissions?.defaultPermissions?"function"==typeof _.permissions.defaultPermissions?await _.permissions.defaultPermissions(a,r):_.permissions.defaultPermissions:void 0,O=w?JSON.stringify(w):S?JSON.stringify(S):void 0,D={configId:_.configId??"default",createdAt:new Date,updatedAt:new Date,name:l??null,prefix:d??_.defaultPrefix??null,start:x,key:R,enabled:!0,expiresAt:c?Q(c,"sec"):_.keyExpiration.defaultExpiresIn?Q(_.keyExpiration.defaultExpiresIn,"sec"):null,referenceId:a,lastRefillAt:null,lastRequest:null,metadata:null,rateLimitMax:E??_.rateLimit.maxRequests??null,rateLimitTimeWindow:A??_.rateLimit.timeWindow??null,remaining:null===f?f:f??h??null,refillAmount:h??null,refillInterval:g??null,rateLimitEnabled:void 0===I?_.rateLimit.enabled??!0:I,requestCount:0,permissions:O};if(m&&(D.metadata=m),"secondary-storage"===_.storage&&_.fallbackToDatabase)n=await r.context.adapter.create({model:em,data:D}),await F(r,n,_);else if("secondary-storage"===_.storage){let e=r.context.generateId({model:"apikey"})||(0,y.f)();n={...D,id:e},await F(r,n,_)}else n=await r.context.adapter.create({model:em,data:D});return r.json({...n,key:U,metadata:m??null,permissions:n.permissions?(0,b.f)(n.permissions):null})})}({defaultKeyGenerator:e,configurations:t,schema:r,deleteAllExpiredApiKeys:ep}),verifyApiKey:function({configurations:e,schema:t,deleteAllExpiredApiKeys:r}){return s.g.serverOnly({method:"POST",body:es},async i=>{let a,{configId:n,key:s}=i.body,l=el(i.context,e,n);if(void 0!==n&&l.customAPIKeyValidator&&!await l.customAPIKeyValidator({ctx:i,key:s}))return i.json({valid:!1,error:{message:o.INVALID_API_KEY,code:"KEY_NOT_FOUND"},key:null});let c=null;try{let o=await er({key:s,permissions:i.body.permissions,ctx:i,lookupOpts:l,configurations:e,schema:t,expectedConfigId:n,runCustomValidator:void 0===n});c=o.apiKey,(a=o.opts).deferUpdates&&i.context.runInBackground(r(i.context).catch(e=>{i.context.logger.error("Failed to delete expired API keys:",e)}))}catch(e){if(i.context.logger.error("Failed to validate API key:",e),e instanceof u.E||e instanceof u.E||e?.name==="APIError")return i.json({valid:!1,error:{...e.body,message:e.body?.message,code:e.body?.code},key:null});return i.json({valid:!1,error:{message:o.INVALID_API_KEY,code:"INVALID_API_KEY"},key:null})}let{key:d,...p}=c??{key:1,permissions:void 0},f=null;return c&&(f=await R(i,c,a)),p.permissions=p.permissions?(0,b.f)(p.permissions):null,i.json({valid:!0,error:null,key:null===c?null:{...p,metadata:f}})})}({configurations:t,schema:r,deleteAllExpiredApiKeys:ep}),getApiKey:function({configurations:e,schema:t,deleteAllExpiredApiKeys:r}){return(0,s.g)("/api-key/get",{method:"GET",query:Z,use:[p.Z],metadata:{openapi:{description:"Retrieve an existing API key by ID",responses:{200:{description:"API key retrieved successfully",content:{"application/json":{schema:{type:"object",properties:{id:{type:"string",description:"ID"},name:{type:"string",nullable:!0,description:"The name of the key"},start:{type:"string",nullable:!0,description:"Shows the first few characters of the API key, including the prefix. This allows you to show those few characters in the UI to make it easier for users to identify the API key."},prefix:{type:"string",nullable:!0,description:"The API Key prefix. Stored as plain text."},userId:{type:"string",description:"The owner of the user id"},refillInterval:{type:"number",nullable:!0,description:"The interval in milliseconds between refills of the `remaining` count. Example: 3600000 // refill every hour (3600000ms = 1h)"},refillAmount:{type:"number",nullable:!0,description:"The amount to refill"},lastRefillAt:{type:"string",format:"date-time",nullable:!0,description:"The last refill date"},enabled:{type:"boolean",description:"Sets if key is enabled or disabled",default:!0},rateLimitEnabled:{type:"boolean",description:"Whether the key has rate limiting enabled"},rateLimitTimeWindow:{type:"number",nullable:!0,description:"The duration in milliseconds"},rateLimitMax:{type:"number",nullable:!0,description:"Maximum amount of requests allowed within a window"},requestCount:{type:"number",description:"The number of requests made within the rate limit time window"},remaining:{type:"number",nullable:!0,description:"Remaining requests (every time api key is used this should updated and should be updated on refill as well)"},lastRequest:{type:"string",format:"date-time",nullable:!0,description:"When last request occurred"},expiresAt:{type:"string",format:"date-time",nullable:!0,description:"Expiry date of a key"},createdAt:{type:"string",format:"date-time",description:"created at"},updatedAt:{type:"string",format:"date-time",description:"updated at"},metadata:{type:"object",nullable:!0,additionalProperties:!0,description:"Extra metadata about the apiKey"},permissions:{type:"string",nullable:!0,description:"Permissions for the api key (stored as JSON string)"}},required:["id","userId","enabled","rateLimitEnabled","requestCount","createdAt","updatedAt"]}}}}}}}},async t=>{let{configId:i,id:a}=t.query,n=t.context.session,s=el(t.context,e,i),l=null;if(!(l=await M(t,a,s))||!ed(l.configId,s.configId))throw u.E.from("NOT_FOUND",o.KEY_NOT_FOUND);let c=el(t.context,e,l.configId);if((c.references??"user")==="organization")await W(t,n.user.id,l.referenceId,"read");else if(l.referenceId!==n.user.id)throw u.E.from("NOT_FOUND",o.KEY_NOT_FOUND);r(t.context);let d=await R(t,l,c),{key:p,...f}=l;return t.json({...f,metadata:d,permissions:f.permissions?(0,b.f)(f.permissions):null})})}({configurations:t,schema:r,deleteAllExpiredApiKeys:ep}),updateApiKey:function({configurations:e,schema:t,deleteAllExpiredApiKeys:r}){return(0,s.g)("/api-key/update",{method:"POST",body:ee,metadata:{openapi:{description:"Update an existing API key by ID",responses:{200:{description:"API key updated successfully",content:{"application/json":{schema:{type:"object",properties:{id:{type:"string",description:"ID"},name:{type:"string",nullable:!0,description:"The name of the key"},start:{type:"string",nullable:!0,description:"Shows the first few characters of the API key, including the prefix. This allows you to show those few characters in the UI to make it easier for users to identify the API key."},prefix:{type:"string",nullable:!0,description:"The API Key prefix. Stored as plain text."},userId:{type:"string",description:"The owner of the user id"},refillInterval:{type:"number",nullable:!0,description:"The interval in milliseconds between refills of the `remaining` count. Example: 3600000 // refill every hour (3600000ms = 1h)"},refillAmount:{type:"number",nullable:!0,description:"The amount to refill"},lastRefillAt:{type:"string",format:"date-time",nullable:!0,description:"The last refill date"},enabled:{type:"boolean",description:"Sets if key is enabled or disabled",default:!0},rateLimitEnabled:{type:"boolean",description:"Whether the key has rate limiting enabled"},rateLimitTimeWindow:{type:"number",nullable:!0,description:"The duration in milliseconds"},rateLimitMax:{type:"number",nullable:!0,description:"Maximum amount of requests allowed within a window"},requestCount:{type:"number",description:"The number of requests made within the rate limit time window"},remaining:{type:"number",nullable:!0,description:"Remaining requests (every time api key is used this should updated and should be updated on refill as well)"},lastRequest:{type:"string",format:"date-time",nullable:!0,description:"When last request occurred"},expiresAt:{type:"string",format:"date-time",nullable:!0,description:"Expiry date of a key"},createdAt:{type:"string",format:"date-time",description:"created at"},updatedAt:{type:"string",format:"date-time",description:"updated at"},metadata:{type:"object",nullable:!0,additionalProperties:!0,description:"Extra metadata about the apiKey"},permissions:{type:"string",nullable:!0,description:"Permissions for the api key (stored as JSON string)"}},required:["id","userId","enabled","rateLimitEnabled","requestCount","createdAt","updatedAt"]}}}}}}}},async t=>{let{configId:i,keyId:a,expiresIn:n,enabled:s,metadata:l,refillAmount:c,refillInterval:d,remaining:f,name:m,permissions:h,rateLimitEnabled:g,rateLimitTimeWindow:w,rateLimitMax:y}=t.body,E=await (0,p.D)(t,{disableCookieCache:!0}),A=t.request||t.headers,I=A&&!E?null:E?.user||{id:t.body.userId};if(!I?.id||E&&t.body.userId&&E?.user.id!==t.body.userId)throw u.E.from("UNAUTHORIZED",o.UNAUTHORIZED_SESSION);if(A&&(void 0!==c||void 0!==d||void 0!==y||void 0!==w||void 0!==g||void 0!==f||void 0!==h))throw u.E.from("BAD_REQUEST",o.SERVER_ONLY_PROPERTY);let _=el(t.context,e,i),k=null;if(!(k=await M(t,a,_))||!ed(k.configId,_.configId))throw u.E.from("NOT_FOUND",o.KEY_NOT_FOUND);let T=el(t.context,e,k.configId);if((T.references??"user")==="organization")await W(t,I.id,k.referenceId,"update");else if(k.referenceId!==I.id)throw u.E.from("NOT_FOUND",o.KEY_NOT_FOUND);let v={};if(void 0!==m){if(m.length<T.minimumNameLength||m.length>T.maximumNameLength)throw u.E.from("BAD_REQUEST",o.INVALID_NAME_LENGTH);v.name=m}if(void 0!==s&&(v.enabled=s),void 0!==n){if(!0===T.keyExpiration.disableCustomExpiresTime)throw u.E.from("BAD_REQUEST",o.KEY_DISABLED_EXPIRATION);if(null!==n){let e=n/86400;if(e<T.keyExpiration.minExpiresIn)throw u.E.from("BAD_REQUEST",o.EXPIRES_IN_IS_TOO_SMALL);if(e>T.keyExpiration.maxExpiresIn)throw u.E.from("BAD_REQUEST",o.EXPIRES_IN_IS_TOO_LARGE)}v.expiresAt=n?Q(n,"sec"):null}if(void 0!==l&&!0===T.enableMetadata){if("object"!=typeof l)throw u.E.from("BAD_REQUEST",o.INVALID_METADATA_TYPE);v.metadata=l}if(void 0!==f&&(v.remaining=f),void 0!==c||void 0!==d){if(void 0!==c&&void 0===d)throw u.E.from("BAD_REQUEST",o.REFILL_AMOUNT_AND_INTERVAL_REQUIRED);if(void 0!==d&&void 0===c)throw u.E.from("BAD_REQUEST",o.REFILL_INTERVAL_AND_AMOUNT_REQUIRED);v.refillAmount=c,v.refillInterval=d}if(void 0!==g&&(v.rateLimitEnabled=g),void 0!==w&&(v.rateLimitTimeWindow=w),void 0!==y&&(v.rateLimitMax=y),void 0!==h&&(v.permissions=JSON.stringify(h)),0===Object.keys(v).length)throw u.E.from("BAD_REQUEST",o.NO_VALUES_TO_UPDATE);let U=k;try{if("secondary-storage"===T.storage&&T.fallbackToDatabase){let e=await t.context.adapter.update({model:em,where:[{field:"id",value:k.id}],update:v});e&&(await F(t,e,T),U=e)}else if("database"===T.storage){let e=await t.context.adapter.update({model:em,where:[{field:"id",value:k.id}],update:v});e&&(U=e)}else{let e={...k,...v,updatedAt:new Date};await F(t,e,T),U=e}}catch(e){throw u.E.fromStatus("INTERNAL_SERVER_ERROR",{message:e?.message})}r(t.context);let x=await R(t,U,T),{key:S,...O}=U;return t.json({...O,metadata:x,permissions:O.permissions?(0,b.f)(O.permissions):null})})}({configurations:t,schema:r,deleteAllExpiredApiKeys:ep}),deleteApiKey:function({configurations:e,schema:t,deleteAllExpiredApiKeys:r}){return(0,s.g)("/api-key/delete",{method:"POST",body:J,use:[p.Z],metadata:{openapi:{description:"Delete an existing API key",requestBody:{content:{"application/json":{schema:{type:"object",properties:{keyId:{type:"string",description:"The id of the API key to delete"}},required:["keyId"]}}}},responses:{200:{description:"API key deleted successfully",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",description:"Indicates if the API key was successfully deleted"}},required:["success"]}}}}}}}},async t=>{let{configId:i,keyId:a}=t.body,n=t.context.session;if(!0===n.user.banned)throw u.E.from("UNAUTHORIZED",o.USER_BANNED);let s=el(t.context,e,i),l=null;if(!(l=await M(t,a,s))||!ed(l.configId,s.configId))throw u.E.from("NOT_FOUND",o.KEY_NOT_FOUND);let c=el(t.context,e,l.configId);if((c.references??"user")==="organization")await W(t,n.user.id,l.referenceId,"delete");else if(l.referenceId!==n.user.id)throw u.E.from("NOT_FOUND",o.KEY_NOT_FOUND);try{"secondary-storage"===c.storage&&c.fallbackToDatabase?(await K(t,l,c),await t.context.adapter.delete({model:em,where:[{field:"id",value:l.id}]})):"database"===c.storage?await t.context.adapter.delete({model:em,where:[{field:"id",value:l.id}]}):await K(t,l,c)}catch(e){throw u.E.fromStatus("INTERNAL_SERVER_ERROR",{message:e?.message})}return r(t.context),t.json({success:!0})})}({configurations:t,schema:r,deleteAllExpiredApiKeys:ep}),listApiKeys:function({configurations:e,schema:t,deleteAllExpiredApiKeys:r}){return(0,s.g)("/api-key/list",{method:"GET",use:[p.Z],query:X,metadata:{openapi:{description:"List all API keys for the authenticated user or for a specific organization",responses:{200:{description:"API keys retrieved successfully",content:{"application/json":{schema:{type:"object",properties:{apiKeys:{type:"array",items:{type:"object",properties:{id:{type:"string",description:"ID"},name:{type:"string",nullable:!0,description:"The name of the key"},start:{type:"string",nullable:!0,description:"Shows the first few characters of the API key, including the prefix. This allows you to show those few characters in the UI to make it easier for users to identify the API key."},prefix:{type:"string",nullable:!0,description:"The API Key prefix. Stored as plain text."},userId:{type:"string",description:"The owner of the user id"},refillInterval:{type:"number",nullable:!0,description:"The interval in milliseconds between refills of the `remaining` count. Example: 3600000 // refill every hour (3600000ms = 1h)"},refillAmount:{type:"number",nullable:!0,description:"The amount to refill"},lastRefillAt:{type:"string",format:"date-time",nullable:!0,description:"The last refill date"},enabled:{type:"boolean",description:"Sets if key is enabled or disabled",default:!0},rateLimitEnabled:{type:"boolean",description:"Whether the key has rate limiting enabled"},rateLimitTimeWindow:{type:"number",nullable:!0,description:"The duration in milliseconds"},rateLimitMax:{type:"number",nullable:!0,description:"Maximum amount of requests allowed within a window"},requestCount:{type:"number",description:"The number of requests made within the rate limit time window"},remaining:{type:"number",nullable:!0,description:"Remaining requests (every time api key is used this should updated and should be updated on refill as well)"},lastRequest:{type:"string",format:"date-time",nullable:!0,description:"When last request occurred"},expiresAt:{type:"string",format:"date-time",nullable:!0,description:"Expiry date of a key"},createdAt:{type:"string",format:"date-time",description:"created at"},updatedAt:{type:"string",format:"date-time",description:"updated at"},metadata:{type:"object",nullable:!0,additionalProperties:!0,description:"Extra metadata about the apiKey"},permissions:{type:"string",nullable:!0,description:"Permissions for the api key (stored as JSON string)"}},required:["id","userId","enabled","rateLimitEnabled","requestCount","createdAt","updatedAt"]}},total:{type:"number",description:"Total number of API keys"},limit:{type:"number",nullable:!0,description:"The limit used for pagination"},offset:{type:"number",nullable:!0,description:"The offset used for pagination"}},required:["apiKeys","total"]}}}}}}}},async t=>{let i=t.context.session,a=t.query?.configId,o=t.query?.organizationId,n=t.query?.limit!=null?Number(t.query.limit):void 0,s=t.query?.offset!=null?Number(t.query.offset):void 0;o&&await W(t,i.user.id,o,"read");let l=o??i.user.id,c=o?"organization":"user",d=[];if(a){let{apiKeys:r}=await H(t,l,el(t.context,e,a),{limit:void 0,offset:void 0,sortBy:t.query?.sortBy,sortDirection:t.query?.sortDirection});d=r}else{let r=new Map;for(let t of e){let e="database"===t.storage?"database":t.customStorage?`custom:${t.configId??"default"}`:t.fallbackToDatabase?"secondary-storage-with-fallback":"secondary-storage";r.has(e)||r.set(e,t)}let i=await Promise.all([...r.values()].map(e=>H(t,l,e,{limit:void 0,offset:void 0,sortBy:t.query?.sortBy,sortDirection:t.query?.sortDirection}))),a=new Set;for(let{apiKeys:e}of i)for(let t of e)a.has(t.id)||(a.add(t.id),d.push(t))}let u=d.filter(t=>(e.find(e=>ec(t.configId)?ec(e.configId):e.configId===t.configId)?.references??"user")===c&&t.referenceId===l);a&&(u=u.filter(e=>ed(e.configId,a)));let p=u.length,f=u;void 0!==s&&(f=f.slice(s)),void 0!==n&&(f=f.slice(0,n)),r(t.context);let m=f.map(e=>{let{key:t,...r}=e;return{...r,metadata:T(e.metadata),permissions:r.permissions?(0,b.f)(r.permissions):null}}),h=e.find(e=>"database"===e.storage||e.fallbackToDatabase);return h&&await t.context.runInBackgroundOrAwait(U(t,f,h)),t.json({apiKeys:m,total:p,limit:n,offset:s})})}({configurations:t,schema:r,deleteAllExpiredApiKeys:ep}),deleteAllExpiredApiKeys:function({deleteAllExpiredApiKeys:e}){return s.g.serverOnly({method:"POST"},async t=>{try{await e(t.context,!0)}catch(e){return t.context.logger.error("[API KEY PLUGIN] Failed to delete expired API keys:",e),t.json({success:!1,error:e})}return t.json({success:!0,error:null})})}({deleteAllExpiredApiKeys:ep})}}({defaultKeyGenerator:async e=>{let t=(0,g.f)(e.length,"a-z","A-Z");return`${e.prefix||""}${t}`},configurations:i,schema:a});return{id:"api-key",version:"1.7.16",$ERROR_CODES:o,hooks:{before:[{matcher:e=>!!n(e),handler:(0,s.a)(async e=>{let{key:t,config:r}=n(e);if("string"!=typeof t)throw u.E.from("BAD_REQUEST",o.INVALID_API_KEY_GETTER_RETURN_TYPE);if(t.length<r.defaultKeyLength||r.customAPIKeyValidator&&!await r.customAPIKeyValidator({ctx:e,key:t}))throw u.E.from("FORBIDDEN",o.INVALID_API_KEY);let{apiKey:s}=await er({key:t,ctx:e,lookupOpts:r,configurations:i,schema:a,expectedConfigId:r.configId}),c=ep(e.context).catch(t=>{e.context.logger.error("Failed to delete expired API keys:",t)});if(r.deferUpdates&&e.context.runInBackground(c),(r.references??"user")!=="user"){let e=o.INVALID_REFERENCE_ID_FROM_API_KEY;throw u.E.from("UNAUTHORIZED",e)}let d=await e.context.internalAdapter.findUserById(s.referenceId);if(!d){let e=o.INVALID_REFERENCE_ID_FROM_API_KEY;throw u.E.from("UNAUTHORIZED",e)}let p={user:d,session:{id:s.id,token:t,userId:s.referenceId,userAgent:e.request?.headers.get("user-agent")??null,ipAddress:e.request?(0,l.M)(e.request,e.context.options):null,createdAt:new Date,updatedAt:new Date,expiresAt:s.expiresAt||Q(e.context.options.session?.expiresIn||604800,"ms")}};return(await h(t),e.context.session=p,"/get-session"===e.path)?p:{context:e}})}]},endpoints:{createApiKey:c.createApiKey,verifyApiKey:c.verifyApiKey,getApiKey:c.getApiKey,updateApiKey:c.updateApiKey,deleteApiKey:c.deleteApiKey,listApiKeys:c.listApiKeys,deleteAllExpiredApiKeys:c.deleteAllExpiredApiKeys},schema:a}}],363004);var eh=e.i(604383),eg=e.i(673278),ew=e.i(55281);function ey(e){return e.charAt(0).toLowerCase()+e.slice(1)}function eb(e){return e?.code==="P2025"}e.s(["f",0,(e,t)=>{let r=null,i=(e,r=!1)=>({getFieldName:i,getModelName:a,getFieldAttributes:o,getDefaultModelName:n,schema:s})=>{let l=(e,t,r)=>{if(!e&&!r)return;let a={};if(e)for(let r of e)a[i({model:t,field:r})]=!0;if(r){if(!e){let e=s[n(t)]?.fields||{};for(let r of(e.id={type:"string"},Object.keys(e)))a[i({model:t,field:r})]=!0}for(let[e,i]of Object.entries(r)){let r=c(t,i.modelKey??e,s);"one-to-one"===i.relation?a[r]=!0:a[r]={take:i.limit}}}return a},c=(e,r,i)=>{try{let o=n(e),s=n(r),l=a(r).toLowerCase(),c=Object.entries(i[s]?.fields||{}).filter(([e,t])=>t.references&&n(t.references.model)===o);if(c.length>0){let[e,r]=c[0];return r?.unique===!0||!0===t.usePlural?l:`${l}s`}if((c=Object.entries(i[o]?.fields||{}).filter(([e,t])=>t.references&&n(t.references.model)===s)).length>0)return l}catch{}return`${a(r).toLowerCase()}s`};function d(e){switch(e){case"starts_with":return"startsWith";case"ends_with":return"endsWith";case"ne":return"not";case"not_in":return"notIn";default:return e}}let p=({action:e,model:r,where:a})=>{if(!a||!a.length)return{};let n=e=>{let a=i({model:r,field:e.field}),n=(e.mode??"sensitive")==="insensitive"&&("string"==typeof e.value||Array.isArray(e.value)&&e.value.every(e=>"string"==typeof e)),s="postgresql"===t.provider||"mongodb"===t.provider,l=n&&s?"insensitive":void 0,c=l?{mode:l}:{};if("ne"===e.operator&&null===e.value)return o({model:r,field:e.field})?.required!==!0?{[a]:{not:null}}:{};if(("in"===e.operator||"not_in"===e.operator)&&Array.isArray(e.value)){let t=e.value.filter(e=>null!=e);if(0===t.length)if("in"===e.operator)return{AND:[{[a]:{equals:"__never__"}},{[a]:{not:"__never__"}}]};else return{};return{[a]:{[d(e.operator)]:t,...c}}}return"eq"!==e.operator&&e.operator?"ne"===e.operator?{[a]:{not:{equals:e.value},...c}}:{[a]:{[d(e.operator)]:e.value,...c}}:{[a]:{equals:e.value,...c}}};if("update"===e){let e=a.filter(e=>"AND"===e.connector||!e.connector),t=a.filter(e=>"OR"===e.connector),o=e.filter(e=>"eq"===e.operator||!e.operator),s=e.filter(e=>"eq"!==e.operator&&void 0!==e.operator).map(e=>n(e)),l=t.map(e=>n(e)),c={};for(let e of o)c[i({model:r,field:e.field})]=e.value;return s.length>0&&(c.AND=s),l.length>0&&(c.OR=l),c}if("delete"===e){let e=a.find(e=>"id"===e.field);if(e){let t=i({model:r,field:"id"}),o=a.filter(e=>"id"!==e.field);if(0===o.length)return{[t]:e.value};let s=o.filter(e=>"AND"===e.connector||!e.connector),l=o.filter(e=>"OR"===e.connector),c=s.map(e=>n(e)),d=l.map(e=>n(e)),u={[t]:e.value};return c.length>0&&(u.AND=c),d.length>0&&(u.OR=d),u}}if(1===a.length){let e=a[0];if(!e)return;return n(e)}let s=a.filter(e=>"AND"===e.connector||!e.connector),l=a.filter(e=>"OR"===e.connector),c=s.map(e=>n(e)),u=l.map(e=>n(e));return{...c.length?{AND:c}:{},...u.length?{OR:u}:{}}};return{async create({model:t,modelKey:r=t,data:i,select:a}){if(!e[t])throw new u.p(`Model ${t} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`);return await e[t].create({data:i,select:l(a,r)})},async findOne({model:t,modelKey:r=t,where:i,select:a,join:o}){let n=p({model:r,where:i,action:"findOne"});if(!e[t])throw new u.p(`Model ${t} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`);let d=new Map;for(let[e,t]of Object.entries(o??{})){let i=c(r,t.modelKey??e,s);d.set(i,e)}let f=l(a,r,o),m=await e[t].findFirst({where:n,select:f});if(o&&m)for(let[e,t]of d.entries())e!==t&&e in m&&(m[t]=m[e],delete m[e]);return m},async findMany({model:t,modelKey:r=t,where:a,limit:o,select:n,offset:d,sortBy:f,join:m}){let h=p({model:r,where:a,action:"findMany"});if(!e[t])throw new u.p(`Model ${t} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`);let g=new Map;if(m)for(let[e,t]of Object.entries(m)){let i=c(r,t.modelKey??e,s);g.set(i,e)}let w=l(n,r,m),y=await e[t].findMany({where:h,take:o||100,skip:d||0,...f?.field?{orderBy:{[i({model:r,field:f.field})]:"desc"===f.direction?"desc":"asc"}}:{},select:w});if(m&&Array.isArray(y))for(let e of y)for(let[t,r]of g.entries())t!==r&&t in e&&(e[r]=e[t],delete e[t]);return y},async count({model:t,modelKey:r=t,where:i}){let a=p({model:r,where:i,action:"count"});if(!e[t])throw new u.p(`Model ${t} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`);return await e[t].count({where:a})},async update({model:r,modelKey:i=r,where:a,update:n}){if(!e[r])throw new u.p(`Model ${r} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`);if(!(a?.length&&a.some(e=>{if("OR"===e.connector||e.operator&&"eq"!==e.operator)return!1;if("insensitive"===e.mode){let r="postgresql"===t.provider||"mongodb"===t.provider,i="string"==typeof e.value||Array.isArray(e.value)&&e.value.every(e=>"string"==typeof e);if(r&&i)return!1}return"id"===e.field||o({model:i,field:e.field})?.unique===!0}))){let t=p({model:i,where:a,action:"updateMany"});return(await e[r].updateMany({where:t,data:n}))?.count?await e[r].findFirst({where:t}):null}let s=p({model:i,where:a,action:"update"});try{return await e[r].update({where:s,data:n})}catch(e){if(eb(e))return null;throw e}},async updateMany({model:t,modelKey:r=t,where:i,update:a}){if(!e[t])throw new u.p(`Model ${t} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`);let o=p({model:r,where:i,action:"updateMany"}),n=await e[t].updateMany({where:o,data:a});return n?n.count:0},async delete({model:t,modelKey:r=t,where:i}){if(!e[t])throw new u.p(`Model ${t} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`);if(!i?.some(e=>"id"===e.field)){let a=p({model:r,where:i,action:"deleteMany"});await e[t].deleteMany({where:a});return}let a=p({model:r,where:i,action:"delete"});try{await e[t].delete({where:a})}catch(e){if(eb(e))return;throw e}},async deleteMany({model:t,modelKey:r=t,where:i}){let a=p({model:r,where:i,action:"deleteMany"}),o=await e[t].deleteMany({where:a});return o?o.count:0},async consumeOne({model:t,modelKey:i=t,where:a}){if(!e[t])throw new u.p(`Model ${t} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`);if(a?.some(e=>"id"===e.field)){let r=p({model:i,where:a,action:"delete"});try{return await e[t].delete({where:r})??null}catch(e){if(eb(e))return null;throw e}}let o=p({model:i,where:a,action:"findOne"}),n=async e=>{let r=await e[t].findFirst({where:o});if(!r)return null;try{return(await e[t].deleteMany({where:p({model:i,where:[...a??[],{field:"id",value:r.id,operator:"eq",connector:"AND",mode:"sensitive"}],action:"deleteMany"})}))?.count>0?r:null}catch(e){if(eb(e))return null;throw e}};return r||"function"!=typeof e.$transaction?n(e):e.$transaction(n)},async incrementOne({model:t,modelKey:i=t,where:a,increment:o,set:n}){if(!e[t])throw new u.p(`Model ${t} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`);let s={...n??{}};for(let[e,t]of Object.entries(o))s[e]={increment:t};if(a?.some(e=>"id"===e.field)){let r=p({model:i,where:a,action:"update"});try{return await e[t].update({where:r,data:s})??null}catch(e){if(eb(e))return null;throw e}}let l=p({model:i,where:a,action:"findOne"}),c=async e=>{let r=await e[t].findFirst({where:l});if(!r)return null;try{return await e[t].update({where:p({model:i,where:[...a,{field:"id",value:r.id,operator:"eq",connector:"AND",mode:"sensitive"}],action:"update"}),data:s})??null}catch(e){if(eb(e))return null;throw e}};return r||"function"!=typeof e.$transaction?c(e):e.$transaction(c)},options:t}},a=null;a={config:{adapterId:"prisma",adapterName:"Prisma Adapter",usePlural:t.usePlural??!1,debugLogs:t.debugLogs??!1,supportsUUIDs:"postgresql"===t.provider,supportsArrays:"postgresql"===t.provider||"mongodb"===t.provider,transaction:!!t.transaction&&(t=>e.$transaction(e=>t((0,eh.f)({config:{...a.config,transaction:!1},adapter:i(e,!0)})(r))))},adapter:i(e)};let o=(0,eh.f)(a);return i=>{let a;r=i;let n=o(i),s="object"==typeof(a=e._runtimeDataModel)&&null!==a&&"models"in a?a:void 0;if(s){let e=(0,eg.t)(()=>{var e,r,a;let o;return e=s,r=i,a=t.usePlural,o=Object.fromEntries(Object.entries((0,ew.w)(r,{usePlural:a})).map(([e,t])=>[ey(e),t])),(0,ew.I)(o,Object.entries(e.models).map(([e,{fields:t}])=>({name:ey(e),columns:t.filter(e=>"object"!==e.kind).map(e=>({name:e.name,nullable:!0!==e.isRequired,hasDefault:!0===e.hasDefaultValue||!0===e.isUpdatedAt}))})))},"prisma");(0,eg.E)(n,e,{runtimeEnabled:(0,eg.S)(i)})}return n}}],931129);var eE=e.i(169774),eA=e.i(990126);async function eI(t,r){let i;if(t.database)i="function"==typeof t.database?t.database(t):await r(t);else{let r=Object.keys((0,eE.R)(t)).reduce((e,t)=>(e[t]=[],e),{}),{memoryAdapter:a}=await e.A(563921);i=a(r)(t)}return i.transaction||(eA.y.warn("Adapter does not correctly implement transaction function, patching it automatically. Please update your adapter implementation."),i.transaction=async e=>e(i)),i}async function e_(t){return eI(t,async t=>{let{createKyselyAdapter:r,kyselyAdapter:i}=await e.A(246120),{kysely:a,databaseType:o,transaction:n}=await r(t);if(!a)throw new u.p("Failed to initialize database adapter");return i(a,{type:o||"sqlite",debugLogs:!!t.database&&"debugLogs"in t.database&&t.database.debugLogs,transaction:n})(t)})}var ek=u,eT=e.i(643638),ev=e.i(146378),eU=e.i(631139),eR=e.i(367409),ex=e.i(877113);let eS={postgres:{string:["character varying","varchar","text","uuid"],number:["int4","int8","integer","bigint","smallint","numeric","real","double precision"],boolean:["bool","boolean"],date:["timestamptz","timestamp","date"],json:["json","jsonb"]},mysql:{string:["varchar","text","uuid"],number:["integer","int","bigint","smallint","decimal","float","double"],boolean:["boolean","tinyint"],date:["timestamp","datetime","date"],json:["json"]},sqlite:{string:["TEXT"],number:["INTEGER","REAL","BIGINT"],boolean:["INTEGER","BOOLEAN"],date:["DATE","INTEGER"],json:["TEXT"]},mssql:{string:["varchar","nvarchar","uniqueidentifier"],number:["int","bigint","smallint","decimal","float","double"],boolean:["bit","smallint"],date:["datetime2","date","datetime"],json:["varchar","nvarchar"]}};function eO(e,t){return`${(0,eR.d)(e)}\0${(0,eR.d)(t)}`}function eD(e,t){return`${e}\0${t}`}function eN(e,t){return e.unique===(t.unique??!1)&&e.validFullColumns&&e.columns.length===t.columns.length&&e.columns.every((e,r)=>e===t.columns[r])}function eL(e){return"boolean"==typeof e?e:"number"==typeof e?0!==e:"1"===e||e?.toLowerCase()==="true"||"t"===e}function eP(e){return new Map(e.map(e=>{let t=[...e.columns].sort((e,t)=>e.position-t.position);return[eO(e.table,e.name),{columns:t.flatMap(e=>null===e.name?[]:[e.name]),name:e.name,table:e.table,unique:e.unique,validFullColumns:e.valid&&!e.partial&&t.length>0&&t.every(e=>null!==e.name&&e.fullLength)}]}))}async function eC(e,t,r,i){let a;if(i)return eP(await i(r));switch(t.type){case"sqlite":a=(await ex.f`
|
|
1
|
+
module.exports=[363004,931129,950551,342e3,729522,100762,661372,374091,339507,204721,e=>{"use strict";let t,r,i,a,o=(0,e.i(672823).f)({INVALID_METADATA_TYPE:"metadata must be an object or undefined",REFILL_AMOUNT_AND_INTERVAL_REQUIRED:"refillAmount is required when refillInterval is provided",REFILL_INTERVAL_AND_AMOUNT_REQUIRED:"refillInterval is required when refillAmount is provided",USER_BANNED:"User is banned",UNAUTHORIZED_SESSION:"Unauthorized or invalid session",KEY_NOT_FOUND:"API Key not found",KEY_DISABLED:"API Key is disabled",KEY_EXPIRED:"API Key has expired",USAGE_EXCEEDED:"API Key has reached its usage limit",KEY_NOT_RECOVERABLE:"API Key is not recoverable",EXPIRES_IN_IS_TOO_SMALL:"The expiresIn is smaller than the predefined minimum value.",EXPIRES_IN_IS_TOO_LARGE:"The expiresIn is larger than the predefined maximum value.",INVALID_REMAINING:"The remaining count is either too large or too small.",INVALID_PREFIX_LENGTH:"The prefix length is either too large or too small.",INVALID_NAME_LENGTH:"The name length is either too large or too small.",METADATA_DISABLED:"Metadata is disabled.",RATE_LIMIT_EXCEEDED:"Rate limit exceeded.",NO_VALUES_TO_UPDATE:"No values to update.",KEY_DISABLED_EXPIRATION:"Custom key expiration values are disabled.",INVALID_API_KEY:"Invalid API key.",INVALID_USER_ID_FROM_API_KEY:"The user id from the API key is invalid.",INVALID_REFERENCE_ID_FROM_API_KEY:"The reference id from the API key is invalid.",INVALID_API_KEY_GETTER_RETURN_TYPE:"API Key getter returned an invalid key type. Expected string.",SERVER_ONLY_PROPERTY:"The property you're trying to set can only be set from the server auth instance only.",FAILED_TO_UPDATE_API_KEY:"Failed to update API key",NAME_REQUIRED:"API Key name is required.",ORGANIZATION_ID_REQUIRED:"Organization ID is required for organization-owned API keys.",USER_NOT_MEMBER_OF_ORGANIZATION:"You are not a member of the organization that owns this API key.",INSUFFICIENT_API_KEY_PERMISSIONS:"You do not have permission to perform this action on organization API keys.",NO_DEFAULT_API_KEY_CONFIGURATION_FOUND:"No default api-key configuration found.",ORGANIZATION_PLUGIN_REQUIRED:"Organization plugin is required for organization-owned API keys. Please install and configure the organization plugin."});var n,s=e.i(890659),l=e.i(835860),c=e.i(530501),d=e.i(282318),u=e.i(71616),p=e.i(112996),f=e.i(824374);let{get:m}=(0,f.z)(()=>new Set);async function h(e){(await m()).add(e)}var g=e.i(51144),w=e.i(756023),y=e.i(818195),b=e.i(630283),E=e.i(907855),A=e.i(754257);async function I(e,t,r){let i=e.length;if(0===i)return[];let{signal:a}=r;if(a?.aborted)throw a.reason;let o=Math.floor(r.concurrency),n=Math.min(i,o>=1?o:1),s=Array(i),l=0,c=!1,d=async()=>{for(;!c&&l<i;){if(a?.aborted)throw a.reason;let r=l++;try{s[r]=await t(e[r],r)}catch(e){throw c=!0,e}}};return await Promise.all(Array.from({length:n},d)),s}var _=e.i(483319),k=e.i(174311);function T(e){return null==e?null:"object"==typeof e?e:(0,b.f)(e)}function v(e){return null!=e&&"string"==typeof e}async function U(e,t,r){if("database"!==r.storage&&!r.fallbackToDatabase)return;let i=t.filter(e=>v(e.metadata));if(0===i.length)return;let a=i.map(async t=>{let r=T(t.metadata);try{await e.context.adapter.update({model:"apikey",where:[{field:"id",value:t.id}],update:{metadata:r}})}catch(r){e.context.logger.warn(`Failed to migrate double-stringified metadata for API key ${t.id}:`,r)}});await Promise.all(a)}async function R(e,t,r){let i=T(t.metadata);if(v(t.metadata)&&("database"===r.storage||r.fallbackToDatabase))try{await e.context.adapter.update({model:"apikey",where:[{field:"id",value:t.id}],update:{metadata:i}})}catch(r){e.context.logger.warn(`Failed to migrate double-stringified metadata for API key ${t.id}:`,r)}return i}function S(e){return`api-key:${e}`}function x(e){return`api-key:by-id:${e}`}function O(e){return`api-key:by-ref:${e}`}function D(e){if(!e)return null;try{let t="string"==typeof e?JSON.parse(e):e;return{...t,createdAt:new Date(t.createdAt),updatedAt:new Date(t.updatedAt),expiresAt:t.expiresAt?new Date(t.expiresAt):null,lastRefillAt:t.lastRefillAt?new Date(t.lastRefillAt):null,lastRequest:t.lastRequest?new Date(t.lastRequest):null}}catch{return null}}function N(e,t){return t.customStorage?t.customStorage:e.context.secondaryStorage||null}function L(e){if(e.expiresAt){let t=Date.now(),r=Math.floor((new Date(e.expiresAt).getTime()-t)/1e3);if(r>0)return r}}async function P(e,t,r){let i=S(t);return D(await r.get(i))}async function C(e,t,r){let i=x(t);return D(await r.get(i))}let q=new Map;async function j(e,t,r){var i;let a;await (i=async()=>{let i=await e.get(t),a=[];if(i&&"string"==typeof i)try{a=JSON.parse(i)}catch{a=[]}else Array.isArray(i)&&(a=i);let o=r(a);0===o.length?await e.delete(t):await e.set(t,JSON.stringify(o))},a=(q.get(t)??Promise.resolve()).then(i,i).finally(()=>{q.get(t)===a&&q.delete(t)}),q.set(t,a),a)}async function $(e,t,r,i,a){let o=JSON.stringify({...t,createdAt:t.createdAt.toISOString(),updatedAt:t.updatedAt.toISOString(),expiresAt:t.expiresAt?.toISOString()??null,lastRefillAt:t.lastRefillAt?.toISOString()??null,lastRequest:t.lastRequest?.toISOString()??null}),n=O(t.referenceId);a.fallbackToDatabase?await Promise.all([r.set(S(t.key),o,i),r.set(x(t.id),o,i),r.delete(n)]):(await Promise.all([r.set(S(t.key),o,i),r.set(x(t.id),o,i)]),await j(r,n,e=>e.includes(t.id)?e:[...e,t.id]))}async function B(e,t,r,i){let a=O(t.referenceId);i.fallbackToDatabase?await Promise.all([r.delete(S(t.key)),r.delete(x(t.id)),r.delete(a)]):await Promise.all([r.delete(S(t.key)),r.delete(x(t.id)),j(r,a,e=>e.filter(e=>e!==t.id))])}async function V(e,t,r){let i=N(e,r);if("database"===r.storage)return await e.context.adapter.findOne({model:"apikey",where:[{field:"key",value:t}]});if("secondary-storage"===r.storage&&r.fallbackToDatabase){if(i){let r=await P(e,t,i);if(r)return r}let a=await e.context.adapter.findOne({model:"apikey",where:[{field:"key",value:t}]});return a&&i&&await $(e,a,i,L(a),r),a}return"secondary-storage"===r.storage?i?await P(e,t,i):null:await e.context.adapter.findOne({model:"apikey",where:[{field:"key",value:t}]})}async function M(e,t,r){let i=N(e,r);if("database"===r.storage)return await e.context.adapter.findOne({model:"apikey",where:[{field:"id",value:t}]});if("secondary-storage"===r.storage&&r.fallbackToDatabase){if(i){let r=await C(e,t,i);if(r)return r}let a=await e.context.adapter.findOne({model:"apikey",where:[{field:"id",value:t}]});return a&&i&&await $(e,a,i,L(a),r),a}return"secondary-storage"===r.storage?i?await C(e,t,i):null:await e.context.adapter.findOne({model:"apikey",where:[{field:"id",value:t}]})}async function F(e,t,r){let i=N(e,r),a=L(t);if("database"!==r.storage&&"secondary-storage"===r.storage){if(!i)throw Error("Secondary storage is required when storage mode is 'secondary-storage'");await $(e,t,i,a,r);return}}async function K(e,t,r){let i=N(e,r);if("database"!==r.storage&&"secondary-storage"===r.storage){if(!i)throw Error("Secondary storage is required when storage mode is 'secondary-storage'");await B(e,t,i,r);return}}function z(e,t,r,i,a){let o=[...e];if(t){let e=r||"asc";o.sort((r,i)=>{let a=r[t],o=i[t];return null==a&&null==o?0:null==a?"asc"===e?-1:1:null==o?"asc"===e?1:-1:a<o?"asc"===e?-1:1:a>o?"asc"===e?1:-1:0})}return void 0!==a&&(o=o.slice(a)),void 0!==i&&(o=o.slice(0,i)),o}async function H(e,t,r,i){let a=N(e,r),{limit:o,offset:n,sortBy:s,sortDirection:l}=i||{};if("database"===r.storage){let[r,i]=await Promise.all([e.context.adapter.findMany({model:"apikey",where:[{field:"referenceId",value:t}],limit:o,offset:n,sortBy:s?{field:s,direction:l||"asc"}:void 0}),e.context.adapter.count({model:"apikey",where:[{field:"referenceId",value:t}]})]);return{apiKeys:r,total:i}}if("secondary-storage"===r.storage&&r.fallbackToDatabase){let i=O(t);if(a){let t=await a.get(i),r=[];if(t&&"string"==typeof t)try{r=JSON.parse(t)}catch{r=[]}else Array.isArray(t)&&(r=t);if(r.length>0){let t=(await I(r,t=>C(e,t,a),{concurrency:10})).filter(e=>null!=e);return{apiKeys:z(t,s,l,o,n),total:t.length}}}let[c,d]=await Promise.all([e.context.adapter.findMany({model:"apikey",where:[{field:"referenceId",value:t}],limit:o,offset:n,sortBy:s?{field:s,direction:l||"asc"}:void 0}),e.context.adapter.count({model:"apikey",where:[{field:"referenceId",value:t}]})]);if(a&&c.length>0){await I(c,t=>$(e,t,a,L(t),r),{concurrency:10});let t=c.map(e=>e.id);await a.set(i,JSON.stringify(t))}return{apiKeys:c,total:d}}if("secondary-storage"===r.storage){if(!a)return{apiKeys:[],total:0};let r=O(t),i=await a.get(r),c=[];if(i&&"string"==typeof i)try{c=JSON.parse(i)}catch{return{apiKeys:[],total:0}}else{if(!Array.isArray(i))return{apiKeys:[],total:0};c=i}let d=(await I(c,t=>C(e,t,a),{concurrency:10})).filter(e=>null!=e);return{apiKeys:z(d,s,l,o,n),total:d.length}}let[c,d]=await Promise.all([e.context.adapter.findMany({model:"apikey",where:[{field:"referenceId",value:t}],limit:o,offset:n,sortBy:s?{field:s,direction:l||"asc"}:void 0}),e.context.adapter.count({model:"apikey",where:[{field:"referenceId",value:t}]})]);return{apiKeys:c,total:d}}async function W(e,t,r,i){let a=function(e){let t=e.context;if("orgOptions"in t&&t.orgOptions)return t.orgOptions;let r=t.getPlugin?.("organization");return r&&"options"in r?r.options:null}(e);if(!a){let e=o.ORGANIZATION_PLUGIN_REQUIRED;throw u.E.from("INTERNAL_SERVER_ERROR",e)}let n=await e.context.adapter.findOne({model:"member",where:[{field:"userId",value:t},{field:"organizationId",value:r}]});if(!n){let e=o.USER_NOT_MEMBER_OF_ORGANIZATION;throw u.E.from("FORBIDDEN",e)}if(!await Y(e,n.role,r,i,a)){let e=o.INSUFFICIENT_API_KEY_PERMISSIONS;throw u.E.from("FORBIDDEN",e)}return n}async function Y(t,r,i,a,o){let{hasPermission:n}=await e.A(450257);try{return await n({role:r,options:o,permissions:{apiKey:[a]},organizationId:i,allowCreatorAllPermissions:!0},t)}catch{return!1}}let Q=(e,t="ms")=>new Date(Date.now()+("sec"===t?1e3*e:e)),G=E.object({configId:E.string().meta({description:"The configuration ID to use for the API key. If not provided, the default configuration will be used."}).optional(),name:E.string().meta({description:"Name of the Api Key"}).optional(),expiresIn:E.number().meta({description:"Expiration time of the Api Key in seconds"}).min(1).optional().nullable().default(null),prefix:E.string().meta({description:"Prefix of the Api Key"}).regex(/^[a-zA-Z0-9_-]+$/,{message:"Invalid prefix format, must be alphanumeric and contain only underscores and hyphens."}).optional(),remaining:E.number().meta({description:"Remaining number of requests. Server side only"}).min(0).optional().nullable().default(null),metadata:E.any().optional(),refillAmount:E.number().meta({description:"Amount to refill the remaining count of the Api Key. server-only. Eg: 100"}).min(1).optional(),refillInterval:E.number().meta({description:"Interval to refill the Api Key in milliseconds. server-only. Eg: 1000"}).optional(),rateLimitTimeWindow:E.number().meta({description:"The duration in milliseconds where each request is counted. Once the `maxRequests` is reached, the request will be rejected until the `timeWindow` has passed, at which point the `timeWindow` will be reset. server-only. Eg: 1000"}).optional(),rateLimitMax:E.number().meta({description:"Maximum amount of requests allowed within a window. Once the `maxRequests` is reached, the request will be rejected until the `timeWindow` has passed, at which point the `timeWindow` will be reset. server-only. Eg: 100"}).optional(),rateLimitEnabled:E.boolean().meta({description:"Whether the key has rate limiting enabled. server-only. Eg: true"}).optional(),permissions:E.record(E.string(),E.array(E.string())).meta({description:"Permissions of the Api Key."}).optional(),userId:A.f.string().meta({description:'User Id of the user that the Api Key belongs to. server-only. Eg: "user-id"'}).optional(),organizationId:A.f.string().meta({description:"Organization Id of the organization that the Api Key belongs to. Eg: 'org-id'"}).optional()}),J=E.object({configId:E.string().meta({description:"The configuration ID to use for the API key lookup. If not provided, the default configuration will be used."}).optional(),keyId:E.string().meta({description:"The id of the Api Key"})}),Z=E.object({configId:E.string().meta({description:"The configuration ID to use for the API key lookup. If not provided, the default configuration will be used."}).optional(),id:E.string().meta({description:"The id of the Api Key"})}),X=E.object({configId:E.string().meta({description:"Filter by configuration ID. If not provided, returns keys from all configurations."}).optional(),organizationId:E.string().meta({description:"Organization ID to list keys for. If provided, returns organization-owned keys. If not provided, returns user-owned keys."}).optional(),limit:A.f.number().int().nonnegative().meta({description:"The number of API keys to return"}).optional(),offset:A.f.number().int().nonnegative().meta({description:"The offset to start from"}).optional(),sortBy:E.string().meta({description:"The field to sort by (e.g., createdAt, name, expiresAt)"}).optional(),sortDirection:E.enum(["asc","desc"]).meta({description:"The direction to sort by"}).optional()}).optional(),ee=E.object({configId:E.string().meta({description:"The configuration ID to use for the API key lookup. If not provided, the default configuration will be used."}).optional(),keyId:E.string().meta({description:"The id of the Api Key"}),userId:A.f.string().meta({description:'The id of the user which the api key belongs to. server-only. Eg: "some-user-id"'}).optional(),name:E.string().meta({description:"The name of the key"}).optional(),enabled:E.boolean().meta({description:"Whether the Api Key is enabled or not"}).optional(),remaining:E.number().meta({description:"The number of remaining requests"}).min(1).optional(),refillAmount:E.number().meta({description:"The refill amount"}).optional(),refillInterval:E.number().meta({description:"The refill interval"}).optional(),metadata:E.any().optional(),expiresIn:E.number().meta({description:"Expiration time of the Api Key in seconds"}).min(1).optional().nullable(),rateLimitEnabled:E.boolean().meta({description:"Whether the key has rate limiting enabled."}).optional(),rateLimitTimeWindow:E.number().meta({description:"The duration in milliseconds where each request is counted. server-only. Eg: 1000"}).optional(),rateLimitMax:E.number().meta({description:"Maximum amount of requests allowed within a window. Once the `maxRequests` is reached, the request will be rejected until the `timeWindow` has passed, at which point the `timeWindow` will be reset. server-only. Eg: 100"}).optional(),permissions:E.record(E.string(),E.array(E.string())).meta({description:"Update the permissions on the API Key. server-only."}).optional().nullable()});function et(e,t){let r=new Date,i=e.lastRequest,a=e.rateLimitTimeWindow,n=e.rateLimitMax;if(!1===t.rateLimit.enabled||!1===e.rateLimitEnabled)return{type:"skip",lastRequest:r};if(null===a||null===n)return{type:"skip",lastRequest:null};if(null===i)return{type:"start",now:r};let s=r.getTime()-new Date(i).getTime();return s>a?{type:"reset",now:r,windowStart:new Date(r.getTime()-a)}:e.requestCount>=n?{type:"deny",message:o.RATE_LIMIT_EXCEEDED.message,tryAgainIn:Math.ceil(a-s)}:{type:"increment",now:r,max:n,windowStart:new Date(r.getTime()-a)}}async function er({key:e,ctx:t,lookupOpts:r,configurations:i,schema:a,permissions:n,expectedConfigId:s,runCustomValidator:l}){let c=r.disableKeyHashing?e:await ef(e),d=await V(t,c,r);if(!d||void 0!==s&&!ed(d.configId,s))throw u.E.from("UNAUTHORIZED",o.INVALID_API_KEY);let p=el(t.context,i,d.configId);if(l&&p.customAPIKeyValidator&&!await p.customAPIKeyValidator({ctx:t,key:e}))throw u.E.from("UNAUTHORIZED",o.KEY_NOT_FOUND);if(!1===d.enabled)throw u.E.from("UNAUTHORIZED",o.KEY_DISABLED);if(d.expiresAt&&Date.now()>new Date(d.expiresAt).getTime()){let e=async()=>{"secondary-storage"===p.storage&&p.fallbackToDatabase?(await K(t,d,p),await t.context.adapter.delete({model:em,where:[{field:"id",value:d.id}]})):"secondary-storage"===p.storage?await K(t,d,p):await t.context.adapter.delete({model:em,where:[{field:"id",value:d.id}]})};throw p.deferUpdates?t.context.runInBackground(e().catch(e=>{t.context.logger.error("Deferred update failed:",e)})):await e(),u.E.from("UNAUTHORIZED",o.KEY_EXPIRED)}if(n){let e=d.permissions?(0,b.f)(d.permissions):null;if(!e||!(0,_.Y)(e).authorize(n).success)throw u.E.from("UNAUTHORIZED",o.KEY_NOT_FOUND)}if(0===d.remaining&&null===d.refillAmount){let e=async()=>{"secondary-storage"===p.storage&&p.fallbackToDatabase?(await K(t,d,p),await t.context.adapter.delete({model:em,where:[{field:"id",value:d.id}]})):"secondary-storage"===p.storage?await K(t,d,p):await t.context.adapter.delete({model:em,where:[{field:"id",value:d.id}]})};throw p.deferUpdates?t.context.runInBackground(e().catch(e=>{t.context.logger.error("Deferred update failed:",e)})):await e(),u.E.from("TOO_MANY_REQUESTS",o.USAGE_EXCEEDED)}return{apiKey:"database"===p.storage||"secondary-storage"===p.storage&&p.fallbackToDatabase?await ei({ctx:t,apiKey:d,opts:p,hashedKey:c}):await en({ctx:t,apiKey:d,opts:p,hashedKey:c}),opts:p}}async function ei({ctx:e,apiKey:t,opts:r,hashedKey:i}){let a=t;null!==t.remaining&&(a=await ea(e,t)),a=await eo(e,a,r);let n=await e.context.adapter.update({model:em,where:[{field:"id",value:a.id}],update:{updatedAt:new Date}});if(!n)throw u.E.from("UNAUTHORIZED",o.INVALID_API_KEY);return"secondary-storage"===r.storage&&r.fallbackToDatabase&&await F(e,n,r),n}async function ea(e,t){let r=new Date,{refillInterval:i,refillAmount:a}=t;if(i&&a){let o=new Date(t.lastRefillAt??t.createdAt).getTime();if(r.getTime()-o>i){let i=await e.context.adapter.incrementOne({model:em,where:[{field:"id",value:t.id},{field:"lastRefillAt",value:t.lastRefillAt}],increment:{},set:{remaining:a-1,lastRefillAt:r}});if(i)return i}}let n=await e.context.adapter.incrementOne({model:em,where:[{field:"id",value:t.id},{field:"remaining",operator:"gt",value:0}],increment:{remaining:-1}});if(!n)throw u.E.from("TOO_MANY_REQUESTS",o.USAGE_EXCEEDED);return n}async function eo(e,t,r){let i=et(t,r);if("deny"===i.type)throw new u.E("TOO_MANY_REQUESTS",{message:i.message,code:"RATE_LIMITED",details:{tryAgainIn:i.tryAgainIn}});if("skip"===i.type)return null===i.lastRequest?t:await e.context.adapter.update({model:"apikey",where:[{field:"id",value:t.id}],update:{lastRequest:i.lastRequest}})??t;if("increment"===i.type){let a=await e.context.adapter.incrementOne({model:em,where:[{field:"id",value:t.id},{field:"lastRequest",operator:"gt",value:i.windowStart},{field:"requestCount",operator:"lt",value:i.max}],increment:{requestCount:1},set:{lastRequest:i.now}});if(a)return a;let n=await e.context.adapter.findOne({model:em,where:[{field:"id",value:t.id}]});if(!n)throw u.E.from("UNAUTHORIZED",o.INVALID_API_KEY);return eo(e,n,r)}let a="reset"===i.type?{field:"lastRequest",operator:"lte",value:i.windowStart}:{field:"lastRequest",operator:"eq",value:null},n=await e.context.adapter.incrementOne({model:em,where:[{field:"id",value:t.id},a],increment:{},set:{requestCount:1,lastRequest:i.now}});if(n)return n;let s=await e.context.adapter.findOne({model:em,where:[{field:"id",value:t.id}]});if(!s)throw u.E.from("UNAUTHORIZED",o.INVALID_API_KEY);return eo(e,s,r)}async function en({ctx:e,apiKey:t,opts:r,hashedKey:i}){let a=t.remaining,n=t.lastRefillAt;if(null!==a){let e=Date.now(),{refillInterval:r,refillAmount:i}=t,s=new Date(n??t.createdAt).getTime();if(r&&i&&e-s>r&&(a=i,n=new Date),0===a)throw u.E.from("TOO_MANY_REQUESTS",o.USAGE_EXCEEDED);a--}let s={...function(e,t){let r=et(e,t);switch(r.type){case"deny":throw new u.E("TOO_MANY_REQUESTS",{message:r.message,code:"RATE_LIMITED",details:{tryAgainIn:r.tryAgainIn}});case"skip":return null===r.lastRequest?{}:{lastRequest:r.lastRequest};case"start":case"reset":return{lastRequest:r.now,requestCount:1};case"increment":return{lastRequest:r.now,requestCount:e.requestCount+1}}}(t,r),remaining:a,lastRefillAt:n,updatedAt:new Date},l=async()=>{let t=await V(e,i,r);if(!t)return null;let a={...t,...s};return await F(e,a,r),a};if(r.deferUpdates)return e.context.runInBackground(l().catch(t=>{e.context.logger.error("Failed to update API key:",t)})),{...t,...s};let c=await l();if(!c)throw u.E.from("INTERNAL_SERVER_ERROR",o.FAILED_TO_UPDATE_API_KEY);return c}let es=E.object({configId:E.string().meta({description:"Configuration ID to scope verification to. When omitted, the key is validated against its own configuration."}).optional(),key:E.string().meta({description:"The key to verify"}),permissions:E.record(E.string(),E.array(E.string())).meta({description:"The permissions to verify."}).optional()});function el(e,t,r){let i=()=>{let r=t.find(e=>!e.configId||"default"===e.configId);if(!r){e.logger.error("No default api-key configuration found. Either provide an api-key configuration with configId 'default' or provide a configuration with no `configId` set.");let t=o.NO_DEFAULT_API_KEY_CONFIGURATION_FOUND;throw u.E.from("BAD_REQUEST",t)}return{...r,configId:"default"}};return r?t.find(e=>e.configId===r)??i():i()}function ec(e){return!e||"default"===e}function ed(e,t){return!!(ec(e)&&ec(t))||e===t}let eu=null;async function ep(e,t=!1){eu&&!t&&(new Date).getTime()-eu.getTime()<1e4||(eu=new Date,await e.adapter.deleteMany({model:em,where:[{field:"expiresAt",operator:"lt",value:new Date},{field:"expiresAt",operator:"ne",value:null}]}).catch(t=>{e.logger.error("Failed to delete expired API keys:",t)}))}let ef=async e=>{let t=await (0,d.f)("SHA-256").digest(new TextEncoder().encode(e));return c.W.encode(new Uint8Array(t),{padding:!1})},em="apikey";e.s(["f",0,function(e,t){if(Array.isArray(e)&&e.length>0){if(!e.every(e=>e.configId))throw new u.p("configId is required for each API key configuration in the api-key plugin.");let t=e.map(e=>e.configId);if(new Set(t).size!==t.length)throw new u.p("configId must be unique for each API key configuration in the api-key plugin.")}let r=t??{schema:Array.isArray(e)?void 0:e?.schema},i=[...(Array.isArray(e)?e:[e]).map(e=>({...e,apiKeyHeaders:e?.apiKeyHeaders??"x-api-key",defaultKeyLength:e?.defaultKeyLength||64,maximumPrefixLength:e?.maximumPrefixLength??32,minimumPrefixLength:e?.minimumPrefixLength??1,maximumNameLength:e?.maximumNameLength??32,minimumNameLength:e?.minimumNameLength??1,enableMetadata:e?.enableMetadata??!1,disableKeyHashing:e?.disableKeyHashing??!1,requireName:e?.requireName??!1,storage:e?.storage??"database",rateLimit:{enabled:e?.rateLimit?.enabled===void 0||e?.rateLimit?.enabled,timeWindow:e?.rateLimit?.timeWindow??864e5,maxRequests:e?.rateLimit?.maxRequests??10},keyExpiration:{defaultExpiresIn:e?.keyExpiration?.defaultExpiresIn??null,disableCustomExpiresTime:e?.keyExpiration?.disableCustomExpiresTime??!1,maxExpiresIn:e?.keyExpiration?.maxExpiresIn??365,minExpiresIn:e?.keyExpiration?.minExpiresIn??1},startingCharactersConfig:{shouldStore:e?.startingCharactersConfig?.shouldStore??!0,charactersLength:e?.startingCharactersConfig?.charactersLength??6},enableSessionForAPIKeys:e?.enableSessionForAPIKeys??!1,fallbackToDatabase:e?.fallbackToDatabase??!1,customStorage:e?.customStorage,deferUpdates:e?.deferUpdates??!1}))],a=(0,w.C)((({defaultRateLimitMax:e,defaultTimeWindow:t})=>({apikey:{fields:{configId:{type:"string",required:!0,defaultValue:"default",input:!1,index:!0},name:{type:"string",required:!1,input:!1},start:{type:"string",required:!1,input:!1},referenceId:{type:"string",required:!0,input:!1,index:!0},prefix:{type:"string",required:!1,input:!1},key:{type:"string",required:!0,input:!1,index:!0},refillInterval:{type:"number",required:!1,input:!1},refillAmount:{type:"number",required:!1,input:!1},lastRefillAt:{type:"date",required:!1,input:!1},enabled:{type:"boolean",required:!1,input:!1,defaultValue:!0},rateLimitEnabled:{type:"boolean",required:!1,input:!1,defaultValue:!0},rateLimitTimeWindow:{type:"number",required:!1,input:!1,defaultValue:t},rateLimitMax:{type:"number",required:!1,input:!1,defaultValue:e},requestCount:{type:"number",required:!1,input:!1,defaultValue:0},remaining:{type:"number",required:!1,input:!1},lastRequest:{type:"date",required:!1,input:!1},expiresAt:{type:"date",required:!1,input:!1},createdAt:{type:"date",required:!0,input:!1},updatedAt:{type:"date",required:!0,input:!1},permissions:{type:"string",required:!1,input:!1},metadata:{type:"string",required:!1,input:!0,transform:{input:e=>JSON.stringify(e),output:e=>e?(0,k.f)(e):null}}}}}))({defaultRateLimitMax:(1===i.length?i[0]?.rateLimit.maxRequests:void 0)??10,defaultTimeWindow:(1===i.length?i[0]?.rateLimit.timeWindow:void 0)??864e5}),r.schema);function n(e){for(let t of i){if(!t.enableSessionForAPIKeys)continue;let r=function(e,t){if(t.customAPIKeyGetter)return t.customAPIKeyGetter(e);if(Array.isArray(t.apiKeyHeaders)){for(let r of t.apiKeyHeaders){let t=e.headers?.get(r);if(t)return t}return null}return e.headers?.get(t.apiKeyHeaders)??null}(e,t);if(r)return{key:r,config:t}}return null}let c=function({defaultKeyGenerator:e,configurations:t,schema:r}){return{createApiKey:function({defaultKeyGenerator:e,configurations:t,schema:r,deleteAllExpiredApiKeys:i}){return(0,s.g)("/api-key/create",{method:"POST",body:G,metadata:{openapi:{description:"Create a new API key for a user",responses:{200:{description:"API key created successfully",content:{"application/json":{schema:{type:"object",properties:{id:{type:"string",description:"Unique identifier of the API key"},createdAt:{type:"string",format:"date-time",description:"Creation timestamp"},updatedAt:{type:"string",format:"date-time",description:"Last update timestamp"},name:{type:"string",nullable:!0,description:"Name of the API key"},prefix:{type:"string",nullable:!0,description:"Prefix of the API key"},start:{type:"string",nullable:!0,description:"Starting characters of the key (if configured)"},key:{type:"string",description:"The full API key (only returned on creation)"},enabled:{type:"boolean",description:"Whether the key is enabled"},expiresAt:{type:"string",format:"date-time",nullable:!0,description:"Expiration timestamp"},referenceId:{type:"string",description:"ID of the reference owning the key"},lastRefillAt:{type:"string",format:"date-time",nullable:!0,description:"Last refill timestamp"},lastRequest:{type:"string",format:"date-time",nullable:!0,description:"Last request timestamp"},metadata:{type:"object",nullable:!0,additionalProperties:!0,description:"Metadata associated with the key"},rateLimitMax:{type:"number",nullable:!0,description:"Maximum requests in time window"},rateLimitTimeWindow:{type:"number",nullable:!0,description:"Rate limit time window in milliseconds"},remaining:{type:"number",nullable:!0,description:"Remaining requests"},refillAmount:{type:"number",nullable:!0,description:"Amount to refill"},refillInterval:{type:"number",nullable:!0,description:"Refill interval in milliseconds"},rateLimitEnabled:{type:"boolean",description:"Whether rate limiting is enabled"},requestCount:{type:"number",description:"Current request count in window"},permissions:{type:"object",nullable:!0,additionalProperties:{type:"array",items:{type:"string"}},description:"Permissions associated with the key"}},required:["id","createdAt","updatedAt","key","enabled","referenceId","rateLimitEnabled","requestCount"]}}}}}}}},async r=>{let a,n,{configId:s,name:l,expiresIn:c,prefix:d,remaining:f,metadata:m,refillAmount:h,refillInterval:g,permissions:w,rateLimitMax:E,rateLimitTimeWindow:A,rateLimitEnabled:I}=r.body,_=el(r.context,t,s),k=_.customKeyGenerator||e,T=await (0,p.D)(r,{disableCookieCache:!0}),v=r.request||r.headers;if(v&&(void 0!==h||void 0!==g||void 0!==E||void 0!==A||void 0!==I||void 0!==w||null!==f))throw u.E.from("BAD_REQUEST",o.SERVER_ONLY_PROPERTY);if(r.request&&void 0!==r.body.userId)throw u.E.from("UNAUTHORIZED",o.UNAUTHORIZED_SESSION);if("organization"===(_.references??"user")){let e=r.body.organizationId;if(!e){let e=o.ORGANIZATION_ID_REQUIRED;throw u.E.from("BAD_REQUEST",e)}let t=T?.user.id||r.body.userId;if(!t)throw u.E.from("UNAUTHORIZED",o.UNAUTHORIZED_SESSION);await W(r,t,e,"create"),a=e}else if(v){if(!T?.user.id){let e=o.UNAUTHORIZED_SESSION;throw u.E.from("UNAUTHORIZED",e)}a=T.user.id}else{let e=r.body.userId,t=T?.user.id;if(!t&&!e||T&&e&&t!==e){let e=o.UNAUTHORIZED_SESSION;throw u.E.from("UNAUTHORIZED",e)}a=t||e}if(m){if(!1===_.enableMetadata)throw u.E.from("BAD_REQUEST",o.METADATA_DISABLED);if("object"!=typeof m)throw u.E.from("BAD_REQUEST",o.INVALID_METADATA_TYPE)}if(h&&!g){let e=o.REFILL_AMOUNT_AND_INTERVAL_REQUIRED;throw u.E.from("BAD_REQUEST",e)}if(g&&!h){let e=o.REFILL_INTERVAL_AND_AMOUNT_REQUIRED;throw u.E.from("BAD_REQUEST",e)}if(c){if(!0===_.keyExpiration.disableCustomExpiresTime){let e=o.KEY_DISABLED_EXPIRATION;throw u.E.from("BAD_REQUEST",e)}let e=c/86400;if(_.keyExpiration.minExpiresIn>e){let e=o.EXPIRES_IN_IS_TOO_SMALL;throw u.E.from("BAD_REQUEST",e)}if(_.keyExpiration.maxExpiresIn<e){let e=o.EXPIRES_IN_IS_TOO_LARGE;throw u.E.from("BAD_REQUEST",e)}}if(d&&(d.length<_.minimumPrefixLength||d.length>_.maximumPrefixLength))throw u.E.from("BAD_REQUEST",o.INVALID_PREFIX_LENGTH);if(l){if(l.length<_.minimumNameLength||l.length>_.maximumNameLength)throw u.E.from("BAD_REQUEST",o.INVALID_NAME_LENGTH)}else if(_.requireName)throw u.E.from("BAD_REQUEST",o.NAME_REQUIRED);i(r.context);let U=await k({length:_.defaultKeyLength,prefix:d||_.defaultPrefix}),R=_.disableKeyHashing?U:await ef(U),S=null;_.startingCharactersConfig.shouldStore&&(S=U.substring(0,_.startingCharactersConfig.charactersLength));let x=_.permissions?.defaultPermissions?"function"==typeof _.permissions.defaultPermissions?await _.permissions.defaultPermissions(a,r):_.permissions.defaultPermissions:void 0,O=w?JSON.stringify(w):x?JSON.stringify(x):void 0,D={configId:_.configId??"default",createdAt:new Date,updatedAt:new Date,name:l??null,prefix:d??_.defaultPrefix??null,start:S,key:R,enabled:!0,expiresAt:c?Q(c,"sec"):_.keyExpiration.defaultExpiresIn?Q(_.keyExpiration.defaultExpiresIn,"sec"):null,referenceId:a,lastRefillAt:null,lastRequest:null,metadata:null,rateLimitMax:E??_.rateLimit.maxRequests??null,rateLimitTimeWindow:A??_.rateLimit.timeWindow??null,remaining:null===f?f:f??h??null,refillAmount:h??null,refillInterval:g??null,rateLimitEnabled:void 0===I?_.rateLimit.enabled??!0:I,requestCount:0,permissions:O};if(m&&(D.metadata=m),"secondary-storage"===_.storage&&_.fallbackToDatabase)n=await r.context.adapter.create({model:em,data:D}),await F(r,n,_);else if("secondary-storage"===_.storage){let e=r.context.generateId({model:"apikey"})||(0,y.f)();n={...D,id:e},await F(r,n,_)}else n=await r.context.adapter.create({model:em,data:D});return r.json({...n,key:U,metadata:m??null,permissions:n.permissions?(0,b.f)(n.permissions):null})})}({defaultKeyGenerator:e,configurations:t,schema:r,deleteAllExpiredApiKeys:ep}),verifyApiKey:function({configurations:e,schema:t,deleteAllExpiredApiKeys:r}){return s.g.serverOnly({method:"POST",body:es},async i=>{let a,{configId:n,key:s}=i.body,l=el(i.context,e,n);if(void 0!==n&&l.customAPIKeyValidator&&!await l.customAPIKeyValidator({ctx:i,key:s}))return i.json({valid:!1,error:{message:o.INVALID_API_KEY,code:"KEY_NOT_FOUND"},key:null});let c=null;try{let o=await er({key:s,permissions:i.body.permissions,ctx:i,lookupOpts:l,configurations:e,schema:t,expectedConfigId:n,runCustomValidator:void 0===n});c=o.apiKey,(a=o.opts).deferUpdates&&i.context.runInBackground(r(i.context).catch(e=>{i.context.logger.error("Failed to delete expired API keys:",e)}))}catch(e){if(i.context.logger.error("Failed to validate API key:",e),e instanceof u.E||e instanceof u.E||e?.name==="APIError")return i.json({valid:!1,error:{...e.body,message:e.body?.message,code:e.body?.code},key:null});return i.json({valid:!1,error:{message:o.INVALID_API_KEY,code:"INVALID_API_KEY"},key:null})}let{key:d,...p}=c??{key:1,permissions:void 0},f=null;return c&&(f=await R(i,c,a)),p.permissions=p.permissions?(0,b.f)(p.permissions):null,i.json({valid:!0,error:null,key:null===c?null:{...p,metadata:f}})})}({configurations:t,schema:r,deleteAllExpiredApiKeys:ep}),getApiKey:function({configurations:e,schema:t,deleteAllExpiredApiKeys:r}){return(0,s.g)("/api-key/get",{method:"GET",query:Z,use:[p.Z],metadata:{openapi:{description:"Retrieve an existing API key by ID",responses:{200:{description:"API key retrieved successfully",content:{"application/json":{schema:{type:"object",properties:{id:{type:"string",description:"ID"},name:{type:"string",nullable:!0,description:"The name of the key"},start:{type:"string",nullable:!0,description:"Shows the first few characters of the API key, including the prefix. This allows you to show those few characters in the UI to make it easier for users to identify the API key."},prefix:{type:"string",nullable:!0,description:"The API Key prefix. Stored as plain text."},userId:{type:"string",description:"The owner of the user id"},refillInterval:{type:"number",nullable:!0,description:"The interval in milliseconds between refills of the `remaining` count. Example: 3600000 // refill every hour (3600000ms = 1h)"},refillAmount:{type:"number",nullable:!0,description:"The amount to refill"},lastRefillAt:{type:"string",format:"date-time",nullable:!0,description:"The last refill date"},enabled:{type:"boolean",description:"Sets if key is enabled or disabled",default:!0},rateLimitEnabled:{type:"boolean",description:"Whether the key has rate limiting enabled"},rateLimitTimeWindow:{type:"number",nullable:!0,description:"The duration in milliseconds"},rateLimitMax:{type:"number",nullable:!0,description:"Maximum amount of requests allowed within a window"},requestCount:{type:"number",description:"The number of requests made within the rate limit time window"},remaining:{type:"number",nullable:!0,description:"Remaining requests (every time api key is used this should updated and should be updated on refill as well)"},lastRequest:{type:"string",format:"date-time",nullable:!0,description:"When last request occurred"},expiresAt:{type:"string",format:"date-time",nullable:!0,description:"Expiry date of a key"},createdAt:{type:"string",format:"date-time",description:"created at"},updatedAt:{type:"string",format:"date-time",description:"updated at"},metadata:{type:"object",nullable:!0,additionalProperties:!0,description:"Extra metadata about the apiKey"},permissions:{type:"string",nullable:!0,description:"Permissions for the api key (stored as JSON string)"}},required:["id","userId","enabled","rateLimitEnabled","requestCount","createdAt","updatedAt"]}}}}}}}},async t=>{let{configId:i,id:a}=t.query,n=t.context.session,s=el(t.context,e,i),l=null;if(!(l=await M(t,a,s))||!ed(l.configId,s.configId))throw u.E.from("NOT_FOUND",o.KEY_NOT_FOUND);let c=el(t.context,e,l.configId);if((c.references??"user")==="organization")await W(t,n.user.id,l.referenceId,"read");else if(l.referenceId!==n.user.id)throw u.E.from("NOT_FOUND",o.KEY_NOT_FOUND);r(t.context);let d=await R(t,l,c),{key:p,...f}=l;return t.json({...f,metadata:d,permissions:f.permissions?(0,b.f)(f.permissions):null})})}({configurations:t,schema:r,deleteAllExpiredApiKeys:ep}),updateApiKey:function({configurations:e,schema:t,deleteAllExpiredApiKeys:r}){return(0,s.g)("/api-key/update",{method:"POST",body:ee,metadata:{openapi:{description:"Update an existing API key by ID",responses:{200:{description:"API key updated successfully",content:{"application/json":{schema:{type:"object",properties:{id:{type:"string",description:"ID"},name:{type:"string",nullable:!0,description:"The name of the key"},start:{type:"string",nullable:!0,description:"Shows the first few characters of the API key, including the prefix. This allows you to show those few characters in the UI to make it easier for users to identify the API key."},prefix:{type:"string",nullable:!0,description:"The API Key prefix. Stored as plain text."},userId:{type:"string",description:"The owner of the user id"},refillInterval:{type:"number",nullable:!0,description:"The interval in milliseconds between refills of the `remaining` count. Example: 3600000 // refill every hour (3600000ms = 1h)"},refillAmount:{type:"number",nullable:!0,description:"The amount to refill"},lastRefillAt:{type:"string",format:"date-time",nullable:!0,description:"The last refill date"},enabled:{type:"boolean",description:"Sets if key is enabled or disabled",default:!0},rateLimitEnabled:{type:"boolean",description:"Whether the key has rate limiting enabled"},rateLimitTimeWindow:{type:"number",nullable:!0,description:"The duration in milliseconds"},rateLimitMax:{type:"number",nullable:!0,description:"Maximum amount of requests allowed within a window"},requestCount:{type:"number",description:"The number of requests made within the rate limit time window"},remaining:{type:"number",nullable:!0,description:"Remaining requests (every time api key is used this should updated and should be updated on refill as well)"},lastRequest:{type:"string",format:"date-time",nullable:!0,description:"When last request occurred"},expiresAt:{type:"string",format:"date-time",nullable:!0,description:"Expiry date of a key"},createdAt:{type:"string",format:"date-time",description:"created at"},updatedAt:{type:"string",format:"date-time",description:"updated at"},metadata:{type:"object",nullable:!0,additionalProperties:!0,description:"Extra metadata about the apiKey"},permissions:{type:"string",nullable:!0,description:"Permissions for the api key (stored as JSON string)"}},required:["id","userId","enabled","rateLimitEnabled","requestCount","createdAt","updatedAt"]}}}}}}}},async t=>{let{configId:i,keyId:a,expiresIn:n,enabled:s,metadata:l,refillAmount:c,refillInterval:d,remaining:f,name:m,permissions:h,rateLimitEnabled:g,rateLimitTimeWindow:w,rateLimitMax:y}=t.body,E=await (0,p.D)(t,{disableCookieCache:!0}),A=t.request||t.headers,I=A&&!E?null:E?.user||{id:t.body.userId};if(!I?.id||E&&t.body.userId&&E?.user.id!==t.body.userId)throw u.E.from("UNAUTHORIZED",o.UNAUTHORIZED_SESSION);if(A&&(void 0!==c||void 0!==d||void 0!==y||void 0!==w||void 0!==g||void 0!==f||void 0!==h))throw u.E.from("BAD_REQUEST",o.SERVER_ONLY_PROPERTY);let _=el(t.context,e,i),k=null;if(!(k=await M(t,a,_))||!ed(k.configId,_.configId))throw u.E.from("NOT_FOUND",o.KEY_NOT_FOUND);let T=el(t.context,e,k.configId);if((T.references??"user")==="organization")await W(t,I.id,k.referenceId,"update");else if(k.referenceId!==I.id)throw u.E.from("NOT_FOUND",o.KEY_NOT_FOUND);let v={};if(void 0!==m){if(m.length<T.minimumNameLength||m.length>T.maximumNameLength)throw u.E.from("BAD_REQUEST",o.INVALID_NAME_LENGTH);v.name=m}if(void 0!==s&&(v.enabled=s),void 0!==n){if(!0===T.keyExpiration.disableCustomExpiresTime)throw u.E.from("BAD_REQUEST",o.KEY_DISABLED_EXPIRATION);if(null!==n){let e=n/86400;if(e<T.keyExpiration.minExpiresIn)throw u.E.from("BAD_REQUEST",o.EXPIRES_IN_IS_TOO_SMALL);if(e>T.keyExpiration.maxExpiresIn)throw u.E.from("BAD_REQUEST",o.EXPIRES_IN_IS_TOO_LARGE)}v.expiresAt=n?Q(n,"sec"):null}if(void 0!==l&&!0===T.enableMetadata){if("object"!=typeof l)throw u.E.from("BAD_REQUEST",o.INVALID_METADATA_TYPE);v.metadata=l}if(void 0!==f&&(v.remaining=f),void 0!==c||void 0!==d){if(void 0!==c&&void 0===d)throw u.E.from("BAD_REQUEST",o.REFILL_AMOUNT_AND_INTERVAL_REQUIRED);if(void 0!==d&&void 0===c)throw u.E.from("BAD_REQUEST",o.REFILL_INTERVAL_AND_AMOUNT_REQUIRED);v.refillAmount=c,v.refillInterval=d}if(void 0!==g&&(v.rateLimitEnabled=g),void 0!==w&&(v.rateLimitTimeWindow=w),void 0!==y&&(v.rateLimitMax=y),void 0!==h&&(v.permissions=JSON.stringify(h)),0===Object.keys(v).length)throw u.E.from("BAD_REQUEST",o.NO_VALUES_TO_UPDATE);let U=k;try{if("secondary-storage"===T.storage&&T.fallbackToDatabase){let e=await t.context.adapter.update({model:em,where:[{field:"id",value:k.id}],update:v});e&&(await F(t,e,T),U=e)}else if("database"===T.storage){let e=await t.context.adapter.update({model:em,where:[{field:"id",value:k.id}],update:v});e&&(U=e)}else{let e={...k,...v,updatedAt:new Date};await F(t,e,T),U=e}}catch(e){throw u.E.fromStatus("INTERNAL_SERVER_ERROR",{message:e?.message})}r(t.context);let S=await R(t,U,T),{key:x,...O}=U;return t.json({...O,metadata:S,permissions:O.permissions?(0,b.f)(O.permissions):null})})}({configurations:t,schema:r,deleteAllExpiredApiKeys:ep}),deleteApiKey:function({configurations:e,schema:t,deleteAllExpiredApiKeys:r}){return(0,s.g)("/api-key/delete",{method:"POST",body:J,use:[p.Z],metadata:{openapi:{description:"Delete an existing API key",requestBody:{content:{"application/json":{schema:{type:"object",properties:{keyId:{type:"string",description:"The id of the API key to delete"}},required:["keyId"]}}}},responses:{200:{description:"API key deleted successfully",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",description:"Indicates if the API key was successfully deleted"}},required:["success"]}}}}}}}},async t=>{let{configId:i,keyId:a}=t.body,n=t.context.session;if(!0===n.user.banned)throw u.E.from("UNAUTHORIZED",o.USER_BANNED);let s=el(t.context,e,i),l=null;if(!(l=await M(t,a,s))||!ed(l.configId,s.configId))throw u.E.from("NOT_FOUND",o.KEY_NOT_FOUND);let c=el(t.context,e,l.configId);if((c.references??"user")==="organization")await W(t,n.user.id,l.referenceId,"delete");else if(l.referenceId!==n.user.id)throw u.E.from("NOT_FOUND",o.KEY_NOT_FOUND);try{"secondary-storage"===c.storage&&c.fallbackToDatabase?(await K(t,l,c),await t.context.adapter.delete({model:em,where:[{field:"id",value:l.id}]})):"database"===c.storage?await t.context.adapter.delete({model:em,where:[{field:"id",value:l.id}]}):await K(t,l,c)}catch(e){throw u.E.fromStatus("INTERNAL_SERVER_ERROR",{message:e?.message})}return r(t.context),t.json({success:!0})})}({configurations:t,schema:r,deleteAllExpiredApiKeys:ep}),listApiKeys:function({configurations:e,schema:t,deleteAllExpiredApiKeys:r}){return(0,s.g)("/api-key/list",{method:"GET",use:[p.Z],query:X,metadata:{openapi:{description:"List all API keys for the authenticated user or for a specific organization",responses:{200:{description:"API keys retrieved successfully",content:{"application/json":{schema:{type:"object",properties:{apiKeys:{type:"array",items:{type:"object",properties:{id:{type:"string",description:"ID"},name:{type:"string",nullable:!0,description:"The name of the key"},start:{type:"string",nullable:!0,description:"Shows the first few characters of the API key, including the prefix. This allows you to show those few characters in the UI to make it easier for users to identify the API key."},prefix:{type:"string",nullable:!0,description:"The API Key prefix. Stored as plain text."},userId:{type:"string",description:"The owner of the user id"},refillInterval:{type:"number",nullable:!0,description:"The interval in milliseconds between refills of the `remaining` count. Example: 3600000 // refill every hour (3600000ms = 1h)"},refillAmount:{type:"number",nullable:!0,description:"The amount to refill"},lastRefillAt:{type:"string",format:"date-time",nullable:!0,description:"The last refill date"},enabled:{type:"boolean",description:"Sets if key is enabled or disabled",default:!0},rateLimitEnabled:{type:"boolean",description:"Whether the key has rate limiting enabled"},rateLimitTimeWindow:{type:"number",nullable:!0,description:"The duration in milliseconds"},rateLimitMax:{type:"number",nullable:!0,description:"Maximum amount of requests allowed within a window"},requestCount:{type:"number",description:"The number of requests made within the rate limit time window"},remaining:{type:"number",nullable:!0,description:"Remaining requests (every time api key is used this should updated and should be updated on refill as well)"},lastRequest:{type:"string",format:"date-time",nullable:!0,description:"When last request occurred"},expiresAt:{type:"string",format:"date-time",nullable:!0,description:"Expiry date of a key"},createdAt:{type:"string",format:"date-time",description:"created at"},updatedAt:{type:"string",format:"date-time",description:"updated at"},metadata:{type:"object",nullable:!0,additionalProperties:!0,description:"Extra metadata about the apiKey"},permissions:{type:"string",nullable:!0,description:"Permissions for the api key (stored as JSON string)"}},required:["id","userId","enabled","rateLimitEnabled","requestCount","createdAt","updatedAt"]}},total:{type:"number",description:"Total number of API keys"},limit:{type:"number",nullable:!0,description:"The limit used for pagination"},offset:{type:"number",nullable:!0,description:"The offset used for pagination"}},required:["apiKeys","total"]}}}}}}}},async t=>{let i=t.context.session,a=t.query?.configId,o=t.query?.organizationId,n=t.query?.limit!=null?Number(t.query.limit):void 0,s=t.query?.offset!=null?Number(t.query.offset):void 0;o&&await W(t,i.user.id,o,"read");let l=o??i.user.id,c=o?"organization":"user",d=[];if(a){let{apiKeys:r}=await H(t,l,el(t.context,e,a),{limit:void 0,offset:void 0,sortBy:t.query?.sortBy,sortDirection:t.query?.sortDirection});d=r}else{let r=new Map;for(let t of e){let e="database"===t.storage?"database":t.customStorage?`custom:${t.configId??"default"}`:t.fallbackToDatabase?"secondary-storage-with-fallback":"secondary-storage";r.has(e)||r.set(e,t)}let i=await Promise.all([...r.values()].map(e=>H(t,l,e,{limit:void 0,offset:void 0,sortBy:t.query?.sortBy,sortDirection:t.query?.sortDirection}))),a=new Set;for(let{apiKeys:e}of i)for(let t of e)a.has(t.id)||(a.add(t.id),d.push(t))}let u=d.filter(t=>(e.find(e=>ec(t.configId)?ec(e.configId):e.configId===t.configId)?.references??"user")===c&&t.referenceId===l);a&&(u=u.filter(e=>ed(e.configId,a)));let p=u.length,f=u;void 0!==s&&(f=f.slice(s)),void 0!==n&&(f=f.slice(0,n)),r(t.context);let m=f.map(e=>{let{key:t,...r}=e;return{...r,metadata:T(e.metadata),permissions:r.permissions?(0,b.f)(r.permissions):null}}),h=e.find(e=>"database"===e.storage||e.fallbackToDatabase);return h&&await t.context.runInBackgroundOrAwait(U(t,f,h)),t.json({apiKeys:m,total:p,limit:n,offset:s})})}({configurations:t,schema:r,deleteAllExpiredApiKeys:ep}),deleteAllExpiredApiKeys:function({deleteAllExpiredApiKeys:e}){return s.g.serverOnly({method:"POST"},async t=>{try{await e(t.context,!0)}catch(e){return t.context.logger.error("[API KEY PLUGIN] Failed to delete expired API keys:",e),t.json({success:!1,error:e})}return t.json({success:!0,error:null})})}({deleteAllExpiredApiKeys:ep})}}({defaultKeyGenerator:async e=>{let t=(0,g.f)(e.length,"a-z","A-Z");return`${e.prefix||""}${t}`},configurations:i,schema:a});return{id:"api-key",version:"1.7.16",$ERROR_CODES:o,hooks:{before:[{matcher:e=>!!n(e),handler:(0,s.a)(async e=>{let{key:t,config:r}=n(e);if("string"!=typeof t)throw u.E.from("BAD_REQUEST",o.INVALID_API_KEY_GETTER_RETURN_TYPE);if(t.length<r.defaultKeyLength||r.customAPIKeyValidator&&!await r.customAPIKeyValidator({ctx:e,key:t}))throw u.E.from("FORBIDDEN",o.INVALID_API_KEY);let{apiKey:s}=await er({key:t,ctx:e,lookupOpts:r,configurations:i,schema:a,expectedConfigId:r.configId}),c=ep(e.context).catch(t=>{e.context.logger.error("Failed to delete expired API keys:",t)});if(r.deferUpdates&&e.context.runInBackground(c),(r.references??"user")!=="user"){let e=o.INVALID_REFERENCE_ID_FROM_API_KEY;throw u.E.from("UNAUTHORIZED",e)}let d=await e.context.internalAdapter.findUserById(s.referenceId);if(!d){let e=o.INVALID_REFERENCE_ID_FROM_API_KEY;throw u.E.from("UNAUTHORIZED",e)}let p={user:d,session:{id:s.id,token:t,userId:s.referenceId,userAgent:e.request?.headers.get("user-agent")??null,ipAddress:e.request?(0,l.M)(e.request,e.context.options):null,createdAt:new Date,updatedAt:new Date,expiresAt:s.expiresAt||Q(e.context.options.session?.expiresIn||604800,"ms")}};return(await h(t),e.context.session=p,"/get-session"===e.path)?p:{context:e}})}]},endpoints:{createApiKey:c.createApiKey,verifyApiKey:c.verifyApiKey,getApiKey:c.getApiKey,updateApiKey:c.updateApiKey,deleteApiKey:c.deleteApiKey,listApiKeys:c.listApiKeys,deleteAllExpiredApiKeys:c.deleteAllExpiredApiKeys},schema:a}}],363004);var eh=e.i(604383),eg=e.i(673278),ew=e.i(55281);function ey(e){return e.charAt(0).toLowerCase()+e.slice(1)}function eb(e){return e?.code==="P2025"}e.s(["f",0,(e,t)=>{let r=null,i=(e,r=!1)=>({getFieldName:i,getModelName:a,getFieldAttributes:o,getDefaultModelName:n,schema:s})=>{let l=(e,t,r)=>{if(!e&&!r)return;let a={};if(e)for(let r of e)a[i({model:t,field:r})]=!0;if(r){if(!e){let e=s[n(t)]?.fields||{};for(let r of(e.id={type:"string"},Object.keys(e)))a[i({model:t,field:r})]=!0}for(let[e,i]of Object.entries(r)){let r=c(t,i.modelKey??e,s);"one-to-one"===i.relation?a[r]=!0:a[r]={take:i.limit}}}return a},c=(e,r,i)=>{try{let o=n(e),s=n(r),l=a(r).toLowerCase(),c=Object.entries(i[s]?.fields||{}).filter(([e,t])=>t.references&&n(t.references.model)===o);if(c.length>0){let[e,r]=c[0];return r?.unique===!0||!0===t.usePlural?l:`${l}s`}if((c=Object.entries(i[o]?.fields||{}).filter(([e,t])=>t.references&&n(t.references.model)===s)).length>0)return l}catch{}return`${a(r).toLowerCase()}s`};function d(e){switch(e){case"starts_with":return"startsWith";case"ends_with":return"endsWith";case"ne":return"not";case"not_in":return"notIn";default:return e}}let p=({action:e,model:r,where:a})=>{if(!a||!a.length)return{};let n=e=>{let a=i({model:r,field:e.field}),n=(e.mode??"sensitive")==="insensitive"&&("string"==typeof e.value||Array.isArray(e.value)&&e.value.every(e=>"string"==typeof e)),s="postgresql"===t.provider||"mongodb"===t.provider,l=n&&s?"insensitive":void 0,c=l?{mode:l}:{};if("ne"===e.operator&&null===e.value)return o({model:r,field:e.field})?.required!==!0?{[a]:{not:null}}:{};if(("in"===e.operator||"not_in"===e.operator)&&Array.isArray(e.value)){let t=e.value.filter(e=>null!=e);if(0===t.length)if("in"===e.operator)return{AND:[{[a]:{equals:"__never__"}},{[a]:{not:"__never__"}}]};else return{};return{[a]:{[d(e.operator)]:t,...c}}}return"eq"!==e.operator&&e.operator?"ne"===e.operator?{[a]:{not:{equals:e.value},...c}}:{[a]:{[d(e.operator)]:e.value,...c}}:{[a]:{equals:e.value,...c}}};if("update"===e){let e=a.filter(e=>"AND"===e.connector||!e.connector),t=a.filter(e=>"OR"===e.connector),o=e.filter(e=>"eq"===e.operator||!e.operator),s=e.filter(e=>"eq"!==e.operator&&void 0!==e.operator).map(e=>n(e)),l=t.map(e=>n(e)),c={};for(let e of o)c[i({model:r,field:e.field})]=e.value;return s.length>0&&(c.AND=s),l.length>0&&(c.OR=l),c}if("delete"===e){let e=a.find(e=>"id"===e.field);if(e){let t=i({model:r,field:"id"}),o=a.filter(e=>"id"!==e.field);if(0===o.length)return{[t]:e.value};let s=o.filter(e=>"AND"===e.connector||!e.connector),l=o.filter(e=>"OR"===e.connector),c=s.map(e=>n(e)),d=l.map(e=>n(e)),u={[t]:e.value};return c.length>0&&(u.AND=c),d.length>0&&(u.OR=d),u}}if(1===a.length){let e=a[0];if(!e)return;return n(e)}let s=a.filter(e=>"AND"===e.connector||!e.connector),l=a.filter(e=>"OR"===e.connector),c=s.map(e=>n(e)),u=l.map(e=>n(e));return{...c.length?{AND:c}:{},...u.length?{OR:u}:{}}};return{async create({model:t,modelKey:r=t,data:i,select:a}){if(!e[t])throw new u.p(`Model ${t} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`);return await e[t].create({data:i,select:l(a,r)})},async findOne({model:t,modelKey:r=t,where:i,select:a,join:o}){let n=p({model:r,where:i,action:"findOne"});if(!e[t])throw new u.p(`Model ${t} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`);let d=new Map;for(let[e,t]of Object.entries(o??{})){let i=c(r,t.modelKey??e,s);d.set(i,e)}let f=l(a,r,o),m=await e[t].findFirst({where:n,select:f});if(o&&m)for(let[e,t]of d.entries())e!==t&&e in m&&(m[t]=m[e],delete m[e]);return m},async findMany({model:t,modelKey:r=t,where:a,limit:o,select:n,offset:d,sortBy:f,join:m}){let h=p({model:r,where:a,action:"findMany"});if(!e[t])throw new u.p(`Model ${t} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`);let g=new Map;if(m)for(let[e,t]of Object.entries(m)){let i=c(r,t.modelKey??e,s);g.set(i,e)}let w=l(n,r,m),y=await e[t].findMany({where:h,take:o||100,skip:d||0,...f?.field?{orderBy:{[i({model:r,field:f.field})]:"desc"===f.direction?"desc":"asc"}}:{},select:w});if(m&&Array.isArray(y))for(let e of y)for(let[t,r]of g.entries())t!==r&&t in e&&(e[r]=e[t],delete e[t]);return y},async count({model:t,modelKey:r=t,where:i}){let a=p({model:r,where:i,action:"count"});if(!e[t])throw new u.p(`Model ${t} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`);return await e[t].count({where:a})},async update({model:r,modelKey:i=r,where:a,update:n}){if(!e[r])throw new u.p(`Model ${r} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`);if(!(a?.length&&a.some(e=>{if("OR"===e.connector||e.operator&&"eq"!==e.operator)return!1;if("insensitive"===e.mode){let r="postgresql"===t.provider||"mongodb"===t.provider,i="string"==typeof e.value||Array.isArray(e.value)&&e.value.every(e=>"string"==typeof e);if(r&&i)return!1}return"id"===e.field||o({model:i,field:e.field})?.unique===!0}))){let t=p({model:i,where:a,action:"updateMany"});return(await e[r].updateMany({where:t,data:n}))?.count?await e[r].findFirst({where:t}):null}let s=p({model:i,where:a,action:"update"});try{return await e[r].update({where:s,data:n})}catch(e){if(eb(e))return null;throw e}},async updateMany({model:t,modelKey:r=t,where:i,update:a}){if(!e[t])throw new u.p(`Model ${t} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`);let o=p({model:r,where:i,action:"updateMany"}),n=await e[t].updateMany({where:o,data:a});return n?n.count:0},async delete({model:t,modelKey:r=t,where:i}){if(!e[t])throw new u.p(`Model ${t} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`);if(!i?.some(e=>"id"===e.field)){let a=p({model:r,where:i,action:"deleteMany"});await e[t].deleteMany({where:a});return}let a=p({model:r,where:i,action:"delete"});try{await e[t].delete({where:a})}catch(e){if(eb(e))return;throw e}},async deleteMany({model:t,modelKey:r=t,where:i}){let a=p({model:r,where:i,action:"deleteMany"}),o=await e[t].deleteMany({where:a});return o?o.count:0},async consumeOne({model:t,modelKey:i=t,where:a}){if(!e[t])throw new u.p(`Model ${t} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`);if(a?.some(e=>"id"===e.field)){let r=p({model:i,where:a,action:"delete"});try{return await e[t].delete({where:r})??null}catch(e){if(eb(e))return null;throw e}}let o=p({model:i,where:a,action:"findOne"}),n=async e=>{let r=await e[t].findFirst({where:o});if(!r)return null;try{return(await e[t].deleteMany({where:p({model:i,where:[...a??[],{field:"id",value:r.id,operator:"eq",connector:"AND",mode:"sensitive"}],action:"deleteMany"})}))?.count>0?r:null}catch(e){if(eb(e))return null;throw e}};return r||"function"!=typeof e.$transaction?n(e):e.$transaction(n)},async incrementOne({model:t,modelKey:i=t,where:a,increment:o,set:n}){if(!e[t])throw new u.p(`Model ${t} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`);let s={...n??{}};for(let[e,t]of Object.entries(o))s[e]={increment:t};if(a?.some(e=>"id"===e.field)){let r=p({model:i,where:a,action:"update"});try{return await e[t].update({where:r,data:s})??null}catch(e){if(eb(e))return null;throw e}}let l=p({model:i,where:a,action:"findOne"}),c=async e=>{let r=await e[t].findFirst({where:l});if(!r)return null;try{return await e[t].update({where:p({model:i,where:[...a,{field:"id",value:r.id,operator:"eq",connector:"AND",mode:"sensitive"}],action:"update"}),data:s})??null}catch(e){if(eb(e))return null;throw e}};return r||"function"!=typeof e.$transaction?c(e):e.$transaction(c)},options:t}},a=null;a={config:{adapterId:"prisma",adapterName:"Prisma Adapter",usePlural:t.usePlural??!1,debugLogs:t.debugLogs??!1,supportsUUIDs:"postgresql"===t.provider,supportsArrays:"postgresql"===t.provider||"mongodb"===t.provider,transaction:!!t.transaction&&(t=>e.$transaction(e=>t((0,eh.f)({config:{...a.config,transaction:!1},adapter:i(e,!0)})(r))))},adapter:i(e)};let o=(0,eh.f)(a);return i=>{let a;r=i;let n=o(i),s="object"==typeof(a=e._runtimeDataModel)&&null!==a&&"models"in a?a:void 0;if(s){let e=(0,eg.t)(()=>{var e,r,a;let o;return e=s,r=i,a=t.usePlural,o=Object.fromEntries(Object.entries((0,ew.w)(r,{usePlural:a})).map(([e,t])=>[ey(e),t])),(0,ew.I)(o,Object.entries(e.models).map(([e,{fields:t}])=>({name:ey(e),columns:t.filter(e=>"object"!==e.kind).map(e=>({name:e.name,nullable:!0!==e.isRequired,hasDefault:!0===e.hasDefaultValue||!0===e.isUpdatedAt}))})))},"prisma");(0,eg.E)(n,e,{runtimeEnabled:(0,eg.S)(i)})}return n}}],931129);var eE=e.i(169774),eA=e.i(990126);async function eI(t,r){let i;if(t.database)i="function"==typeof t.database?t.database(t):await r(t);else{let r=Object.keys((0,eE.R)(t)).reduce((e,t)=>(e[t]=[],e),{}),{memoryAdapter:a}=await e.A(563921);i=a(r)(t)}return i.transaction||(eA.y.warn("Adapter does not correctly implement transaction function, patching it automatically. Please update your adapter implementation."),i.transaction=async e=>e(i)),i}async function e_(t){return eI(t,async t=>{let{createKyselyAdapter:r,kyselyAdapter:i}=await e.A(246120),{kysely:a,databaseType:o,transaction:n}=await r(t);if(!a)throw new u.p("Failed to initialize database adapter");return i(a,{type:o||"sqlite",debugLogs:!!t.database&&"debugLogs"in t.database&&t.database.debugLogs,transaction:n})(t)})}var ek=u,eT=e.i(643638),ev=e.i(146378),eU=e.i(631139),eR=e.i(367409),eS=e.i(877113);let ex={postgres:{string:["character varying","varchar","text","uuid"],number:["int4","int8","integer","bigint","smallint","numeric","real","double precision"],boolean:["bool","boolean"],date:["timestamptz","timestamp","date"],json:["json","jsonb"]},mysql:{string:["varchar","text","uuid"],number:["integer","int","bigint","smallint","decimal","float","double"],boolean:["boolean","tinyint"],date:["timestamp","datetime","date"],json:["json"]},sqlite:{string:["TEXT"],number:["INTEGER","REAL","BIGINT"],boolean:["INTEGER","BOOLEAN"],date:["DATE","INTEGER"],json:["TEXT"]},mssql:{string:["varchar","nvarchar","uniqueidentifier"],number:["int","bigint","smallint","decimal","float","double"],boolean:["bit","smallint"],date:["datetime2","date","datetime"],json:["varchar","nvarchar"]}};function eO(e,t){return`${(0,eR.d)(e)}\0${(0,eR.d)(t)}`}function eD(e,t){return`${e}\0${t}`}function eN(e,t){return e.unique===(t.unique??!1)&&e.validFullColumns&&e.columns.length===t.columns.length&&e.columns.every((e,r)=>e===t.columns[r])}function eL(e){return"boolean"==typeof e?e:"number"==typeof e?0!==e:"1"===e||e?.toLowerCase()==="true"||"t"===e}function eP(e){return new Map(e.map(e=>{let t=[...e.columns].sort((e,t)=>e.position-t.position);return[eO(e.table,e.name),{columns:t.flatMap(e=>null===e.name?[]:[e.name]),name:e.name,table:e.table,unique:e.unique,validFullColumns:e.valid&&!e.partial&&t.length>0&&t.every(e=>null!==e.name&&e.fullLength)}]}))}async function eC(e,t,r,i){let a;if(i)return eP(await i(r));switch(t.type){case"sqlite":a=(await eS.f`
|
|
2
2
|
SELECT
|
|
3
3
|
tables.name AS "tableName",
|
|
4
4
|
index_list.name AS "indexName",
|
|
@@ -10,7 +10,7 @@ module.exports=[363004,931129,950551,342e3,729522,100762,661372,374091,339507,20
|
|
|
10
10
|
INNER JOIN pragma_index_list(tables.name) AS index_list
|
|
11
11
|
INNER JOIN pragma_index_info(index_list.name) AS index_info
|
|
12
12
|
WHERE tables.type = 'table'
|
|
13
|
-
`.execute(e)).rows;break;case"postgres":a=(await
|
|
13
|
+
`.execute(e)).rows;break;case"postgres":a=(await eS.f`
|
|
14
14
|
SELECT
|
|
15
15
|
table_class.relname AS "tableName",
|
|
16
16
|
index_class.relname AS "indexName",
|
|
@@ -35,7 +35,7 @@ module.exports=[363004,931129,950551,342e3,729522,100762,661372,374091,339507,20
|
|
|
35
35
|
WHERE table_namespace.nspname = ${t.schema}
|
|
36
36
|
AND table_class.relkind = 'r'
|
|
37
37
|
AND index_column.ordinality <= index_data.indnkeyatts
|
|
38
|
-
`.execute(e)).rows;break;case"mysql":a=(await
|
|
38
|
+
`.execute(e)).rows;break;case"mysql":a=(await eS.f`
|
|
39
39
|
SELECT
|
|
40
40
|
table_name AS tableName,
|
|
41
41
|
index_name AS indexName,
|
|
@@ -46,7 +46,7 @@ module.exports=[363004,931129,950551,342e3,729522,100762,661372,374091,339507,20
|
|
|
46
46
|
COALESCE(LOWER(comment) = 'disabled', FALSE) AS isDisabled
|
|
47
47
|
FROM information_schema.statistics
|
|
48
48
|
WHERE table_schema = DATABASE()
|
|
49
|
-
`.execute(e)).rows;break;case"mssql":a=(await
|
|
49
|
+
`.execute(e)).rows;break;case"mssql":a=(await eS.f`
|
|
50
50
|
SELECT
|
|
51
51
|
tables.name AS "tableName",
|
|
52
52
|
indexes.name AS "indexName",
|
|
@@ -70,14 +70,14 @@ module.exports=[363004,931129,950551,342e3,729522,100762,661372,374091,339507,20
|
|
|
70
70
|
WHERE table_schemas.name = ${t.schema}
|
|
71
71
|
AND indexes.name IS NOT NULL
|
|
72
72
|
AND index_columns.key_ordinal > 0
|
|
73
|
-
`.execute(e)).rows}let o=new Map;for(let e of a){let t=e.tableName??e.table_name??e.TABLE_NAME??e.tablename??e.tbl_name,r=e.indexName??e.index_name??e.INDEX_NAME??e.name,i=e.columnName??e.column_name??e.COLUMN_NAME;if(!t||!r)continue;let a=eO(t,r),n=e.nonUnique??e.non_unique??e.NON_UNIQUE,s=void 0===n?eL(e.isUnique??e.is_unique):!eL(n),l=Number(e.columnPosition??e.column_position??e.keyOrdinal??e.key_ordinal??e.ordinality??e.seqInIndex??e.seq_in_index??e.SEQ_IN_INDEX??e.seqno??0),c={fullLength:null!=i&&(void 0===e.prefixLength||null===e.prefixLength),name:i??null,position:l},d=eL(e.isPartial),u=!eL(e.isDisabled)&&!eL(e.isHypothetical)&&(void 0===e.isValid||eL(e.isValid)),p=o.get(a);o.set(a,p?{...p,columns:[...p.columns,c],partial:p.partial||d,valid:p.valid&&u}:{columns:[c],name:r,partial:d,table:t,unique:s,valid:u})}return eP([...o.values()])}async function eq(e,t){let r;switch(t.type){case"postgres":case"sqlite":return new Map;case"mysql":r=(await
|
|
73
|
+
`.execute(e)).rows}let o=new Map;for(let e of a){let t=e.tableName??e.table_name??e.TABLE_NAME??e.tablename??e.tbl_name,r=e.indexName??e.index_name??e.INDEX_NAME??e.name,i=e.columnName??e.column_name??e.COLUMN_NAME;if(!t||!r)continue;let a=eO(t,r),n=e.nonUnique??e.non_unique??e.NON_UNIQUE,s=void 0===n?eL(e.isUnique??e.is_unique):!eL(n),l=Number(e.columnPosition??e.column_position??e.keyOrdinal??e.key_ordinal??e.ordinality??e.seqInIndex??e.seq_in_index??e.SEQ_IN_INDEX??e.seqno??0),c={fullLength:null!=i&&(void 0===e.prefixLength||null===e.prefixLength),name:i??null,position:l},d=eL(e.isPartial),u=!eL(e.isDisabled)&&!eL(e.isHypothetical)&&(void 0===e.isValid||eL(e.isValid)),p=o.get(a);o.set(a,p?{...p,columns:[...p.columns,c],partial:p.partial||d,valid:p.valid&&u}:{columns:[c],name:r,partial:d,table:t,unique:s,valid:u})}return eP([...o.values()])}async function eq(e,t){let r;switch(t.type){case"postgres":case"sqlite":return new Map;case"mysql":r=(await eS.f`
|
|
74
74
|
SELECT
|
|
75
75
|
table_name AS tableName,
|
|
76
76
|
column_name AS columnName,
|
|
77
77
|
character_octet_length AS maxIndexBytes
|
|
78
78
|
FROM information_schema.columns
|
|
79
79
|
WHERE table_schema = DATABASE()
|
|
80
|
-
`.execute(e)).rows;break;case"mssql":r=(await
|
|
80
|
+
`.execute(e)).rows;break;case"mssql":r=(await eS.f`
|
|
81
81
|
SELECT
|
|
82
82
|
tables.name AS "tableName",
|
|
83
83
|
columns.name AS "columnName",
|
|
@@ -88,10 +88,10 @@ module.exports=[363004,931129,950551,342e3,729522,100762,661372,374091,339507,20
|
|
|
88
88
|
INNER JOIN sys.schemas AS table_schemas
|
|
89
89
|
ON table_schemas.schema_id = tables.schema_id
|
|
90
90
|
WHERE table_schemas.name = ${t.schema}
|
|
91
|
-
`.execute(e)).rows}let i=new Map;for(let e of r){let t=e.tableName??e.TABLE_NAME,r=e.columnName??e.COLUMN_NAME;if(!t||!r)continue;let a=Number(e.maxIndexBytes??e.MAX_INDEX_BYTES??-1);i.set(eD(t,r),{maxIndexBytes:a<0?null:a})}return i}var ej=class extends ek.p{};async function e$(e,t,r){let i=e.selectFrom(r).select(ex.f`1`.as("present"));return(await ("mssql"===t?i.top(1):i.limit(1)).execute()).length>0}async function eB(e,{throwOnUnsafe:t=!0}={}){let r,{schema:i,tables:a,referenceKeys:o}=function(e){let{indexesByTable:t,tables:r}=(0,eE.j)(e),i=new Map,a={};for(let e in r){let t=r[e],o=t.fields,n={};if(Object.entries(o).forEach(([e,t])=>{let a=t.references,o=a?r[a.model]:void 0,s=a&&o?{...t,references:{...a,model:o.modelName}}:t;n[t.fieldName||e]=s,a&&i.set(s,{modelKey:a.model,fieldKey:a.field})}),a[t.modelName]){a[t.modelName].fields={...a[t.modelName].fields,...n},t.disableMigrations&&(a[t.modelName].disableMigrations=!0);continue}a[t.modelName]={fields:n,order:t.order||1/0,disableMigrations:t.disableMigrations}}for(let[e,r]of t)a[e]&&(a[e].indexes=r);return{schema:a,tables:r,referenceKeys:i}}(e),n=(0,eA.J)(e.logger),s=[],l=e=>{if(t)throw new ej(e);s.push(e)},{kysely:c,databaseType:d,introspectIndexes:u,schemaName:p}=await (0,eT.createKyselyAdapter)(e);d||(n.warn("Could not determine database type, defaulting to sqlite. Please provide a type in the database options to avoid this."),d="sqlite"),c||(n.error("Only kysely adapter is supported for migrations. You can use `generate` command to generate the schema, if you're using a different adapter."),process.exit(1));let f=await c.introspection.getTables(),m=f;switch(d){case"postgres":{let e=p??await (0,eT.getPostgresSchema)(c);r={type:"postgres",schema:e},n.debug(`PostgreSQL migration: Using schema '${e}' (${p?"from database.schemaName":"from search_path"})`);try{(await c.introspection.getSchemas()).some(({name:t})=>t===e)||(p?n.debug(`Schema '${e}' does not exist yet. The migration creates it before creating tables.`):n.warn(`Schema '${e}' does not exist. Create it before running migrations or check your database configuration.`))}catch(e){n.debug(`Could not verify schema existence: ${e instanceof Error?e.message:String(e)}`)}m=f.filter(t=>t.schema===e&&!t.isView&&!("isForeign"in t&&t.isForeign)),n.debug(`Found ${m.length} table(s) in schema '${e}': ${m.map(e=>e.name).join(", ")||"(none)"}`);break}case"mssql":{let e=await (0,eT.getMssqlSchema)(c);r={type:"mssql",schema:e},n.debug(`SQL Server migration: Using schema '${e}' (from the current user's default schema)`),m=f.filter(t=>t.schema===e);break}case"mysql":r={type:"mysql"};break;case"sqlite":r={type:"sqlite"}}let h=await eC(c,r,f.map(e=>e.name),u),g=await eq(c,r),w=(0,ew.I)((0,eT.toPhysicalSchema)(c,i),(0,eT.toIntrospectedTables)(m)).filter(e=>"unexpected-required-column"===e.kind).map(e=>(0,ew.u)(e,"database")),y=[],b=[],E=[],A=new Map;for(let[e,t]of Object.entries(i)){if(t.disableMigrations)continue;let r=m.find(t=>t.name===e);for(let i of t.indexes??[]){let a=i.name,o=eO(e,a),n=h.get(o);if(n){if(!eN(n,i))throw new ek.p(`Database index "${a}" on table "${e}" does not match the configured fields and uniqueness. Rename or replace the existing index, then run the migration again.`);continue}if("sqlite"===d||"postgres"===d){let t=[...h.values()].find(t=>(0,eR.d)(t.name)===(0,eR.d)(a)&&(0,eR.d)(t.table)!==(0,eR.d)(e));if(t)throw new ek.p(`Database index name "${a}" is already used by table "${t.table}". Index names must be unique across the schema.`)}let s=A.get(o);if(s){if(!eN({columns:s.columns,name:s.name,table:e,unique:s.unique??!1,validFullColumns:!0},i))throw new ek.p(`Database index name "${a}" identifies more than one index on table "${e}".`);continue}r&&("mysql"===d||"mssql"===d)&&function({columnBounds:e,dbType:t,existingColumns:r,fields:i,indexes:a,index:o,table:n}){let s="mysql"===t?3072:1700,l=0;for(let s of o.columns){let c=i[s];if(c)if("string"===c.type||Array.isArray(c.type)){if(!r.has(s)){l+=((0,eR.e)({columnName:s,dialect:t,fields:i,indexes:a})??0)*("mysql"===t?4:1);continue}let c=e.get(eD(n,s));if(!c?.maxIndexBytes)throw new ek.p(`Cannot create database index "${o.name}" on existing table "${n}" because column "${s}" is not bounded for ${"mysql"===t?"MySQL":"SQL Server"}. Change it to a bounded string column, resolve oversized values, then run the migration again.`);l+=c.maxIndexBytes}else l+=16}if(l>s)throw new ek.p(`Cannot create database index "${o.name}" on existing table "${n}" because its columns can exceed ${"mysql"===t?"MySQL":"SQL Server"}'s ${s}-byte index-key limit. Bound the indexed string columns to the generated schema lengths, resolve oversized values, then run the migration again.`)}({columnBounds:g,dbType:d,existingColumns:new Set(r.columns.map(e=>e.name)),fields:t.fields,index:i,indexes:t.indexes??[],table:e}),A.set(o,i),E.push({table:e,index:i,name:a})}if(!r){let r=y.findIndex(t=>t.table===e),i={table:e,fields:t.fields,order:t.order||1/0},a=y.findIndex(e=>(e.order||1/0)>i.order);-1===a?-1===r?y.push(i):y[r].fields={...y[r].fields,...t.fields}:y.splice(a,0,i);continue}let i={};for(let[a,o]of Object.entries(t.fields)){let t=r.columns.find(e=>e.name===a);if(!t){i[a]=o;continue}!1!==o.required&&t.isNullable&&n.warn(`Column "${a}" on table "${e}" stays nullable while the schema declares the field required, so existing rows can still hold null. Backfill every row for this column and enforce NOT NULL to remove the drift.`),!function(e,t,r){if("string[]"===t||"number[]"===t)return e.toLowerCase().includes("json");let i=eS[r];return(Array.isArray(t)?i.string.map(e=>e.toLowerCase()):i[t].map(e=>e.toLowerCase())).includes(e.toLowerCase().split("(")[0].trim())}(t.dataType,o.type,d)&&n.warn(`Field ${a} in table ${e} has a different type in the database. Expected ${o.type} but got ${t.dataType}.`)}Object.keys(i).length>0&&b.push({table:e,fields:i,order:t.order||1/0})}let I=[];p&&y.length>0&&I.push(c.schema.createSchema(p).ifNotExists());let _=e.advanced?.database?.generateId==="uuid",k=e.advanced?.database?.generateId==="serial";function T(e,t,r){let i=e.type,a=d||"sqlite",o={string:{sqlite:"text",postgres:"text",mysql:r?`varchar(${r})`:e.unique?"varchar(255)":e.references?"varchar(36)":e.sortable||e.index?"varchar(255)":"text",mssql:r?`varchar(${r})`:e.unique||e.sortable?"varchar(255)":e.references?"varchar(36)":"varchar(8000)"},boolean:{sqlite:"integer",postgres:"boolean",mysql:"boolean",mssql:"smallint"},number:{sqlite:e.bigint?"bigint":"integer",postgres:e.bigint?"bigint":"integer",mysql:e.bigint?"bigint":"integer",mssql:e.bigint?"bigint":"integer"},date:{sqlite:"date",postgres:"timestamptz",mysql:"timestamp(3)",mssql:ex.f`datetime2(3)`},json:{sqlite:"text",postgres:"jsonb",mysql:"json",mssql:"varchar(8000)"},id:{postgres:k?ex.f`integer GENERATED BY DEFAULT AS IDENTITY`:_?"uuid":"text",mysql:k?"integer":"varchar(36)",mssql:k?"integer":"varchar(36)",sqlite:k?"integer":"text"},foreignKeyId:{postgres:k?"integer":_?"uuid":"text",mysql:k?"integer":"varchar(36)",mssql:k?"integer":"varchar(36)",sqlite:k?"integer":"text"},"string[]":{sqlite:"text",postgres:"jsonb",mysql:"json",mssql:"varchar(8000)"},"number[]":{sqlite:"text",postgres:"jsonb",mysql:"json",mssql:"varchar(8000)"}};if("id"===t||e.references?.field==="id")return"id"===t?o.id[a]:o.foreignKeyId[a];if(Array.isArray(i))return"text";if(!(i in o))throw Error(`Unsupported field type '${String(i)}' for field '${t}'. Allowed types are: string, number, boolean, date, string[], number[]. If you need to store structured data, store it as a JSON string (type: "string") or split it into primitive fields. See https://better-auth.com/docs/advanced/schema#additional-fields`);return o[i][a]}let v=(0,eU.f)({schema:a,usePlural:!1}),U=(0,ev.f)({schema:a,usePlural:!1});function R(e){let t=e.references;if(!t)throw new ek.p("Cannot resolve a field without references.");let r=o.get(e);if(!r)throw new ek.p(`Missing migration reference metadata for "${t.model}.${t.field}".`);try{return`${v(r.modelKey)}.${U({model:r.modelKey,field:r.fieldKey})}`}catch{return`${t.model}.${t.field}`}}let x=[],S=(e,t)=>{if("mysql"!==d&&"mssql"!==d)return;let r=i[e];if(r)return(0,eR.e)({columnName:t,dialect:d,fields:r.fields,indexes:r.indexes??[]})};if(b.length){let e=new Map;for(let t of b)for(let[r,i]of Object.entries(t.fields)){var O;let a=(O=d,"date"===i.type&&"function"==typeof i.defaultValue&&("postgres"===O||"mysql"===O||"mssql"===O)),o=!(i.unique&&!1===i.required)&&("string"===i.type||"number"===i.type||"boolean"===i.type)&&void 0!==i.defaultValue&&null!==i.defaultValue&&"function"!=typeof i.defaultValue;if(!1!==i.required&&!a&&!o){let a=e.get(t.table);if(void 0===a&&(a=await e$(c,d,t.table),e.set(t.table,a)),a){let e="string"===i.type?" For a text column, every existing row ends up with the same empty string.":"";l(`Cannot add required column "${r}" to populated table "${t.table}": the schema declares no default value, so existing rows have no value to backfill. MySQL accepts this statement instead of rejecting it and fills every existing row with an implicit default for the column type, reporting a successful migration over corrupted data.${e} Add the column as nullable, backfill a correct value for every row, then make it NOT NULL.`)}}let s=T(i,r,S(t.table,r)),u=c.schema.alterTable(t.table);if(i.index||i.unique){let e=(0,eR.j)(t.table,r,i.unique??!1),a=c.schema.createIndex(e).on(t.table).columns([r]);i.unique&&(a=a.unique(),!1===i.required&&"mssql"===d&&(a=a.where(r,"is not",null)),!1!==i.required&&void 0!==i.defaultValue&&null!==i.defaultValue&&"function"!=typeof i.defaultValue&&n.warn(`Adding unique column "${r}" to existing table "${t.table}" backfills every existing row with its default value. If the table has more than one row, creating the unique index "${e}" will fail; backfill distinct values manually, then re-run the migration or create the index yourself.`)),x.push(a)}let p=u.addColumn(r,s,e=>(e=!1!==i.required?e.notNull():e,i.references&&(e=e.references(R(i)).onDelete(i.references.onDelete||"cascade")),a?e="mysql"===d?e.defaultTo(ex.f`CURRENT_TIMESTAMP(3)`):e.defaultTo(ex.f`CURRENT_TIMESTAMP`):o&&(e=e.defaultTo("boolean"==typeof i.defaultValue&&("sqlite"===d||"mssql"===d)?+!!i.defaultValue:i.defaultValue)),e));I.push(p)}}if(y.length)for(let e of y){let t=T({type:k?"number":"string"},"id"),r=c.schema.createTable(e.table).addColumn("id",t,e=>{if(k)return"postgres"===d?e.primaryKey().notNull():"sqlite"===d?e.primaryKey().notNull():"mssql"===d?e.identity().primaryKey().notNull():e.autoIncrement().primaryKey().notNull();return _&&"postgres"===d?e.primaryKey().defaultTo(ex.f`pg_catalog.gen_random_uuid()`).notNull():e.primaryKey().notNull()});for(let[t,i]of Object.entries(e.fields)){let a=T(i,t,S(e.table,t));if(r=r.addColumn(t,a,e=>(e=!1!==i.required?e.notNull():e,i.references&&(e=e.references(R(i)).onDelete(i.references.onDelete||"cascade")),i.unique&&(e=e.unique()),"date"===i.type&&"function"==typeof i.defaultValue&&("postgres"===d||"mysql"===d||"mssql"===d)&&(e="mysql"===d?e.defaultTo(ex.f`CURRENT_TIMESTAMP(3)`):e.defaultTo(ex.f`CURRENT_TIMESTAMP`)),e)),i.index&&!i.unique){let r=c.schema.createIndex((0,eR.j)(e.table,t,!1)).on(e.table).columns([t]);x.push(r)}}I.push(r)}for(let{table:e,index:t,name:r}of E){let i=c.schema.createIndex(r).on(e).columns([...t.columns]);t.unique&&(i=i.unique()),x.push(i)}for(let e of x)I.push(e);return{toBeCreated:y,toBeAdded:b,toBeAddedIndexes:E,unsafeChanges:s,schemaProblems:w,runMigrations:async function(){try{for(let e of I)await e.execute()}finally{I.length&&e.database&&(0,eg.P)(e.database)}},compileMigrations:async function(){return I.map(e=>e.compile().sql).join(";\n\n")+";"}}}var eV=e.i(796481),eM=e.i(76411);let eF=/[\u0000-\u001f\u007f-\u009f]/,eK="https://better-auth.invalid",ez=/%2[fF]|%5[cC]/,eH=/^(?=.*\d)[\d*?.]+$/,eW=/^\d{1,3}(?:\.\d{1,3}){3}$/,eY=(e,t)=>{let r=e.split(":")[0];return!eH.test(r)||eW.test(t.split(":")[0])},eQ=(e,t=!1)=>{if(eF.test(e))return null;let r=e.indexOf(":");if(r<=0)return null;let i=e.slice(0,r).toLowerCase(),a=e.slice(r+1),o="";if(a.startsWith("//")){let e=(a=a.slice(2)).search(t?/[/#]/:/[/?#]/);-1===e?(o=a,a=""):(o=a.slice(0,e),a=a.slice(e))}let n=a.search(t?/#/:/[?#]/),s=(e=>{let t=e;try{t=decodeURIComponent(e)}catch{}let r=[];for(let e of t.split("/"))".."===e?r.pop():"."!==e&&""!==e&&r.push(e);return r.length>0?`/${r.join("/")}`:""})(-1===n?a:a.slice(0,n));return{scheme:i,authority:o.toLowerCase(),path:s}},eG=(e,t,r)=>{if(e.startsWith("/"))return r?.allowRelativePaths===!0&&(e=>{if(!e.startsWith("/")||e.startsWith("//")||e.includes("\\")||eF.test(e))return!1;let t=e.search(/[?#]/),r=-1===t?e:e.slice(0,t);if(ez.test(r))return!1;try{return new URL(e,eK).origin===eK}catch{return!1}})(e);let i=t.includes("*")||t.includes("?");if(i&&!t.includes("://")){let r=(0,eV.$)(e);return!!r&&(0,eM.f)(t)(r)&&eY(t,r)}let a=(0,eV.Y)(e);if("http:"===a||"https:"===a||!a){if(!i)return t===(0,eV.H)(e);let r=(0,eV.H)(e);return null!==r&&!!(0,eM.f)(t)(r)&&eY(t.slice(t.indexOf("://")+3),r.slice(r.indexOf("://")+3))}let o=eQ(e),n=eQ(t,i);return!!o&&!!n&&o.scheme===n.scheme&&(i?!o.authority.includes("@")&&(!n.authority||!!((0,eM.f)(n.authority)(o.authority)&&eY(n.authority,o.authority)))&&(!n.path||(0,eM.f)(n.path)(o.path||"/")):(!n.authority||o.authority===n.authority)&&(!n.path||o.path===n.path||o.path.startsWith(`${n.path}/`)))};var eJ=e.i(67850),eZ=e.i(776660),eX=e.i(549611),e0=e.i(370728),e1=e.i(542158);function e2(e){if(!e?.method)throw new u.E("FORBIDDEN",{code:"validation_source_missing",message:"User validation source is required"});if("oauth"===e.method&&!e.oauth?.providerId)throw new u.E("FORBIDDEN",{code:"validation_source_missing",message:"OAuth user validation source requires oauth.providerId"});if(("sso-oidc"===e.method||"sso-saml"===e.method)&&!e.sso?.providerId)throw new u.E("FORBIDDEN",{code:"validation_source_missing",message:"SSO user validation source requires sso.providerId"})}async function e3(e,t){let r,i=e.context.options.user?.validateUserInfo;if(i){e2(t.source);try{r=await i(t,e)}catch(t){throw e.context.logger.error("validateUserInfo callback threw",t),new u.E("FORBIDDEN",{code:"validation_failed",message:"User validation failed"})}if(r?.error)throw new u.E("FORBIDDEN",{code:r.error,message:r.errorDescription||r.error})}}let e6=async e=>{let t=await (0,d.f)("SHA-256").digest(new TextEncoder().encode(e));return c.W.encode(new Uint8Array(t),{padding:!1})};async function e5(e,t){return t&&"plain"!==t?"hashed"===t?e6(e):"object"==typeof t&&"hash"in t?t.hash(e):e:e}function e4(e,t){if(t){if("object"==typeof t&&"default"in t){if(t.overrides){for(let[r,i]of Object.entries(t.overrides))if(e.startsWith(r))return i}return t.default}return t}}var e7=e.i(173436),e8=e.i(497515),e9=e.i(713082),te=e.i(133931),tt=e.i(24891);function tr(e,t=Date.now()){return Math.max(Math.floor((("number"==typeof e?e:e.getTime())-t)/1e3),0)}let ti=(e,t)=>{let r,i,a=t.logger,o=t.options,n=o.secondaryStorage,s=new Map,c=o.session?.expiresIn||604800,p=!!n&&o.session?.storeSessionInDatabase===!0&&o.session?.preserveSessionInDatabase!==!0,{createWithHooks:f,updateWithHooks:m,updateManyWithHooks:h,deleteWithHooks:g,deleteManyWithHooks:E,consumeOneWithHooks:A}=(r=(0,te.f)(t.options),i=t.hooks,{createWithHooks:async function(t,a,o){let n=(0,e8.G)(),s=t;for(let{source:e,hooks:t}of i){let i=t[a]?.create?.before;if(i){let t=await r(`db create.before ${a}`,{[e9.A]:"create.before",[e9.d]:a,[e9.s]:e},()=>i(s,n));if(!1===t)return null;"object"==typeof t&&"data"in t&&(s={...s,...t.data})}}let l=null;for(let{source:t,hooks:c}of((!o||o.executeMainFn)&&(l=await (await (0,e7.g)(e)).create({model:a,data:s,forceAllowId:!0})),o?.fn&&(l=await o.fn(l??s)),i)){let e=c[a]?.create?.after;e&&await (0,e7.A)(async()=>{await r(`db create.after ${a}`,{[e9.A]:"create.after",[e9.d]:a,[e9.s]:t},()=>e(l,n))})}return l},updateWithHooks:async function(t,a,o,n){let s=(0,e8.G)(),l=t;for(let{source:e,hooks:a}of i){let i=a[o]?.update?.before;if(i){let a=await r(`db update.before ${o}`,{[e9.A]:"update.before",[e9.d]:o,[e9.s]:e},()=>i(t,s));if(!1===a)return null;"object"==typeof a&&"data"in a&&(l={...l,...a.data})}}let c=n?await n.fn(l):null,d=!n||n.executeMainFn?await (await (0,e7.g)(e)).update({model:o,update:l,where:a}):c;for(let{source:e,hooks:t}of i){let i=t[o]?.update?.after;i&&await (0,e7.A)(async()=>{await r(`db update.after ${o}`,{[e9.A]:"update.after",[e9.d]:o,[e9.s]:e},()=>i(d,s))})}return d},updateManyWithHooks:async function(t,a,o,n){let s=(0,e8.G)(),l=t;for(let{source:e,hooks:a}of i){let i=a[o]?.update?.before;if(i){let a=await r(`db updateMany.before ${o}`,{[e9.A]:"updateMany.before",[e9.d]:o,[e9.s]:e},()=>i(t,s));if(!1===a)return null;"object"==typeof a&&"data"in a&&(l={...l,...a.data})}}let c=n?await n.fn(l):null,d=!n||n.executeMainFn?await (await (0,e7.g)(e)).updateMany({model:o,update:l,where:a}):c;for(let{source:e,hooks:t}of i){let i=t[o]?.update?.after;i&&await (0,e7.A)(async()=>{await r(`db updateMany.after ${o}`,{[e9.A]:"updateMany.after",[e9.d]:o,[e9.s]:e},()=>i(d,s))})}return d},deleteWithHooks:async function(t,a,o){let n=(0,e8.G)(),s=null;try{s=(await (await (0,e7.g)(e)).findMany({model:a,where:t,limit:1}))[0]||null}catch{}if(s)for(let{source:e,hooks:t}of i){let i=t[a]?.delete?.before;if(i&&await r(`db delete.before ${a}`,{[e9.A]:"delete.before",[e9.d]:a,[e9.s]:e},()=>i(s,n))===!1)return null}let l=o?await o.fn(t):null,c=(!o||o.executeMainFn)&&s?await (await (0,e7.g)(e)).delete({model:a,where:t}):l;if(s)for(let{source:e,hooks:t}of i){let i=t[a]?.delete?.after;i&&await (0,e7.A)(async()=>{await r(`db delete.after ${a}`,{[e9.A]:"delete.after",[e9.d]:a,[e9.s]:e},()=>i(s,n))})}return c},deleteManyWithHooks:async function(t,a,o){let n=(0,e8.G)(),s=[];try{s=await (await (0,e7.g)(e)).findMany({model:a,where:t})}catch{}for(let e of s)for(let{source:t,hooks:o}of i){let i=o[a]?.delete?.before;if(i&&await r(`db delete.before ${a}`,{[e9.A]:"delete.before",[e9.d]:a,[e9.s]:t},()=>i(e,n))===!1)return null}let l=o?await o.fn(t):null,c=!o||o.executeMainFn?await (await (0,e7.g)(e)).deleteMany({model:a,where:t}):l;for(let e of s)for(let{source:t,hooks:o}of i){let i=o[a]?.delete?.after;i&&await (0,e7.A)(async()=>{await r(`db delete.after ${a}`,{[e9.A]:"delete.after",[e9.d]:a,[e9.s]:t},()=>i(e,n))})}return c},consumeOneWithHooks:async function(t,a,o,n){let s=(0,e8.G)(),l=i.flatMap(({source:e,hooks:r})=>{let i=r[t]?.delete?.before;return i?[{source:e,fn:i}]:[]}),c=n??null;if(l.length){if(!c)try{c=(await (await (0,e7.g)(e)).findMany({model:t,where:a,limit:1}))[0]||null}catch{}if(c){for(let{source:e,fn:i}of l)if(await r(`db delete.before ${t}`,{[e9.A]:"delete.before",[e9.d]:t,[e9.s]:e},()=>i(c,s))===!1)return null}}let d=await o();if(!d)return null;for(let{source:e,hooks:a}of i){let i=a[t]?.delete?.after;i&&await (0,e7.A)(async()=>{await r(`db delete.after ${t}`,{[e9.A]:"delete.after",[e9.d]:t,[e9.s]:e},()=>i(d,s))})}return d}}),I=t=>{let r=[...t,{field:"expiresAt",value:new Date,operator:"gt"}];return E(r,"session",{fn:async()=>{await (await (0,e7.g)(e)).updateMany({model:"session",where:r,update:{expiresAt:new Date}})},executeMainFn:!1})};async function _(e){if(!n)return;let t=await n.get(`active-sessions-${e.id}`);if(!t)return;let r=Date.now(),i=((0,b.f)(t)||[]).filter(e=>e.expiresAt>r);await Promise.all(i.map(async({token:t})=>{let i=await n.get(t);if(!i)return;let a=(0,b.f)(i);if(!a)return;let o=tr(a.session.expiresAt,r);await n.set(t,JSON.stringify({session:a.session,user:e}),Math.floor(o))}))}async function k(e){if(!n)return[];let t=await n.get(`active-sessions-${e}`);return t&&(0,b.f)(t)||[]}let T=e=>`revoked-sessions-before-${e}`,v=Math.max(c,86400,Number(o.plugins?.find(e=>"admin"===e.id)?.options?.impersonationSessionDuration)||0);async function U(e,t){if(!n)return!1;let r=t?.get(e.userId)??Number(await n.get(T(e.userId)));return t?.set(e.userId,r),new Date(e.createdAt).getTime()<r}async function R(e,t,r){if(!n)return;let i=Number(await n.get(T(e)));await n.set(T(e),String(Math.max(r,i||0)),v);let a=new Set(t.map(e=>e.token));for(let{token:e}of t)await n.delete(e);let o=`active-sessions-${e}`,s=await k(e),l=Date.now(),c=s.filter(e=>e.expiresAt>l&&!a.has(e.token));c.sort((e,t)=>e.expiresAt-t.expiresAt);let d=c.at(-1)?.expiresAt;d?await n.set(o,JSON.stringify(c),tr(d,l)):await n.delete(o)}async function x(e,t){if(!n)return;let r=t??await k(e),i=Date.now();await (0,e7.A)(()=>R(e,r,i),{onError(e){a.error("Failed to delete committed user sessions from secondary storage",e)}})}async function S(e,t){let r,i=s.get(e)??Promise.resolve(),a=new Promise(e=>{r=e}),o=i.catch(()=>{}).then(()=>a);s.set(e,o),await i.catch(()=>{});try{return await t()}finally{r(),s.get(e)===o&&s.delete(e)}}return{createOAuthUser:async(t,r)=>(0,e7.n)(e,async()=>{let e=await f({createdAt:new Date,updatedAt:new Date,...t,email:t.email?.toLowerCase()},"user",void 0);if(!e)throw new u.E("BAD_REQUEST",{message:"Failed to create user"});return{user:e,account:await f({...r,userId:e.id,createdAt:new Date,updatedAt:new Date},"account",void 0)}}),createUser:async(e,t)=>{let r={createdAt:new Date,updatedAt:new Date,...e,email:e.email?.toLowerCase()};if(o.user?.validateUserInfo){let e,i={...t,action:"create-user"};e2(i);try{e=(0,e8.g)()}catch(e){throw a.error("Unable to run validateUserInfo: missing endpoint context",e),new u.E("FORBIDDEN",{code:"validation_context_missing",message:"User validation requires an endpoint context"})}await e3(e,{user:r,source:i})}return await f(r,"user",void 0)},createAccount:async e=>await f({createdAt:new Date,updatedAt:new Date,...e},"account",void 0),listSessions:async(r,i)=>{if(p)return(await (await (0,e7.g)(e)).findMany({model:"session",where:[{field:"userId",value:r},{field:"expiresAt",value:new Date,operator:"gt"}]})).map(e=>(0,w.Q)(t.options,e));if(n){let e=await n.get(`active-sessions-${r}`);if(!e)return[];let i=(0,b.f)(e)||[],a=Date.now(),o=new Set,s=[],l=new Map;for(let{token:e,expiresAt:r}of i){if(r<=a||o.has(e))continue;o.add(e);let i=await n.get(e);if(i)try{let e="string"==typeof i?JSON.parse(i):i;if(!e?.session||await U(e.session,l))continue;s.push((0,w.Q)(t.options,{...e.session,expiresAt:new Date(e.session.expiresAt)}))}catch{continue}}return s}return await (await (0,e7.g)(e)).findMany({model:"session",where:[{field:"userId",value:r},...i?.onlyActiveSessions?[{field:"expiresAt",value:new Date,operator:"gt"}]:[]]})},listUsers:async(t,r,i,a)=>await (await (0,e7.g)(e)).findMany({model:"user",limit:t,offset:r,sortBy:i,where:a}),countTotalUsers:async t=>{let r=await (await (0,e7.g)(e)).count({model:"user",where:t});return"string"==typeof r?parseInt(r):r},deleteUser:async e=>{let t=await k(e);(!n||o.session?.storeSessionInDatabase)&&await E([{field:"userId",value:e}],"session",void 0),await E([{field:"userId",value:e}],"account",void 0),await g([{field:"id",value:e}],"user",void 0)!==null&&await x(e,t)},createSession:async(r,i,s,d,u)=>{let m,h=await (async()=>{let e=(0,e8.G)();return e?.headers||e?.request?.headers})(),g=o.session?.storeSessionInDatabase,E=u?.deferSecondaryStorageWrites===!0&&p,{id:A,...I}=s||{};if(n&&!g){let e=t.generateId({model:"session"});m=!1!==e?e:(0,y.f)()}let _=(0,w.P)(o),k={...m?{id:m}:{},ipAddress:h&&(0,l.M)(h,o)||"",userAgent:h?.get("user-agent")||"",...I,expiresAt:i?(0,e1.f)(86400,"sec"):(0,e1.f)(c,"sec"),userId:r,token:(0,y.f)(32),createdAt:new Date,updatedAt:new Date,..._,...d?I:{}},T=async t=>{if(!n)return t;let i=await n.get(`active-sessions-${r}`),a=[],o=Date.now();i&&(a=(a=(0,b.f)(i)||[]).filter(e=>e.expiresAt>o&&e.token!==k.token));let s=[...a,{token:k.token,expiresAt:k.expiresAt.getTime()}].sort((e,t)=>e.expiresAt-t.expiresAt),l=tr(s.at(-1)?.expiresAt??k.expiresAt.getTime(),o);l>0&&await n.set(`active-sessions-${r}`,JSON.stringify(s),l);let c=await (await (0,e7.g)(e)).findOne({model:"user",where:[{field:"id",value:r}]}),d=tr(k.expiresAt,o);return d>0&&await n.set(k.token,JSON.stringify({session:{...t,createdAt:k.createdAt},user:c}),d),t};return await f(k,"session",n?{fn:async e=>E?(await (0,e7.A)(async()=>{await T(e)},{onError(e){a.error("Failed to mirror committed session to secondary storage",e)}}),e):T(e),executeMainFn:g}:void 0)},findSession:async r=>{if(n){let e=await n.get(r);if(!e&&(!o.session?.storeSessionInDatabase||t.options.session?.preserveSessionInDatabase))return null;if(e){let r=(0,b.f)(e);return!r||await U(r.session)?null:{session:(0,w.Q)(t.options,{...r.session,expiresAt:new Date(r.session.expiresAt),createdAt:new Date(r.session.createdAt),updatedAt:new Date(r.session.updatedAt)}),user:(0,w.$)(t.options,{...r.user,createdAt:new Date(r.user.createdAt),updatedAt:new Date(r.user.updatedAt)})}}}let i=await (await (0,e7.g)(e)).findOne({model:"session",where:[{value:r,field:"token"}],join:{user:!0}});if(!i)return null;let{user:a,...s}=i;return a?{session:(0,w.Q)(t.options,s),user:(0,w.$)(t.options,a)}:null},findSessions:async(t,r)=>{let i=[...new Set(t)],a=new Map,o=[],s=new Map;if(n)for(let e of i){let t=await n.get(e);if(t)try{let i="string"==typeof t?JSON.parse(t):t;if(!i||await U(i.session,s))continue;let o=new Date(i.session.expiresAt);if(r?.onlyActiveSessions&&o<=new Date)continue;let n={session:{...i.session,expiresAt:new Date(i.session.expiresAt)},user:{...i.user,createdAt:new Date(i.user.createdAt),updatedAt:new Date(i.user.updatedAt)}};a.set(e,n)}catch{continue}else o.push(e)}let l=n?o:i;if(l.length>0&&(!n||p))for(let{user:t,...i}of(await (await (0,e7.g)(e)).findMany({model:"session",limit:l.length,where:[{field:"token",value:l,operator:"in"},...r?.onlyActiveSessions?[{field:"expiresAt",value:new Date,operator:"gt"}]:[]],join:{user:!0}})))t&&a.set(i.token,{session:i,user:t});return i.flatMap(e=>{let t=a.get(e);return t?[t]:[]})},updateSession:async(e,r)=>await m(r,[{field:"token",value:e}],"session",n?{async fn(r){let i=await n.get(e);if(!i)return null;let a=(0,b.f)(i);if(!a)return null;let o={...a.session,...r,expiresAt:new Date(r.expiresAt??a.session.expiresAt),createdAt:new Date(a.session.createdAt),updatedAt:new Date(r.updatedAt??a.session.updatedAt)},s=(0,w.Q)(t.options,o),l=Date.now(),c=new Date(s.expiresAt).getTime(),d=tr(c,l);if(d>0){await n.set(e,JSON.stringify({session:s,user:a.user}),d);let t=`active-sessions-${s.userId}`,r=await n.get(t),i=(r&&(0,b.f)(r)||[]).filter(t=>t.token!==e&&t.expiresAt>l).concat([{token:e,expiresAt:c}]).sort((e,t)=>e.expiresAt-t.expiresAt),o=i.at(-1)?.expiresAt;o&&o>l?await n.set(t,JSON.stringify(i),tr(o,l)):await n.delete(t)}return s},executeMainFn:o.session?.storeSessionInDatabase}:void 0),deleteSession:async e=>{if(n){let r=await n.get(e);if(r){let{session:t}=(0,b.f)(r)??{};if(!t)return void a.error("Session not found in secondary storage");let i=t.userId,o=await n.get(`active-sessions-${i}`);if(o){let t=(0,b.f)(o)||[],r=Date.now(),a=t.filter(t=>t.expiresAt>r&&t.token!==e),s=a.sort((e,t)=>e.expiresAt-t.expiresAt).at(-1)?.expiresAt;a.length>0&&s&&s>Date.now()?await n.set(`active-sessions-${i}`,JSON.stringify(a),tr(s,r)):await n.delete(`active-sessions-${i}`)}else a.error("Active sessions list not found in secondary storage")}if(await n.delete(e),!o.session?.storeSessionInDatabase)return;if(t.options.session?.preserveSessionInDatabase)return void await I([{field:"token",value:e}])}await g([{field:"token",value:e}],"session",void 0)},deleteAccounts:async e=>{await E([{field:"userId",value:e}],"account",void 0)},deleteAccount:async e=>{await g([{field:"id",value:e}],"account",void 0)},deleteUserSessions:async e=>{let r=await k(e);if(n){if(!o.session?.storeSessionInDatabase)return void await x(e,r);if(t.options.session?.preserveSessionInDatabase){await I([{field:"userId",value:e}])!==null&&await x(e,r);return}}await E([{field:"userId",value:e}],"session",void 0)!==null&&await x(e,r)},deleteSessions:async e=>{if(n){if(await Promise.all(e.map(e=>n.delete(e))),!o.session?.storeSessionInDatabase)return;if(t.options.session?.preserveSessionInDatabase)return void await I([{field:"token",value:e,operator:"in"}])}await E([{field:"token",value:e,operator:"in"}],"session",void 0)},findAccountOwnerByKey:async({providerId:t,accountId:r})=>{let i=await (await (0,e7.g)(e)).findMany({model:"account",where:[{field:"providerId",value:t},{field:"accountId",value:r}],limit:2,join:{user:!0}});if(i.length>1)throw new u.p(`Multiple accounts match the same accountId for provider ${JSON.stringify(t)}. Resolve duplicate account identities before continuing.`);let a=i[0];if(!a)return null;let{user:o,...n}=a;return o?{kind:"owned",user:o,account:n}:{kind:"orphaned",account:n}},findUserByEmail:async(t,r)=>{let i=await (await (0,e7.g)(e)).findOne({model:"user",where:[{value:t.toLowerCase(),field:"email"}],join:{...r?.includeAccounts?{account:!0}:{}}});if(!i)return null;let a=e=>e.normalize("NFC").toLowerCase();if(a(i.email)!==a(t))return null;let{account:o,...n}=i;return{user:n,accounts:o??[]}},findUserById:async t=>t?await (await (0,e7.g)(e)).findOne({model:"user",where:[{field:"id",value:t}]}):null,linkAccount:async e=>await f({createdAt:new Date,updatedAt:new Date,...e},"account",void 0),updateUser:async(e,t)=>{let r=await m({...t,...t.email?{email:t.email.toLowerCase()}:{}},[{field:"id",value:e}],"user",void 0);return await (0,e7.A)(()=>_(r),{onError(e){a.error("Failed to refresh committed user sessions in secondary storage",e)}}),r},updateUserByEmail:async(e,t)=>{let r=await m({...t,...t.email?{email:t.email.toLowerCase()}:{}},[{field:"email",value:e.toLowerCase()}],"user",void 0);return await (0,e7.A)(()=>_(r),{onError(e){a.error("Failed to refresh committed user sessions in secondary storage",e)}}),r},updatePassword:async(e,t)=>{await h({password:t},[{field:"userId",value:e},{field:"providerId",value:"credential"},{field:"accountId",value:e}],"account",void 0)},findAccounts:async t=>await (await (0,e7.g)(e)).findMany({model:"account",where:[{field:"userId",value:t}]}),findCredentialAccount:async t=>(await (0,e7.g)(e)).findOne({model:"account",where:[{field:"userId",value:t},{field:"providerId",value:"credential"},{field:"accountId",value:t}]}),findAccountByKey:async({providerId:t,accountId:r})=>{let i=await (await (0,e7.g)(e)).findMany({model:"account",limit:2,where:[{field:"providerId",value:t},{field:"accountId",value:r}]});if(i.length>1)throw new u.p(`Multiple accounts match the same accountId for provider ${JSON.stringify(t)}. Resolve duplicate account identities before continuing.`);return i[0]??null},findAccountByUserId:async t=>await (await (0,e7.g)(e)).findMany({model:"account",where:[{field:"userId",value:t}]}),updateAccount:async(e,t)=>await m(t,[{field:"id",value:e}],"account",void 0),createVerificationValue:async e=>{let t=e4(e.identifier,o.verification?.storeIdentifier),r=await e5(e.identifier,t);return await f({createdAt:new Date,updatedAt:new Date,...e,identifier:r},"verification",n?{async fn(e){let t=tr(e.expiresAt);return t>0&&await n.set(`verification:${r}`,JSON.stringify(e),t),e},executeMainFn:o.verification?.storeInDatabase}:void 0)},findVerificationValue:async t=>{let r=e4(t,o.verification?.storeIdentifier),i=await e5(t,r);if(n){let e=await n.get(`verification:${i}`);if(e){let t=(0,b.f)(e);if(t)return t}if(r&&"plain"!==r){let e=await n.get(`verification:${t}`);if(e){let t=(0,b.f)(e);if(t)return t}}if(!o.verification?.storeInDatabase)return null}let a=await (0,e7.g)(e);async function s(e){return a.findMany({model:"verification",where:[{field:"identifier",value:e}],sortBy:{field:"createdAt",direction:"desc"},limit:1})}let l=await s(i);return!l.length&&r&&"plain"!==r&&(l=await s(t)),o.verification?.disableCleanup||await E([{field:"expiresAt",value:new Date,operator:"lt"}],"verification",void 0),l[0]||null},deleteVerificationByIdentifier:async e=>{let t=e4(e,o.verification?.storeIdentifier),r=await e5(e,t);n&&await n.delete(`verification:${r}`),(!n||o.verification?.storeInDatabase)&&await g([{field:"identifier",value:r}],"verification",void 0)},consumeVerificationValue:async t=>{let r=e4(t,o.verification?.storeIdentifier),i=await e5(t,r),a=r&&"plain"!==r?[i,t]:[i],s=null;if(n&&!o.verification?.storeInDatabase){let e=async e=>(e=>{if(!e)return null;let t="string"==typeof e?(0,b.f)(e):"object"==typeof e?e:null;if(!t)return null;let r=new Date(t.expiresAt);return Number.isFinite(r.getTime())?{...t,expiresAt:r}:null})(await n.getAndDelete(e));for(let t of a){let r=await e(`verification:${t}`);if(r){await Promise.all(a.filter(e=>e!==t).map(e=>n.delete(`verification:${e}`))),s=r;break}}}else{let t=async t=>S(`verification:${t}`,()=>(0,e7.n)(e,async()=>{let r=await (0,e7.g)(e),i=[{field:"identifier",value:t}],a=(await r.findMany({model:"verification",where:i,sortBy:{field:"createdAt",direction:"desc"},limit:1}))[0]??null;return a?A("verification",[{field:"id",value:a.id}],async()=>{let e=await r.consumeOne({model:"verification",where:[{field:"id",value:a.id}]});return e?(await r.deleteMany({model:"verification",where:i}),e):null},a):null}));for(let e of a)if(s=await t(e))break;s&&n&&await Promise.all(a.map(e=>n.delete(`verification:${e}`)))}return!s||s.expiresAt<new Date?null:s},reserveVerificationValue:async t=>{let r=(0,tt.$)(new Uint8Array(await (0,d.f)("SHA-256").digest(new TextEncoder().encode("reserve:"+t.identifier))),o),i=e4(t.identifier,o.verification?.storeIdentifier),a=await e5(t.identifier,i);if(n&&!o.verification?.storeInDatabase)throw new u.p("reserveVerificationValue requires database-backed verification storage. Set verification.storeInDatabase to true for flows that reserve verification values.");try{await e.create({model:"verification",data:{id:r,identifier:a,value:t.value,expiresAt:t.expiresAt,createdAt:new Date,updatedAt:new Date},forceAllowId:!0})}catch(t){if(await e.findOne({model:"verification",where:[{field:"id",value:r}]}))return!1;throw t}if(n){let e=tr(t.expiresAt);e>0&&await n.set(`verification:${a}`,JSON.stringify({id:r,identifier:a,value:t.value,expiresAt:t.expiresAt}),e)}return!0},updateVerificationByIdentifier:async(e,t)=>{let r=e4(e,o.verification?.storeIdentifier),i=await e5(e,r);if(n){let e=await n.get(`verification:${i}`);if(e){let r=(0,b.f)(e);if(r){let e={...r,...t},a=e.expiresAt??r.expiresAt,s=tr(a instanceof Date?a:new Date(a));if(s>0&&await n.set(`verification:${i}`,JSON.stringify(e),s),!o.verification?.storeInDatabase)return e}}}return!n||o.verification?.storeInDatabase?await m(t,[{field:"identifier",value:i}],"verification",void 0):t},refreshUserSessions:_}};var ta=e.i(147391),to=e.i(129776),tn=e.i(783968);async function ts(e){let t=e.options,r=t.plugins||[],i=[],a=[];for(let o of r)if(o.init){let r,n=o.init(e);if("object"==typeof(r=(0,eZ.f)(n)?await n:n)){if(r.options){let{databaseHooks:e,trustedOrigins:n,...s}=r.options;e&&a.push({source:`plugin:${o.id}`,hooks:e}),n&&i.push(n),t=(0,to.e)(t,s)}r.context&&Object.assign(e,r.context)}}if(i.length>0){let e=[...t.trustedOrigins?[t.trustedOrigins]:[],...i],r=e.filter(Array.isArray).flat(),a=e.filter(e=>"function"==typeof e);a.length>0?t.trustedOrigins=async e=>[...r,...(await Promise.all(a.map(t=>t(e)))).flat()].filter(e=>"string"==typeof e&&""!==e):t.trustedOrigins=r}t.databaseHooks&&a.push({source:"user",hooks:t.databaseHooks}),e.internalAdapter=ti(e.adapter,{options:t,logger:e.logger,hooks:a,generateId:e.generateId}),e.options=t}async function tl(e,t){let r=[];if((0,eV._)(e.baseURL)){let t=e.baseURL.allowedHosts,i=e.baseURL.protocol;for(let e of t)e.includes("://")?r.push(e):(i&&"https"!==i&&"auto"!==i||r.push(`https://${e}`),("http"===i||"auto"===i||(0,tn.g)(e))&&r.push(`http://${e}`));if(e.baseURL.fallback)try{r.push(new URL(e.baseURL.fallback).origin)}catch{}}else{let i=(0,eV.X)("string"==typeof e.baseURL?e.baseURL:void 0,e.basePath,t);i&&r.push(new URL(i).origin)}if(e.trustedOrigins&&(Array.isArray(e.trustedOrigins)&&r.push(...e.trustedOrigins),"function"==typeof e.trustedOrigins)){let i=await e.trustedOrigins(t);r.push(...i)}let i=ta.$.BETTER_AUTH_TRUSTED_ORIGINS;return i&&r.push(...i.split(",")),r.filter(e=>!!e)}function tc(e){return e.advanced?.trustedProxyHeaders??!1}async function td(e,t,r){let i,a=e.options.baseURL,o=e.options.basePath||"/api/auth",n=(0,eV.A)(a,o,t,void 0,r);if(!n)throw new u.p("Could not resolve base URL from request. Check your allowedHosts config.");let s=Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e));s.baseURL=n,s.options={...e.options,baseURL:(0,eV.H)(n)||void 0};let l={...s.options,baseURL:a};return i="function"==typeof e.options.trustedOrigins||"function"==typeof e.options.account?.accountLinking?.trustedProviders?(0,eV.T)(t)?t:t?new Request(n,{headers:t}):void 0:void 0,s.trustedOrigins=await tl(l,i),s.trustedProviders=await tp(s.options,i),e.options.advanced?.crossSubDomainCookies?.enabled&&(s.authCookies=(0,e0.e)(s.options),s.createAuthCookie=(0,e0.g)(s.options)),s}async function tu(e,t){if(e)for(let r of e){let e="function"==typeof r?await r():r;if(e[t.field??"id"]===t.value)return e}}async function tp(e,t){let r=e.account?.accountLinking?.trustedProviders;return r?Array.isArray(r)?r.filter(e=>!!e):(await r(t)??[]).filter(e=>!!e):[]}var tf=e.i(910228);function tm(e,t){if(t.length<e.context.password.config.minPasswordLength)throw e.context.logger.warn("Password is too short"),u.E.from("BAD_REQUEST",tf.f.PASSWORD_TOO_SHORT)}function th(e,t){if(t.length>e.context.password.config.maxPasswordLength)throw e.context.logger.warn("Password is too long"),u.E.from("BAD_REQUEST",tf.f.PASSWORD_TOO_LONG)}async function tg(e,t,r,i){await (0,e7.n)(e.context.adapter,async()=>{(await i?.(),e.context.options.emailAndPassword?.revokeSessionsOnPasswordReset&&await e.context.internalAdapter.deleteUserSessions(t),await e.context.internalAdapter.findCredentialAccount(t))?await e.context.internalAdapter.updatePassword(t,r):await e.context.internalAdapter.createAccount({userId:t,providerId:"credential",accountId:t,password:r})})}async function tw(e,t){th(e,t.password);let r=await e.context.internalAdapter.findCredentialAccount(t.userId),i=r?.password;return!!r&&!!i&&await e.context.password.verify({hash:i,password:t.password})}async function ty(e,t){let r=t.body.password;"string"==typeof r&&th(t,r);let i=await t.context.internalAdapter.findCredentialAccount(e),a=i?.password;if(!i||!a||!r)throw r&&await t.context.password.hash(r),u.E.from("BAD_REQUEST",tf.f.INVALID_PASSWORD);if(!await t.context.password.verify({hash:a,password:r}))throw u.E.from("BAD_REQUEST",tf.f.INVALID_PASSWORD);return!0}e.s(["a",0,th,"b",0,tm,"B",0,ty,"J",0,tg,"c",0,tw],950551);var tb=e.i(786198),tE=e.i(155036);function tA(e){return!0===e.context.skipOriginCheck&&e.context.options.advanced?.disableCSRFCheck===void 0}function tI(e){let t=e.context.skipOriginCheck;if(!0===t)return!0;if(Array.isArray(t)&&e.request)try{let r=new URL(e.context.baseURL).pathname,i=(0,tE.s)(e.request.url,r);return t.some(e=>{let t=e.replace(/\/+$/,"");return i===t||i.startsWith(`${t}/`)})}catch{}return!1}let t_=(n=function(){},a=!1,function(...e){return a||(((void 0)??console.warn)("[Deprecation] disableOriginCheck: true currently also disables CSRF checks. In a future version, disableOriginCheck will ONLY disable URL validation. To keep CSRF disabled, add disableCSRFCheck: true to your config."),a=!0),n.apply(this,e)}),tk=(0,s.a)(async e=>{if(e.request?.method==="GET"||e.request?.method==="OPTIONS"||e.request?.method==="HEAD"||!e.request||(await tv(e),tI(e)))return;let{body:t,query:r}=e,i=t?.callbackURL||r?.callbackURL,a=t?.redirectTo,o=t?.errorCallbackURL,n=t?.newUserCallbackURL,s=(t,r)=>{if(t){if("string"!=typeof t)throw u.E.fromStatus("BAD_REQUEST",{message:`Invalid ${r}: expected a string`});if(!e.context.isTrustedOrigin(t,{allowRelativePaths:"origin"!==r})){if(e.context.logger.error(`Invalid ${r}: ${t}`),e.context.logger.info(`If it's a valid URL, please add ${t} to trustedOrigins in your auth config
|
|
91
|
+
`.execute(e)).rows}let i=new Map;for(let e of r){let t=e.tableName??e.TABLE_NAME,r=e.columnName??e.COLUMN_NAME;if(!t||!r)continue;let a=Number(e.maxIndexBytes??e.MAX_INDEX_BYTES??-1);i.set(eD(t,r),{maxIndexBytes:a<0?null:a})}return i}var ej=class extends ek.p{};async function e$(e,t,r){let i=e.selectFrom(r).select(eS.f`1`.as("present"));return(await ("mssql"===t?i.top(1):i.limit(1)).execute()).length>0}async function eB(e,{throwOnUnsafe:t=!0}={}){let r,{schema:i,tables:a,referenceKeys:o}=function(e){let{indexesByTable:t,tables:r}=(0,eE.j)(e),i=new Map,a={};for(let e in r){let t=r[e],o=t.fields,n={};if(Object.entries(o).forEach(([e,t])=>{let a=t.references,o=a?r[a.model]:void 0,s=a&&o?{...t,references:{...a,model:o.modelName}}:t;n[t.fieldName||e]=s,a&&i.set(s,{modelKey:a.model,fieldKey:a.field})}),a[t.modelName]){a[t.modelName].fields={...a[t.modelName].fields,...n},t.disableMigrations&&(a[t.modelName].disableMigrations=!0);continue}a[t.modelName]={fields:n,order:t.order||1/0,disableMigrations:t.disableMigrations}}for(let[e,r]of t)a[e]&&(a[e].indexes=r);return{schema:a,tables:r,referenceKeys:i}}(e),n=(0,eA.J)(e.logger),s=[],l=e=>{if(t)throw new ej(e);s.push(e)},{kysely:c,databaseType:d,introspectIndexes:u,schemaName:p}=await (0,eT.createKyselyAdapter)(e);d||(n.warn("Could not determine database type, defaulting to sqlite. Please provide a type in the database options to avoid this."),d="sqlite"),c||(n.error("Only kysely adapter is supported for migrations. You can use `generate` command to generate the schema, if you're using a different adapter."),process.exit(1));let f=await c.introspection.getTables(),m=f;switch(d){case"postgres":{let e=p??await (0,eT.getPostgresSchema)(c);r={type:"postgres",schema:e},n.debug(`PostgreSQL migration: Using schema '${e}' (${p?"from database.schemaName":"from search_path"})`);try{(await c.introspection.getSchemas()).some(({name:t})=>t===e)||(p?n.debug(`Schema '${e}' does not exist yet. The migration creates it before creating tables.`):n.warn(`Schema '${e}' does not exist. Create it before running migrations or check your database configuration.`))}catch(e){n.debug(`Could not verify schema existence: ${e instanceof Error?e.message:String(e)}`)}m=f.filter(t=>t.schema===e&&!t.isView&&!("isForeign"in t&&t.isForeign)),n.debug(`Found ${m.length} table(s) in schema '${e}': ${m.map(e=>e.name).join(", ")||"(none)"}`);break}case"mssql":{let e=await (0,eT.getMssqlSchema)(c);r={type:"mssql",schema:e},n.debug(`SQL Server migration: Using schema '${e}' (from the current user's default schema)`),m=f.filter(t=>t.schema===e);break}case"mysql":r={type:"mysql"};break;case"sqlite":r={type:"sqlite"}}let h=await eC(c,r,f.map(e=>e.name),u),g=await eq(c,r),w=(0,ew.I)((0,eT.toPhysicalSchema)(c,i),(0,eT.toIntrospectedTables)(m)).filter(e=>"unexpected-required-column"===e.kind).map(e=>(0,ew.u)(e,"database")),y=[],b=[],E=[],A=new Map;for(let[e,t]of Object.entries(i)){if(t.disableMigrations)continue;let r=m.find(t=>t.name===e);for(let i of t.indexes??[]){let a=i.name,o=eO(e,a),n=h.get(o);if(n){if(!eN(n,i))throw new ek.p(`Database index "${a}" on table "${e}" does not match the configured fields and uniqueness. Rename or replace the existing index, then run the migration again.`);continue}if("sqlite"===d||"postgres"===d){let t=[...h.values()].find(t=>(0,eR.d)(t.name)===(0,eR.d)(a)&&(0,eR.d)(t.table)!==(0,eR.d)(e));if(t)throw new ek.p(`Database index name "${a}" is already used by table "${t.table}". Index names must be unique across the schema.`)}let s=A.get(o);if(s){if(!eN({columns:s.columns,name:s.name,table:e,unique:s.unique??!1,validFullColumns:!0},i))throw new ek.p(`Database index name "${a}" identifies more than one index on table "${e}".`);continue}r&&("mysql"===d||"mssql"===d)&&function({columnBounds:e,dbType:t,existingColumns:r,fields:i,indexes:a,index:o,table:n}){let s="mysql"===t?3072:1700,l=0;for(let s of o.columns){let c=i[s];if(c)if("string"===c.type||Array.isArray(c.type)){if(!r.has(s)){l+=((0,eR.e)({columnName:s,dialect:t,fields:i,indexes:a})??0)*("mysql"===t?4:1);continue}let c=e.get(eD(n,s));if(!c?.maxIndexBytes)throw new ek.p(`Cannot create database index "${o.name}" on existing table "${n}" because column "${s}" is not bounded for ${"mysql"===t?"MySQL":"SQL Server"}. Change it to a bounded string column, resolve oversized values, then run the migration again.`);l+=c.maxIndexBytes}else l+=16}if(l>s)throw new ek.p(`Cannot create database index "${o.name}" on existing table "${n}" because its columns can exceed ${"mysql"===t?"MySQL":"SQL Server"}'s ${s}-byte index-key limit. Bound the indexed string columns to the generated schema lengths, resolve oversized values, then run the migration again.`)}({columnBounds:g,dbType:d,existingColumns:new Set(r.columns.map(e=>e.name)),fields:t.fields,index:i,indexes:t.indexes??[],table:e}),A.set(o,i),E.push({table:e,index:i,name:a})}if(!r){let r=y.findIndex(t=>t.table===e),i={table:e,fields:t.fields,order:t.order||1/0},a=y.findIndex(e=>(e.order||1/0)>i.order);-1===a?-1===r?y.push(i):y[r].fields={...y[r].fields,...t.fields}:y.splice(a,0,i);continue}let i={};for(let[a,o]of Object.entries(t.fields)){let t=r.columns.find(e=>e.name===a);if(!t){i[a]=o;continue}!1!==o.required&&t.isNullable&&n.warn(`Column "${a}" on table "${e}" stays nullable while the schema declares the field required, so existing rows can still hold null. Backfill every row for this column and enforce NOT NULL to remove the drift.`),!function(e,t,r){if("string[]"===t||"number[]"===t)return e.toLowerCase().includes("json");let i=ex[r];return(Array.isArray(t)?i.string.map(e=>e.toLowerCase()):i[t].map(e=>e.toLowerCase())).includes(e.toLowerCase().split("(")[0].trim())}(t.dataType,o.type,d)&&n.warn(`Field ${a} in table ${e} has a different type in the database. Expected ${o.type} but got ${t.dataType}.`)}Object.keys(i).length>0&&b.push({table:e,fields:i,order:t.order||1/0})}let I=[];p&&y.length>0&&I.push(c.schema.createSchema(p).ifNotExists());let _=e.advanced?.database?.generateId==="uuid",k=e.advanced?.database?.generateId==="serial";function T(e,t,r){let i=e.type,a=d||"sqlite",o={string:{sqlite:"text",postgres:"text",mysql:r?`varchar(${r})`:e.unique?"varchar(255)":e.references?"varchar(36)":e.sortable||e.index?"varchar(255)":"text",mssql:r?`varchar(${r})`:e.unique||e.sortable?"varchar(255)":e.references?"varchar(36)":"varchar(8000)"},boolean:{sqlite:"integer",postgres:"boolean",mysql:"boolean",mssql:"smallint"},number:{sqlite:e.bigint?"bigint":"integer",postgres:e.bigint?"bigint":"integer",mysql:e.bigint?"bigint":"integer",mssql:e.bigint?"bigint":"integer"},date:{sqlite:"date",postgres:"timestamptz",mysql:"timestamp(3)",mssql:eS.f`datetime2(3)`},json:{sqlite:"text",postgres:"jsonb",mysql:"json",mssql:"varchar(8000)"},id:{postgres:k?eS.f`integer GENERATED BY DEFAULT AS IDENTITY`:_?"uuid":"text",mysql:k?"integer":"varchar(36)",mssql:k?"integer":"varchar(36)",sqlite:k?"integer":"text"},foreignKeyId:{postgres:k?"integer":_?"uuid":"text",mysql:k?"integer":"varchar(36)",mssql:k?"integer":"varchar(36)",sqlite:k?"integer":"text"},"string[]":{sqlite:"text",postgres:"jsonb",mysql:"json",mssql:"varchar(8000)"},"number[]":{sqlite:"text",postgres:"jsonb",mysql:"json",mssql:"varchar(8000)"}};if("id"===t||e.references?.field==="id")return"id"===t?o.id[a]:o.foreignKeyId[a];if(Array.isArray(i))return"text";if(!(i in o))throw Error(`Unsupported field type '${String(i)}' for field '${t}'. Allowed types are: string, number, boolean, date, string[], number[]. If you need to store structured data, store it as a JSON string (type: "string") or split it into primitive fields. See https://better-auth.com/docs/advanced/schema#additional-fields`);return o[i][a]}let v=(0,eU.f)({schema:a,usePlural:!1}),U=(0,ev.f)({schema:a,usePlural:!1});function R(e){let t=e.references;if(!t)throw new ek.p("Cannot resolve a field without references.");let r=o.get(e);if(!r)throw new ek.p(`Missing migration reference metadata for "${t.model}.${t.field}".`);try{return`${v(r.modelKey)}.${U({model:r.modelKey,field:r.fieldKey})}`}catch{return`${t.model}.${t.field}`}}let S=[],x=(e,t)=>{if("mysql"!==d&&"mssql"!==d)return;let r=i[e];if(r)return(0,eR.e)({columnName:t,dialect:d,fields:r.fields,indexes:r.indexes??[]})};if(b.length){let e=new Map;for(let t of b)for(let[r,i]of Object.entries(t.fields)){var O;let a=(O=d,"date"===i.type&&"function"==typeof i.defaultValue&&("postgres"===O||"mysql"===O||"mssql"===O)),o=!(i.unique&&!1===i.required)&&("string"===i.type||"number"===i.type||"boolean"===i.type)&&void 0!==i.defaultValue&&null!==i.defaultValue&&"function"!=typeof i.defaultValue;if(!1!==i.required&&!a&&!o){let a=e.get(t.table);if(void 0===a&&(a=await e$(c,d,t.table),e.set(t.table,a)),a){let e="string"===i.type?" For a text column, every existing row ends up with the same empty string.":"";l(`Cannot add required column "${r}" to populated table "${t.table}": the schema declares no default value, so existing rows have no value to backfill. MySQL accepts this statement instead of rejecting it and fills every existing row with an implicit default for the column type, reporting a successful migration over corrupted data.${e} Add the column as nullable, backfill a correct value for every row, then make it NOT NULL.`)}}let s=T(i,r,x(t.table,r)),u=c.schema.alterTable(t.table);if(i.index||i.unique){let e=(0,eR.j)(t.table,r,i.unique??!1),a=c.schema.createIndex(e).on(t.table).columns([r]);i.unique&&(a=a.unique(),!1===i.required&&"mssql"===d&&(a=a.where(r,"is not",null)),!1!==i.required&&void 0!==i.defaultValue&&null!==i.defaultValue&&"function"!=typeof i.defaultValue&&n.warn(`Adding unique column "${r}" to existing table "${t.table}" backfills every existing row with its default value. If the table has more than one row, creating the unique index "${e}" will fail; backfill distinct values manually, then re-run the migration or create the index yourself.`)),S.push(a)}let p=u.addColumn(r,s,e=>(e=!1!==i.required?e.notNull():e,i.references&&(e=e.references(R(i)).onDelete(i.references.onDelete||"cascade")),a?e="mysql"===d?e.defaultTo(eS.f`CURRENT_TIMESTAMP(3)`):e.defaultTo(eS.f`CURRENT_TIMESTAMP`):o&&(e=e.defaultTo("boolean"==typeof i.defaultValue&&("sqlite"===d||"mssql"===d)?+!!i.defaultValue:i.defaultValue)),e));I.push(p)}}if(y.length)for(let e of y){let t=T({type:k?"number":"string"},"id"),r=c.schema.createTable(e.table).addColumn("id",t,e=>{if(k)return"postgres"===d?e.primaryKey().notNull():"sqlite"===d?e.primaryKey().notNull():"mssql"===d?e.identity().primaryKey().notNull():e.autoIncrement().primaryKey().notNull();return _&&"postgres"===d?e.primaryKey().defaultTo(eS.f`pg_catalog.gen_random_uuid()`).notNull():e.primaryKey().notNull()});for(let[t,i]of Object.entries(e.fields)){let a=T(i,t,x(e.table,t));if(r=r.addColumn(t,a,e=>(e=!1!==i.required?e.notNull():e,i.references&&(e=e.references(R(i)).onDelete(i.references.onDelete||"cascade")),i.unique&&(e=e.unique()),"date"===i.type&&"function"==typeof i.defaultValue&&("postgres"===d||"mysql"===d||"mssql"===d)&&(e="mysql"===d?e.defaultTo(eS.f`CURRENT_TIMESTAMP(3)`):e.defaultTo(eS.f`CURRENT_TIMESTAMP`)),e)),i.index&&!i.unique){let r=c.schema.createIndex((0,eR.j)(e.table,t,!1)).on(e.table).columns([t]);S.push(r)}}I.push(r)}for(let{table:e,index:t,name:r}of E){let i=c.schema.createIndex(r).on(e).columns([...t.columns]);t.unique&&(i=i.unique()),S.push(i)}for(let e of S)I.push(e);return{toBeCreated:y,toBeAdded:b,toBeAddedIndexes:E,unsafeChanges:s,schemaProblems:w,runMigrations:async function(){try{for(let e of I)await e.execute()}finally{I.length&&e.database&&(0,eg.P)(e.database)}},compileMigrations:async function(){return I.map(e=>e.compile().sql).join(";\n\n")+";"}}}var eV=e.i(796481),eM=e.i(76411);let eF=/[\u0000-\u001f\u007f-\u009f]/,eK="https://better-auth.invalid",ez=/%2[fF]|%5[cC]/,eH=/^(?=.*\d)[\d*?.]+$/,eW=/^\d{1,3}(?:\.\d{1,3}){3}$/,eY=(e,t)=>{let r=e.split(":")[0];return!eH.test(r)||eW.test(t.split(":")[0])},eQ=(e,t=!1)=>{if(eF.test(e))return null;let r=e.indexOf(":");if(r<=0)return null;let i=e.slice(0,r).toLowerCase(),a=e.slice(r+1),o="";if(a.startsWith("//")){let e=(a=a.slice(2)).search(t?/[/#]/:/[/?#]/);-1===e?(o=a,a=""):(o=a.slice(0,e),a=a.slice(e))}let n=a.search(t?/#/:/[?#]/),s=(e=>{let t=e;try{t=decodeURIComponent(e)}catch{}let r=[];for(let e of t.split("/"))".."===e?r.pop():"."!==e&&""!==e&&r.push(e);return r.length>0?`/${r.join("/")}`:""})(-1===n?a:a.slice(0,n));return{scheme:i,authority:o.toLowerCase(),path:s}},eG=(e,t,r)=>{if(e.startsWith("/"))return r?.allowRelativePaths===!0&&(e=>{if(!e.startsWith("/")||e.startsWith("//")||e.includes("\\")||eF.test(e))return!1;let t=e.search(/[?#]/),r=-1===t?e:e.slice(0,t);if(ez.test(r))return!1;try{return new URL(e,eK).origin===eK}catch{return!1}})(e);let i=t.includes("*")||t.includes("?");if(i&&!t.includes("://")){let r=(0,eV.$)(e);return!!r&&(0,eM.f)(t)(r)&&eY(t,r)}let a=(0,eV.Y)(e);if("http:"===a||"https:"===a||!a){if(!i)return t===(0,eV.H)(e);let r=(0,eV.H)(e);return null!==r&&!!(0,eM.f)(t)(r)&&eY(t.slice(t.indexOf("://")+3),r.slice(r.indexOf("://")+3))}let o=eQ(e),n=eQ(t,i);return!!o&&!!n&&o.scheme===n.scheme&&(i?!o.authority.includes("@")&&(!n.authority||!!((0,eM.f)(n.authority)(o.authority)&&eY(n.authority,o.authority)))&&(!n.path||(0,eM.f)(n.path)(o.path||"/")):(!n.authority||o.authority===n.authority)&&(!n.path||o.path===n.path||o.path.startsWith(`${n.path}/`)))};var eJ=e.i(67850),eZ=e.i(776660),eX=e.i(549611),e0=e.i(370728),e1=e.i(542158);function e2(e){if(!e?.method)throw new u.E("FORBIDDEN",{code:"validation_source_missing",message:"User validation source is required"});if("oauth"===e.method&&!e.oauth?.providerId)throw new u.E("FORBIDDEN",{code:"validation_source_missing",message:"OAuth user validation source requires oauth.providerId"});if(("sso-oidc"===e.method||"sso-saml"===e.method)&&!e.sso?.providerId)throw new u.E("FORBIDDEN",{code:"validation_source_missing",message:"SSO user validation source requires sso.providerId"})}async function e3(e,t){let r,i=e.context.options.user?.validateUserInfo;if(i){e2(t.source);try{r=await i(t,e)}catch(t){throw e.context.logger.error("validateUserInfo callback threw",t),new u.E("FORBIDDEN",{code:"validation_failed",message:"User validation failed"})}if(r?.error)throw new u.E("FORBIDDEN",{code:r.error,message:r.errorDescription||r.error})}}let e6=async e=>{let t=await (0,d.f)("SHA-256").digest(new TextEncoder().encode(e));return c.W.encode(new Uint8Array(t),{padding:!1})};async function e5(e,t){return t&&"plain"!==t?"hashed"===t?e6(e):"object"==typeof t&&"hash"in t?t.hash(e):e:e}function e4(e,t){if(t){if("object"==typeof t&&"default"in t){if(t.overrides){for(let[r,i]of Object.entries(t.overrides))if(e.startsWith(r))return i}return t.default}return t}}var e7=e.i(173436),e8=e.i(497515),e9=e.i(713082),te=e.i(133931),tt=e.i(24891);function tr(e,t=Date.now()){return Math.max(Math.floor((("number"==typeof e?e:e.getTime())-t)/1e3),0)}let ti=(e,t)=>{let r,i,a=t.logger,o=t.options,n=o.secondaryStorage,s=new Map,c=o.session?.expiresIn||604800,p=!!n&&o.session?.storeSessionInDatabase===!0&&o.session?.preserveSessionInDatabase!==!0,{createWithHooks:f,updateWithHooks:m,updateManyWithHooks:h,deleteWithHooks:g,deleteManyWithHooks:E,consumeOneWithHooks:A}=(r=(0,te.f)(t.options),i=t.hooks,{createWithHooks:async function(t,a,o){let n=(0,e8.G)(),s=t;for(let{source:e,hooks:t}of i){let i=t[a]?.create?.before;if(i){let t=await r(`db create.before ${a}`,{[e9.A]:"create.before",[e9.d]:a,[e9.s]:e},()=>i(s,n));if(!1===t)return null;"object"==typeof t&&"data"in t&&(s={...s,...t.data})}}let l=null;for(let{source:t,hooks:c}of((!o||o.executeMainFn)&&(l=await (await (0,e7.g)(e)).create({model:a,data:s,forceAllowId:!0})),o?.fn&&(l=await o.fn(l??s)),i)){let e=c[a]?.create?.after;e&&await (0,e7.A)(async()=>{await r(`db create.after ${a}`,{[e9.A]:"create.after",[e9.d]:a,[e9.s]:t},()=>e(l,n))})}return l},updateWithHooks:async function(t,a,o,n){let s=(0,e8.G)(),l=t;for(let{source:e,hooks:a}of i){let i=a[o]?.update?.before;if(i){let a=await r(`db update.before ${o}`,{[e9.A]:"update.before",[e9.d]:o,[e9.s]:e},()=>i(t,s));if(!1===a)return null;"object"==typeof a&&"data"in a&&(l={...l,...a.data})}}let c=n?await n.fn(l):null,d=!n||n.executeMainFn?await (await (0,e7.g)(e)).update({model:o,update:l,where:a}):c;for(let{source:e,hooks:t}of i){let i=t[o]?.update?.after;i&&await (0,e7.A)(async()=>{await r(`db update.after ${o}`,{[e9.A]:"update.after",[e9.d]:o,[e9.s]:e},()=>i(d,s))})}return d},updateManyWithHooks:async function(t,a,o,n){let s=(0,e8.G)(),l=t;for(let{source:e,hooks:a}of i){let i=a[o]?.update?.before;if(i){let a=await r(`db updateMany.before ${o}`,{[e9.A]:"updateMany.before",[e9.d]:o,[e9.s]:e},()=>i(t,s));if(!1===a)return null;"object"==typeof a&&"data"in a&&(l={...l,...a.data})}}let c=n?await n.fn(l):null,d=!n||n.executeMainFn?await (await (0,e7.g)(e)).updateMany({model:o,update:l,where:a}):c;for(let{source:e,hooks:t}of i){let i=t[o]?.update?.after;i&&await (0,e7.A)(async()=>{await r(`db updateMany.after ${o}`,{[e9.A]:"updateMany.after",[e9.d]:o,[e9.s]:e},()=>i(d,s))})}return d},deleteWithHooks:async function(t,a,o){let n=(0,e8.G)(),s=null;try{s=(await (await (0,e7.g)(e)).findMany({model:a,where:t,limit:1}))[0]||null}catch{}if(s)for(let{source:e,hooks:t}of i){let i=t[a]?.delete?.before;if(i&&await r(`db delete.before ${a}`,{[e9.A]:"delete.before",[e9.d]:a,[e9.s]:e},()=>i(s,n))===!1)return null}let l=o?await o.fn(t):null,c=(!o||o.executeMainFn)&&s?await (await (0,e7.g)(e)).delete({model:a,where:t}):l;if(s)for(let{source:e,hooks:t}of i){let i=t[a]?.delete?.after;i&&await (0,e7.A)(async()=>{await r(`db delete.after ${a}`,{[e9.A]:"delete.after",[e9.d]:a,[e9.s]:e},()=>i(s,n))})}return c},deleteManyWithHooks:async function(t,a,o){let n=(0,e8.G)(),s=[];try{s=await (await (0,e7.g)(e)).findMany({model:a,where:t})}catch{}for(let e of s)for(let{source:t,hooks:o}of i){let i=o[a]?.delete?.before;if(i&&await r(`db delete.before ${a}`,{[e9.A]:"delete.before",[e9.d]:a,[e9.s]:t},()=>i(e,n))===!1)return null}let l=o?await o.fn(t):null,c=!o||o.executeMainFn?await (await (0,e7.g)(e)).deleteMany({model:a,where:t}):l;for(let e of s)for(let{source:t,hooks:o}of i){let i=o[a]?.delete?.after;i&&await (0,e7.A)(async()=>{await r(`db delete.after ${a}`,{[e9.A]:"delete.after",[e9.d]:a,[e9.s]:t},()=>i(e,n))})}return c},consumeOneWithHooks:async function(t,a,o,n){let s=(0,e8.G)(),l=i.flatMap(({source:e,hooks:r})=>{let i=r[t]?.delete?.before;return i?[{source:e,fn:i}]:[]}),c=n??null;if(l.length){if(!c)try{c=(await (await (0,e7.g)(e)).findMany({model:t,where:a,limit:1}))[0]||null}catch{}if(c){for(let{source:e,fn:i}of l)if(await r(`db delete.before ${t}`,{[e9.A]:"delete.before",[e9.d]:t,[e9.s]:e},()=>i(c,s))===!1)return null}}let d=await o();if(!d)return null;for(let{source:e,hooks:a}of i){let i=a[t]?.delete?.after;i&&await (0,e7.A)(async()=>{await r(`db delete.after ${t}`,{[e9.A]:"delete.after",[e9.d]:t,[e9.s]:e},()=>i(d,s))})}return d}}),I=t=>{let r=[...t,{field:"expiresAt",value:new Date,operator:"gt"}];return E(r,"session",{fn:async()=>{await (await (0,e7.g)(e)).updateMany({model:"session",where:r,update:{expiresAt:new Date}})},executeMainFn:!1})};async function _(e){if(!n)return;let t=await n.get(`active-sessions-${e.id}`);if(!t)return;let r=Date.now(),i=((0,b.f)(t)||[]).filter(e=>e.expiresAt>r);await Promise.all(i.map(async({token:t})=>{let i=await n.get(t);if(!i)return;let a=(0,b.f)(i);if(!a)return;let o=tr(a.session.expiresAt,r);await n.set(t,JSON.stringify({session:a.session,user:e}),Math.floor(o))}))}async function k(e){if(!n)return[];let t=await n.get(`active-sessions-${e}`);return t&&(0,b.f)(t)||[]}let T=e=>`revoked-sessions-before-${e}`,v=Math.max(c,86400,Number(o.plugins?.find(e=>"admin"===e.id)?.options?.impersonationSessionDuration)||0);async function U(e,t){if(!n)return!1;let r=t?.get(e.userId)??Number(await n.get(T(e.userId)));return t?.set(e.userId,r),new Date(e.createdAt).getTime()<r}async function R(e,t,r){if(!n)return;let i=Number(await n.get(T(e)));await n.set(T(e),String(Math.max(r,i||0)),v);let a=new Set(t.map(e=>e.token));for(let{token:e}of t)await n.delete(e);let o=`active-sessions-${e}`,s=await k(e),l=Date.now(),c=s.filter(e=>e.expiresAt>l&&!a.has(e.token));c.sort((e,t)=>e.expiresAt-t.expiresAt);let d=c.at(-1)?.expiresAt;d?await n.set(o,JSON.stringify(c),tr(d,l)):await n.delete(o)}async function S(e,t){if(!n)return;let r=t??await k(e),i=Date.now();await (0,e7.A)(()=>R(e,r,i),{onError(e){a.error("Failed to delete committed user sessions from secondary storage",e)}})}async function x(e,t){let r,i=s.get(e)??Promise.resolve(),a=new Promise(e=>{r=e}),o=i.catch(()=>{}).then(()=>a);s.set(e,o),await i.catch(()=>{});try{return await t()}finally{r(),s.get(e)===o&&s.delete(e)}}return{createOAuthUser:async(t,r)=>(0,e7.n)(e,async()=>{let e=await f({createdAt:new Date,updatedAt:new Date,...t,email:t.email?.toLowerCase()},"user",void 0);if(!e)throw new u.E("BAD_REQUEST",{message:"Failed to create user"});return{user:e,account:await f({...r,userId:e.id,createdAt:new Date,updatedAt:new Date},"account",void 0)}}),createUser:async(e,t)=>{let r={createdAt:new Date,updatedAt:new Date,...e,email:e.email?.toLowerCase()};if(o.user?.validateUserInfo){let e,i={...t,action:"create-user"};e2(i);try{e=(0,e8.g)()}catch(e){throw a.error("Unable to run validateUserInfo: missing endpoint context",e),new u.E("FORBIDDEN",{code:"validation_context_missing",message:"User validation requires an endpoint context"})}await e3(e,{user:r,source:i})}return await f(r,"user",void 0)},createAccount:async e=>await f({createdAt:new Date,updatedAt:new Date,...e},"account",void 0),listSessions:async(r,i)=>{if(p)return(await (await (0,e7.g)(e)).findMany({model:"session",where:[{field:"userId",value:r},{field:"expiresAt",value:new Date,operator:"gt"}]})).map(e=>(0,w.Q)(t.options,e));if(n){let e=await n.get(`active-sessions-${r}`);if(!e)return[];let i=(0,b.f)(e)||[],a=Date.now(),o=new Set,s=[],l=new Map;for(let{token:e,expiresAt:r}of i){if(r<=a||o.has(e))continue;o.add(e);let i=await n.get(e);if(i)try{let e="string"==typeof i?JSON.parse(i):i;if(!e?.session||await U(e.session,l))continue;s.push((0,w.Q)(t.options,{...e.session,expiresAt:new Date(e.session.expiresAt)}))}catch{continue}}return s}return await (await (0,e7.g)(e)).findMany({model:"session",where:[{field:"userId",value:r},...i?.onlyActiveSessions?[{field:"expiresAt",value:new Date,operator:"gt"}]:[]]})},listUsers:async(t,r,i,a)=>await (await (0,e7.g)(e)).findMany({model:"user",limit:t,offset:r,sortBy:i,where:a}),countTotalUsers:async t=>{let r=await (await (0,e7.g)(e)).count({model:"user",where:t});return"string"==typeof r?parseInt(r):r},deleteUser:async e=>{let t=await k(e);(!n||o.session?.storeSessionInDatabase)&&await E([{field:"userId",value:e}],"session",void 0),await E([{field:"userId",value:e}],"account",void 0),await g([{field:"id",value:e}],"user",void 0)!==null&&await S(e,t)},createSession:async(r,i,s,d,u)=>{let m,h=await (async()=>{let e=(0,e8.G)();return e?.headers||e?.request?.headers})(),g=o.session?.storeSessionInDatabase,E=u?.deferSecondaryStorageWrites===!0&&p,{id:A,...I}=s||{};if(n&&!g){let e=t.generateId({model:"session"});m=!1!==e?e:(0,y.f)()}let _=(0,w.P)(o),k={...m?{id:m}:{},ipAddress:h&&(0,l.M)(h,o)||"",userAgent:h?.get("user-agent")||"",...I,expiresAt:i?(0,e1.f)(86400,"sec"):(0,e1.f)(c,"sec"),userId:r,token:(0,y.f)(32),createdAt:new Date,updatedAt:new Date,..._,...d?I:{}},T=async t=>{if(!n)return t;let i=await n.get(`active-sessions-${r}`),a=[],o=Date.now();i&&(a=(a=(0,b.f)(i)||[]).filter(e=>e.expiresAt>o&&e.token!==k.token));let s=[...a,{token:k.token,expiresAt:k.expiresAt.getTime()}].sort((e,t)=>e.expiresAt-t.expiresAt),l=tr(s.at(-1)?.expiresAt??k.expiresAt.getTime(),o);l>0&&await n.set(`active-sessions-${r}`,JSON.stringify(s),l);let c=await (await (0,e7.g)(e)).findOne({model:"user",where:[{field:"id",value:r}]}),d=tr(k.expiresAt,o);return d>0&&await n.set(k.token,JSON.stringify({session:{...t,createdAt:k.createdAt},user:c}),d),t};return await f(k,"session",n?{fn:async e=>E?(await (0,e7.A)(async()=>{await T(e)},{onError(e){a.error("Failed to mirror committed session to secondary storage",e)}}),e):T(e),executeMainFn:g}:void 0)},findSession:async r=>{if(n){let e=await n.get(r);if(!e&&(!o.session?.storeSessionInDatabase||t.options.session?.preserveSessionInDatabase))return null;if(e){let r=(0,b.f)(e);return!r||await U(r.session)?null:{session:(0,w.Q)(t.options,{...r.session,expiresAt:new Date(r.session.expiresAt),createdAt:new Date(r.session.createdAt),updatedAt:new Date(r.session.updatedAt)}),user:(0,w.$)(t.options,{...r.user,createdAt:new Date(r.user.createdAt),updatedAt:new Date(r.user.updatedAt)})}}}let i=await (await (0,e7.g)(e)).findOne({model:"session",where:[{value:r,field:"token"}],join:{user:!0}});if(!i)return null;let{user:a,...s}=i;return a?{session:(0,w.Q)(t.options,s),user:(0,w.$)(t.options,a)}:null},findSessions:async(t,r)=>{let i=[...new Set(t)],a=new Map,o=[],s=new Map;if(n)for(let e of i){let t=await n.get(e);if(t)try{let i="string"==typeof t?JSON.parse(t):t;if(!i||await U(i.session,s))continue;let o=new Date(i.session.expiresAt);if(r?.onlyActiveSessions&&o<=new Date)continue;let n={session:{...i.session,expiresAt:new Date(i.session.expiresAt)},user:{...i.user,createdAt:new Date(i.user.createdAt),updatedAt:new Date(i.user.updatedAt)}};a.set(e,n)}catch{continue}else o.push(e)}let l=n?o:i;if(l.length>0&&(!n||p))for(let{user:t,...i}of(await (await (0,e7.g)(e)).findMany({model:"session",limit:l.length,where:[{field:"token",value:l,operator:"in"},...r?.onlyActiveSessions?[{field:"expiresAt",value:new Date,operator:"gt"}]:[]],join:{user:!0}})))t&&a.set(i.token,{session:i,user:t});return i.flatMap(e=>{let t=a.get(e);return t?[t]:[]})},updateSession:async(e,r)=>await m(r,[{field:"token",value:e}],"session",n?{async fn(r){let i=await n.get(e);if(!i)return null;let a=(0,b.f)(i);if(!a)return null;let o={...a.session,...r,expiresAt:new Date(r.expiresAt??a.session.expiresAt),createdAt:new Date(a.session.createdAt),updatedAt:new Date(r.updatedAt??a.session.updatedAt)},s=(0,w.Q)(t.options,o),l=Date.now(),c=new Date(s.expiresAt).getTime(),d=tr(c,l);if(d>0){await n.set(e,JSON.stringify({session:s,user:a.user}),d);let t=`active-sessions-${s.userId}`,r=await n.get(t),i=(r&&(0,b.f)(r)||[]).filter(t=>t.token!==e&&t.expiresAt>l).concat([{token:e,expiresAt:c}]).sort((e,t)=>e.expiresAt-t.expiresAt),o=i.at(-1)?.expiresAt;o&&o>l?await n.set(t,JSON.stringify(i),tr(o,l)):await n.delete(t)}return s},executeMainFn:o.session?.storeSessionInDatabase}:void 0),deleteSession:async e=>{if(n){let r=await n.get(e);if(r){let{session:t}=(0,b.f)(r)??{};if(!t)return void a.error("Session not found in secondary storage");let i=t.userId,o=await n.get(`active-sessions-${i}`);if(o){let t=(0,b.f)(o)||[],r=Date.now(),a=t.filter(t=>t.expiresAt>r&&t.token!==e),s=a.sort((e,t)=>e.expiresAt-t.expiresAt).at(-1)?.expiresAt;a.length>0&&s&&s>Date.now()?await n.set(`active-sessions-${i}`,JSON.stringify(a),tr(s,r)):await n.delete(`active-sessions-${i}`)}else a.error("Active sessions list not found in secondary storage")}if(await n.delete(e),!o.session?.storeSessionInDatabase)return;if(t.options.session?.preserveSessionInDatabase)return void await I([{field:"token",value:e}])}await g([{field:"token",value:e}],"session",void 0)},deleteAccounts:async e=>{await E([{field:"userId",value:e}],"account",void 0)},deleteAccount:async e=>{await g([{field:"id",value:e}],"account",void 0)},deleteUserSessions:async e=>{let r=await k(e);if(n){if(!o.session?.storeSessionInDatabase)return void await S(e,r);if(t.options.session?.preserveSessionInDatabase){await I([{field:"userId",value:e}])!==null&&await S(e,r);return}}await E([{field:"userId",value:e}],"session",void 0)!==null&&await S(e,r)},deleteSessions:async e=>{if(n){if(await Promise.all(e.map(e=>n.delete(e))),!o.session?.storeSessionInDatabase)return;if(t.options.session?.preserveSessionInDatabase)return void await I([{field:"token",value:e,operator:"in"}])}await E([{field:"token",value:e,operator:"in"}],"session",void 0)},findAccountOwnerByKey:async({providerId:t,accountId:r})=>{let i=await (await (0,e7.g)(e)).findMany({model:"account",where:[{field:"providerId",value:t},{field:"accountId",value:r}],limit:2,join:{user:!0}});if(i.length>1)throw new u.p(`Multiple accounts match the same accountId for provider ${JSON.stringify(t)}. Resolve duplicate account identities before continuing.`);let a=i[0];if(!a)return null;let{user:o,...n}=a;return o?{kind:"owned",user:o,account:n}:{kind:"orphaned",account:n}},findUserByEmail:async(t,r)=>{let i=await (await (0,e7.g)(e)).findOne({model:"user",where:[{value:t.toLowerCase(),field:"email"}],join:{...r?.includeAccounts?{account:!0}:{}}});if(!i)return null;let a=e=>e.normalize("NFC").toLowerCase();if(a(i.email)!==a(t))return null;let{account:o,...n}=i;return{user:n,accounts:o??[]}},findUserById:async t=>t?await (await (0,e7.g)(e)).findOne({model:"user",where:[{field:"id",value:t}]}):null,linkAccount:async e=>await f({createdAt:new Date,updatedAt:new Date,...e},"account",void 0),updateUser:async(e,t)=>{let r=await m({...t,...t.email?{email:t.email.toLowerCase()}:{}},[{field:"id",value:e}],"user",void 0);return await (0,e7.A)(()=>_(r),{onError(e){a.error("Failed to refresh committed user sessions in secondary storage",e)}}),r},updateUserByEmail:async(e,t)=>{let r=await m({...t,...t.email?{email:t.email.toLowerCase()}:{}},[{field:"email",value:e.toLowerCase()}],"user",void 0);return await (0,e7.A)(()=>_(r),{onError(e){a.error("Failed to refresh committed user sessions in secondary storage",e)}}),r},updatePassword:async(e,t)=>{await h({password:t},[{field:"userId",value:e},{field:"providerId",value:"credential"},{field:"accountId",value:e}],"account",void 0)},findAccounts:async t=>await (await (0,e7.g)(e)).findMany({model:"account",where:[{field:"userId",value:t}]}),findCredentialAccount:async t=>(await (0,e7.g)(e)).findOne({model:"account",where:[{field:"userId",value:t},{field:"providerId",value:"credential"},{field:"accountId",value:t}]}),findAccountByKey:async({providerId:t,accountId:r})=>{let i=await (await (0,e7.g)(e)).findMany({model:"account",limit:2,where:[{field:"providerId",value:t},{field:"accountId",value:r}]});if(i.length>1)throw new u.p(`Multiple accounts match the same accountId for provider ${JSON.stringify(t)}. Resolve duplicate account identities before continuing.`);return i[0]??null},findAccountByUserId:async t=>await (await (0,e7.g)(e)).findMany({model:"account",where:[{field:"userId",value:t}]}),updateAccount:async(e,t)=>await m(t,[{field:"id",value:e}],"account",void 0),createVerificationValue:async e=>{let t=e4(e.identifier,o.verification?.storeIdentifier),r=await e5(e.identifier,t);return await f({createdAt:new Date,updatedAt:new Date,...e,identifier:r},"verification",n?{async fn(e){let t=tr(e.expiresAt);return t>0&&await n.set(`verification:${r}`,JSON.stringify(e),t),e},executeMainFn:o.verification?.storeInDatabase}:void 0)},findVerificationValue:async t=>{let r=e4(t,o.verification?.storeIdentifier),i=await e5(t,r);if(n){let e=await n.get(`verification:${i}`);if(e){let t=(0,b.f)(e);if(t)return t}if(r&&"plain"!==r){let e=await n.get(`verification:${t}`);if(e){let t=(0,b.f)(e);if(t)return t}}if(!o.verification?.storeInDatabase)return null}let a=await (0,e7.g)(e);async function s(e){return a.findMany({model:"verification",where:[{field:"identifier",value:e}],sortBy:{field:"createdAt",direction:"desc"},limit:1})}let l=await s(i);return!l.length&&r&&"plain"!==r&&(l=await s(t)),o.verification?.disableCleanup||await E([{field:"expiresAt",value:new Date,operator:"lt"}],"verification",void 0),l[0]||null},deleteVerificationByIdentifier:async e=>{let t=e4(e,o.verification?.storeIdentifier),r=await e5(e,t);n&&await n.delete(`verification:${r}`),(!n||o.verification?.storeInDatabase)&&await g([{field:"identifier",value:r}],"verification",void 0)},consumeVerificationValue:async t=>{let r=e4(t,o.verification?.storeIdentifier),i=await e5(t,r),a=r&&"plain"!==r?[i,t]:[i],s=null;if(n&&!o.verification?.storeInDatabase){let e=async e=>(e=>{if(!e)return null;let t="string"==typeof e?(0,b.f)(e):"object"==typeof e?e:null;if(!t)return null;let r=new Date(t.expiresAt);return Number.isFinite(r.getTime())?{...t,expiresAt:r}:null})(await n.getAndDelete(e));for(let t of a){let r=await e(`verification:${t}`);if(r){await Promise.all(a.filter(e=>e!==t).map(e=>n.delete(`verification:${e}`))),s=r;break}}}else{let t=async t=>x(`verification:${t}`,()=>(0,e7.n)(e,async()=>{let r=await (0,e7.g)(e),i=[{field:"identifier",value:t}],a=(await r.findMany({model:"verification",where:i,sortBy:{field:"createdAt",direction:"desc"},limit:1}))[0]??null;return a?A("verification",[{field:"id",value:a.id}],async()=>{let e=await r.consumeOne({model:"verification",where:[{field:"id",value:a.id}]});return e?(await r.deleteMany({model:"verification",where:i}),e):null},a):null}));for(let e of a)if(s=await t(e))break;s&&n&&await Promise.all(a.map(e=>n.delete(`verification:${e}`)))}return!s||s.expiresAt<new Date?null:s},reserveVerificationValue:async t=>{let r=(0,tt.$)(new Uint8Array(await (0,d.f)("SHA-256").digest(new TextEncoder().encode("reserve:"+t.identifier))),o),i=e4(t.identifier,o.verification?.storeIdentifier),a=await e5(t.identifier,i);if(n&&!o.verification?.storeInDatabase)throw new u.p("reserveVerificationValue requires database-backed verification storage. Set verification.storeInDatabase to true for flows that reserve verification values.");try{await e.create({model:"verification",data:{id:r,identifier:a,value:t.value,expiresAt:t.expiresAt,createdAt:new Date,updatedAt:new Date},forceAllowId:!0})}catch(t){if(await e.findOne({model:"verification",where:[{field:"id",value:r}]}))return!1;throw t}if(n){let e=tr(t.expiresAt);e>0&&await n.set(`verification:${a}`,JSON.stringify({id:r,identifier:a,value:t.value,expiresAt:t.expiresAt}),e)}return!0},updateVerificationByIdentifier:async(e,t)=>{let r=e4(e,o.verification?.storeIdentifier),i=await e5(e,r);if(n){let e=await n.get(`verification:${i}`);if(e){let r=(0,b.f)(e);if(r){let e={...r,...t},a=e.expiresAt??r.expiresAt,s=tr(a instanceof Date?a:new Date(a));if(s>0&&await n.set(`verification:${i}`,JSON.stringify(e),s),!o.verification?.storeInDatabase)return e}}}return!n||o.verification?.storeInDatabase?await m(t,[{field:"identifier",value:i}],"verification",void 0):t},refreshUserSessions:_}};var ta=e.i(147391),to=e.i(129776),tn=e.i(783968);async function ts(e){let t=e.options,r=t.plugins||[],i=[],a=[];for(let o of r)if(o.init){let r,n=o.init(e);if("object"==typeof(r=(0,eZ.f)(n)?await n:n)){if(r.options){let{databaseHooks:e,trustedOrigins:n,...s}=r.options;e&&a.push({source:`plugin:${o.id}`,hooks:e}),n&&i.push(n),t=(0,to.e)(t,s)}r.context&&Object.assign(e,r.context)}}if(i.length>0){let e=[...t.trustedOrigins?[t.trustedOrigins]:[],...i],r=e.filter(Array.isArray).flat(),a=e.filter(e=>"function"==typeof e);a.length>0?t.trustedOrigins=async e=>[...r,...(await Promise.all(a.map(t=>t(e)))).flat()].filter(e=>"string"==typeof e&&""!==e):t.trustedOrigins=r}t.databaseHooks&&a.push({source:"user",hooks:t.databaseHooks}),e.internalAdapter=ti(e.adapter,{options:t,logger:e.logger,hooks:a,generateId:e.generateId}),e.options=t}async function tl(e,t){let r=[];if((0,eV._)(e.baseURL)){let t=e.baseURL.allowedHosts,i=e.baseURL.protocol;for(let e of t)e.includes("://")?r.push(e):(i&&"https"!==i&&"auto"!==i||r.push(`https://${e}`),("http"===i||"auto"===i||(0,tn.g)(e))&&r.push(`http://${e}`));if(e.baseURL.fallback)try{r.push(new URL(e.baseURL.fallback).origin)}catch{}}else{let i=(0,eV.X)("string"==typeof e.baseURL?e.baseURL:void 0,e.basePath,t);i&&r.push(new URL(i).origin)}if(e.trustedOrigins&&(Array.isArray(e.trustedOrigins)&&r.push(...e.trustedOrigins),"function"==typeof e.trustedOrigins)){let i=await e.trustedOrigins(t);r.push(...i)}let i=ta.$.BETTER_AUTH_TRUSTED_ORIGINS;return i&&r.push(...i.split(",")),r.filter(e=>!!e)}function tc(e){return e.advanced?.trustedProxyHeaders??!1}async function td(e,t,r){let i,a=e.options.baseURL,o=e.options.basePath||"/api/auth",n=(0,eV.A)(a,o,t,void 0,r);if(!n)throw new u.p("Could not resolve base URL from request. Check your allowedHosts config.");let s=Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e));s.baseURL=n,s.options={...e.options,baseURL:(0,eV.H)(n)||void 0};let l={...s.options,baseURL:a};return i="function"==typeof e.options.trustedOrigins||"function"==typeof e.options.account?.accountLinking?.trustedProviders?(0,eV.T)(t)?t:t?new Request(n,{headers:t}):void 0:void 0,s.trustedOrigins=await tl(l,i),s.trustedProviders=await tp(s.options,i),e.options.advanced?.crossSubDomainCookies?.enabled&&(s.authCookies=(0,e0.e)(s.options),s.createAuthCookie=(0,e0.g)(s.options)),s}async function tu(e,t){if(e)for(let r of e){let e="function"==typeof r?await r():r;if(e[t.field??"id"]===t.value)return e}}async function tp(e,t){let r=e.account?.accountLinking?.trustedProviders;return r?Array.isArray(r)?r.filter(e=>!!e):(await r(t)??[]).filter(e=>!!e):[]}var tf=e.i(910228);function tm(e,t){if(t.length<e.context.password.config.minPasswordLength)throw e.context.logger.warn("Password is too short"),u.E.from("BAD_REQUEST",tf.f.PASSWORD_TOO_SHORT)}function th(e,t){if(t.length>e.context.password.config.maxPasswordLength)throw e.context.logger.warn("Password is too long"),u.E.from("BAD_REQUEST",tf.f.PASSWORD_TOO_LONG)}async function tg(e,t,r,i){await (0,e7.n)(e.context.adapter,async()=>{(await i?.(),e.context.options.emailAndPassword?.revokeSessionsOnPasswordReset&&await e.context.internalAdapter.deleteUserSessions(t),await e.context.internalAdapter.findCredentialAccount(t))?await e.context.internalAdapter.updatePassword(t,r):await e.context.internalAdapter.createAccount({userId:t,providerId:"credential",accountId:t,password:r})})}async function tw(e,t){th(e,t.password);let r=await e.context.internalAdapter.findCredentialAccount(t.userId),i=r?.password;return!!r&&!!i&&await e.context.password.verify({hash:i,password:t.password})}async function ty(e,t){let r=t.body.password;"string"==typeof r&&th(t,r);let i=await t.context.internalAdapter.findCredentialAccount(e),a=i?.password;if(!i||!a||!r)throw r&&await t.context.password.hash(r),u.E.from("BAD_REQUEST",tf.f.INVALID_PASSWORD);if(!await t.context.password.verify({hash:a,password:r}))throw u.E.from("BAD_REQUEST",tf.f.INVALID_PASSWORD);return!0}e.s(["a",0,th,"b",0,tm,"B",0,ty,"J",0,tg,"c",0,tw],950551);var tb=e.i(786198),tE=e.i(155036);function tA(e){return!0===e.context.skipOriginCheck&&e.context.options.advanced?.disableCSRFCheck===void 0}function tI(e){let t=e.context.skipOriginCheck;if(!0===t)return!0;if(Array.isArray(t)&&e.request)try{let r=new URL(e.context.baseURL).pathname,i=(0,tE.s)(e.request.url,r);return t.some(e=>{let t=e.replace(/\/+$/,"");return i===t||i.startsWith(`${t}/`)})}catch{}return!1}let t_=(n=function(){},a=!1,function(...e){return a||(((void 0)??console.warn)("[Deprecation] disableOriginCheck: true currently also disables CSRF checks. In a future version, disableOriginCheck will ONLY disable URL validation. To keep CSRF disabled, add disableCSRFCheck: true to your config."),a=!0),n.apply(this,e)}),tk=(0,s.a)(async e=>{if(e.request?.method==="GET"||e.request?.method==="OPTIONS"||e.request?.method==="HEAD"||!e.request||(await tv(e),tI(e)))return;let{body:t,query:r}=e,i=t?.callbackURL||r?.callbackURL,a=t?.redirectTo,o=t?.errorCallbackURL,n=t?.newUserCallbackURL,s=(t,r)=>{if(t){if("string"!=typeof t)throw u.E.fromStatus("BAD_REQUEST",{message:`Invalid ${r}: expected a string`});if(!e.context.isTrustedOrigin(t,{allowRelativePaths:"origin"!==r})){if(e.context.logger.error(`Invalid ${r}: ${t}`),e.context.logger.info(`If it's a valid URL, please add ${t} to trustedOrigins in your auth config
|
|
92
92
|
`,`Current list of trustedOrigins: ${e.context.trustedOrigins}`),"origin"===r)throw u.E.from("FORBIDDEN",tf.f.INVALID_ORIGIN);if("callbackURL"===r)throw u.E.from("FORBIDDEN",tf.f.INVALID_CALLBACK_URL);if("redirectURL"===r)throw u.E.from("FORBIDDEN",tf.f.INVALID_REDIRECT_URL);if("errorCallbackURL"===r)throw u.E.from("FORBIDDEN",tf.f.INVALID_ERROR_CALLBACK_URL);if("newUserCallbackURL"===r)throw u.E.from("FORBIDDEN",tf.f.INVALID_NEW_USER_CALLBACK_URL);throw u.E.fromStatus("FORBIDDEN",{message:`Invalid ${r}`})}}};i&&s(i,"callbackURL"),a&&s(a,"redirectURL"),o&&s(o,"errorCallbackURL"),n&&s(n,"newUserCallbackURL")}),tT=e=>(0,s.a)(async t=>{if(!t.request||tI(t))return;let r=e(t),i=(e,r)=>{if(e&&!t.context.isTrustedOrigin(e,{allowRelativePaths:"origin"!==r})){if(t.context.logger.error(`Invalid ${r}: ${e}`),t.context.logger.info(`If it's a valid URL, please add ${e} to trustedOrigins in your auth config
|
|
93
93
|
`,`Current list of trustedOrigins: ${t.context.trustedOrigins}`),"origin"===r)throw u.E.from("FORBIDDEN",tf.f.INVALID_ORIGIN);if("callbackURL"===r)throw u.E.from("FORBIDDEN",tf.f.INVALID_CALLBACK_URL);if("redirectURL"===r)throw u.E.from("FORBIDDEN",tf.f.INVALID_REDIRECT_URL);if("errorCallbackURL"===r)throw u.E.from("FORBIDDEN",tf.f.INVALID_ERROR_CALLBACK_URL);if("newUserCallbackURL"===r)throw u.E.from("FORBIDDEN",tf.f.INVALID_NEW_USER_CALLBACK_URL);throw u.E.fromStatus("FORBIDDEN",{message:`Invalid ${r}`})}};for(let e of Array.isArray(r)?r:[r])i(e,"callbackURL")});async function tv(e,t=!1){let r=e.request?.headers;if(!r||!e.request)return;let i=r.get("origin"),a=i||r.get("referer")||"",o=r.has("cookie");if(e.context.skipCSRFCheck)return;if(tA(e)){e.context.options.advanced?.disableOriginCheck===!0&&t_();return}if(tI(e)||!(t||o))return;let n="null"===i&&"same-origin"===r.get("sec-fetch-site")?(0,eV.X)(void 0,e.context.options.basePath,e.request,!1,e.context.options.advanced?.trustedProxyHeaders):void 0,s=(n?(0,eV.H)(n):void 0)??a;if(!s||"null"===s)throw u.E.from("FORBIDDEN",tf.f.MISSING_OR_NULL_ORIGIN);let l=Array.isArray(e.context.options.trustedOrigins)?e.context.trustedOrigins:[...e.context.trustedOrigins,...(await e.context.options.trustedOrigins?.(e.request))?.filter(e=>!!e)||[]];if(!l.some(e=>eG(s,e)))throw e.context.logger.error(`Invalid origin: ${s}`),e.context.logger.info(`If it's a valid URL, please add ${s} to trustedOrigins in your auth config
|
|
94
|
-
`,`Current list of trustedOrigins: ${l}`),u.E.from("FORBIDDEN",tf.f.INVALID_ORIGIN)}let tU=(0,s.a)(async e=>{e.request&&await tR(e)});async function tR(e){let t=e.request;if(!t||e.context.skipCSRFCheck||tA(e))return;let r=t.headers;if(r.has("cookie"))return await tv(e);let i=r.get("Sec-Fetch-Site"),a=r.get("Sec-Fetch-Mode"),o=r.get("Sec-Fetch-Dest");if(i&&i.trim()||a&&a.trim()||o&&o.trim()){if("cross-site"===i&&"navigate"===a)throw e.context.logger.error("Blocked cross-site navigation login attempt (CSRF protection)",{secFetchSite:i,secFetchMode:a,secFetchDest:o}),u.E.from("FORBIDDEN",tf.f.CROSS_SITE_NAVIGATION_LOGIN_BLOCKED);return await tv(e,!0)}if(r.get("origin")||r.get("referer"))return await tv(e,!0)}let tx=new Map;function tS(e,t){return Math.ceil((e+1e3*t-Date.now())/1e3)}let tO=!1;async function tD(e,t){let r=new URL(t.baseURL).pathname,i=(0,tE.s)(e.url,r),a=t.rateLimit.window,o=t.rateLimit.max,n=(0,l.M)(e,t.options);if(!n&&t.options.advanced?.ipAddress?.disableIpTracking)return null;n||tO||(t.logger.warn("Rate limiting could not determine a client IP and is falling back to a single shared per-path bucket. Ensure your runtime forwards a trusted client IP header, then set `advanced.ipAddress.ipAddressHeaders` or `advanced.ipAddress.trustedProxies` so the address can be resolved."),tO=!0);let s=(0,l.q)(n??"no-trusted-ip",i),c=tL().find(e=>e.pathMatcher(i));for(let e of(c&&(a=c.window,o=c.max),t.options.plugins||[]))if(e.rateLimit){let t=e.rateLimit.find(e=>e.pathMatcher(i));if(t){a=t.window,o=t.max;break}}if(t.rateLimit.customRules){let r=Object.keys(t.rateLimit.customRules).find(e=>e.includes("*")?(0,eM.f)(e)(i):e===i);if(r){let i=t.rateLimit.customRules[r],n="function"==typeof i?await i(e,{window:a,max:o}):i;if(n&&(a=n.window,o=n.max),!1===n)return null}}return{key:s,currentWindow:a,currentMax:o}}async function tN(e,t){if(!t.rateLimit.enabled)return;let r=await tD(e,t);if(!r)return;let{key:i,currentWindow:a,currentMax:o}=r,n=function(e){let t,r,i,a,o,n;if(e.options.rateLimit?.customStorage)return e.options.rateLimit.customStorage;let s=e.rateLimit.storage;if("secondary-storage"===s){let t=e.options.secondaryStorage?.increment;if(!t)throw new u.p("Secondary-storage rate limiting requires SecondaryStorage.increment.");return{consume:async(r,i)=>await t(r,i.window??e.options.rateLimit?.window??10)<=i.max?{allowed:!0,retryAfter:null}:{allowed:!1,retryAfter:i.window}}}return"memory"===s?{async consume(t,r){var i;let a;!function(){let e=Date.now();for(let[t,r]of tx)e>=r.expiresAt&&tx.delete(t);if(tx.size<=1e5)return;let t=tx.size-1e5,r=0;for(let e of tx.keys())if(tx.delete(e),++r>=t)break}();let o=Date.now(),n=tx.get(t),s=(i=n&&o<n.expiresAt?n.data:void 0,a=1e3*r.window,i?o-i.lastRequest>=a?{next:{...i,count:1,lastRequest:o},update:!0,allowed:!0,retryAfter:null}:i.count>=r.max?{next:i,update:!0,allowed:!1,retryAfter:tS(i.lastRequest,r.window)}:{next:{...i,count:i.count+1,lastRequest:o},update:!0,allowed:!0,retryAfter:null}:{next:{key:"",count:1,lastRequest:o},update:!1,allowed:!0,retryAfter:null});return s.allowed&&tx.set(t,{data:{...s.next,key:t},expiresAt:o+1e3*(r.window??e.options.rateLimit?.window??10)}),{allowed:s.allowed,retryAfter:s.retryAfter}}}:(t="rateLimit",r=e.adapter,i=Math.max(...function(e){let t=[e.rateLimit.window,...tL().map(e=>e.window)];for(let r of e.options.plugins||[])r.rateLimit&&t.push(...r.rateLimit.map(e=>e.window));if(e.rateLimit.customRules)for(let r of Object.values(e.rateLimit.customRules))r&&"function"!=typeof r&&t.push(r.window);let r=t.filter(e=>Number.isFinite(e)&&e>0);return r.length>0?r:[e.rateLimit.window]}(e)),a=async e=>{let i=(await r.findMany({model:t,where:[{field:"key",value:e}]}))[0];return i&&(i.lastRequest=Number(i.lastRequest)),i},o=async(e,s)=>{s.window>i&&(i=s.window);let l=1e3*s.window,c=await a(e),d=Date.now();if(!c)try{return await r.create({model:t,data:{key:e,count:1,lastRequest:d}}),{allowed:!0,retryAfter:null}}catch(t){if(!await a(e))throw t;return o(e,s)}if(d-c.lastRequest>=l)return await r.incrementOne({model:t,where:[{field:"key",value:e},{field:"lastRequest",operator:"lte",value:c.lastRequest}],increment:{},set:{count:1,lastRequest:d}})?(await n(d),{allowed:!0,retryAfter:null}):o(e,s);let u=d-l;if(await r.incrementOne({model:t,where:[{field:"key",value:e},{field:"lastRequest",operator:"gt",value:u},{field:"count",operator:"lt",value:s.max}],increment:{count:1},set:{lastRequest:d}}))return{allowed:!0,retryAfter:null};let p=await a(e);return!p||d-p.lastRequest>=l?o(e,s):{allowed:!1,retryAfter:tS(p.lastRequest,s.window)}},n=async a=>{let o=a-1e3*i;await e.runInBackgroundOrAwait(r.deleteMany({model:t,where:[{field:"lastRequest",operator:"lt",value:o}]}).then(()=>void 0).catch(t=>e.logger.error("Error pruning rate limit rows",t)))},{consume:o})}(t),{allowed:s,retryAfter:l}=await n.consume(i,{window:a,max:o});if(!s){var c;return c=l??a,new Response(JSON.stringify({message:"Too many requests. Please try again later."}),{status:429,statusText:"Too Many Requests",headers:{"Content-Type":"application/json","X-Retry-After":c.toString()}})}}function tL(){return[{pathMatcher:e=>e.startsWith("/sign-in")||e.startsWith("/sign-up")||e.startsWith("/change-password")||e.startsWith("/change-email"),window:10,max:3},{pathMatcher:e=>"/request-password-reset"===e||"/send-verification-email"===e||e.startsWith("/forget-password")||"/email-otp/send-verification-otp"===e||"/email-otp/request-password-reset"===e,window:60,max:3}]}e.i(682868);var tP=e.i(826719),tC=e.i(805650),tq=e.i(496161),tj=e.i(869381),t$=e.i(1083),tB=e.i(697858);let tV=(0,tB.k)("better-auth:oauth-encryption:v1");function tM(e,t){return(0,tB.w)((0,tj.f)(t$.E,(0,tB.k)(e),tV,(0,tB.k)(`better-auth:${t}:v1`),32))}function tF(e,t){return"string"==typeof e?tM(e,t):{keys:new Map(Array.from(e.keys,([e,r])=>[e,tM(r,t)])),currentVersion:e.currentVersion,...e.legacySecret&&{legacySecret:tM(e.legacySecret,t)}}}async function tK(e,t,r){let i=e.accountSubject,a=await i({tokens:t,profile:r}),o=String(a);if("number"==typeof a&&!Number.isFinite(a)||0===o.trim().length||"undefined"===o||"null"===o)throw new u.p("OAUTH_ACCOUNT_SUBJECT_INVALID");return{providerId:e.id,accountId:o}}async function tz(e,t,r){try{return await tK(e,t,r)}catch{throw u.E.from("UNAUTHORIZED",tf.f.FAILED_TO_GET_USER_INFO)}}let tH="invalid_code",tW="unable_to_get_user_info",tY="unable_to_link_account",tQ="email_not_verified";function tG(e,t,r,i){let a=new URLSearchParams({error:r});i&&a.set("error_description",i);let o=(0,tE.M)(t,a);throw e.redirect(o)}function tJ(e,t){return`${t?.source==="generic"?`Generic OAuth provider "${e}"`:`Provider "${e}"`} did not return an email${t?.source==="id_token"?" in the id token":""}. Either request the provider's email scope, or create a placeholder via \`mapProfileToUser\`. See https://www.better-auth.com/docs/concepts/oauth#handling-providers-without-email`}function tZ(e){return"true"===e||!0===e}function tX(e,t){if(!e)return e;if(t.options.account?.encryptOAuthTokens)return e.startsWith("$ba$")||e.length%2==0&&/^[0-9a-f]+$/i.test(e)?(0,tC.u)({key:t.secretConfig,data:e}):e;return e}function t0(e,t){return t.options.account?.encryptOAuthTokens&&e?(0,tC.M)({key:t.secretConfig,data:e}):e}function t1(e){return e.callbackPath?e.callbackPath.startsWith("/")?e.callbackPath:`/${e.callbackPath}`:`/callback/${e.id}`}e.s(["f",0,tZ],342e3);var t2=e.i(375742);function t3(e){if(e)try{return e.clone()}catch{return new Request(e.url,{cache:e.cache,credentials:e.credentials,headers:e.headers,integrity:e.integrity,keepalive:e.keepalive,method:e.method,mode:e.mode,redirect:e.redirect,referrer:e.referrer,referrerPolicy:e.referrerPolicy,signal:e.signal})}}var t6=e.i(709939),t5=e.i(865466);async function t4(e,t,r,i=3600,a){return await (0,t2.X)({email:t.toLowerCase(),updateTo:r?.toLowerCase(),...a},e,i)}async function t7(e,t){if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),u.E.from("BAD_REQUEST",tf.f.VERIFICATION_EMAIL_NOT_ENABLED);let r=await t4(e.context.secret,t.email,void 0,e.context.options.emailVerification?.expiresIn,{userId:t.id}),i=e.body.callbackURL?encodeURIComponent(e.body.callbackURL):encodeURIComponent("/"),a=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${i}`;await e.context.options.emailVerification.sendVerificationEmail({user:t,url:a,token:r},e.request)}let t8=(0,s.g)("/send-verification-email",{method:"POST",operationId:"sendVerificationEmail",cloneRequest:!0,body:E.object({email:E.email().meta({description:"The email to send the verification email to"}),callbackURL:E.string().meta({description:"The URL to use for email verification callback"}).optional()}),metadata:{openapi:{operationId:"sendVerificationEmail",description:"Send a verification email to the user",requestBody:{content:{"application/json":{schema:{type:"object",properties:{email:{type:"string",description:"The email to send the verification email to",example:"user@example.com"},callbackURL:{type:"string",description:"The URL to use for email verification callback",example:"https://example.com/callback",nullable:!0}},required:["email"]}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean",description:"Indicates if the email was sent successfully",example:!0}}}}}},400:{description:"Bad Request",content:{"application/json":{schema:{type:"object",properties:{message:{type:"string",description:"Error message",example:"Verification email isn't enabled"}}}}}}}}}},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),u.E.from("BAD_REQUEST",tf.f.VERIFICATION_EMAIL_NOT_ENABLED);let{email:t}=e.body,r=await (0,p.D)(e);if(!r){let r,i=Date.now(),a=await e.context.internalAdapter.findUserByEmail(t);if(!a||a.user.emailVerified)await t4(e.context.secret,t,void 0,e.context.options.emailVerification?.expiresIn);else try{await t7(e,a.user)}catch(e){r=e}let o=500-(Date.now()-i);if(o>0&&await new Promise(e=>setTimeout(e,o)),r)throw r;return e.json({status:!0})}if(r?.user.email.toLowerCase()!==t.toLowerCase())throw u.E.from("BAD_REQUEST",tf.f.EMAIL_MISMATCH);if(r?.user.emailVerified)throw u.E.from("BAD_REQUEST",tf.f.EMAIL_ALREADY_VERIFIED);return await t7(e,r.user),e.json({status:!0})}),t9=(0,s.g)("/verify-email",{method:"GET",operationId:"verifyEmail",query:E.object({token:E.string().meta({description:"The token to verify the email"}),callbackURL:E.string().meta({description:"The URL to redirect to after email verification"}).optional()}),use:[tT(e=>e.query.callbackURL)],metadata:{openapi:{description:"Verify the email of the user",parameters:[{name:"token",in:"query",description:"The token to verify the email",required:!0,schema:{type:"string"}},{name:"callbackURL",in:"query",description:"The URL to redirect to after email verification",required:!1,schema:{type:"string"}}],responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object",$ref:"#/components/schemas/User"},status:{type:"boolean",description:"Indicates if the email was verified successfully"}},required:["user","status"]}}}}}}}},async e=>{let t;function r(t){if(e.query.callbackURL){let r=new URLSearchParams({error:t.code}),i=(0,tE.M)(e.query.callbackURL,r);throw e.redirect(i)}throw u.E.from("UNAUTHORIZED",t)}let{token:i}=e.query;try{t=await (0,t6.f)(i,new TextEncoder().encode(e.context.secret),{algorithms:["HS256"]})}catch(e){if(e instanceof t5.JWTExpired)return r(tf.f.TOKEN_EXPIRED);return r(tf.f.INVALID_TOKEN)}let a=E.object({email:E.email(),updateTo:E.string().optional(),requestType:E.string().optional(),userId:E.string().optional()}).parse(t.payload);if(a.updateTo){if(!a.userId)return r(tf.f.INVALID_TOKEN);let t=await e.context.internalAdapter.findUserById(a.userId);if(!t)return r(tf.f.USER_NOT_FOUND);if(t.email.toLowerCase()!==a.email)return r(tf.f.INVALID_TOKEN);let i=await (0,p.D)(e);if(i&&i.user.id!==t.id)return r(tf.f.INVALID_USER);switch(a.requestType){case"change-email-confirmation":{let r=await t4(e.context.secret,a.email,a.updateTo,e.context.options.emailVerification?.expiresIn,{requestType:"change-email-verification",userId:t.id}),i=e.query.callbackURL?encodeURIComponent(e.query.callbackURL):encodeURIComponent("/"),o=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${i}`;if(e.context.options.emailVerification?.sendVerificationEmail&&await e.context.runInBackgroundOrAwait(e.context.options.emailVerification.sendVerificationEmail({user:{...t,email:a.updateTo},url:o,token:r},t3(e.request))),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0})}case"change-email-verification":{let r=t.emailVerified,o=await e.context.internalAdapter.updateUser(t.id,{email:a.updateTo,emailVerified:r});if(r&&e.context.options.emailVerification?.afterEmailVerification&&await e.context.options.emailVerification.afterEmailVerification(o,e.request),i&&await (0,e0.V)(e,{session:i.session,user:{...i.user,email:a.updateTo,emailVerified:r}}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:(0,w.$)(e.context.options,o)})}default:{let r=await e.context.internalAdapter.updateUser(t.id,{email:a.updateTo,emailVerified:!1}),o=await t4(e.context.secret,a.updateTo,void 0,void 0,{userId:t.id}),n=e.query.callbackURL?encodeURIComponent(e.query.callbackURL):encodeURIComponent("/");if(e.context.options.emailVerification?.sendVerificationEmail&&await e.context.runInBackgroundOrAwait(e.context.options.emailVerification.sendVerificationEmail({user:r,url:`${e.context.baseURL}/verify-email?token=${o}&callbackURL=${n}`,token:o},t3(e.request))),i&&await (0,e0.V)(e,{session:i.session,user:{...i.user,email:a.updateTo,emailVerified:!1}}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:(0,w.$)(e.context.options,r)})}}}let o=await e.context.internalAdapter.findUserByEmail(a.email);if(!o)return r(tf.f.USER_NOT_FOUND);if(a.userId&&a.userId!==o.user.id)return r(tf.f.INVALID_TOKEN);if(o.user.emailVerified){if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:null})}e.context.options.emailVerification?.beforeEmailVerification&&await e.context.options.emailVerification.beforeEmailVerification(o.user,e.request);let n=await e.context.internalAdapter.updateUserByEmail(a.email,{emailVerified:!0});if(e.context.options.emailVerification?.afterEmailVerification&&await e.context.options.emailVerification.afterEmailVerification(n,e.request),e.context.options.emailVerification?.autoSignInAfterVerification){let t=await (0,p.D)(e);if(t&&t.user.email===a.email)await (0,e0.V)(e,{session:t.session,user:{...t.user,emailVerified:!0}});else{let t=await e.context.internalAdapter.createSession(o.user.id);if(!t)throw u.E.from("INTERNAL_SERVER_ERROR",tf.f.FAILED_TO_CREATE_SESSION);await (0,e0.V)(e,{session:t,user:{...o.user,emailVerified:!0}})}}if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:null})});var re=e.i(945e3);function rt(e,t){return{linked:!1,error:{code:e,message:t}}}async function rr(e,t){if(!t.encryptedSessionToken||!(0,p.f)(e))return!0;let r=await (0,tC.u)({key:tF(e.context.secretConfig,"oauth-link-session-token"),data:t.encryptedSessionToken}).catch(()=>null);if(!r)return!1;let i=await e.context.internalAdapter.findSession(r);return!!i&&i.session.userId===t.userId&&i.session.expiresAt>new Date}async function ri(e,t){let{link:r,account:i,profile:a,scopes:o}=t,n={...t.userInfo,emailVerified:tZ(t.userInfo.emailVerified)};if(!await rr(e,r))return rt(tY);try{await e3(e,{user:{...n,id:r.userId,email:n.email??void 0},source:{action:"link-account",method:"oauth",oauth:{providerId:i.providerId,profile:a}}})}catch(e){if(!(0,tb.f)(e)||!e.body?.code)throw e;return rt(e.body.code,e.body.message)}if(!e.context.trustedProviders.includes(i.providerId)&&!n.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)return e.context.logger.error("Unable to link account - untrusted provider"),rt(tY);if(n.email?.toLowerCase()!==r.email.toLowerCase()&&e.context.options.account?.accountLinking?.allowDifferentEmails!==!0)return rt("email_does_not_match");let s=await e.context.internalAdapter.findAccountByKey(i);if(s){if(s.userId.toString()!==r.userId.toString())return rt("account_already_linked_to_different_user");let t=(0,re.w)(s.scope,o),a=Object.fromEntries(Object.entries({providerId:i.providerId,accessToken:await t0(i.accessToken,e.context),refreshToken:await t0(i.refreshToken,e.context),idToken:i.idToken,accessTokenExpiresAt:i.accessTokenExpiresAt,refreshTokenExpiresAt:i.refreshTokenExpiresAt,scope:t||void 0}).filter(([e,t])=>void 0!==t));await e.context.internalAdapter.updateAccount(s.id,a)}else if(!await e.context.internalAdapter.createAccount({userId:r.userId,...i,accessToken:await t0(i.accessToken,e.context),refreshToken:await t0(i.refreshToken,e.context),scope:o?.join(",")??i.scope}))return rt(tY);return await rn(e,r.userId,n),{linked:!0}}async function ra(e,t){let{account:r,callbackURL:i,disableSignUp:a,overrideUserInfo:o}=t,n={...t.userInfo,emailVerified:tZ(t.userInfo.emailVerified)},s=t.source??{method:"oauth",oauth:{providerId:r.providerId}},l=!!t.selectedUser||!0===t.requireExactAccountBinding,c=null,d=await e.context.internalAdapter.findAccountOwnerByKey({providerId:r.providerId,accountId:r.accountId}).catch(t=>{e.context.logger.error("Better auth was unable to query your database.\nError: ",t);let r=e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`;tG(e,r,"internal_server_error")});if(d?.kind==="orphaned")return e.context.logger.error("OAuth account references a missing user. Repair the account before retrying authentication."),{error:"unable to link account",data:null,isRegister:!1};let p=await (async()=>{if(d?.kind==="owned"){if(t.selectedUser&&d.user.id!==t.selectedUser.userId)throw new u.E("CONFLICT",{code:"account_ownership_conflict",message:"Account is already linked to another user"});return{user:d.user,linkedAccount:d.account,accounts:[d.account]}}if(t.selectedUser){let r=await e.context.internalAdapter.findUserById(t.selectedUser.userId);if(!r)throw new u.E("NOT_FOUND",{code:"user_not_found",message:"User not found"});return{user:r,linkedAccount:null,accounts:[]}}let r=await e.context.internalAdapter.findUserByEmail(n.email.toLowerCase(),{includeAccounts:!0});return r?{user:r.user,linkedAccount:null,accounts:r.accounts}:null})().catch(t=>{if((0,tb.f)(t))throw t;e.context.logger.error("Better auth was unable to query your database.\nError: ",t);let r=e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`;tG(e,r,"internal_server_error")}),f=p?.user,m=!f;if(p){let i=p.linkedAccount??p.accounts.find(e=>e.providerId===r.providerId&&e.accountId===r.accountId);if(i){let{id:a,...o}=n;await e3(e,{user:{...o,id:p.user.id,email:n.email.toLowerCase()},source:{...s,action:"sign-in"}});let d=e.context.options.account?.updateAccountOnSignIn!==!1?Object.fromEntries(Object.entries({providerId:r.providerId,idToken:r.idToken,accessToken:await t0(r.accessToken,e.context),refreshToken:await t0(r.refreshToken,e.context),accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt}).filter(([e,t])=>void 0!==t)):{};if(e.context.options.account?.storeAccountCookie){let r={...i,...d};t.deferNonDatabaseWrites?c=r:await (0,tq.L)(e,r)}if(Object.keys(d).length>0){let a=await e.context.internalAdapter.updateAccount(i.id,d);if(!a)return{error:"unable to update account",data:null};if(l&&(a.accountId!==r.accountId||a.providerId!==r.providerId||a.userId!==p.user.id))throw new u.E("CONFLICT",{code:"account_hook_binding_conflict",message:"Account hook changed the selected authentication binding"});t.deferNonDatabaseWrites&&c&&(c=a)}t.selectedUser||!n.emailVerified||p.user.emailVerified||n.email.toLowerCase()!==p.user.email||await e.context.internalAdapter.updateUser(p.user.id,{emailVerified:!0})}else{let i=e.context.options.account?.accountLinking,a=t.isTrustedProvider||!1!==t.trustProviderByName&&e.context.trustedProviders.includes(r.providerId),o=i?.requireLocalEmailVerified??!0;if(!t.selectedUser&&(!a&&!n.emailVerified||o&&!p.user.emailVerified||i?.enabled===!1||i?.disableImplicitLinking===!0))return(0,ta.o)()&&e.context.logger.warn(`User already exist but account isn't linked to ${r.providerId}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`),{error:"account not linked",data:null};try{let{id:i,...a}=n;await e3(e,{user:{...a,id:p.user.id,email:n.email.toLowerCase()},source:{...s,action:"link-account"}});let o=await e.context.internalAdapter.linkAccount({providerId:r.providerId,accountId:r.accountId,userId:p.user.id,accessToken:await t0(r.accessToken,e.context),refreshToken:await t0(r.refreshToken,e.context),idToken:r.idToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:r.scope});if(!o)return{error:"unable to link account",data:null};if(l&&(o.accountId!==r.accountId||o.providerId!==r.providerId||o.userId!==p.user.id))throw new u.E("CONFLICT",{code:"account_hook_binding_conflict",message:"Account hook changed the selected authentication binding"});e.context.options.account?.storeAccountCookie&&(t.deferNonDatabaseWrites?c=o:await (0,tq.L)(e,o))}catch(t){if((0,tb.f)(t))throw t;return e.context.logger.error("Unable to link account",t),{error:"unable to link account",data:null}}t.selectedUser||!n.emailVerified||p.user.emailVerified||n.email.toLowerCase()!==p.user.email||await e.context.internalAdapter.updateUser(p.user.id,{emailVerified:!0}),t.selectedUser||(f=await rn(e,p.user.id,n)??f)}if(t.selectedUser?"update"===t.selectedUser.profile:o){let{id:r,email:i,emailVerified:a,name:o,image:s,...l}=n,c=(0,w.W)(e.context.options,l,"update"),d=await e.context.internalAdapter.updateUser(p.user.id,{name:o,image:s,...c,email:n.email.toLowerCase(),emailVerified:n.email.toLowerCase()===p.user.email&&p.user.emailVerified||n.emailVerified});if(null==d&&e.context.logger.warn("Could not update user info during OAuth sign in; preserving existing user for session."),t.selectedUser&&d&&d.id!==t.selectedUser.userId)throw new u.E("CONFLICT",{code:"user_hook_selection_conflict",message:"User hook changed the selected user"});f=d??f}}else{if(a)return{error:"signup disabled",data:null,isRegister:!1};try{let{id:i,email:a,emailVerified:o,name:d,image:p,...m}=n,h=(0,w.W)(e.context.options,m,"create"),g={accessToken:await t0(r.accessToken,e.context),refreshToken:await t0(r.refreshToken,e.context),idToken:r.idToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:r.scope,providerId:r.providerId,accountId:r.accountId},{createdUser:y,createdAccount:b}=await (0,e7.n)(e.context.adapter,async()=>{let t=await e.context.internalAdapter.createUser({name:d,image:p,...h,email:n.email.toLowerCase(),emailVerified:n.emailVerified},s);return{createdUser:t,createdAccount:await e.context.internalAdapter.createAccount({...g,userId:t.id})}});if(l&&(b.accountId!==r.accountId||b.providerId!==r.providerId||b.userId!==y.id))throw new u.E("CONFLICT",{code:"account_hook_binding_conflict",message:"Account hook changed the selected authentication binding"});f=y,e.context.options.account?.storeAccountCookie&&(t.deferNonDatabaseWrites?c=b:await (0,tq.L)(e,b))}catch(t){if((0,tb.f)(t))throw t;return e.context.logger.error("Unable to create OAuth user",t),{error:"unable to create user",data:null,isRegister:!1}}}if(!f)return{error:"unable to create user",data:null,isRegister:!1};let h=e.context.socialProviders.find(e=>e.id===r.providerId)?.options?.requireEmailVerification;if(m&&!f.emailVerified&&(e.context.options.emailVerification?.sendOnSignUp??h)&&await ro(e,f,i,t.deferNonDatabaseWrites),h&&!f.emailVerified)return!m&&e.context.options.emailVerification?.sendOnSignIn&&await ro(e,f,i,t.deferNonDatabaseWrites),{error:tQ,data:null,isRegister:m};let g=await e.context.internalAdapter.createSession(f.id,void 0,void 0,void 0,{deferSecondaryStorageWrites:!0===t.deferNonDatabaseWrites});if(!g)return{error:"unable to create session",data:null,isRegister:!1};if(l&&g.userId!==(t.selectedUser?.userId??f.id))throw new u.E("CONFLICT",{code:"session_hook_user_conflict",message:"Session hook changed the selected user"});return{data:{session:g,user:f},error:null,isRegister:m,accountCookie:c}}async function ro(e,t,r,i){let a=e.context.options.emailVerification?.sendVerificationEmail;if(!a)return;let o=async()=>{try{let i=await t4(e.context.secret,t.email,void 0,e.context.options.emailVerification?.expiresIn,{userId:t.id}),o=`${e.context.baseURL}/verify-email?token=${i}&callbackURL=${encodeURIComponent(r||"/")}`;await e.context.runInBackgroundOrAwait(a({user:t,url:o,token:i},e.request))}catch(t){e.context.logger.error("Failed to send OAuth verification email",t)}};i?await (0,e7.A)(o):await o()}async function rn(e,t,r){if(e.context.options.account?.accountLinking?.updateUserInfoOnLink===!0)try{let{email:i,emailVerified:a,name:o,image:n,...s}=r,l=(0,w.W)(e.context.options,s,"update");return await e.context.internalAdapter.updateUser(t,{name:o,image:n,...l})}catch(t){e.context.logger.warn("Could not update user info on account link",t);return}}var rs=u;let rl=E.looseObject({callbackURL:E.string(),codeVerifier:E.string(),errorURL:E.string().optional(),newUserURL:E.string().optional(),expiresAt:E.number(),oauthState:E.string().optional(),link:E.object({email:E.string(),userId:A.f.string(),encryptedSessionToken:E.string().optional()}).optional(),requestSignUp:E.boolean().optional(),idTokenNonce:E.string().optional(),serverContext:E.record(E.string(),E.unknown()).optional()}),rc=e=>`auth-state:${e}`;new Set(Object.keys(rl.shape));var rd=class extends rs.p{code;details;errorURL;constructor(e,t){super(e,t),this.code=t.code,this.details=t.details,this.errorURL=t.errorURL}};async function ru(e,t,r){let i=(0,g.f)(32);if("cookie"===e.context.oauthConfig.storeStateStrategy){let a={...t,oauthState:i},o=await (0,tC.M)({key:tF(e.context.secretConfig,"oauth-state-cookie"),data:JSON.stringify(a)}),n=e.context.createAuthCookie(r?.cookieName??"oauth_state",{maxAge:600});return e.setCookie(n.name,o,n.attributes),{state:i,codeVerifier:t.codeVerifier}}let a=e.context.createAuthCookie(r?.cookieName??"state",{maxAge:300});await e.setSignedCookie(a.name,i,e.context.secret,a.attributes);let o=new Date;if(o.setMinutes(o.getMinutes()+10),!await e.context.internalAdapter.createVerificationValue({value:JSON.stringify({...t,oauthState:i}),identifier:rc(i),expiresAt:o}))throw new rd("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database",{code:"state_generation_error"});return{state:i,codeVerifier:t.codeVerifier}}async function rp(e,t,r){let i;if(!t)throw new rd("State not found in OAuth callback",{code:"state_not_found"});if("cookie"===e.context.oauthConfig.storeStateStrategy){let a=e.context.createAuthCookie(r?.cookieName??"oauth_state"),o=e.getCookie(a.name);if(!o)throw new rd("State mismatch: auth state cookie not found",{code:"state_mismatch",details:{state:t}});try{let t=await (0,tC.u)({key:tF(e.context.secretConfig,"oauth-state-cookie"),data:o});i=rl.parse(JSON.parse(t))}catch(e){throw new rd("State invalid: Failed to decrypt or parse auth state",{code:"state_invalid",details:{state:t},cause:e})}if(!i.oauthState||i.oauthState!==t)throw new rd("State mismatch: OAuth state parameter does not match stored state",{code:"state_security_mismatch",details:{state:t},errorURL:i.errorURL});(0,e0.c)(e,a)}else{let a=await e.context.internalAdapter.findVerificationValue(rc(t));if(!a)throw new rd("State mismatch: verification not found",{code:"state_mismatch",details:{state:t}});if(void 0!==(i=rl.parse(JSON.parse(a.value))).oauthState&&i.oauthState!==t)throw new rd("State mismatch: OAuth state parameter does not match stored state",{code:"state_security_mismatch",details:{state:t},errorURL:i.errorURL});let o=e.context.createAuthCookie(r?.cookieName??"state"),n=await e.getSignedCookie(o.name,e.context.secret);if(!(r?.skipStateCookieCheck??e.context.oauthConfig.skipStateCookieCheck)&&(!n||n!==t))throw new rd("State mismatch: State not persisted correctly",{code:"state_security_mismatch",details:{state:t},errorURL:i.errorURL});(0,e0.c)(e,o),await e.context.internalAdapter.deleteVerificationByIdentifier(rc(t))}if(i.expiresAt<Date.now())throw new rd("Invalid state: request expired",{code:"state_mismatch",details:{expiresAt:i.expiresAt},errorURL:i.errorURL});return i}function rf(e){return e.requiresIdTokenNonce?(0,g.f)(32):void 0}async function rm(e,t){let r=e.body?.callbackURL||e.context.options.baseURL;if(!r)throw u.E.from("BAD_REQUEST",tf.f.CALLBACK_URL_REQUIRED);let i=t?.codeVerifier??(0,g.f)(128),a=await (0,tP.r)(),o=a&&Object.keys(a).length?a:void 0,n={...t?.additionalData?t.additionalData:{},callbackURL:r,codeVerifier:i,errorURL:e.body?.errorCallbackURL,newUserURL:e.body?.newUserCallbackURL,link:t?.link,serverContext:o,expiresAt:Date.now()+6e5,requestSignUp:e.body?.requestSignUp,idTokenNonce:t?.idTokenNonce};await (0,tP.K)(n);try{return ru(e,n)}catch(t){throw e.context.logger.error("Failed to create verification",t),new u.E("INTERNAL_SERVER_ERROR",{message:"Unable to create verification",cause:t})}}async function rh(e){let t,r=e.query.state||e.body?.state,i=e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`;try{t=await rp(e,r)}catch(a){e.context.logger.error("Failed to parse state",a);let t="internal_server_error",r=i;a instanceof rd&&(t="state_security_mismatch"===a.code?"state_mismatch":a.code,r=a.errorURL||i),tG(e,r,t)}return t.errorURL||(t.errorURL=i),t&&await (0,tP.K)(t),t}let rg=["state","client_id","redirect_uri","response_type","code_challenge","code_challenge_method","nonce","scope"],rw=new Set(rg);async function ry({id:e,options:t,authorizationEndpoint:r,state:i,codeVerifier:a,scopes:o,claims:n,redirectURI:s,duration:l,prompt:c,accessType:d,responseType:u,display:p,loginHint:f,nonce:m,hd:h,responseMode:g,additionalParams:w,scopeJoiner:y}){let b=new URL((t="function"==typeof t?await t():t).authorizationEndpoint||r);b.searchParams.set("response_type",u||"code");let E=(0,re.B)(t.clientId);if(!E)throw Error("OAuth provider requires clientId");if(b.searchParams.set("client_id",E),b.searchParams.set("state",i),o?.length&&b.searchParams.set("scope",o.join(y||" ")),b.searchParams.set("redirect_uri",t.redirectURI||s),l&&b.searchParams.set("duration",l),p&&b.searchParams.set("display",p),f&&b.searchParams.set("login_hint",f),m&&b.searchParams.set("nonce",m),c&&b.searchParams.set("prompt",c),h&&b.searchParams.set("hd",h),d&&b.searchParams.set("access_type",d),g&&b.searchParams.set("response_mode",g),a){let e=await (0,re.F)(a);b.searchParams.set("code_challenge_method","S256"),b.searchParams.set("code_challenge",e)}if(n){let e=n.reduce((e,t)=>(e[t]=null,e),{});b.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...e}}))}if(w)for(let[e,t]of Object.entries(w))rw.has(e)||b.searchParams.set(e,t);return b}e.s(["k",0,rg,"Z",0,rw,"V",0,ry],729522);let rb=E.record(E.string(),E.string()).refine(e=>!Object.keys(e).some(e=>rw.has(e)),{message:`additionalParams cannot include reserved OAuth parameters: ${rg.join(", ")}`}).meta({description:"Extra query parameters to append to the provider authorization URL (e.g. Cognito identity_provider, Google hd)."}).optional(),rE=["iss","sub","aud","exp","iat"];function rA(e){return{issuer:e.issuer,audience:e.audience,algorithms:e.algorithms,maxTokenAge:e.maxTokenAge,requiredClaims:rE,clockTolerance:30}}async function rI(e){let t=new TextEncoder().encode(e);return Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256",t))).map(e=>e.toString(16).padStart(2,"0")).join("")}async function r_(e,t,r="exact"){return"string"==typeof e&&(e===t||"exact-or-sha256"===r&&e===await rI(t))}async function rk(e,t,r){if(![t.audience].flat().some(Boolean))throw Error("ID token audience is not configured");let i=await (0,t6.f)(e,t.jwks,rA(t));if(r&&!await r_(i.payload.nonce,r,t.nonceComparison))throw Error("ID token nonce does not match");if(t.verifyClaims&&!t.verifyClaims(i.payload))throw Error("ID token claims were rejected");return i}function rT(e){let t=e.options??{};return!t.disableIdTokenSignIn&&!!(e.idToken||t.verifyIdToken)}async function rv(e,t,r,i){let a=e.options??{};if(a.disableIdTokenSignIn)return!1;try{if(a.verifyIdToken)return await a.verifyIdToken(t,r,i);let o=e.idToken;if(!o)return!1;if("verify"in o)return await o.verify(t,r,i);if(3!==t.split(".").length)return!0===o.allowOpaqueToken;return await rk(t,o,r),!0}catch{return!1}}e.s(["M",0,rA,"x",0,rT,"n",0,rv],100762);var rU=e.i(748860),rR=e.i(109083),rx=e.i(432741);function rS(e,t,r){if(t.clientSecret||r.has("client_secret"))throw Error(`${e} token endpoint authentication cannot be combined with clientSecret`)}function rO(e,t){t&&e.set("client_id",t)}function rD(e,t){if(!t.clientSecret)throw Error(`${e} token endpoint authentication requires clientSecret`)}function rN(e,t){if(!t)throw Error(`${e} token endpoint authentication requires clientId`)}function rL(e){if(e.has("client_assertion")!==e.has("client_assertion_type"))throw Error("client_assertion and client_assertion_type must both be provided")}async function rP({body:e,headers:t,options:r,tokenEndpoint:i,grantType:a,tokenEndpointAuth:o,authentication:n}){rL(e);let s=(0,re.B)(r.clientId);if(e.has("client_assertion")){if(o)throw Error("client_assertion body parameters cannot be combined with tokenEndpointAuth");rS("private_key_jwt",r,e),rO(e,s);return}let l=o??("basic"===n?{method:"client_secret_basic"}:r.clientSecret?{method:"client_secret_post"}:{method:"none"});if("custom"===l.method){await l.customizeRequest({body:e,headers:t,options:r,tokenEndpoint:i,grantType:a}),rL(e);return}if("private_key_jwt"===l.method){if(rS(l.method,r,e),rN(l.method,s),!i)throw Error("private_key_jwt token endpoint authentication requires tokenEndpoint");let t=await (0,rx.B)({getClientAssertion:l.getClientAssertion,context:{clientId:s,tokenEndpoint:i,grantType:a}});for(let[r,i]of(rO(e,s),Object.entries(t)))e.set(r,i);return}if("none"===l.method){if(rS(l.method,r,e),"client_credentials"===a)throw Error("none token endpoint authentication cannot be used with client_credentials grant");rN(l.method,s),rO(e,s);return}"client_secret_basic"===l.method?function({headers:e,options:t,clientId:r,body:i}){if(i.has("client_secret"))throw Error("client_secret_basic token endpoint authentication cannot be combined with client_secret body parameters");rD("client_secret_basic",t),rN("client_secret_basic",r),e.authorization=(0,rR.n)(r,t.clientSecret)}({headers:t,options:r,clientId:s,body:e}):function({body:e,options:t,clientId:r,requireClientSecret:i}){i&&rD("client_secret_post",t),t.clientSecret&&(rN("client_secret_post",r),rO(e,r),e.set("client_secret",t.clientSecret))}({body:e,options:r,clientId:s,requireClientSecret:o?.method==="client_secret_post"})}let rC=new Set(["grant_type","refresh_token","__proto__","constructor","prototype"]);async function rq({refreshToken:e,options:t,authentication:r,tokenEndpointAuth:i,tokenEndpoint:a,extraParams:o,resource:n}){let s=function({refreshToken:e,options:t,extraParams:r,resource:i}){let a=new URLSearchParams;if(a.set("grant_type","refresh_token"),a.set("refresh_token",e),i)if("string"==typeof i)a.append("resource",i);else for(let e of i)a.append("resource",e);return r&&function(e,t){if(t)for(let[r,i]of Object.entries(t))rC.has(r)||e.set(r,i)}(a,r),{body:a,headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json"}}}({refreshToken:e,options:t="function"==typeof t?await t():t,extraParams:o,resource:n});return await rP({body:s.body,headers:s.headers,options:t,tokenEndpoint:a??"",grantType:"refresh_token",tokenEndpointAuth:i,authentication:r}),s}async function rj({refreshToken:e,options:t,tokenEndpoint:r,authentication:i,tokenEndpointAuth:a,extraParams:o,resource:n}){let{body:s,headers:l}=await rq({refreshToken:e,options:t,authentication:i,tokenEndpointAuth:a,tokenEndpoint:r,extraParams:o,resource:n}),{data:c,error:d}=await (0,rU.f)(r,{method:"POST",body:s,headers:l});if(d)throw d;let u={accessToken:c.access_token,refreshToken:c.refresh_token,tokenType:c.token_type,scopes:(0,re.V)(c.scope),idToken:c.id_token};return c.expires_in&&(u.accessTokenExpiresAt=new Date((new Date).getTime()+1e3*c.expires_in)),c.refresh_token_expires_in&&(u.refreshTokenExpiresAt=new Date((new Date).getTime()+1e3*c.refresh_token_expires_in)),u}async function r$({code:e,codeVerifier:t,redirectURI:r,options:i,authentication:a,tokenEndpointAuth:o,tokenEndpoint:n,deviceId:s,headers:l,additionalParams:c={},resource:d}){let u=function({code:e,codeVerifier:t,redirectURI:r,options:i,deviceId:a,headers:o,additionalParams:n={},resource:s}){let l=new URLSearchParams,c={"content-type":"application/x-www-form-urlencoded",accept:"application/json",...o};if(l.set("grant_type","authorization_code"),l.set("code",e),t&&l.set("code_verifier",t),i.clientKey&&l.set("client_key",i.clientKey),a&&l.set("device_id",a),l.set("redirect_uri",i.redirectURI||r),s)if("string"==typeof s)l.append("resource",s);else for(let e of s)l.append("resource",e);for(let[e,t]of Object.entries(n))l.has(e)||l.append(e,t);return{body:l,headers:c}}({code:e,codeVerifier:t,redirectURI:r,options:i="function"==typeof i?await i():i,deviceId:s,headers:l,additionalParams:c,resource:d});return await rP({body:u.body,headers:u.headers,options:i,tokenEndpoint:n??"",grantType:"authorization_code",tokenEndpointAuth:o,authentication:a}),u}async function rB({code:e,codeVerifier:t,redirectURI:r,options:i,tokenEndpoint:a,authentication:o,tokenEndpointAuth:n,deviceId:s,headers:l,additionalParams:c={},resource:d}){let{body:u,headers:p}=await r$({code:e,codeVerifier:t,redirectURI:r,options:i,authentication:o,tokenEndpointAuth:n,tokenEndpoint:a,deviceId:s,headers:l,additionalParams:c,resource:d}),{data:f,error:m}=await (0,rU.f)(a,{method:"POST",body:u,headers:p});if(m)throw m;return(0,re.i)(f)}e.s(["f",0,rj],661372),e.i(728895),e.s(["j",0,r$,"M",0,rB],374091);var rV=e.i(878175),rM=e.i(397554);let rF=async e=>{let{data:t}=await (0,rU.f)("https://appleid.apple.com/auth/keys");if(!t?.keys)throw new u.E("BAD_REQUEST",{message:"Keys not found"});let r=t.keys.find(t=>t.kid===e);if(!r)throw Error(`JWK with kid ${e} not found`);return await (0,rM.g)(r,r.alg)};var rK=e.i(533078);let rz="https://dash.cloudflare.com/oauth2/token",rH=e=>e.tokenEndpointAuth??{method:e.tokenEndpointAuthMethod??(e.clientSecret?"client_secret_basic":"none")},rW=async(e,t,r)=>{let i=`https://cognito-idp.${t}.amazonaws.com/${r}/.well-known/jwks.json`;try{let{data:t}=await (0,rU.f)(i);if(!t?.keys)throw new u.E("BAD_REQUEST",{message:"Keys not found"});let r=t.keys.find(t=>t.kid===e);if(!r)throw Error(`JWK with kid ${e} not found`);return await (0,rM.g)(r,r.alg)}catch(e){throw eA.y.error("Failed to fetch Cognito public key:",e),e}};var rY=e.i(550064);async function rQ(e,t){let r=(0,re.B)(t.clientId);if(!r||!t.clientSecret)return null;let i=Array.isArray(t.clientId)?t.clientId:[t.clientId],a=`${r}|${t.clientSecret}`,{data:o,error:n}=await (0,rU.f)("https://graph.facebook.com/debug_token",{query:{input_token:e,access_token:a}});if(n||!o?.data)return null;let{is_valid:s,app_id:l,user_id:c}=o.data;return!0===s&&l&&i.includes(l)&&c?c:null}let rG=(e="")=>e.split("://").map(e=>e.replace(/\/{2,}/g,"/")).join("://");e.i(741242);let rJ="RS256",rZ=[rJ],rX=(e,t)=>!e||"string"==typeof t&&!!t&&("*"===e||t===e),r0=async e=>{let[t]=await r1(e);if(!t)throw Error(`JWK with kid ${e} not found`);return t},r1=async e=>{let{data:t}=await (0,rU.f)("https://www.googleapis.com/oauth2/v3/certs");if(!t?.keys)throw new u.E("BAD_REQUEST",{message:"Keys not found"});let r=e?t.keys.filter(t=>t.kid===e):t.keys;if(!r.length)throw Error(`JWK with kid ${e} not found`);return Promise.all(r.map(e=>(0,rM.g)(e,rJ)))},r2="9188040d-6c67-4c5b-b112-36a304b66dad",r3=async(e,t,r)=>{let{data:i}=await (0,rU.f)(`${r}/${t}/discovery/v2.0/keys`);if(!i?.keys)throw new u.E("BAD_REQUEST",{message:"Keys not found"});let a=i.keys.find(t=>t.kid===e);if(!a)throw Error(`JWK with kid ${e} not found`);return await (0,rM.g)(a,a.alg??"RS256")},r6="https://backboard.railway.com/oauth/token";function r5({identifier:e,namespace:t}){let r=E.email().safeParse(`${e}@${t}.placeholder.invalid`);if(!r.success)throw TypeError("Invalid placeholder email");return r.data}e.s(["f",0,r5],339507);let r4={apple:e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",accountSubject:({profile:e})=>e.sub,async createAuthorizationURL({state:t,scopes:r,redirectURI:i,additionalParams:a,codeVerifier:o}){if(!(0,re.B)(e.clientId)||!e.clientSecret)throw eA.y.error("Client ID and client secret are required for Apple. Make sure to provide them in the options."),new u.p("CLIENT_ID_AND_SECRET_REQUIRED");let n=e.disableDefaultScope?[]:["email","name"];return e.scope&&n.push(...e.scope),r&&n.push(...r),await ry({id:"apple",options:e,authorizationEndpoint:"https://appleid.apple.com/auth/authorize",scopes:n,state:t,redirectURI:i,codeVerifier:o,responseMode:"form_post",responseType:"code id_token",additionalParams:a})},validateAuthorizationCode:async({code:r,codeVerifier:i,redirectURI:a})=>rB({code:r,codeVerifier:i,redirectURI:a,options:e,tokenEndpoint:t}),idToken:{jwks:e=>rF(e.kid),issuer:"https://appleid.apple.com",algorithms:["RS256"],audience:e.audience&&e.audience.length?e.audience:e.appBundleIdentifier?e.appBundleIdentifier:e.clientId,maxTokenAge:"1h",nonceComparison:"exact-or-sha256"},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>rj({refreshToken:r,options:e,tokenEndpoint:t}),async getUserInfo(t){let r;if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let i=(0,rV.f)(t.idToken);if(!i)return null;r=t.user?.name?`${t.user.name.firstName||""} ${t.user.name.lastName||""}`.trim():i.name||"";let a="boolean"==typeof i.email_verified?i.email_verified:"true"===i.email_verified,o={...i,name:r},n=await e.mapProfileToUser?.(o);return{user:{name:o.name,emailVerified:a,email:i.email,...n},data:o}},options:e}},atlassian:e=>{let t="https://auth.atlassian.com/oauth/token";return{id:"atlassian",name:"Atlassian",accountSubject:({profile:e})=>e.account_id,async createAuthorizationURL({state:t,scopes:r,codeVerifier:i,redirectURI:a,additionalParams:o}){if(!e.clientId||!e.clientSecret)throw eA.y.error("Client Id and Secret are required for Atlassian"),new u.p("CLIENT_ID_AND_SECRET_REQUIRED");if(!i)throw new u.p("codeVerifier is required for Atlassian");let n=e.disableDefaultScope?[]:["read:jira-user","offline_access"];return e.scope&&n.push(...e.scope),r&&n.push(...r),ry({id:"atlassian",options:e,authorizationEndpoint:"https://auth.atlassian.com/authorize",scopes:n,state:t,codeVerifier:i,redirectURI:a,additionalParams:{...o??{},audience:"api.atlassian.com"},prompt:e.prompt})},validateAuthorizationCode:async({code:r,codeVerifier:i,redirectURI:a})=>rB({code:r,codeVerifier:i,redirectURI:a,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>rj({refreshToken:r,options:{clientId:e.clientId,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.accessToken)return null;try{let{data:r}=await (0,rK.f)("https://api.atlassian.com/me",{headers:{Authorization:`Bearer ${t.accessToken}`}});if(!r)return null;let i=await e.mapProfileToUser?.(r);return{user:{name:r.name,email:r.email,image:r.picture,emailVerified:!1,...i},data:r}}catch(e){return eA.y.error("Failed to fetch user info from Atlassian:",e),null}},options:e}},cloudflare:e=>({id:"cloudflare",name:"Cloudflare",accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:r,codeVerifier:i,redirectURI:a}){let o=e.disableDefaultScope?[]:["user-details.read"];return e.scope?.length&&o.push(...e.scope),r?.length&&o.push(...r),ry({id:"cloudflare",options:e,authorizationEndpoint:"https://dash.cloudflare.com/oauth2/auth",scopes:o.length?[...new Set(o)]:void 0,state:t,codeVerifier:i,redirectURI:a})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:i})=>rB({code:t,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:rz,tokenEndpointAuth:rH(e)}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>rj({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:rz,tokenEndpointAuth:rH(e)}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:i}=await (0,rK.f)("https://api.cloudflare.com/client/v4/user",{headers:{authorization:`Bearer ${t.accessToken}`}});if(i||!r?.success||!r.result)return eA.y.error("Failed to fetch user info from Cloudflare:",i??r?.errors),null;let a=r.result,o=[a.first_name,a.last_name].filter(Boolean).join(" ")||a.email,n=await e.mapProfileToUser?.(a);return{user:{name:o,email:a.email,emailVerified:!1,...n},data:a}},options:e}),cognito:e=>{if(!e.domain||!e.region||!e.userPoolId)throw eA.y.error("Domain, region and userPoolId are required for Amazon Cognito. Make sure to provide them in the options."),new u.p("DOMAIN_AND_REGION_REQUIRED");let t=e.domain.replace(/^https?:\/\//,""),r=`https://${t}/oauth2/authorize`,i=`https://${t}/oauth2/token`,a=`https://${t}/oauth2/userinfo`;return{id:"cognito",name:"Cognito",accountSubject:({profile:e})=>e.sub,async createAuthorizationURL({state:t,scopes:i,codeVerifier:a,redirectURI:o,additionalParams:n}){if(!(0,re.B)(e.clientId))throw eA.y.error("ClientId is required for Amazon Cognito. Make sure to provide them in the options."),new u.p("CLIENT_ID_AND_SECRET_REQUIRED");if(e.requireClientSecret&&!e.clientSecret)throw eA.y.error("Client Secret is required when requireClientSecret is true. Make sure to provide it in the options."),new u.p("CLIENT_SECRET_REQUIRED");let s=e.disableDefaultScope?[]:["openid","profile","email"];e.scope&&s.push(...e.scope),i&&s.push(...i);let l=await ry({id:"cognito",options:{...e},authorizationEndpoint:r,scopes:s,state:t,codeVerifier:a,redirectURI:o,prompt:e.prompt,additionalParams:{...e.identityProvider?{identity_provider:e.identityProvider}:{},...n??{}}}),c=l.searchParams.get("scope");if(c){l.searchParams.delete("scope");let e=encodeURIComponent(c),t=l.toString(),r=t.includes("?")?"&":"?";return new URL(`${t}${r}scope=${e}`)}return l},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:a})=>rB({code:t,codeVerifier:r,redirectURI:a,options:e,tokenEndpoint:i}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>rj({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:i}),idToken:{jwks:t=>rW(t.kid,e.region,e.userPoolId),issuer:`https://cognito-idp.${e.region}.amazonaws.com/${e.userPoolId}`,audience:e.clientId,algorithms:["RS256"],maxTokenAge:"1h"},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(t.idToken)try{let r=(0,rV.f)(t.idToken);if(!r)return null;let i=r.name||r.given_name||r.username||"",a={...r,name:i},o=await e.mapProfileToUser?.(a);return{user:{name:a.name,email:r.email,image:r.picture,emailVerified:r.email_verified,...o},data:a}}catch(e){eA.y.error("Failed to decode ID token:",e)}if(t.accessToken)try{let{data:r}=await (0,rK.f)(a,{headers:{Authorization:`Bearer ${t.accessToken}`}});if(r){let t=await e.mapProfileToUser?.(r);return{user:{name:r.name||r.given_name||r.username||"",email:r.email,image:r.picture,emailVerified:(0,re.r)(r.email_verified),...t},data:r}}}catch(e){eA.y.error("Failed to fetch user info from Cognito:",e)}return null},options:e}},discord:e=>{let t="https://discord.com/api/oauth2/token";return{id:"discord",name:"Discord",accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:r,redirectURI:i,additionalParams:a}){let o=e.disableDefaultScope?[]:["identify","email"];r&&o.push(...r),e.scope&&o.push(...e.scope);let n=o.includes("bot");return ry({id:"discord",options:e,authorizationEndpoint:"https://discord.com/api/oauth2/authorize",scopes:o,state:t,redirectURI:i,prompt:e.prompt||"none",additionalParams:{...n&&void 0!==e.permissions?{permissions:String(e.permissions)}:{},...a??{}}})},validateAuthorizationCode:async({code:r,redirectURI:i})=>rB({code:r,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>rj({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:i}=await (0,rK.f)("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(i)return null;if(null===r.avatar)r.image_url=`https://cdn.discordapp.com/embed/avatars/${"0"===r.discriminator?Number(BigInt(r.id)>>BigInt(22))%6:parseInt(r.discriminator)%5}.png`;else{let e=r.avatar.startsWith("a_")?"gif":"png";r.image_url=`https://cdn.discordapp.com/avatars/${r.id}/${r.avatar}.${e}`}let a=await e.mapProfileToUser?.(r);return{user:{name:r.global_name||r.username||"",email:r.email,emailVerified:r.verified,image:r.image_url,...a},data:r}},options:e}},facebook:e=>({id:"facebook",name:"Facebook",accountSubject:({profile:e})=>"sub"in e?e.sub:e.id,async createAuthorizationURL({state:t,scopes:r,redirectURI:i,loginHint:a,additionalParams:o}){if(!(0,re.B)(e.clientId)||!e.clientSecret)throw eA.y.error("Client ID and client secret are required for Facebook. Make sure to provide them in the options."),new u.p("CLIENT_ID_AND_SECRET_REQUIRED");let n=e.disableDefaultScope?[]:["email","public_profile"];return e.scope&&n.push(...e.scope),r&&n.push(...r),await ry({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v24.0/dialog/oauth",scopes:n,state:t,redirectURI:i,loginHint:a,additionalParams:{...e.configId?{config_id:e.configId}:{},...o??{}}})},validateAuthorizationCode:async({code:t,redirectURI:r})=>rB({code:t,redirectURI:r,options:e,tokenEndpoint:"https://graph.facebook.com/v24.0/oauth/access_token"}),idToken:{jwks:(0,rY.R)(new URL("https://limited.facebook.com/.well-known/oauth/openid/jwks/")),issuer:"https://www.facebook.com",audience:e.clientId,algorithms:["RS256"],allowOpaqueToken:!0},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>rj({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:"https://graph.facebook.com/v24.0/oauth/access_token"}),async getUserInfo(t){if(e.getUserInfo){let r=!!t.idToken&&3!==t.idToken.split(".").length,i=t.accessToken||(r?t.idToken:void 0);return i&&!await rQ(i,e)?null:e.getUserInfo(t)}if(t.idToken&&3===t.idToken.split(".").length){let r=(0,rV.f)(t.idToken),i=await e.mapProfileToUser?.(r);return{user:{name:r.name,email:r.email,image:r.picture,emailVerified:!1,...i},data:r}}let r=t.accessToken;if(!r)return null;let i=await rQ(r,e);if(!i)return null;let a=["id","name","email","picture",...e?.fields||[]],{data:o,error:n}=await (0,rK.f)("https://graph.facebook.com/me?fields="+a.join(","),{auth:{type:"Bearer",token:r}});if(n||o.id!==i)return null;let s=await e.mapProfileToUser?.(o);return{user:{name:o.name,email:o.email,image:o.picture.data.url,emailVerified:o.email_verified??!1,...s},data:o}},options:e}),figma:e=>{let t="https://api.figma.com/v1/oauth/token";return{id:"figma",name:"Figma",accountSubject:({profile:e})=>e.id,async createAuthorizationURL({state:t,scopes:r,codeVerifier:i,redirectURI:a,additionalParams:o}){if(!e.clientId||!e.clientSecret)throw eA.y.error("Client Id and Client Secret are required for Figma. Make sure to provide them in the options."),new u.p("CLIENT_ID_AND_SECRET_REQUIRED");if(!i)throw new u.p("codeVerifier is required for Figma");let n=e.disableDefaultScope?[]:["current_user:read"];return e.scope&&n.push(...e.scope),r&&n.push(...r),await ry({id:"figma",options:e,authorizationEndpoint:"https://www.figma.com/oauth",scopes:n,state:t,codeVerifier:i,redirectURI:a,additionalParams:o})},validateAuthorizationCode:async({code:r,codeVerifier:i,redirectURI:a})=>rB({code:r,codeVerifier:i,redirectURI:a,options:e,tokenEndpoint:t,authentication:"basic"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>rj({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t,authentication:"basic"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);try{let{data:r}=await (0,rK.f)("https://api.figma.com/v1/me",{headers:{Authorization:`Bearer ${t.accessToken}`}});if(!r)return eA.y.error("Failed to fetch user from Figma"),null;let i=await e.mapProfileToUser?.(r);return{user:{name:r.handle,email:r.email,image:r.img_url,emailVerified:!1,...i},data:r}}catch(e){return eA.y.error("Failed to fetch user info from Figma:",e),null}},options:e}},github:e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:r,loginHint:i,codeVerifier:a,redirectURI:o,additionalParams:n}){let s=e.disableDefaultScope?[]:["read:user","user:email"];return e.scope&&s.push(...e.scope),r&&s.push(...r),ry({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:t,codeVerifier:a,redirectURI:o,loginHint:i,prompt:e.prompt,additionalParams:n})},validateAuthorizationCode:async({code:r,codeVerifier:i,redirectURI:a})=>{let{body:o,headers:n}=await r$({code:r,codeVerifier:i,redirectURI:a,options:e}),{data:s,error:l}=await (0,rU.f)(t,{method:"POST",body:o,headers:n});return l?(eA.y.error("GitHub OAuth token exchange failed:",l),null):"error"in s?(eA.y.error("GitHub OAuth token exchange failed:",s),null):(0,re.i)(s)},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>rj({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:i}=await (0,rK.f)("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${t.accessToken}`}});if(i)return null;let{data:a}=await (0,rK.f)("https://api.github.com/user/emails",{headers:{Authorization:`Bearer ${t.accessToken}`,"User-Agent":"better-auth"}});!r.email&&a&&(r.email=(a.find(e=>e.primary)??a[0])?.email);let o=a?.find(e=>e.email===r.email)?.verified??!1,n=await e.mapProfileToUser?.(r);return{user:{name:r.name||r.login||"",email:r.email,image:r.avatar_url,emailVerified:o,...n},data:r}},options:e}},microsoft:e=>{let t=e.tenantId||"common",r=e.authority||"https://login.microsoftonline.com";for(;r.endsWith("/");)r=r.slice(0,-1);let i=`${r}/${t}/oauth2/v2.0/authorize`,a=`${r}/${t}/oauth2/v2.0/token`;if(e.clientSecret&&e.clientAssertion)throw new u.p("Microsoft Entra ID clientAssertion cannot be combined with clientSecret");let o=e.clientAssertion?{method:"private_key_jwt",getClientAssertion:e.clientAssertion}:void 0;return{id:"microsoft",name:"Microsoft EntraID",accountSubject:({profile:e})=>e.oid,createAuthorizationURL(t){if(!(0,re.B)(e.clientId))throw eA.y.error("Client Id is required for Microsoft Entra ID. Make sure to provide it in the options."),new u.p("CLIENT_ID_AND_SECRET_REQUIRED");let r=e.disableDefaultScope?[]:["openid","profile","email","User.Read","offline_access"];return e.scope&&r.push(...e.scope),t.scopes&&r.push(...t.scopes),ry({id:"microsoft",options:e,authorizationEndpoint:i,state:t.state,codeVerifier:t.codeVerifier,scopes:r,redirectURI:t.redirectURI,prompt:e.prompt,loginHint:t.loginHint,additionalParams:t.additionalParams})},validateAuthorizationCode:({code:t,codeVerifier:r,redirectURI:i})=>rB({code:t,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:a,tokenEndpointAuth:o}),idToken:{jwks:e=>r3(e.kid,t,r),algorithms:["RS256"],audience:e.clientId,maxTokenAge:"1h",issuer:"common"!==t&&"organizations"!==t&&"consumers"!==t?`${r}/${t}/v2.0`:void 0,verifyClaims:e=>{let i=e.tid;return"string"==typeof i&&e.iss===`${r}/${i}/v2.0`&&("organizations"!==t||i!==r2)&&("consumers"!==t||i===r2)}},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let r=(0,rV.f)(t.idToken);if("string"!=typeof r.oid||0===r.oid.trim().length)return eA.y.error("Microsoft Entra ID token did not include a valid oid claim; unable to resolve a stable account identifier."),null;let i=e.profilePhotoSize||48;!e.disableProfilePhoto&&t.accessToken&&await (0,rK.f)(`https://graph.microsoft.com/v1.0/me/photos/${i}x${i}/$value`,{headers:{Authorization:`Bearer ${t.accessToken}`},async onResponse(e){if(e.response.ok)try{let t=await e.response.clone().arrayBuffer(),i=c.t.encode(t);r.picture=`data:image/jpeg;base64, ${i}`}catch(e){eA.y.error(e&&"object"==typeof e&&"name"in e?e.name:"",e)}}});let a=await e.mapProfileToUser?.(r),o=void 0!==r.email_verified?(0,re.r)(r.email_verified):!!(r.email&&(r.verified_primary_email?.includes(r.email)||r.verified_secondary_email?.includes(r.email)));return{user:{name:r.name,email:r.email,image:r.picture,emailVerified:o,...a},data:r}},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>{let r=e.disableDefaultScope?[]:["openid","profile","email","User.Read","offline_access"];return e.scope&&r.push(...e.scope),rj({refreshToken:t,options:{clientId:e.clientId,clientSecret:e.clientSecret},extraParams:{scope:r.join(" ")},tokenEndpoint:a,tokenEndpointAuth:o})},options:e}},google:e=>({id:"google",name:"Google",accountSubject:({profile:e})=>e.sub,async createAuthorizationURL({state:t,scopes:r,codeVerifier:i,redirectURI:a,loginHint:o,display:n,additionalParams:s}){if(!(0,re.B)(e.clientId)||!e.clientSecret)throw eA.y.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new u.p("CLIENT_ID_AND_SECRET_REQUIRED");if(!i)throw new u.p("codeVerifier is required for Google");let l=e.disableDefaultScope?[]:["email","profile","openid"];return e.scope&&l.push(...e.scope),r&&l.push(...r),await ry({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/v2/auth",scopes:l,state:t,codeVerifier:i,redirectURI:a,prompt:e.prompt,accessType:e.accessType,display:n||e.display,loginHint:o,hd:e.hd,additionalParams:{...!1===e.includeGrantedScopes?{}:{include_granted_scopes:"true"},...s??{}}})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:i})=>rB({code:t,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>rj({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:"https://oauth2.googleapis.com/token"}),idToken:{jwks:e=>r0(e.kid),issuer:["https://accounts.google.com","accounts.google.com"],audience:e.clientId,algorithms:rZ,maxTokenAge:"1h",verifyClaims:e.hd?t=>rX(e.hd,t.hd):void 0},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let r=(0,rV.f)(t.idToken);if(!rX(e.hd,r.hd))return eA.y.error(`Google sign-in rejected: id token hosted domain (hd) "${r.hd??"<missing>"}" does not satisfy the configured "hd" option "${e.hd}".`),null;let i=await e.mapProfileToUser?.(r);return{user:{name:r.name,email:r.email,image:r.picture,emailVerified:r.email_verified,...i},data:r}},options:e}),huggingface:e=>{let t="https://huggingface.co/oauth/token";return{id:"huggingface",name:"Hugging Face",accountSubject:({profile:e})=>e.sub,createAuthorizationURL({state:t,scopes:r,codeVerifier:i,redirectURI:a,additionalParams:o}){let n=e.disableDefaultScope?[]:["openid","profile","email"];return e.scope&&n.push(...e.scope),r&&n.push(...r),ry({id:"huggingface",options:e,authorizationEndpoint:"https://huggingface.co/oauth/authorize",scopes:n,state:t,codeVerifier:i,redirectURI:a,additionalParams:o})},validateAuthorizationCode:async({code:r,codeVerifier:i,redirectURI:a})=>rB({code:r,codeVerifier:i,redirectURI:a,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>rj({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:i}=await (0,rK.f)("https://huggingface.co/oauth/userinfo",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(i)return null;let a=await e.mapProfileToUser?.(r);return{user:{name:r.name||r.preferred_username||"",email:r.email,image:r.picture,emailVerified:r.email_verified??!1,...a},data:r}},options:e}},slack:e=>{let t="https://slack.com/api/openid.connect.token";return{id:"slack",name:"Slack",accountSubject:({profile:e})=>e["https://slack.com/user_id"],createAuthorizationURL({state:t,scopes:r,redirectURI:i,additionalParams:a}){let o=e.disableDefaultScope?[]:["openid","profile","email"];return r&&o.push(...r),e.scope&&o.push(...e.scope),ry({id:"slack",options:e,authorizationEndpoint:"https://slack.com/openid/connect/authorize",scopes:o,state:t,redirectURI:i,additionalParams:a})},validateAuthorizationCode:async({code:r,redirectURI:i})=>rB({code:r,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>rj({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:i}=await (0,rK.f)("https://slack.com/api/openid.connect.userInfo",{headers:{authorization:`Bearer ${t.accessToken}`}});if(i)return null;let a=await e.mapProfileToUser?.(r);return{user:{name:r.name||"",email:r.email,emailVerified:r.email_verified,image:r.picture||r["https://slack.com/user_image_512"],...a},data:r}},options:e}},spotify:e=>{let t="https://accounts.spotify.com/api/token";return{id:"spotify",name:"Spotify",accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:r,codeVerifier:i,redirectURI:a,additionalParams:o}){let n=e.disableDefaultScope?[]:["user-read-email"];return e.scope&&n.push(...e.scope),r&&n.push(...r),ry({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:n,state:t,codeVerifier:i,redirectURI:a,additionalParams:o})},validateAuthorizationCode:async({code:r,codeVerifier:i,redirectURI:a})=>rB({code:r,codeVerifier:i,redirectURI:a,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>rj({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:i}=await (0,rK.f)("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(i)return null;let a=await e.mapProfileToUser?.(r);return{user:{name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1,...a},data:r}},options:e}},twitch:e=>{let t="https://id.twitch.tv/oauth2/token";return{id:"twitch",name:"Twitch",accountSubject:({profile:e})=>e.sub,createAuthorizationURL({state:t,scopes:r,redirectURI:i,additionalParams:a}){let o=e.disableDefaultScope?[]:["user:read:email","openid"];return e.scope&&o.push(...e.scope),r&&o.push(...r),ry({id:"twitch",redirectURI:i,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:o,state:t,claims:e.claims||["email","email_verified","preferred_username","picture"],additionalParams:a})},validateAuthorizationCode:async({code:r,redirectURI:i})=>rB({code:r,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>rj({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let r=t.idToken;if(!r)return eA.y.error("No idToken found in token"),null;let i=(0,rV.f)(r),a=await e.mapProfileToUser?.(i);return{user:{name:i.preferred_username,email:i.email,image:i.picture,emailVerified:i.email_verified,...a},data:i}},options:e}},twitter:e=>{let t="https://api.x.com/2/oauth2/token";return{id:"twitter",name:"Twitter",accountSubject:({profile:e})=>e.data.id,createAuthorizationURL(t){let r=e.disableDefaultScope?[]:["users.read","tweet.read","offline.access","users.email"];return e.scope&&r.push(...e.scope),t.scopes&&r.push(...t.scopes),ry({id:"twitter",options:e,authorizationEndpoint:"https://x.com/i/oauth2/authorize",scopes:r,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI,additionalParams:t.additionalParams})},validateAuthorizationCode:async({code:r,codeVerifier:i,redirectURI:a})=>rB({code:r,codeVerifier:i,authentication:"basic",redirectURI:a,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>rj({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},authentication:"basic",tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:i}=await (0,rK.f)("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(i)return null;let{data:a,error:o}=await (0,rK.f)("https://api.x.com/2/users/me?user.fields=confirmed_email",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}}),n=!1;!o&&a?.data?.confirmed_email&&(r.data.email=a.data.confirmed_email,n=!0);let s=await e.mapProfileToUser?.(r);return{user:{name:r.data.name,email:r.data.email||r5({identifier:r.data.id,namespace:"twitter"}),image:r.data.profile_image_url,emailVerified:n,...s},data:r}},options:e}},dropbox:e=>{let t="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",accountSubject:({profile:e})=>e.account_id,createAuthorizationURL:async({state:t,scopes:r,codeVerifier:i,redirectURI:a,additionalParams:o})=>{let n=e.disableDefaultScope?[]:["account_info.read"];return e.scope&&n.push(...e.scope),r&&n.push(...r),await ry({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:n,state:t,redirectURI:a,codeVerifier:i,additionalParams:{...e.accessType?{token_access_type:e.accessType}:{},...o??{}}})},validateAuthorizationCode:async({code:r,codeVerifier:i,redirectURI:a})=>await rB({code:r,codeVerifier:i,redirectURI:a,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>rj({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:i}=await (0,rK.f)("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${t.accessToken}`}});if(i)return null;let a=await e.mapProfileToUser?.(r);return{user:{name:r.name?.display_name,email:r.email,emailVerified:r.email_verified||!1,image:r.profile_photo_url,...a},data:r}},options:e}},kick:e=>({id:"kick",name:"Kick",accountSubject:({profile:e})=>e.user_id,createAuthorizationURL({state:t,scopes:r,redirectURI:i,codeVerifier:a,additionalParams:o}){let n=e.disableDefaultScope?[]:["user:read"];return e.scope&&n.push(...e.scope),r&&n.push(...r),ry({id:"kick",redirectURI:i,options:e,authorizationEndpoint:"https://id.kick.com/oauth/authorize",scopes:n,codeVerifier:a,state:t,additionalParams:o})},validateAuthorizationCode:async({code:t,redirectURI:r,codeVerifier:i})=>rB({code:t,redirectURI:r,options:e,tokenEndpoint:"https://id.kick.com/oauth/token",codeVerifier:i}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>rj({refreshToken:t,options:{clientId:e.clientId,clientSecret:e.clientSecret},tokenEndpoint:"https://id.kick.com/oauth/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:i}=await (0,rK.f)("https://api.kick.com/public/v1/users",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(i)return null;let a=r.data[0],o=await e.mapProfileToUser?.(a);return{user:{name:a.name,email:a.email,image:a.profile_picture,emailVerified:!1,...o},data:a}},options:e}),linear:e=>{let t="https://api.linear.app/oauth/token";return{id:"linear",name:"Linear",accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:r,loginHint:i,redirectURI:a,additionalParams:o}){let n=e.disableDefaultScope?[]:["read"];return e.scope&&n.push(...e.scope),r&&n.push(...r),ry({id:"linear",options:e,authorizationEndpoint:"https://linear.app/oauth/authorize",scopes:n,state:t,redirectURI:a,loginHint:i,additionalParams:o})},validateAuthorizationCode:async({code:r,redirectURI:i})=>rB({code:r,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>rj({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:i}=await (0,rK.f)("https://api.linear.app/graphql",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.accessToken}`},body:JSON.stringify({query:`
|
|
94
|
+
`,`Current list of trustedOrigins: ${l}`),u.E.from("FORBIDDEN",tf.f.INVALID_ORIGIN)}let tU=(0,s.a)(async e=>{e.request&&await tR(e)});async function tR(e){let t=e.request;if(!t||e.context.skipCSRFCheck||tA(e))return;let r=t.headers;if(r.has("cookie"))return await tv(e);let i=r.get("Sec-Fetch-Site"),a=r.get("Sec-Fetch-Mode"),o=r.get("Sec-Fetch-Dest");if(i&&i.trim()||a&&a.trim()||o&&o.trim()){if("cross-site"===i&&"navigate"===a)throw e.context.logger.error("Blocked cross-site navigation login attempt (CSRF protection)",{secFetchSite:i,secFetchMode:a,secFetchDest:o}),u.E.from("FORBIDDEN",tf.f.CROSS_SITE_NAVIGATION_LOGIN_BLOCKED);return await tv(e,!0)}if(r.get("origin")||r.get("referer"))return await tv(e,!0)}let tS=new Map;function tx(e,t){return Math.ceil((e+1e3*t-Date.now())/1e3)}let tO=!1;async function tD(e,t){let r=new URL(t.baseURL).pathname,i=(0,tE.s)(e.url,r),a=t.rateLimit.window,o=t.rateLimit.max,n=(0,l.M)(e,t.options);if(!n&&t.options.advanced?.ipAddress?.disableIpTracking)return null;n||tO||(t.logger.warn("Rate limiting could not determine a client IP and is falling back to a single shared per-path bucket. Ensure your runtime forwards a trusted client IP header, then set `advanced.ipAddress.ipAddressHeaders` or `advanced.ipAddress.trustedProxies` so the address can be resolved."),tO=!0);let s=(0,l.q)(n??"no-trusted-ip",i),c=tL().find(e=>e.pathMatcher(i));for(let e of(c&&(a=c.window,o=c.max),t.options.plugins||[]))if(e.rateLimit){let t=e.rateLimit.find(e=>e.pathMatcher(i));if(t){a=t.window,o=t.max;break}}if(t.rateLimit.customRules){let r=Object.keys(t.rateLimit.customRules).find(e=>e.includes("*")?(0,eM.f)(e)(i):e===i);if(r){let i=t.rateLimit.customRules[r],n="function"==typeof i?await i(e,{window:a,max:o}):i;if(n&&(a=n.window,o=n.max),!1===n)return null}}return{key:s,currentWindow:a,currentMax:o}}async function tN(e,t){if(!t.rateLimit.enabled)return;let r=await tD(e,t);if(!r)return;let{key:i,currentWindow:a,currentMax:o}=r,n=function(e){let t,r,i,a,o,n;if(e.options.rateLimit?.customStorage)return e.options.rateLimit.customStorage;let s=e.rateLimit.storage;if("secondary-storage"===s){let t=e.options.secondaryStorage?.increment;if(!t)throw new u.p("Secondary-storage rate limiting requires SecondaryStorage.increment.");return{consume:async(r,i)=>await t(r,i.window??e.options.rateLimit?.window??10)<=i.max?{allowed:!0,retryAfter:null}:{allowed:!1,retryAfter:i.window}}}return"memory"===s?{async consume(t,r){var i;let a;!function(){let e=Date.now();for(let[t,r]of tS)e>=r.expiresAt&&tS.delete(t);if(tS.size<=1e5)return;let t=tS.size-1e5,r=0;for(let e of tS.keys())if(tS.delete(e),++r>=t)break}();let o=Date.now(),n=tS.get(t),s=(i=n&&o<n.expiresAt?n.data:void 0,a=1e3*r.window,i?o-i.lastRequest>=a?{next:{...i,count:1,lastRequest:o},update:!0,allowed:!0,retryAfter:null}:i.count>=r.max?{next:i,update:!0,allowed:!1,retryAfter:tx(i.lastRequest,r.window)}:{next:{...i,count:i.count+1,lastRequest:o},update:!0,allowed:!0,retryAfter:null}:{next:{key:"",count:1,lastRequest:o},update:!1,allowed:!0,retryAfter:null});return s.allowed&&tS.set(t,{data:{...s.next,key:t},expiresAt:o+1e3*(r.window??e.options.rateLimit?.window??10)}),{allowed:s.allowed,retryAfter:s.retryAfter}}}:(t="rateLimit",r=e.adapter,i=Math.max(...function(e){let t=[e.rateLimit.window,...tL().map(e=>e.window)];for(let r of e.options.plugins||[])r.rateLimit&&t.push(...r.rateLimit.map(e=>e.window));if(e.rateLimit.customRules)for(let r of Object.values(e.rateLimit.customRules))r&&"function"!=typeof r&&t.push(r.window);let r=t.filter(e=>Number.isFinite(e)&&e>0);return r.length>0?r:[e.rateLimit.window]}(e)),a=async e=>{let i=(await r.findMany({model:t,where:[{field:"key",value:e}]}))[0];return i&&(i.lastRequest=Number(i.lastRequest)),i},o=async(e,s)=>{s.window>i&&(i=s.window);let l=1e3*s.window,c=await a(e),d=Date.now();if(!c)try{return await r.create({model:t,data:{key:e,count:1,lastRequest:d}}),{allowed:!0,retryAfter:null}}catch(t){if(!await a(e))throw t;return o(e,s)}if(d-c.lastRequest>=l)return await r.incrementOne({model:t,where:[{field:"key",value:e},{field:"lastRequest",operator:"lte",value:c.lastRequest}],increment:{},set:{count:1,lastRequest:d}})?(await n(d),{allowed:!0,retryAfter:null}):o(e,s);let u=d-l;if(await r.incrementOne({model:t,where:[{field:"key",value:e},{field:"lastRequest",operator:"gt",value:u},{field:"count",operator:"lt",value:s.max}],increment:{count:1},set:{lastRequest:d}}))return{allowed:!0,retryAfter:null};let p=await a(e);return!p||d-p.lastRequest>=l?o(e,s):{allowed:!1,retryAfter:tx(p.lastRequest,s.window)}},n=async a=>{let o=a-1e3*i;await e.runInBackgroundOrAwait(r.deleteMany({model:t,where:[{field:"lastRequest",operator:"lt",value:o}]}).then(()=>void 0).catch(t=>e.logger.error("Error pruning rate limit rows",t)))},{consume:o})}(t),{allowed:s,retryAfter:l}=await n.consume(i,{window:a,max:o});if(!s){var c;return c=l??a,new Response(JSON.stringify({message:"Too many requests. Please try again later."}),{status:429,statusText:"Too Many Requests",headers:{"Content-Type":"application/json","X-Retry-After":c.toString()}})}}function tL(){return[{pathMatcher:e=>e.startsWith("/sign-in")||e.startsWith("/sign-up")||e.startsWith("/change-password")||e.startsWith("/change-email"),window:10,max:3},{pathMatcher:e=>"/request-password-reset"===e||"/send-verification-email"===e||e.startsWith("/forget-password")||"/email-otp/send-verification-otp"===e||"/email-otp/request-password-reset"===e,window:60,max:3}]}e.i(682868);var tP=e.i(826719),tC=e.i(805650),tq=e.i(496161),tj=e.i(869381),t$=e.i(1083),tB=e.i(697858);let tV=(0,tB.k)("better-auth:oauth-encryption:v1");function tM(e,t){return(0,tB.w)((0,tj.f)(t$.E,(0,tB.k)(e),tV,(0,tB.k)(`better-auth:${t}:v1`),32))}function tF(e,t){return"string"==typeof e?tM(e,t):{keys:new Map(Array.from(e.keys,([e,r])=>[e,tM(r,t)])),currentVersion:e.currentVersion,...e.legacySecret&&{legacySecret:tM(e.legacySecret,t)}}}async function tK(e,t,r){let i=e.accountSubject,a=await i({tokens:t,profile:r}),o=String(a);if("number"==typeof a&&!Number.isFinite(a)||0===o.trim().length||"undefined"===o||"null"===o)throw new u.p("OAUTH_ACCOUNT_SUBJECT_INVALID");return{providerId:e.id,accountId:o}}async function tz(e,t,r){try{return await tK(e,t,r)}catch{throw u.E.from("UNAUTHORIZED",tf.f.FAILED_TO_GET_USER_INFO)}}let tH="invalid_code",tW="unable_to_get_user_info",tY="unable_to_link_account",tQ="email_not_verified";function tG(e,t,r,i){let a=new URLSearchParams({error:r});i&&a.set("error_description",i);let o=(0,tE.M)(t,a);throw e.redirect(o)}function tJ(e,t){return`${t?.source==="generic"?`Generic OAuth provider "${e}"`:`Provider "${e}"`} did not return an email${t?.source==="id_token"?" in the id token":""}. Either request the provider's email scope, or create a placeholder via \`mapProfileToUser\`. See https://www.better-auth.com/docs/concepts/oauth#handling-providers-without-email`}function tZ(e){return"true"===e||!0===e}function tX(e,t){if(!e)return e;if(t.options.account?.encryptOAuthTokens)return e.startsWith("$ba$")||e.length%2==0&&/^[0-9a-f]+$/i.test(e)?(0,tC.u)({key:t.secretConfig,data:e}):e;return e}function t0(e,t){return t.options.account?.encryptOAuthTokens&&e?(0,tC.M)({key:t.secretConfig,data:e}):e}function t1(e){return e.callbackPath?e.callbackPath.startsWith("/")?e.callbackPath:`/${e.callbackPath}`:`/callback/${e.id}`}e.s(["f",0,tZ],342e3);var t2=e.i(375742);function t3(e){if(e)try{return e.clone()}catch{return new Request(e.url,{cache:e.cache,credentials:e.credentials,headers:e.headers,integrity:e.integrity,keepalive:e.keepalive,method:e.method,mode:e.mode,redirect:e.redirect,referrer:e.referrer,referrerPolicy:e.referrerPolicy,signal:e.signal})}}var t6=e.i(709939),t5=e.i(865466);async function t4(e,t,r,i=3600,a){return await (0,t2.X)({email:t.toLowerCase(),updateTo:r?.toLowerCase(),...a},e,i)}async function t7(e,t){if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),u.E.from("BAD_REQUEST",tf.f.VERIFICATION_EMAIL_NOT_ENABLED);let r=await t4(e.context.secret,t.email,void 0,e.context.options.emailVerification?.expiresIn,{userId:t.id}),i=e.body.callbackURL?encodeURIComponent(e.body.callbackURL):encodeURIComponent("/"),a=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${i}`;await e.context.options.emailVerification.sendVerificationEmail({user:t,url:a,token:r},e.request)}let t8=(0,s.g)("/send-verification-email",{method:"POST",operationId:"sendVerificationEmail",cloneRequest:!0,body:E.object({email:E.email().meta({description:"The email to send the verification email to"}),callbackURL:E.string().meta({description:"The URL to use for email verification callback"}).optional()}),metadata:{openapi:{operationId:"sendVerificationEmail",description:"Send a verification email to the user",requestBody:{content:{"application/json":{schema:{type:"object",properties:{email:{type:"string",description:"The email to send the verification email to",example:"user@example.com"},callbackURL:{type:"string",description:"The URL to use for email verification callback",example:"https://example.com/callback",nullable:!0}},required:["email"]}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean",description:"Indicates if the email was sent successfully",example:!0}}}}}},400:{description:"Bad Request",content:{"application/json":{schema:{type:"object",properties:{message:{type:"string",description:"Error message",example:"Verification email isn't enabled"}}}}}}}}}},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),u.E.from("BAD_REQUEST",tf.f.VERIFICATION_EMAIL_NOT_ENABLED);let{email:t}=e.body,r=await (0,p.D)(e);if(!r){let r,i=Date.now(),a=await e.context.internalAdapter.findUserByEmail(t);if(!a||a.user.emailVerified)await t4(e.context.secret,t,void 0,e.context.options.emailVerification?.expiresIn);else try{await t7(e,a.user)}catch(e){r=e}let o=500-(Date.now()-i);if(o>0&&await new Promise(e=>setTimeout(e,o)),r)throw r;return e.json({status:!0})}if(r?.user.email.toLowerCase()!==t.toLowerCase())throw u.E.from("BAD_REQUEST",tf.f.EMAIL_MISMATCH);if(r?.user.emailVerified)throw u.E.from("BAD_REQUEST",tf.f.EMAIL_ALREADY_VERIFIED);return await t7(e,r.user),e.json({status:!0})}),t9=(0,s.g)("/verify-email",{method:"GET",operationId:"verifyEmail",query:E.object({token:E.string().meta({description:"The token to verify the email"}),callbackURL:E.string().meta({description:"The URL to redirect to after email verification"}).optional()}),use:[tT(e=>e.query.callbackURL)],metadata:{openapi:{description:"Verify the email of the user",parameters:[{name:"token",in:"query",description:"The token to verify the email",required:!0,schema:{type:"string"}},{name:"callbackURL",in:"query",description:"The URL to redirect to after email verification",required:!1,schema:{type:"string"}}],responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object",$ref:"#/components/schemas/User"},status:{type:"boolean",description:"Indicates if the email was verified successfully"}},required:["user","status"]}}}}}}}},async e=>{let t;function r(t){if(e.query.callbackURL){let r=new URLSearchParams({error:t.code}),i=(0,tE.M)(e.query.callbackURL,r);throw e.redirect(i)}throw u.E.from("UNAUTHORIZED",t)}let{token:i}=e.query;try{t=await (0,t6.f)(i,new TextEncoder().encode(e.context.secret),{algorithms:["HS256"]})}catch(e){if(e instanceof t5.JWTExpired)return r(tf.f.TOKEN_EXPIRED);return r(tf.f.INVALID_TOKEN)}let a=E.object({email:E.email(),updateTo:E.string().optional(),requestType:E.string().optional(),userId:E.string().optional()}).parse(t.payload);if(a.updateTo){if(!a.userId)return r(tf.f.INVALID_TOKEN);let t=await e.context.internalAdapter.findUserById(a.userId);if(!t)return r(tf.f.USER_NOT_FOUND);if(t.email.toLowerCase()!==a.email)return r(tf.f.INVALID_TOKEN);let i=await (0,p.D)(e);if(i&&i.user.id!==t.id)return r(tf.f.INVALID_USER);switch(a.requestType){case"change-email-confirmation":{let r=await t4(e.context.secret,a.email,a.updateTo,e.context.options.emailVerification?.expiresIn,{requestType:"change-email-verification",userId:t.id}),i=e.query.callbackURL?encodeURIComponent(e.query.callbackURL):encodeURIComponent("/"),o=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${i}`;if(e.context.options.emailVerification?.sendVerificationEmail&&await e.context.runInBackgroundOrAwait(e.context.options.emailVerification.sendVerificationEmail({user:{...t,email:a.updateTo},url:o,token:r},t3(e.request))),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0})}case"change-email-verification":{let r=t.emailVerified,o=await e.context.internalAdapter.updateUser(t.id,{email:a.updateTo,emailVerified:r});if(r&&e.context.options.emailVerification?.afterEmailVerification&&await e.context.options.emailVerification.afterEmailVerification(o,e.request),i&&await (0,e0.V)(e,{session:i.session,user:{...i.user,email:a.updateTo,emailVerified:r}}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:(0,w.$)(e.context.options,o)})}default:{let r=await e.context.internalAdapter.updateUser(t.id,{email:a.updateTo,emailVerified:!1}),o=await t4(e.context.secret,a.updateTo,void 0,void 0,{userId:t.id}),n=e.query.callbackURL?encodeURIComponent(e.query.callbackURL):encodeURIComponent("/");if(e.context.options.emailVerification?.sendVerificationEmail&&await e.context.runInBackgroundOrAwait(e.context.options.emailVerification.sendVerificationEmail({user:r,url:`${e.context.baseURL}/verify-email?token=${o}&callbackURL=${n}`,token:o},t3(e.request))),i&&await (0,e0.V)(e,{session:i.session,user:{...i.user,email:a.updateTo,emailVerified:!1}}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:(0,w.$)(e.context.options,r)})}}}let o=await e.context.internalAdapter.findUserByEmail(a.email);if(!o)return r(tf.f.USER_NOT_FOUND);if(a.userId&&a.userId!==o.user.id)return r(tf.f.INVALID_TOKEN);if(o.user.emailVerified){if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:null})}e.context.options.emailVerification?.beforeEmailVerification&&await e.context.options.emailVerification.beforeEmailVerification(o.user,e.request);let n=await e.context.internalAdapter.updateUserByEmail(a.email,{emailVerified:!0});if(e.context.options.emailVerification?.afterEmailVerification&&await e.context.options.emailVerification.afterEmailVerification(n,e.request),e.context.options.emailVerification?.autoSignInAfterVerification){let t=await (0,p.D)(e);if(t&&t.user.email===a.email)await (0,e0.V)(e,{session:t.session,user:{...t.user,emailVerified:!0}});else{let t=await e.context.internalAdapter.createSession(o.user.id);if(!t)throw u.E.from("INTERNAL_SERVER_ERROR",tf.f.FAILED_TO_CREATE_SESSION);await (0,e0.V)(e,{session:t,user:{...o.user,emailVerified:!0}})}}if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:null})});var re=e.i(945e3);function rt(e,t){return{linked:!1,error:{code:e,message:t}}}async function rr(e,t){if(!t.encryptedSessionToken||!(0,p.f)(e))return!0;let r=await (0,tC.u)({key:tF(e.context.secretConfig,"oauth-link-session-token"),data:t.encryptedSessionToken}).catch(()=>null);if(!r)return!1;let i=await e.context.internalAdapter.findSession(r);return!!i&&i.session.userId===t.userId&&i.session.expiresAt>new Date}async function ri(e,t){let{link:r,account:i,profile:a,scopes:o}=t,n={...t.userInfo,emailVerified:tZ(t.userInfo.emailVerified)};if(!await rr(e,r))return rt(tY);try{await e3(e,{user:{...n,id:r.userId,email:n.email??void 0},source:{action:"link-account",method:"oauth",oauth:{providerId:i.providerId,profile:a}}})}catch(e){if(!(0,tb.f)(e)||!e.body?.code)throw e;return rt(e.body.code,e.body.message)}if(!e.context.trustedProviders.includes(i.providerId)&&!n.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)return e.context.logger.error("Unable to link account - untrusted provider"),rt(tY);if(n.email?.toLowerCase()!==r.email.toLowerCase()&&e.context.options.account?.accountLinking?.allowDifferentEmails!==!0)return rt("email_does_not_match");let s=await e.context.internalAdapter.findAccountByKey(i);if(s){if(s.userId.toString()!==r.userId.toString())return rt("account_already_linked_to_different_user");let t=(0,re.w)(s.scope,o),a=Object.fromEntries(Object.entries({providerId:i.providerId,accessToken:await t0(i.accessToken,e.context),refreshToken:await t0(i.refreshToken,e.context),idToken:i.idToken,accessTokenExpiresAt:i.accessTokenExpiresAt,refreshTokenExpiresAt:i.refreshTokenExpiresAt,scope:t||void 0}).filter(([e,t])=>void 0!==t));await e.context.internalAdapter.updateAccount(s.id,a)}else if(!await e.context.internalAdapter.createAccount({userId:r.userId,...i,accessToken:await t0(i.accessToken,e.context),refreshToken:await t0(i.refreshToken,e.context),scope:o?.join(",")??i.scope}))return rt(tY);return await rn(e,r.userId,n),{linked:!0}}async function ra(e,t){let{account:r,callbackURL:i,disableSignUp:a,overrideUserInfo:o}=t,n={...t.userInfo,emailVerified:tZ(t.userInfo.emailVerified)},s=t.source??{method:"oauth",oauth:{providerId:r.providerId}},l=!!t.selectedUser||!0===t.requireExactAccountBinding,c=null,d=await e.context.internalAdapter.findAccountOwnerByKey({providerId:r.providerId,accountId:r.accountId}).catch(t=>{e.context.logger.error("Better auth was unable to query your database.\nError: ",t);let r=e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`;tG(e,r,"internal_server_error")});if(d?.kind==="orphaned")return e.context.logger.error("OAuth account references a missing user. Repair the account before retrying authentication."),{error:"unable to link account",data:null,isRegister:!1};let p=await (async()=>{if(d?.kind==="owned"){if(t.selectedUser&&d.user.id!==t.selectedUser.userId)throw new u.E("CONFLICT",{code:"account_ownership_conflict",message:"Account is already linked to another user"});return{user:d.user,linkedAccount:d.account,accounts:[d.account]}}if(t.selectedUser){let r=await e.context.internalAdapter.findUserById(t.selectedUser.userId);if(!r)throw new u.E("NOT_FOUND",{code:"user_not_found",message:"User not found"});return{user:r,linkedAccount:null,accounts:[]}}let r=await e.context.internalAdapter.findUserByEmail(n.email.toLowerCase(),{includeAccounts:!0});return r?{user:r.user,linkedAccount:null,accounts:r.accounts}:null})().catch(t=>{if((0,tb.f)(t))throw t;e.context.logger.error("Better auth was unable to query your database.\nError: ",t);let r=e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`;tG(e,r,"internal_server_error")}),f=p?.user,m=!f;if(p){let i=p.linkedAccount??p.accounts.find(e=>e.providerId===r.providerId&&e.accountId===r.accountId);if(i){let{id:a,...o}=n;await e3(e,{user:{...o,id:p.user.id,email:n.email.toLowerCase()},source:{...s,action:"sign-in"}});let d=e.context.options.account?.updateAccountOnSignIn!==!1?Object.fromEntries(Object.entries({providerId:r.providerId,idToken:r.idToken,accessToken:await t0(r.accessToken,e.context),refreshToken:await t0(r.refreshToken,e.context),accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt}).filter(([e,t])=>void 0!==t)):{};if(e.context.options.account?.storeAccountCookie){let r={...i,...d};t.deferNonDatabaseWrites?c=r:await (0,tq.L)(e,r)}if(Object.keys(d).length>0){let a=await e.context.internalAdapter.updateAccount(i.id,d);if(!a)return{error:"unable to update account",data:null};if(l&&(a.accountId!==r.accountId||a.providerId!==r.providerId||a.userId!==p.user.id))throw new u.E("CONFLICT",{code:"account_hook_binding_conflict",message:"Account hook changed the selected authentication binding"});t.deferNonDatabaseWrites&&c&&(c=a)}t.selectedUser||!n.emailVerified||p.user.emailVerified||n.email.toLowerCase()!==p.user.email||await e.context.internalAdapter.updateUser(p.user.id,{emailVerified:!0})}else{let i=e.context.options.account?.accountLinking,a=t.isTrustedProvider||!1!==t.trustProviderByName&&e.context.trustedProviders.includes(r.providerId),o=i?.requireLocalEmailVerified??!0;if(!t.selectedUser&&(!a&&!n.emailVerified||o&&!p.user.emailVerified||i?.enabled===!1||i?.disableImplicitLinking===!0))return(0,ta.o)()&&e.context.logger.warn(`User already exist but account isn't linked to ${r.providerId}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`),{error:"account not linked",data:null};try{let{id:i,...a}=n;await e3(e,{user:{...a,id:p.user.id,email:n.email.toLowerCase()},source:{...s,action:"link-account"}});let o=await e.context.internalAdapter.linkAccount({providerId:r.providerId,accountId:r.accountId,userId:p.user.id,accessToken:await t0(r.accessToken,e.context),refreshToken:await t0(r.refreshToken,e.context),idToken:r.idToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:r.scope});if(!o)return{error:"unable to link account",data:null};if(l&&(o.accountId!==r.accountId||o.providerId!==r.providerId||o.userId!==p.user.id))throw new u.E("CONFLICT",{code:"account_hook_binding_conflict",message:"Account hook changed the selected authentication binding"});e.context.options.account?.storeAccountCookie&&(t.deferNonDatabaseWrites?c=o:await (0,tq.L)(e,o))}catch(t){if((0,tb.f)(t))throw t;return e.context.logger.error("Unable to link account",t),{error:"unable to link account",data:null}}t.selectedUser||!n.emailVerified||p.user.emailVerified||n.email.toLowerCase()!==p.user.email||await e.context.internalAdapter.updateUser(p.user.id,{emailVerified:!0}),t.selectedUser||(f=await rn(e,p.user.id,n)??f)}if(t.selectedUser?"update"===t.selectedUser.profile:o){let{id:r,email:i,emailVerified:a,name:o,image:s,...l}=n,c=(0,w.W)(e.context.options,l,"update"),d=await e.context.internalAdapter.updateUser(p.user.id,{name:o,image:s,...c,email:n.email.toLowerCase(),emailVerified:n.email.toLowerCase()===p.user.email&&p.user.emailVerified||n.emailVerified});if(null==d&&e.context.logger.warn("Could not update user info during OAuth sign in; preserving existing user for session."),t.selectedUser&&d&&d.id!==t.selectedUser.userId)throw new u.E("CONFLICT",{code:"user_hook_selection_conflict",message:"User hook changed the selected user"});f=d??f}}else{if(a)return{error:"signup disabled",data:null,isRegister:!1};try{let{id:i,email:a,emailVerified:o,name:d,image:p,...m}=n,h=(0,w.W)(e.context.options,m,"create"),g={accessToken:await t0(r.accessToken,e.context),refreshToken:await t0(r.refreshToken,e.context),idToken:r.idToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:r.scope,providerId:r.providerId,accountId:r.accountId},{createdUser:y,createdAccount:b}=await (0,e7.n)(e.context.adapter,async()=>{let t=await e.context.internalAdapter.createUser({name:d,image:p,...h,email:n.email.toLowerCase(),emailVerified:n.emailVerified},s);return{createdUser:t,createdAccount:await e.context.internalAdapter.createAccount({...g,userId:t.id})}});if(l&&(b.accountId!==r.accountId||b.providerId!==r.providerId||b.userId!==y.id))throw new u.E("CONFLICT",{code:"account_hook_binding_conflict",message:"Account hook changed the selected authentication binding"});f=y,e.context.options.account?.storeAccountCookie&&(t.deferNonDatabaseWrites?c=b:await (0,tq.L)(e,b))}catch(t){if((0,tb.f)(t))throw t;return e.context.logger.error("Unable to create OAuth user",t),{error:"unable to create user",data:null,isRegister:!1}}}if(!f)return{error:"unable to create user",data:null,isRegister:!1};let h=e.context.socialProviders.find(e=>e.id===r.providerId)?.options?.requireEmailVerification;if(m&&!f.emailVerified&&(e.context.options.emailVerification?.sendOnSignUp??h)&&await ro(e,f,i,t.deferNonDatabaseWrites),h&&!f.emailVerified)return!m&&e.context.options.emailVerification?.sendOnSignIn&&await ro(e,f,i,t.deferNonDatabaseWrites),{error:tQ,data:null,isRegister:m};let g=await e.context.internalAdapter.createSession(f.id,void 0,void 0,void 0,{deferSecondaryStorageWrites:!0===t.deferNonDatabaseWrites});if(!g)return{error:"unable to create session",data:null,isRegister:!1};if(l&&g.userId!==(t.selectedUser?.userId??f.id))throw new u.E("CONFLICT",{code:"session_hook_user_conflict",message:"Session hook changed the selected user"});return{data:{session:g,user:f},error:null,isRegister:m,accountCookie:c}}async function ro(e,t,r,i){let a=e.context.options.emailVerification?.sendVerificationEmail;if(!a)return;let o=async()=>{try{let i=await t4(e.context.secret,t.email,void 0,e.context.options.emailVerification?.expiresIn,{userId:t.id}),o=`${e.context.baseURL}/verify-email?token=${i}&callbackURL=${encodeURIComponent(r||"/")}`;await e.context.runInBackgroundOrAwait(a({user:t,url:o,token:i},e.request))}catch(t){e.context.logger.error("Failed to send OAuth verification email",t)}};i?await (0,e7.A)(o):await o()}async function rn(e,t,r){if(e.context.options.account?.accountLinking?.updateUserInfoOnLink===!0)try{let{email:i,emailVerified:a,name:o,image:n,...s}=r,l=(0,w.W)(e.context.options,s,"update");return await e.context.internalAdapter.updateUser(t,{name:o,image:n,...l})}catch(t){e.context.logger.warn("Could not update user info on account link",t);return}}var rs=u;let rl=E.looseObject({callbackURL:E.string(),codeVerifier:E.string(),errorURL:E.string().optional(),newUserURL:E.string().optional(),expiresAt:E.number(),oauthState:E.string().optional(),link:E.object({email:E.string(),userId:A.f.string(),encryptedSessionToken:E.string().optional()}).optional(),requestSignUp:E.boolean().optional(),idTokenNonce:E.string().optional(),serverContext:E.record(E.string(),E.unknown()).optional()}),rc=e=>`auth-state:${e}`;new Set(Object.keys(rl.shape));var rd=class extends rs.p{code;details;errorURL;constructor(e,t){super(e,t),this.code=t.code,this.details=t.details,this.errorURL=t.errorURL}};async function ru(e,t,r){let i=(0,g.f)(32);if("cookie"===e.context.oauthConfig.storeStateStrategy){let a={...t,oauthState:i},o=await (0,tC.M)({key:tF(e.context.secretConfig,"oauth-state-cookie"),data:JSON.stringify(a)}),n=e.context.createAuthCookie(r?.cookieName??"oauth_state",{maxAge:600});return e.setCookie(n.name,o,n.attributes),{state:i,codeVerifier:t.codeVerifier}}let a=e.context.createAuthCookie(r?.cookieName??"state",{maxAge:300});await e.setSignedCookie(a.name,i,e.context.secret,a.attributes);let o=new Date;if(o.setMinutes(o.getMinutes()+10),!await e.context.internalAdapter.createVerificationValue({value:JSON.stringify({...t,oauthState:i}),identifier:rc(i),expiresAt:o}))throw new rd("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database",{code:"state_generation_error"});return{state:i,codeVerifier:t.codeVerifier}}async function rp(e,t,r){let i;if(!t)throw new rd("State not found in OAuth callback",{code:"state_not_found"});if("cookie"===e.context.oauthConfig.storeStateStrategy){let a=e.context.createAuthCookie(r?.cookieName??"oauth_state"),o=e.getCookie(a.name);if(!o)throw new rd("State mismatch: auth state cookie not found",{code:"state_mismatch",details:{state:t}});try{let t=await (0,tC.u)({key:tF(e.context.secretConfig,"oauth-state-cookie"),data:o});i=rl.parse(JSON.parse(t))}catch(e){throw new rd("State invalid: Failed to decrypt or parse auth state",{code:"state_invalid",details:{state:t},cause:e})}if(!i.oauthState||i.oauthState!==t)throw new rd("State mismatch: OAuth state parameter does not match stored state",{code:"state_security_mismatch",details:{state:t},errorURL:i.errorURL});(0,e0.c)(e,a)}else{let a=await e.context.internalAdapter.findVerificationValue(rc(t));if(!a)throw new rd("State mismatch: verification not found",{code:"state_mismatch",details:{state:t}});if(void 0!==(i=rl.parse(JSON.parse(a.value))).oauthState&&i.oauthState!==t)throw new rd("State mismatch: OAuth state parameter does not match stored state",{code:"state_security_mismatch",details:{state:t},errorURL:i.errorURL});let o=e.context.createAuthCookie(r?.cookieName??"state"),n=await e.getSignedCookie(o.name,e.context.secret);if(!(r?.skipStateCookieCheck??e.context.oauthConfig.skipStateCookieCheck)&&(!n||n!==t))throw new rd("State mismatch: State not persisted correctly",{code:"state_security_mismatch",details:{state:t},errorURL:i.errorURL});(0,e0.c)(e,o),await e.context.internalAdapter.deleteVerificationByIdentifier(rc(t))}if(i.expiresAt<Date.now())throw new rd("Invalid state: request expired",{code:"state_mismatch",details:{expiresAt:i.expiresAt},errorURL:i.errorURL});return i}function rf(e){return e.requiresIdTokenNonce?(0,g.f)(32):void 0}async function rm(e,t){let r=e.body?.callbackURL||e.context.options.baseURL;if(!r)throw u.E.from("BAD_REQUEST",tf.f.CALLBACK_URL_REQUIRED);let i=t?.codeVerifier??(0,g.f)(128),a=await (0,tP.r)(),o=a&&Object.keys(a).length?a:void 0,n={...t?.additionalData?t.additionalData:{},callbackURL:r,codeVerifier:i,errorURL:e.body?.errorCallbackURL,newUserURL:e.body?.newUserCallbackURL,link:t?.link,serverContext:o,expiresAt:Date.now()+6e5,requestSignUp:e.body?.requestSignUp,idTokenNonce:t?.idTokenNonce};await (0,tP.K)(n);try{return ru(e,n)}catch(t){throw e.context.logger.error("Failed to create verification",t),new u.E("INTERNAL_SERVER_ERROR",{message:"Unable to create verification",cause:t})}}async function rh(e){let t,r=e.query.state||e.body?.state,i=e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`;try{t=await rp(e,r)}catch(a){e.context.logger.error("Failed to parse state",a);let t="internal_server_error",r=i;a instanceof rd&&(t="state_security_mismatch"===a.code?"state_mismatch":a.code,r=a.errorURL||i),tG(e,r,t)}return t.errorURL||(t.errorURL=i),t&&await (0,tP.K)(t),t}let rg=["state","client_id","redirect_uri","response_type","code_challenge","code_challenge_method","nonce","scope"],rw=new Set(rg);async function ry({id:e,options:t,authorizationEndpoint:r,state:i,codeVerifier:a,scopes:o,claims:n,redirectURI:s,duration:l,prompt:c,accessType:d,responseType:u,display:p,loginHint:f,nonce:m,hd:h,responseMode:g,additionalParams:w,scopeJoiner:y}){let b=new URL((t="function"==typeof t?await t():t).authorizationEndpoint||r);b.searchParams.set("response_type",u||"code");let E=(0,re.B)(t.clientId);if(!E)throw Error("OAuth provider requires clientId");if(b.searchParams.set("client_id",E),b.searchParams.set("state",i),o?.length&&b.searchParams.set("scope",o.join(y||" ")),b.searchParams.set("redirect_uri",t.redirectURI||s),l&&b.searchParams.set("duration",l),p&&b.searchParams.set("display",p),f&&b.searchParams.set("login_hint",f),m&&b.searchParams.set("nonce",m),c&&b.searchParams.set("prompt",c),h&&b.searchParams.set("hd",h),d&&b.searchParams.set("access_type",d),g&&b.searchParams.set("response_mode",g),a){let e=await (0,re.F)(a);b.searchParams.set("code_challenge_method","S256"),b.searchParams.set("code_challenge",e)}if(n){let e=n.reduce((e,t)=>(e[t]=null,e),{});b.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...e}}))}if(w)for(let[e,t]of Object.entries(w))rw.has(e)||b.searchParams.set(e,t);return b}e.s(["k",0,rg,"Z",0,rw,"V",0,ry],729522);let rb=E.record(E.string(),E.string()).refine(e=>!Object.keys(e).some(e=>rw.has(e)),{message:`additionalParams cannot include reserved OAuth parameters: ${rg.join(", ")}`}).meta({description:"Extra query parameters to append to the provider authorization URL (e.g. Cognito identity_provider, Google hd)."}).optional(),rE=["iss","sub","aud","exp","iat"];function rA(e){return{issuer:e.issuer,audience:e.audience,algorithms:e.algorithms,maxTokenAge:e.maxTokenAge,requiredClaims:rE,clockTolerance:30}}async function rI(e){let t=new TextEncoder().encode(e);return Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256",t))).map(e=>e.toString(16).padStart(2,"0")).join("")}async function r_(e,t,r="exact"){return"string"==typeof e&&(e===t||"exact-or-sha256"===r&&e===await rI(t))}async function rk(e,t,r){if(![t.audience].flat().some(Boolean))throw Error("ID token audience is not configured");let i=await (0,t6.f)(e,t.jwks,rA(t));if(r&&!await r_(i.payload.nonce,r,t.nonceComparison))throw Error("ID token nonce does not match");if(t.verifyClaims&&!t.verifyClaims(i.payload))throw Error("ID token claims were rejected");return i}function rT(e){let t=e.options??{};return!t.disableIdTokenSignIn&&!!(e.idToken||t.verifyIdToken)}async function rv(e,t,r,i){let a=e.options??{};if(a.disableIdTokenSignIn)return!1;try{if(a.verifyIdToken)return await a.verifyIdToken(t,r,i);let o=e.idToken;if(!o)return!1;if("verify"in o)return await o.verify(t,r,i);if(3!==t.split(".").length)return!0===o.allowOpaqueToken;return await rk(t,o,r),!0}catch{return!1}}e.s(["M",0,rA,"x",0,rT,"n",0,rv],100762);var rU=e.i(748860),rR=e.i(109083),rS=e.i(432741);function rx(e,t,r){if(t.clientSecret||r.has("client_secret"))throw Error(`${e} token endpoint authentication cannot be combined with clientSecret`)}function rO(e,t){t&&e.set("client_id",t)}function rD(e,t){if(!t.clientSecret)throw Error(`${e} token endpoint authentication requires clientSecret`)}function rN(e,t){if(!t)throw Error(`${e} token endpoint authentication requires clientId`)}function rL(e){if(e.has("client_assertion")!==e.has("client_assertion_type"))throw Error("client_assertion and client_assertion_type must both be provided")}async function rP({body:e,headers:t,options:r,tokenEndpoint:i,grantType:a,tokenEndpointAuth:o,authentication:n}){rL(e);let s=(0,re.B)(r.clientId);if(e.has("client_assertion")){if(o)throw Error("client_assertion body parameters cannot be combined with tokenEndpointAuth");rx("private_key_jwt",r,e),rO(e,s);return}let l=o??("basic"===n?{method:"client_secret_basic"}:r.clientSecret?{method:"client_secret_post"}:{method:"none"});if("custom"===l.method){await l.customizeRequest({body:e,headers:t,options:r,tokenEndpoint:i,grantType:a}),rL(e);return}if("private_key_jwt"===l.method){if(rx(l.method,r,e),rN(l.method,s),!i)throw Error("private_key_jwt token endpoint authentication requires tokenEndpoint");let t=await (0,rS.B)({getClientAssertion:l.getClientAssertion,context:{clientId:s,tokenEndpoint:i,grantType:a}});for(let[r,i]of(rO(e,s),Object.entries(t)))e.set(r,i);return}if("none"===l.method){if(rx(l.method,r,e),"client_credentials"===a)throw Error("none token endpoint authentication cannot be used with client_credentials grant");rN(l.method,s),rO(e,s);return}"client_secret_basic"===l.method?function({headers:e,options:t,clientId:r,body:i}){if(i.has("client_secret"))throw Error("client_secret_basic token endpoint authentication cannot be combined with client_secret body parameters");rD("client_secret_basic",t),rN("client_secret_basic",r),e.authorization=(0,rR.n)(r,t.clientSecret)}({headers:t,options:r,clientId:s,body:e}):function({body:e,options:t,clientId:r,requireClientSecret:i}){i&&rD("client_secret_post",t),t.clientSecret&&(rN("client_secret_post",r),rO(e,r),e.set("client_secret",t.clientSecret))}({body:e,options:r,clientId:s,requireClientSecret:o?.method==="client_secret_post"})}let rC=new Set(["grant_type","refresh_token","__proto__","constructor","prototype"]);async function rq({refreshToken:e,options:t,authentication:r,tokenEndpointAuth:i,tokenEndpoint:a,extraParams:o,resource:n}){let s=function({refreshToken:e,options:t,extraParams:r,resource:i}){let a=new URLSearchParams;if(a.set("grant_type","refresh_token"),a.set("refresh_token",e),i)if("string"==typeof i)a.append("resource",i);else for(let e of i)a.append("resource",e);return r&&function(e,t){if(t)for(let[r,i]of Object.entries(t))rC.has(r)||e.set(r,i)}(a,r),{body:a,headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json"}}}({refreshToken:e,options:t="function"==typeof t?await t():t,extraParams:o,resource:n});return await rP({body:s.body,headers:s.headers,options:t,tokenEndpoint:a??"",grantType:"refresh_token",tokenEndpointAuth:i,authentication:r}),s}async function rj({refreshToken:e,options:t,tokenEndpoint:r,authentication:i,tokenEndpointAuth:a,extraParams:o,resource:n}){let{body:s,headers:l}=await rq({refreshToken:e,options:t,authentication:i,tokenEndpointAuth:a,tokenEndpoint:r,extraParams:o,resource:n}),{data:c,error:d}=await (0,rU.f)(r,{method:"POST",body:s,headers:l});if(d)throw d;let u={accessToken:c.access_token,refreshToken:c.refresh_token,tokenType:c.token_type,scopes:(0,re.V)(c.scope),idToken:c.id_token};return c.expires_in&&(u.accessTokenExpiresAt=new Date((new Date).getTime()+1e3*c.expires_in)),c.refresh_token_expires_in&&(u.refreshTokenExpiresAt=new Date((new Date).getTime()+1e3*c.refresh_token_expires_in)),u}async function r$({code:e,codeVerifier:t,redirectURI:r,options:i,authentication:a,tokenEndpointAuth:o,tokenEndpoint:n,deviceId:s,headers:l,additionalParams:c={},resource:d}){let u=function({code:e,codeVerifier:t,redirectURI:r,options:i,deviceId:a,headers:o,additionalParams:n={},resource:s}){let l=new URLSearchParams,c={"content-type":"application/x-www-form-urlencoded",accept:"application/json",...o};if(l.set("grant_type","authorization_code"),l.set("code",e),t&&l.set("code_verifier",t),i.clientKey&&l.set("client_key",i.clientKey),a&&l.set("device_id",a),l.set("redirect_uri",i.redirectURI||r),s)if("string"==typeof s)l.append("resource",s);else for(let e of s)l.append("resource",e);for(let[e,t]of Object.entries(n))l.has(e)||l.append(e,t);return{body:l,headers:c}}({code:e,codeVerifier:t,redirectURI:r,options:i="function"==typeof i?await i():i,deviceId:s,headers:l,additionalParams:c,resource:d});return await rP({body:u.body,headers:u.headers,options:i,tokenEndpoint:n??"",grantType:"authorization_code",tokenEndpointAuth:o,authentication:a}),u}async function rB({code:e,codeVerifier:t,redirectURI:r,options:i,tokenEndpoint:a,authentication:o,tokenEndpointAuth:n,deviceId:s,headers:l,additionalParams:c={},resource:d}){let{body:u,headers:p}=await r$({code:e,codeVerifier:t,redirectURI:r,options:i,authentication:o,tokenEndpointAuth:n,tokenEndpoint:a,deviceId:s,headers:l,additionalParams:c,resource:d}),{data:f,error:m}=await (0,rU.f)(a,{method:"POST",body:u,headers:p});if(m)throw m;return(0,re.i)(f)}e.s(["f",0,rj],661372),e.i(728895),e.s(["j",0,r$,"M",0,rB],374091);var rV=e.i(878175),rM=e.i(397554);let rF=async e=>{let{data:t}=await (0,rU.f)("https://appleid.apple.com/auth/keys");if(!t?.keys)throw new u.E("BAD_REQUEST",{message:"Keys not found"});let r=t.keys.find(t=>t.kid===e);if(!r)throw Error(`JWK with kid ${e} not found`);return await (0,rM.g)(r,r.alg)};var rK=e.i(533078);let rz="https://dash.cloudflare.com/oauth2/token",rH=e=>e.tokenEndpointAuth??{method:e.tokenEndpointAuthMethod??(e.clientSecret?"client_secret_basic":"none")},rW=async(e,t,r)=>{let i=`https://cognito-idp.${t}.amazonaws.com/${r}/.well-known/jwks.json`;try{let{data:t}=await (0,rU.f)(i);if(!t?.keys)throw new u.E("BAD_REQUEST",{message:"Keys not found"});let r=t.keys.find(t=>t.kid===e);if(!r)throw Error(`JWK with kid ${e} not found`);return await (0,rM.g)(r,r.alg)}catch(e){throw eA.y.error("Failed to fetch Cognito public key:",e),e}};var rY=e.i(550064);async function rQ(e,t){let r=(0,re.B)(t.clientId);if(!r||!t.clientSecret)return null;let i=Array.isArray(t.clientId)?t.clientId:[t.clientId],a=`${r}|${t.clientSecret}`,{data:o,error:n}=await (0,rU.f)("https://graph.facebook.com/debug_token",{query:{input_token:e,access_token:a}});if(n||!o?.data)return null;let{is_valid:s,app_id:l,user_id:c}=o.data;return!0===s&&l&&i.includes(l)&&c?c:null}let rG=(e="")=>e.split("://").map(e=>e.replace(/\/{2,}/g,"/")).join("://");e.i(741242);let rJ="RS256",rZ=[rJ],rX=(e,t)=>!e||"string"==typeof t&&!!t&&("*"===e||t===e),r0=async e=>{let[t]=await r1(e);if(!t)throw Error(`JWK with kid ${e} not found`);return t},r1=async e=>{let{data:t}=await (0,rU.f)("https://www.googleapis.com/oauth2/v3/certs");if(!t?.keys)throw new u.E("BAD_REQUEST",{message:"Keys not found"});let r=e?t.keys.filter(t=>t.kid===e):t.keys;if(!r.length)throw Error(`JWK with kid ${e} not found`);return Promise.all(r.map(e=>(0,rM.g)(e,rJ)))},r2="9188040d-6c67-4c5b-b112-36a304b66dad",r3=async(e,t,r)=>{let{data:i}=await (0,rU.f)(`${r}/${t}/discovery/v2.0/keys`);if(!i?.keys)throw new u.E("BAD_REQUEST",{message:"Keys not found"});let a=i.keys.find(t=>t.kid===e);if(!a)throw Error(`JWK with kid ${e} not found`);return await (0,rM.g)(a,a.alg??"RS256")},r6="https://backboard.railway.com/oauth/token";function r5({identifier:e,namespace:t}){let r=E.email().safeParse(`${e}@${t}.placeholder.invalid`);if(!r.success)throw TypeError("Invalid placeholder email");return r.data}e.s(["f",0,r5],339507);let r4={apple:e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",accountSubject:({profile:e})=>e.sub,async createAuthorizationURL({state:t,scopes:r,redirectURI:i,additionalParams:a,codeVerifier:o}){if(!(0,re.B)(e.clientId)||!e.clientSecret)throw eA.y.error("Client ID and client secret are required for Apple. Make sure to provide them in the options."),new u.p("CLIENT_ID_AND_SECRET_REQUIRED");let n=e.disableDefaultScope?[]:["email","name"];return e.scope&&n.push(...e.scope),r&&n.push(...r),await ry({id:"apple",options:e,authorizationEndpoint:"https://appleid.apple.com/auth/authorize",scopes:n,state:t,redirectURI:i,codeVerifier:o,responseMode:"form_post",responseType:"code id_token",additionalParams:a})},validateAuthorizationCode:async({code:r,codeVerifier:i,redirectURI:a})=>rB({code:r,codeVerifier:i,redirectURI:a,options:e,tokenEndpoint:t}),idToken:{jwks:e=>rF(e.kid),issuer:"https://appleid.apple.com",algorithms:["RS256"],audience:e.audience&&e.audience.length?e.audience:e.appBundleIdentifier?e.appBundleIdentifier:e.clientId,maxTokenAge:"1h",nonceComparison:"exact-or-sha256"},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>rj({refreshToken:r,options:e,tokenEndpoint:t}),async getUserInfo(t){let r;if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let i=(0,rV.f)(t.idToken);if(!i)return null;r=t.user?.name?`${t.user.name.firstName||""} ${t.user.name.lastName||""}`.trim():i.name||"";let a="boolean"==typeof i.email_verified?i.email_verified:"true"===i.email_verified,o={...i,name:r},n=await e.mapProfileToUser?.(o);return{user:{name:o.name,emailVerified:a,email:i.email,...n},data:o}},options:e}},atlassian:e=>{let t="https://auth.atlassian.com/oauth/token";return{id:"atlassian",name:"Atlassian",accountSubject:({profile:e})=>e.account_id,async createAuthorizationURL({state:t,scopes:r,codeVerifier:i,redirectURI:a,additionalParams:o}){if(!e.clientId||!e.clientSecret)throw eA.y.error("Client Id and Secret are required for Atlassian"),new u.p("CLIENT_ID_AND_SECRET_REQUIRED");if(!i)throw new u.p("codeVerifier is required for Atlassian");let n=e.disableDefaultScope?[]:["read:jira-user","offline_access"];return e.scope&&n.push(...e.scope),r&&n.push(...r),ry({id:"atlassian",options:e,authorizationEndpoint:"https://auth.atlassian.com/authorize",scopes:n,state:t,codeVerifier:i,redirectURI:a,additionalParams:{...o??{},audience:"api.atlassian.com"},prompt:e.prompt})},validateAuthorizationCode:async({code:r,codeVerifier:i,redirectURI:a})=>rB({code:r,codeVerifier:i,redirectURI:a,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>rj({refreshToken:r,options:{clientId:e.clientId,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.accessToken)return null;try{let{data:r}=await (0,rK.f)("https://api.atlassian.com/me",{headers:{Authorization:`Bearer ${t.accessToken}`}});if(!r)return null;let i=await e.mapProfileToUser?.(r);return{user:{name:r.name,email:r.email,image:r.picture,emailVerified:!1,...i},data:r}}catch(e){return eA.y.error("Failed to fetch user info from Atlassian:",e),null}},options:e}},cloudflare:e=>({id:"cloudflare",name:"Cloudflare",accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:r,codeVerifier:i,redirectURI:a}){let o=e.disableDefaultScope?[]:["user-details.read"];return e.scope?.length&&o.push(...e.scope),r?.length&&o.push(...r),ry({id:"cloudflare",options:e,authorizationEndpoint:"https://dash.cloudflare.com/oauth2/auth",scopes:o.length?[...new Set(o)]:void 0,state:t,codeVerifier:i,redirectURI:a})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:i})=>rB({code:t,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:rz,tokenEndpointAuth:rH(e)}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>rj({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:rz,tokenEndpointAuth:rH(e)}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:i}=await (0,rK.f)("https://api.cloudflare.com/client/v4/user",{headers:{authorization:`Bearer ${t.accessToken}`}});if(i||!r?.success||!r.result)return eA.y.error("Failed to fetch user info from Cloudflare:",i??r?.errors),null;let a=r.result,o=[a.first_name,a.last_name].filter(Boolean).join(" ")||a.email,n=await e.mapProfileToUser?.(a);return{user:{name:o,email:a.email,emailVerified:!1,...n},data:a}},options:e}),cognito:e=>{if(!e.domain||!e.region||!e.userPoolId)throw eA.y.error("Domain, region and userPoolId are required for Amazon Cognito. Make sure to provide them in the options."),new u.p("DOMAIN_AND_REGION_REQUIRED");let t=e.domain.replace(/^https?:\/\//,""),r=`https://${t}/oauth2/authorize`,i=`https://${t}/oauth2/token`,a=`https://${t}/oauth2/userinfo`;return{id:"cognito",name:"Cognito",accountSubject:({profile:e})=>e.sub,async createAuthorizationURL({state:t,scopes:i,codeVerifier:a,redirectURI:o,additionalParams:n}){if(!(0,re.B)(e.clientId))throw eA.y.error("ClientId is required for Amazon Cognito. Make sure to provide them in the options."),new u.p("CLIENT_ID_AND_SECRET_REQUIRED");if(e.requireClientSecret&&!e.clientSecret)throw eA.y.error("Client Secret is required when requireClientSecret is true. Make sure to provide it in the options."),new u.p("CLIENT_SECRET_REQUIRED");let s=e.disableDefaultScope?[]:["openid","profile","email"];e.scope&&s.push(...e.scope),i&&s.push(...i);let l=await ry({id:"cognito",options:{...e},authorizationEndpoint:r,scopes:s,state:t,codeVerifier:a,redirectURI:o,prompt:e.prompt,additionalParams:{...e.identityProvider?{identity_provider:e.identityProvider}:{},...n??{}}}),c=l.searchParams.get("scope");if(c){l.searchParams.delete("scope");let e=encodeURIComponent(c),t=l.toString(),r=t.includes("?")?"&":"?";return new URL(`${t}${r}scope=${e}`)}return l},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:a})=>rB({code:t,codeVerifier:r,redirectURI:a,options:e,tokenEndpoint:i}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>rj({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:i}),idToken:{jwks:t=>rW(t.kid,e.region,e.userPoolId),issuer:`https://cognito-idp.${e.region}.amazonaws.com/${e.userPoolId}`,audience:e.clientId,algorithms:["RS256"],maxTokenAge:"1h"},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(t.idToken)try{let r=(0,rV.f)(t.idToken);if(!r)return null;let i=r.name||r.given_name||r.username||"",a={...r,name:i},o=await e.mapProfileToUser?.(a);return{user:{name:a.name,email:r.email,image:r.picture,emailVerified:r.email_verified,...o},data:a}}catch(e){eA.y.error("Failed to decode ID token:",e)}if(t.accessToken)try{let{data:r}=await (0,rK.f)(a,{headers:{Authorization:`Bearer ${t.accessToken}`}});if(r){let t=await e.mapProfileToUser?.(r);return{user:{name:r.name||r.given_name||r.username||"",email:r.email,image:r.picture,emailVerified:(0,re.r)(r.email_verified),...t},data:r}}}catch(e){eA.y.error("Failed to fetch user info from Cognito:",e)}return null},options:e}},discord:e=>{let t="https://discord.com/api/oauth2/token";return{id:"discord",name:"Discord",accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:r,redirectURI:i,additionalParams:a}){let o=e.disableDefaultScope?[]:["identify","email"];r&&o.push(...r),e.scope&&o.push(...e.scope);let n=o.includes("bot");return ry({id:"discord",options:e,authorizationEndpoint:"https://discord.com/api/oauth2/authorize",scopes:o,state:t,redirectURI:i,prompt:e.prompt||"none",additionalParams:{...n&&void 0!==e.permissions?{permissions:String(e.permissions)}:{},...a??{}}})},validateAuthorizationCode:async({code:r,redirectURI:i})=>rB({code:r,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>rj({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:i}=await (0,rK.f)("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(i)return null;if(null===r.avatar)r.image_url=`https://cdn.discordapp.com/embed/avatars/${"0"===r.discriminator?Number(BigInt(r.id)>>BigInt(22))%6:parseInt(r.discriminator)%5}.png`;else{let e=r.avatar.startsWith("a_")?"gif":"png";r.image_url=`https://cdn.discordapp.com/avatars/${r.id}/${r.avatar}.${e}`}let a=await e.mapProfileToUser?.(r);return{user:{name:r.global_name||r.username||"",email:r.email,emailVerified:r.verified,image:r.image_url,...a},data:r}},options:e}},facebook:e=>({id:"facebook",name:"Facebook",accountSubject:({profile:e})=>"sub"in e?e.sub:e.id,async createAuthorizationURL({state:t,scopes:r,redirectURI:i,loginHint:a,additionalParams:o}){if(!(0,re.B)(e.clientId)||!e.clientSecret)throw eA.y.error("Client ID and client secret are required for Facebook. Make sure to provide them in the options."),new u.p("CLIENT_ID_AND_SECRET_REQUIRED");let n=e.disableDefaultScope?[]:["email","public_profile"];return e.scope&&n.push(...e.scope),r&&n.push(...r),await ry({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v24.0/dialog/oauth",scopes:n,state:t,redirectURI:i,loginHint:a,additionalParams:{...e.configId?{config_id:e.configId}:{},...o??{}}})},validateAuthorizationCode:async({code:t,redirectURI:r})=>rB({code:t,redirectURI:r,options:e,tokenEndpoint:"https://graph.facebook.com/v24.0/oauth/access_token"}),idToken:{jwks:(0,rY.R)(new URL("https://limited.facebook.com/.well-known/oauth/openid/jwks/")),issuer:"https://www.facebook.com",audience:e.clientId,algorithms:["RS256"],allowOpaqueToken:!0},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>rj({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:"https://graph.facebook.com/v24.0/oauth/access_token"}),async getUserInfo(t){if(e.getUserInfo){let r=!!t.idToken&&3!==t.idToken.split(".").length,i=t.accessToken||(r?t.idToken:void 0);return i&&!await rQ(i,e)?null:e.getUserInfo(t)}if(t.idToken&&3===t.idToken.split(".").length){let r=(0,rV.f)(t.idToken),i=await e.mapProfileToUser?.(r);return{user:{name:r.name,email:r.email,image:r.picture,emailVerified:!1,...i},data:r}}let r=t.accessToken;if(!r)return null;let i=await rQ(r,e);if(!i)return null;let a=["id","name","email","picture",...e?.fields||[]],{data:o,error:n}=await (0,rK.f)("https://graph.facebook.com/me?fields="+a.join(","),{auth:{type:"Bearer",token:r}});if(n||o.id!==i)return null;let s=await e.mapProfileToUser?.(o);return{user:{name:o.name,email:o.email,image:o.picture.data.url,emailVerified:o.email_verified??!1,...s},data:o}},options:e}),figma:e=>{let t="https://api.figma.com/v1/oauth/token";return{id:"figma",name:"Figma",accountSubject:({profile:e})=>e.id,async createAuthorizationURL({state:t,scopes:r,codeVerifier:i,redirectURI:a,additionalParams:o}){if(!e.clientId||!e.clientSecret)throw eA.y.error("Client Id and Client Secret are required for Figma. Make sure to provide them in the options."),new u.p("CLIENT_ID_AND_SECRET_REQUIRED");if(!i)throw new u.p("codeVerifier is required for Figma");let n=e.disableDefaultScope?[]:["current_user:read"];return e.scope&&n.push(...e.scope),r&&n.push(...r),await ry({id:"figma",options:e,authorizationEndpoint:"https://www.figma.com/oauth",scopes:n,state:t,codeVerifier:i,redirectURI:a,additionalParams:o})},validateAuthorizationCode:async({code:r,codeVerifier:i,redirectURI:a})=>rB({code:r,codeVerifier:i,redirectURI:a,options:e,tokenEndpoint:t,authentication:"basic"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>rj({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t,authentication:"basic"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);try{let{data:r}=await (0,rK.f)("https://api.figma.com/v1/me",{headers:{Authorization:`Bearer ${t.accessToken}`}});if(!r)return eA.y.error("Failed to fetch user from Figma"),null;let i=await e.mapProfileToUser?.(r);return{user:{name:r.handle,email:r.email,image:r.img_url,emailVerified:!1,...i},data:r}}catch(e){return eA.y.error("Failed to fetch user info from Figma:",e),null}},options:e}},github:e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:r,loginHint:i,codeVerifier:a,redirectURI:o,additionalParams:n}){let s=e.disableDefaultScope?[]:["read:user","user:email"];return e.scope&&s.push(...e.scope),r&&s.push(...r),ry({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:t,codeVerifier:a,redirectURI:o,loginHint:i,prompt:e.prompt,additionalParams:n})},validateAuthorizationCode:async({code:r,codeVerifier:i,redirectURI:a})=>{let{body:o,headers:n}=await r$({code:r,codeVerifier:i,redirectURI:a,options:e}),{data:s,error:l}=await (0,rU.f)(t,{method:"POST",body:o,headers:n});return l?(eA.y.error("GitHub OAuth token exchange failed:",l),null):"error"in s?(eA.y.error("GitHub OAuth token exchange failed:",s),null):(0,re.i)(s)},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>rj({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:i}=await (0,rK.f)("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${t.accessToken}`}});if(i)return null;let{data:a}=await (0,rK.f)("https://api.github.com/user/emails",{headers:{Authorization:`Bearer ${t.accessToken}`,"User-Agent":"better-auth"}});!r.email&&a&&(r.email=(a.find(e=>e.primary)??a[0])?.email);let o=a?.find(e=>e.email===r.email)?.verified??!1,n=await e.mapProfileToUser?.(r);return{user:{name:r.name||r.login||"",email:r.email,image:r.avatar_url,emailVerified:o,...n},data:r}},options:e}},microsoft:e=>{let t=e.tenantId||"common",r=e.authority||"https://login.microsoftonline.com";for(;r.endsWith("/");)r=r.slice(0,-1);let i=`${r}/${t}/oauth2/v2.0/authorize`,a=`${r}/${t}/oauth2/v2.0/token`;if(e.clientSecret&&e.clientAssertion)throw new u.p("Microsoft Entra ID clientAssertion cannot be combined with clientSecret");let o=e.clientAssertion?{method:"private_key_jwt",getClientAssertion:e.clientAssertion}:void 0;return{id:"microsoft",name:"Microsoft EntraID",accountSubject:({profile:e})=>e.oid,createAuthorizationURL(t){if(!(0,re.B)(e.clientId))throw eA.y.error("Client Id is required for Microsoft Entra ID. Make sure to provide it in the options."),new u.p("CLIENT_ID_AND_SECRET_REQUIRED");let r=e.disableDefaultScope?[]:["openid","profile","email","User.Read","offline_access"];return e.scope&&r.push(...e.scope),t.scopes&&r.push(...t.scopes),ry({id:"microsoft",options:e,authorizationEndpoint:i,state:t.state,codeVerifier:t.codeVerifier,scopes:r,redirectURI:t.redirectURI,prompt:e.prompt,loginHint:t.loginHint,additionalParams:t.additionalParams})},validateAuthorizationCode:({code:t,codeVerifier:r,redirectURI:i})=>rB({code:t,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:a,tokenEndpointAuth:o}),idToken:{jwks:e=>r3(e.kid,t,r),algorithms:["RS256"],audience:e.clientId,maxTokenAge:"1h",issuer:"common"!==t&&"organizations"!==t&&"consumers"!==t?`${r}/${t}/v2.0`:void 0,verifyClaims:e=>{let i=e.tid;return"string"==typeof i&&e.iss===`${r}/${i}/v2.0`&&("organizations"!==t||i!==r2)&&("consumers"!==t||i===r2)}},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let r=(0,rV.f)(t.idToken);if("string"!=typeof r.oid||0===r.oid.trim().length)return eA.y.error("Microsoft Entra ID token did not include a valid oid claim; unable to resolve a stable account identifier."),null;let i=e.profilePhotoSize||48;!e.disableProfilePhoto&&t.accessToken&&await (0,rK.f)(`https://graph.microsoft.com/v1.0/me/photos/${i}x${i}/$value`,{headers:{Authorization:`Bearer ${t.accessToken}`},async onResponse(e){if(e.response.ok)try{let t=await e.response.clone().arrayBuffer(),i=c.t.encode(t);r.picture=`data:image/jpeg;base64, ${i}`}catch(e){eA.y.error(e&&"object"==typeof e&&"name"in e?e.name:"",e)}}});let a=await e.mapProfileToUser?.(r),o=void 0!==r.email_verified?(0,re.r)(r.email_verified):!!(r.email&&(r.verified_primary_email?.includes(r.email)||r.verified_secondary_email?.includes(r.email)));return{user:{name:r.name,email:r.email,image:r.picture,emailVerified:o,...a},data:r}},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>{let r=e.disableDefaultScope?[]:["openid","profile","email","User.Read","offline_access"];return e.scope&&r.push(...e.scope),rj({refreshToken:t,options:{clientId:e.clientId,clientSecret:e.clientSecret},extraParams:{scope:r.join(" ")},tokenEndpoint:a,tokenEndpointAuth:o})},options:e}},google:e=>({id:"google",name:"Google",accountSubject:({profile:e})=>e.sub,async createAuthorizationURL({state:t,scopes:r,codeVerifier:i,redirectURI:a,loginHint:o,display:n,additionalParams:s}){if(!(0,re.B)(e.clientId)||!e.clientSecret)throw eA.y.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new u.p("CLIENT_ID_AND_SECRET_REQUIRED");if(!i)throw new u.p("codeVerifier is required for Google");let l=e.disableDefaultScope?[]:["email","profile","openid"];return e.scope&&l.push(...e.scope),r&&l.push(...r),await ry({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/v2/auth",scopes:l,state:t,codeVerifier:i,redirectURI:a,prompt:e.prompt,accessType:e.accessType,display:n||e.display,loginHint:o,hd:e.hd,additionalParams:{...!1===e.includeGrantedScopes?{}:{include_granted_scopes:"true"},...s??{}}})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:i})=>rB({code:t,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>rj({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:"https://oauth2.googleapis.com/token"}),idToken:{jwks:e=>r0(e.kid),issuer:["https://accounts.google.com","accounts.google.com"],audience:e.clientId,algorithms:rZ,maxTokenAge:"1h",verifyClaims:e.hd?t=>rX(e.hd,t.hd):void 0},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let r=(0,rV.f)(t.idToken);if(!rX(e.hd,r.hd))return eA.y.error(`Google sign-in rejected: id token hosted domain (hd) "${r.hd??"<missing>"}" does not satisfy the configured "hd" option "${e.hd}".`),null;let i=await e.mapProfileToUser?.(r);return{user:{name:r.name,email:r.email,image:r.picture,emailVerified:r.email_verified,...i},data:r}},options:e}),huggingface:e=>{let t="https://huggingface.co/oauth/token";return{id:"huggingface",name:"Hugging Face",accountSubject:({profile:e})=>e.sub,createAuthorizationURL({state:t,scopes:r,codeVerifier:i,redirectURI:a,additionalParams:o}){let n=e.disableDefaultScope?[]:["openid","profile","email"];return e.scope&&n.push(...e.scope),r&&n.push(...r),ry({id:"huggingface",options:e,authorizationEndpoint:"https://huggingface.co/oauth/authorize",scopes:n,state:t,codeVerifier:i,redirectURI:a,additionalParams:o})},validateAuthorizationCode:async({code:r,codeVerifier:i,redirectURI:a})=>rB({code:r,codeVerifier:i,redirectURI:a,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>rj({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:i}=await (0,rK.f)("https://huggingface.co/oauth/userinfo",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(i)return null;let a=await e.mapProfileToUser?.(r);return{user:{name:r.name||r.preferred_username||"",email:r.email,image:r.picture,emailVerified:r.email_verified??!1,...a},data:r}},options:e}},slack:e=>{let t="https://slack.com/api/openid.connect.token";return{id:"slack",name:"Slack",accountSubject:({profile:e})=>e["https://slack.com/user_id"],createAuthorizationURL({state:t,scopes:r,redirectURI:i,additionalParams:a}){let o=e.disableDefaultScope?[]:["openid","profile","email"];return r&&o.push(...r),e.scope&&o.push(...e.scope),ry({id:"slack",options:e,authorizationEndpoint:"https://slack.com/openid/connect/authorize",scopes:o,state:t,redirectURI:i,additionalParams:a})},validateAuthorizationCode:async({code:r,redirectURI:i})=>rB({code:r,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>rj({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:i}=await (0,rK.f)("https://slack.com/api/openid.connect.userInfo",{headers:{authorization:`Bearer ${t.accessToken}`}});if(i)return null;let a=await e.mapProfileToUser?.(r);return{user:{name:r.name||"",email:r.email,emailVerified:r.email_verified,image:r.picture||r["https://slack.com/user_image_512"],...a},data:r}},options:e}},spotify:e=>{let t="https://accounts.spotify.com/api/token";return{id:"spotify",name:"Spotify",accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:r,codeVerifier:i,redirectURI:a,additionalParams:o}){let n=e.disableDefaultScope?[]:["user-read-email"];return e.scope&&n.push(...e.scope),r&&n.push(...r),ry({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:n,state:t,codeVerifier:i,redirectURI:a,additionalParams:o})},validateAuthorizationCode:async({code:r,codeVerifier:i,redirectURI:a})=>rB({code:r,codeVerifier:i,redirectURI:a,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>rj({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:i}=await (0,rK.f)("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(i)return null;let a=await e.mapProfileToUser?.(r);return{user:{name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1,...a},data:r}},options:e}},twitch:e=>{let t="https://id.twitch.tv/oauth2/token";return{id:"twitch",name:"Twitch",accountSubject:({profile:e})=>e.sub,createAuthorizationURL({state:t,scopes:r,redirectURI:i,additionalParams:a}){let o=e.disableDefaultScope?[]:["user:read:email","openid"];return e.scope&&o.push(...e.scope),r&&o.push(...r),ry({id:"twitch",redirectURI:i,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:o,state:t,claims:e.claims||["email","email_verified","preferred_username","picture"],additionalParams:a})},validateAuthorizationCode:async({code:r,redirectURI:i})=>rB({code:r,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>rj({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let r=t.idToken;if(!r)return eA.y.error("No idToken found in token"),null;let i=(0,rV.f)(r),a=await e.mapProfileToUser?.(i);return{user:{name:i.preferred_username,email:i.email,image:i.picture,emailVerified:i.email_verified,...a},data:i}},options:e}},twitter:e=>{let t="https://api.x.com/2/oauth2/token";return{id:"twitter",name:"Twitter",accountSubject:({profile:e})=>e.data.id,createAuthorizationURL(t){let r=e.disableDefaultScope?[]:["users.read","tweet.read","offline.access","users.email"];return e.scope&&r.push(...e.scope),t.scopes&&r.push(...t.scopes),ry({id:"twitter",options:e,authorizationEndpoint:"https://x.com/i/oauth2/authorize",scopes:r,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI,additionalParams:t.additionalParams})},validateAuthorizationCode:async({code:r,codeVerifier:i,redirectURI:a})=>rB({code:r,codeVerifier:i,authentication:"basic",redirectURI:a,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>rj({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},authentication:"basic",tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:i}=await (0,rK.f)("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(i)return null;let{data:a,error:o}=await (0,rK.f)("https://api.x.com/2/users/me?user.fields=confirmed_email",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}}),n=!1;!o&&a?.data?.confirmed_email&&(r.data.email=a.data.confirmed_email,n=!0);let s=await e.mapProfileToUser?.(r);return{user:{name:r.data.name,email:r.data.email||r5({identifier:r.data.id,namespace:"twitter"}),image:r.data.profile_image_url,emailVerified:n,...s},data:r}},options:e}},dropbox:e=>{let t="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",accountSubject:({profile:e})=>e.account_id,createAuthorizationURL:async({state:t,scopes:r,codeVerifier:i,redirectURI:a,additionalParams:o})=>{let n=e.disableDefaultScope?[]:["account_info.read"];return e.scope&&n.push(...e.scope),r&&n.push(...r),await ry({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:n,state:t,redirectURI:a,codeVerifier:i,additionalParams:{...e.accessType?{token_access_type:e.accessType}:{},...o??{}}})},validateAuthorizationCode:async({code:r,codeVerifier:i,redirectURI:a})=>await rB({code:r,codeVerifier:i,redirectURI:a,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>rj({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:i}=await (0,rK.f)("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${t.accessToken}`}});if(i)return null;let a=await e.mapProfileToUser?.(r);return{user:{name:r.name?.display_name,email:r.email,emailVerified:r.email_verified||!1,image:r.profile_photo_url,...a},data:r}},options:e}},kick:e=>({id:"kick",name:"Kick",accountSubject:({profile:e})=>e.user_id,createAuthorizationURL({state:t,scopes:r,redirectURI:i,codeVerifier:a,additionalParams:o}){let n=e.disableDefaultScope?[]:["user:read"];return e.scope&&n.push(...e.scope),r&&n.push(...r),ry({id:"kick",redirectURI:i,options:e,authorizationEndpoint:"https://id.kick.com/oauth/authorize",scopes:n,codeVerifier:a,state:t,additionalParams:o})},validateAuthorizationCode:async({code:t,redirectURI:r,codeVerifier:i})=>rB({code:t,redirectURI:r,options:e,tokenEndpoint:"https://id.kick.com/oauth/token",codeVerifier:i}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>rj({refreshToken:t,options:{clientId:e.clientId,clientSecret:e.clientSecret},tokenEndpoint:"https://id.kick.com/oauth/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:i}=await (0,rK.f)("https://api.kick.com/public/v1/users",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(i)return null;let a=r.data[0],o=await e.mapProfileToUser?.(a);return{user:{name:a.name,email:a.email,image:a.profile_picture,emailVerified:!1,...o},data:a}},options:e}),linear:e=>{let t="https://api.linear.app/oauth/token";return{id:"linear",name:"Linear",accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:r,loginHint:i,redirectURI:a,additionalParams:o}){let n=e.disableDefaultScope?[]:["read"];return e.scope&&n.push(...e.scope),r&&n.push(...r),ry({id:"linear",options:e,authorizationEndpoint:"https://linear.app/oauth/authorize",scopes:n,state:t,redirectURI:a,loginHint:i,additionalParams:o})},validateAuthorizationCode:async({code:r,redirectURI:i})=>rB({code:r,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>rj({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:i}=await (0,rK.f)("https://api.linear.app/graphql",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.accessToken}`},body:JSON.stringify({query:`
|
|
95
95
|
query {
|
|
96
96
|
viewer {
|
|
97
97
|
id
|
|
@@ -103,7 +103,7 @@ module.exports=[363004,931129,950551,342e3,729522,100762,661372,374091,339507,20
|
|
|
103
103
|
updatedAt
|
|
104
104
|
}
|
|
105
105
|
}
|
|
106
|
-
`})});if(i||!r?.data?.viewer)return null;let a=r.data.viewer,o=await e.mapProfileToUser?.(a);return{user:{name:r.data.viewer.name,email:r.data.viewer.email,image:r.data.viewer.avatarUrl,emailVerified:!1,...o},data:a}},options:e}},linkedin:e=>{let t="https://www.linkedin.com/oauth/v2/accessToken";return{id:"linkedin",name:"Linkedin",accountSubject:({profile:e})=>e.sub,createAuthorizationURL:async({state:t,scopes:r,redirectURI:i,loginHint:a,additionalParams:o})=>{let n=e.disableDefaultScope?[]:["profile","email","openid"];return e.scope&&n.push(...e.scope),r&&n.push(...r),await ry({id:"linkedin",options:e,authorizationEndpoint:"https://www.linkedin.com/oauth/v2/authorization",scopes:n,state:t,loginHint:a,redirectURI:i,additionalParams:o})},validateAuthorizationCode:async({code:r,redirectURI:i})=>await rB({code:r,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>rj({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:i}=await (0,rK.f)("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(i)return null;let a=await e.mapProfileToUser?.(r);return{user:{name:r.name,email:r.email,emailVerified:r.email_verified??!1,image:r.picture,...a},data:r}},options:e}},gitlab:e=>{let t,{authorizationEndpoint:r,tokenEndpoint:i,userinfoEndpoint:a}=(t=e.issuer||"https://gitlab.com",{authorizationEndpoint:rG(`${t}/oauth/authorize`),tokenEndpoint:rG(`${t}/oauth/token`),userinfoEndpoint:rG(`${t}/api/v4/user`)}),o="gitlab";return{id:o,name:"Gitlab",accountSubject:({profile:e})=>e.id,createAuthorizationURL:async({state:t,scopes:i,codeVerifier:a,loginHint:n,redirectURI:s,additionalParams:l})=>{let c=e.disableDefaultScope?[]:["read_user"];return e.scope&&c.push(...e.scope),i&&c.push(...i),await ry({id:o,options:e,authorizationEndpoint:r,scopes:c,state:t,redirectURI:s,codeVerifier:a,loginHint:n,additionalParams:l})},validateAuthorizationCode:async({code:t,redirectURI:r,codeVerifier:a})=>rB({code:t,redirectURI:r,options:e,codeVerifier:a,tokenEndpoint:i}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>rj({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:i}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:i}=await (0,rK.f)(a,{headers:{authorization:`Bearer ${t.accessToken}`}});if(i||"active"!==r.state||r.locked)return null;let o=await e.mapProfileToUser?.(r);return{user:{name:r.name??r.username??"",email:r.email,image:r.avatar_url,emailVerified:r.email_verified??!1,...o},data:r}},options:e}},tiktok:e=>{let t="https://open.tiktokapis.com/v2/oauth/token/",r={method:"custom",customizeRequest({body:t}){t.set("client_key",e.clientKey),t.set("client_secret",e.clientSecret)}};return{id:"tiktok",name:"TikTok",accountSubject:({profile:e})=>e.data.user.open_id,createAuthorizationURL({state:t,scopes:r,redirectURI:i,additionalParams:a}){let o=e.disableDefaultScope?[]:["user.info.profile"];e.scope&&o.push(...e.scope),r&&o.push(...r);let n=new URL("https://www.tiktok.com/v2/auth/authorize");if(n.searchParams.set("scope",o.join(",")),n.searchParams.set("response_type","code"),n.searchParams.set("client_key",e.clientKey),n.searchParams.set("redirect_uri",e.redirectURI||i),n.searchParams.set("state",t),a)for(let[e,t]of Object.entries(a))rw.has(e)||"client_key"!==e&&n.searchParams.set(e,t);return n},validateAuthorizationCode:async({code:i,codeVerifier:a,redirectURI:o})=>rB({code:i,codeVerifier:a,redirectURI:e.redirectURI||o,options:{},tokenEndpoint:t,tokenEndpointAuth:r}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async e=>rj({refreshToken:e,options:{},tokenEndpoint:t,tokenEndpointAuth:r}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:i}=await (0,rK.f)("https://open.tiktokapis.com/v2/user/info/?fields=open_id,avatar_large_url,display_name,username",{headers:{authorization:`Bearer ${t.accessToken}`}});return i?null:{user:{email:r.data.user.email||r5({identifier:r.data.user.open_id,namespace:"tiktok"}),name:r.data.user.display_name||r.data.user.username||"",image:r.data.user.avatar_large_url,emailVerified:!1},data:r}},options:e}},reddit:e=>{let t="https://www.reddit.com/api/v1/access_token",r={clientId:e.clientId,clientSecret:e.clientSecret},i={method:"client_secret_basic"};return{id:"reddit",name:"Reddit",accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:r,redirectURI:i,additionalParams:a}){let o=e.disableDefaultScope?[]:["identity"];return e.scope&&o.push(...e.scope),r&&o.push(...r),ry({id:"reddit",options:e,authorizationEndpoint:"https://www.reddit.com/api/v1/authorize",scopes:o,state:t,redirectURI:i,duration:e.duration,additionalParams:a})},validateAuthorizationCode:async({code:a,redirectURI:o})=>rB({code:a,redirectURI:e.redirectURI||o,options:r,tokenEndpoint:t,tokenEndpointAuth:i,headers:{accept:"text/plain","user-agent":"better-auth"}}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async e=>rj({refreshToken:e,options:r,tokenEndpoint:t,tokenEndpointAuth:i}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:i}=await (0,rK.f)("https://oauth.reddit.com/api/v1/me",{headers:{Authorization:`Bearer ${t.accessToken}`,"User-Agent":"better-auth"}});if(i)return null;let a=await e.mapProfileToUser?.(r),o=a?.email||r5({identifier:r.id,namespace:"reddit"});return{user:{name:r.name,image:r.icon_img?.split("?")[0],...a,email:o,emailVerified:a?.emailVerified??!1},data:r}},options:e}},roblox:e=>{let t="https://apis.roblox.com/oauth/v1/token";return{id:"roblox",name:"Roblox",accountSubject:({profile:e})=>e.sub,createAuthorizationURL({state:t,scopes:r,redirectURI:i,additionalParams:a}){let o=e.disableDefaultScope?[]:["openid","profile"];return e.scope&&o.push(...e.scope),r&&o.push(...r),ry({id:"roblox",options:e,authorizationEndpoint:"https://apis.roblox.com/oauth/v1/authorize",scopes:o,state:t,redirectURI:i,prompt:e.prompt||"select_account consent",additionalParams:a})},validateAuthorizationCode:async({code:r,redirectURI:i})=>rB({code:r,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:t,authentication:"post"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>rj({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:i}=await (0,rK.f)("https://apis.roblox.com/oauth/v1/userinfo",{headers:{authorization:`Bearer ${t.accessToken}`}});if(i)return null;let a=await e.mapProfileToUser?.(r);return{user:{name:r.nickname||r.preferred_username||"",image:r.picture,email:r5({identifier:r.sub,namespace:"roblox"}),emailVerified:!1,...a},data:{...r}}},options:e}},salesforce:e=>{let t=(e.environment??"production")==="sandbox",r=e.loginUrl?`https://${e.loginUrl}/services/oauth2/authorize`:t?"https://test.salesforce.com/services/oauth2/authorize":"https://login.salesforce.com/services/oauth2/authorize",i=e.loginUrl?`https://${e.loginUrl}/services/oauth2/token`:t?"https://test.salesforce.com/services/oauth2/token":"https://login.salesforce.com/services/oauth2/token",a=e.loginUrl?`https://${e.loginUrl}/services/oauth2/userinfo`:t?"https://test.salesforce.com/services/oauth2/userinfo":"https://login.salesforce.com/services/oauth2/userinfo";return{id:"salesforce",name:"Salesforce",accountSubject:({profile:e})=>e.user_id,async createAuthorizationURL({state:t,scopes:i,codeVerifier:a,redirectURI:o,additionalParams:n}){if(!e.clientId||!e.clientSecret)throw eA.y.error("Client Id and Client Secret are required for Salesforce. Make sure to provide them in the options."),new u.p("CLIENT_ID_AND_SECRET_REQUIRED");if(!a)throw new u.p("codeVerifier is required for Salesforce");let s=e.disableDefaultScope?[]:["openid","email","profile"];return e.scope&&s.push(...e.scope),i&&s.push(...i),ry({id:"salesforce",options:e,authorizationEndpoint:r,scopes:s,state:t,codeVerifier:a,redirectURI:e.redirectURI||o,additionalParams:n})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:a})=>rB({code:t,codeVerifier:r,redirectURI:e.redirectURI||a,options:e,tokenEndpoint:i}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>rj({refreshToken:t,options:{clientId:e.clientId,clientSecret:e.clientSecret},tokenEndpoint:i}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);try{let{data:r}=await (0,rK.f)(a,{headers:{Authorization:`Bearer ${t.accessToken}`}});if(!r)return eA.y.error("Failed to fetch user info from Salesforce"),null;let i=await e.mapProfileToUser?.(r);return{user:{name:r.name,email:r.email,image:r.photos?.picture||r.photos?.thumbnail,emailVerified:r.email_verified??!1,...i},data:r}}catch(e){return eA.y.error("Failed to fetch user info from Salesforce:",e),null}},options:e}},vk:e=>{let t="https://id.vk.com/oauth2/auth";return{id:"vk",name:"VK",accountSubject:({profile:e})=>e.user.user_id,async createAuthorizationURL({state:t,scopes:r,codeVerifier:i,redirectURI:a,additionalParams:o}){let n=e.disableDefaultScope?[]:["email","phone"];return e.scope&&n.push(...e.scope),r&&n.push(...r),ry({id:"vk",options:e,authorizationEndpoint:"https://id.vk.com/authorize",scopes:n,state:t,redirectURI:a,codeVerifier:i,additionalParams:o})},validateAuthorizationCode:async({code:r,codeVerifier:i,redirectURI:a,deviceId:o})=>rB({code:r,codeVerifier:i,redirectURI:e.redirectURI||a,options:e,deviceId:o,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>rj({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.accessToken)return null;let r=new URLSearchParams({access_token:t.accessToken,client_id:e.clientId}).toString(),{data:i,error:a}=await (0,rK.f)("https://id.vk.com/oauth2/user_info",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r});if(a)return null;let o=await e.mapProfileToUser?.(i);return i.user.email||o?.email?{user:{first_name:i.user.first_name,last_name:i.user.last_name,email:i.user.email,image:i.user.avatar,emailVerified:!1,birthday:i.user.birthday,sex:i.user.sex,name:`${i.user.first_name} ${i.user.last_name}`,...o},data:i}:null},options:e}},zoom:e=>{let t={pkce:!0,...e};return{id:"zoom",name:"Zoom",accountSubject:({profile:e})=>e.id,createAuthorizationURL:async({state:e,redirectURI:r,codeVerifier:i,additionalParams:a})=>ry({id:"zoom",options:t,authorizationEndpoint:"https://zoom.us/oauth/authorize",state:e,redirectURI:r,codeVerifier:t.pkce?i:void 0,additionalParams:a}),validateAuthorizationCode:async({code:e,redirectURI:r,codeVerifier:i})=>rB({code:e,redirectURI:t.redirectURI||r,codeVerifier:i,options:t,tokenEndpoint:"https://zoom.us/oauth/token",authentication:"post"}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async e=>rj({refreshToken:e,options:{clientId:t.clientId,clientKey:t.clientKey,clientSecret:t.clientSecret},tokenEndpoint:"https://zoom.us/oauth/token"}),async getUserInfo(e){if(t.getUserInfo)return t.getUserInfo(e);let{data:r,error:i}=await (0,rK.f)("https://api.zoom.us/v2/users/me",{headers:{authorization:`Bearer ${e.accessToken}`}});if(i)return null;let a=await t.mapProfileToUser?.(r);return{user:{name:r.display_name,image:r.pic_url,email:r.email,emailVerified:!!r.verified,...a},data:{...r}}},options:t}},notion:e=>{let t="https://api.notion.com/v1/oauth/token";return{id:"notion",name:"Notion",accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:r,loginHint:i,redirectURI:a,additionalParams:o}){let n=(e.disableDefaultScope,[]);return e.scope&&n.push(...e.scope),r&&n.push(...r),ry({id:"notion",options:e,authorizationEndpoint:"https://api.notion.com/v1/oauth/authorize",scopes:n,state:t,redirectURI:a,loginHint:i,additionalParams:{...o??{},owner:"user"}})},validateAuthorizationCode:async({code:r,redirectURI:i})=>rB({code:r,redirectURI:i,options:e,tokenEndpoint:t,authentication:"basic"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>rj({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:i}=await (0,rK.f)("https://api.notion.com/v1/users/me",{headers:{Authorization:`Bearer ${t.accessToken}`,"Notion-Version":"2022-06-28"}});if(i||!r)return null;let a=r.bot?.owner?.user;if(!a)return null;let o=await e.mapProfileToUser?.(a);return{user:{name:a.name||"",email:a.person?.email||null,image:a.avatar_url,emailVerified:!1,...o},data:a}},options:e}},kakao:e=>{let t="https://kauth.kakao.com/oauth/token";return{id:"kakao",name:"Kakao",accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:r,redirectURI:i,loginHint:a,additionalParams:o}){let n=e.disableDefaultScope?[]:["account_email","profile_image","profile_nickname"];return e.scope&&n.push(...e.scope),r&&n.push(...r),ry({id:"kakao",options:e,authorizationEndpoint:"https://kauth.kakao.com/oauth/authorize",scopes:n,state:t,redirectURI:i,loginHint:a,additionalParams:o})},validateAuthorizationCode:async({code:r,redirectURI:i})=>rB({code:r,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>rj({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:i}=await (0,rK.f)("https://kapi.kakao.com/v2/user/me",{headers:{Authorization:`Bearer ${t.accessToken}`}});if(i||!r)return null;let a=await e.mapProfileToUser?.(r),o=r.kakao_account||{},n=o.profile||{};return{user:{name:n.nickname||o.name||"",email:o.email,image:n.profile_image_url||n.thumbnail_image_url,emailVerified:!!o.is_email_valid&&!!o.is_email_verified,...a},data:r}},options:e}},naver:e=>{let t="https://nid.naver.com/oauth2.0/token";return{id:"naver",name:"Naver",accountSubject:({profile:e})=>e.response.id,createAuthorizationURL({state:t,scopes:r,redirectURI:i,additionalParams:a}){let o=e.disableDefaultScope?[]:["profile","email"];return e.scope&&o.push(...e.scope),r&&o.push(...r),ry({id:"naver",options:e,authorizationEndpoint:"https://nid.naver.com/oauth2.0/authorize",scopes:o,state:t,redirectURI:i,additionalParams:a})},validateAuthorizationCode:async({code:r,redirectURI:i})=>rB({code:r,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>rj({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:i}=await (0,rK.f)("https://openapi.naver.com/v1/nid/me",{headers:{Authorization:`Bearer ${t.accessToken}`}});if(i||!r||"00"!==r.resultcode)return null;let a=await e.mapProfileToUser?.(r),o=r.response||{};return{user:{name:o.name||o.nickname||"",email:o.email,image:o.profile_image,emailVerified:!1,...a},data:r}},options:e}},line:e=>{let t="https://api.line.me/oauth2/v2.1/token";return{id:"line",name:"LINE",accountSubject:({profile:e})=>e.sub,async createAuthorizationURL({state:t,scopes:r,codeVerifier:i,redirectURI:a,loginHint:o,additionalParams:n}){let s=e.disableDefaultScope?[]:["openid","profile","email"];return e.scope&&s.push(...e.scope),r&&s.push(...r),await ry({id:"line",options:e,authorizationEndpoint:"https://access.line.me/oauth2/v2.1/authorize",scopes:s,state:t,codeVerifier:i,redirectURI:a,loginHint:o,additionalParams:n})},validateAuthorizationCode:async({code:r,codeVerifier:i,redirectURI:a})=>rB({code:r,codeVerifier:i,redirectURI:a,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>rj({refreshToken:r,options:{clientId:e.clientId,clientSecret:e.clientSecret},tokenEndpoint:t}),idToken:{verify:async(t,r)=>{let i=new URLSearchParams;i.set("id_token",t),i.set("client_id",e.clientId),r&&i.set("nonce",r);let{data:a,error:o}=await (0,rU.f)("https://api.line.me/oauth2/v2.1/verify",{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:i});return!o&&!!a&&a.aud===e.clientId&&(!a.nonce||a.nonce===r)}},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let r=null;if(t.idToken)try{r=(0,rV.f)(t.idToken)}catch{}if(!r){let{data:e}=await (0,rK.f)("https://api.line.me/oauth2/v2.1/userinfo",{headers:{authorization:`Bearer ${t.accessToken}`}});r=e||null}if(!r)return null;let i=await e.mapProfileToUser?.(r);return{user:{name:r.name||"",email:r.email,image:r.picture,emailVerified:!1,...i},data:r}},options:e}},paybin:e=>{let t=e.issuer||"https://idp.paybin.io",r=`${t}/oauth2/authorize`,i=`${t}/oauth2/token`;return{id:"paybin",name:"Paybin",accountSubject:({profile:e})=>e.sub,async createAuthorizationURL({state:t,scopes:i,codeVerifier:a,redirectURI:o,loginHint:n,additionalParams:s}){if(!e.clientId||!e.clientSecret)throw eA.y.error("Client Id and Client Secret is required for Paybin. Make sure to provide them in the options."),new u.p("CLIENT_ID_AND_SECRET_REQUIRED");if(!a)throw new u.p("codeVerifier is required for Paybin");let l=e.disableDefaultScope?[]:["openid","email","profile"];return e.scope&&l.push(...e.scope),i&&l.push(...i),await ry({id:"paybin",options:e,authorizationEndpoint:r,scopes:l,state:t,codeVerifier:a,redirectURI:o,prompt:e.prompt,loginHint:n,additionalParams:s})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:a})=>rB({code:t,codeVerifier:r,redirectURI:a,options:e,tokenEndpoint:i}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>rj({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:i}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let r=(0,rV.f)(t.idToken),i=await e.mapProfileToUser?.(r);return{user:{name:r.name||r.preferred_username||"",email:r.email,image:r.picture,emailVerified:r.email_verified||!1,...i},data:r}},options:e}},paypal:e=>{let t="sandbox"===(e.environment||"sandbox"),r=t?"https://www.sandbox.paypal.com/signin/authorize":"https://www.paypal.com/signin/authorize",i=t?"https://api-m.sandbox.paypal.com/v1/oauth2/token":"https://api-m.paypal.com/v1/oauth2/token",a=t?"https://api-m.sandbox.paypal.com/v1/identity/oauth2/userinfo":"https://api-m.paypal.com/v1/identity/oauth2/userinfo",o={clientId:e.clientId,clientSecret:e.clientSecret},n={method:"client_secret_basic"};return{id:"paypal",name:"PayPal",accountSubject:({profile:e})=>e.user_id,async createAuthorizationURL({state:t,codeVerifier:i,redirectURI:a,additionalParams:o}){if(!e.clientId||!e.clientSecret)throw eA.y.error("Client Id and Client Secret is required for PayPal. Make sure to provide them in the options."),new u.p("CLIENT_ID_AND_SECRET_REQUIRED");return await ry({id:"paypal",options:e,authorizationEndpoint:r,scopes:[],state:t,codeVerifier:i,redirectURI:a,prompt:e.prompt,additionalParams:o})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:a})=>{try{return await rB({code:t,codeVerifier:r,redirectURI:e.redirectURI||a,options:o,tokenEndpoint:i,tokenEndpointAuth:n})}catch(e){throw eA.y.error("PayPal token exchange failed:",e),new u.p("FAILED_TO_GET_ACCESS_TOKEN")}},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async e=>{try{return await rj({refreshToken:e,options:o,tokenEndpoint:i,tokenEndpointAuth:n})}catch(e){throw eA.y.error("PayPal token refresh failed:",e),new u.p("FAILED_TO_REFRESH_ACCESS_TOKEN")}},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.accessToken)return eA.y.error("Access token is required to fetch PayPal user info"),null;try{let r=await (0,rK.f)(`${a}?schema=paypalv1.1`,{headers:{Authorization:`Bearer ${t.accessToken}`,Accept:"application/json"}});if(!r.data)return eA.y.error("Failed to fetch user info from PayPal"),null;let i=r.data;if(t.idToken){let e;try{e=(0,rV.f)(t.idToken).sub}catch(e){return eA.y.error("Failed to decode PayPal ID token:",e),null}let r=i.sub??i.user_id;if(!e||r!==e)return eA.y.error("PayPal user info subject does not match ID token subject"),null}let o=await e.mapProfileToUser?.(i);return{user:{name:i.name,email:i.email,image:i.picture,emailVerified:i.email_verified,...o},data:i}}catch(e){return eA.y.error("Failed to fetch user info from PayPal:",e),null}},options:e}},polar:e=>{let t="https://api.polar.sh/v1/oauth2/token";return{id:"polar",name:"Polar",accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:r,codeVerifier:i,redirectURI:a,additionalParams:o}){let n=e.disableDefaultScope?[]:["openid","profile","email"];return e.scope&&n.push(...e.scope),r&&n.push(...r),ry({id:"polar",options:e,authorizationEndpoint:"https://polar.sh/oauth2/authorize",scopes:n,state:t,codeVerifier:i,redirectURI:a,prompt:e.prompt,additionalParams:o})},validateAuthorizationCode:async({code:r,codeVerifier:i,redirectURI:a})=>rB({code:r,codeVerifier:i,redirectURI:a,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>rj({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:i}=await (0,rK.f)("https://api.polar.sh/v1/oauth2/userinfo",{headers:{Authorization:`Bearer ${t.accessToken}`}});if(i)return null;let a=await e.mapProfileToUser?.(r);return{user:{name:r.public_name||r.username||"",email:r.email,image:r.avatar_url,emailVerified:r.email_verified??!1,...a},data:r}},options:e}},railway:e=>({id:"railway",name:"Railway",accountSubject:({profile:e})=>e.sub,createAuthorizationURL({state:t,scopes:r,codeVerifier:i,redirectURI:a,additionalParams:o}){let n=e.disableDefaultScope?[]:["openid","email","profile"];return e.scope&&n.push(...e.scope),r&&n.push(...r),ry({id:"railway",options:e,authorizationEndpoint:"https://backboard.railway.com/oauth/auth",scopes:n,state:t,codeVerifier:i,redirectURI:a,additionalParams:o})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:i})=>rB({code:t,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:r6,authentication:"basic"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>rj({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:r6,authentication:"basic"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:i}=await (0,rK.f)("https://backboard.railway.com/oauth/me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(i||!r)return null;let a=await e.mapProfileToUser?.(r);return{user:{name:r.name,email:r.email,image:r.picture,emailVerified:!1,...a},data:r}},options:e}),vercel:e=>{let t=e.tokenEndpointAuth?.method;if(e.clientSecret&&("private_key_jwt"===t||"none"===t))throw new u.p(`Vercel ${t} token endpoint authentication cannot be combined with clientSecret`);if(!e.clientSecret&&("client_secret_basic"===t||"client_secret_post"===t))throw new u.p(`Vercel ${t} token endpoint authentication requires clientSecret`);return{id:"vercel",name:"Vercel",accountSubject:({profile:e})=>e.sub,createAuthorizationURL({state:t,scopes:r,codeVerifier:i,redirectURI:a,additionalParams:o}){let n;if(!i)throw new u.p("codeVerifier is required for Vercel");return(void 0!==e.scope||void 0!==r)&&(n=[],e.scope&&n.push(...e.scope),r&&n.push(...r)),ry({id:"vercel",options:e,authorizationEndpoint:"https://vercel.com/oauth/authorize",scopes:n,state:t,codeVerifier:i,redirectURI:a,additionalParams:o})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:i})=>rB({code:t,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:"https://api.vercel.com/login/oauth/token",tokenEndpointAuth:e.tokenEndpointAuth}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:i}=await (0,rK.f)("https://api.vercel.com/login/oauth/userinfo",{headers:{Authorization:`Bearer ${t.accessToken}`}});if(i||!r)return null;let a=await e.mapProfileToUser?.(r);return{user:{name:r.name??r.preferred_username??"",email:r.email,image:r.picture,emailVerified:r.email_verified??!1,...a},data:r}},options:e}},wechat:e=>({id:"wechat",name:"WeChat",accountSubject:({profile:e})=>e.unionid||e.openid,createAuthorizationURL({state:t,scopes:r,redirectURI:i,additionalParams:a}){let o=e.disableDefaultScope?[]:["snsapi_login"];e.scope&&o.push(...e.scope),r&&o.push(...r);let n=new URL("https://open.weixin.qq.com/connect/qrconnect");if(n.searchParams.set("scope",o.join(",")),n.searchParams.set("response_type","code"),n.searchParams.set("appid",e.clientId),n.searchParams.set("redirect_uri",e.redirectURI||i),n.searchParams.set("state",t),n.searchParams.set("lang",e.lang||"cn"),a)for(let[e,t]of Object.entries(a))rw.has(e)||"appid"!==e&&n.searchParams.set(e,t);return n.hash="wechat_redirect",n},validateAuthorizationCode:async({code:t})=>{let{data:r,error:i}=await (0,rU.f)("https://api.weixin.qq.com/sns/oauth2/access_token",{method:"GET",query:{appid:e.clientId,secret:e.clientSecret,code:t,grant_type:"authorization_code"}});if(i||!r||r.errcode)throw Error(`Failed to validate authorization code: ${r?.errmsg||i?.message||"Unknown error"}`);return{tokenType:"Bearer",accessToken:r.access_token,refreshToken:r.refresh_token,accessTokenExpiresAt:new Date(Date.now()+1e3*r.expires_in),scopes:r.scope.split(","),openid:r.openid,unionid:r.unionid}},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>{let{data:r,error:i}=await (0,rU.f)("https://api.weixin.qq.com/sns/oauth2/refresh_token",{method:"GET",query:{appid:e.clientId,grant_type:"refresh_token",refresh_token:t}});if(i||!r||r.errcode)throw Error(`Failed to refresh access token: ${r?.errmsg||i?.message||"Unknown error"}`);return{tokenType:"Bearer",accessToken:r.access_token,refreshToken:r.refresh_token,accessTokenExpiresAt:new Date(Date.now()+1e3*r.expires_in),scopes:r.scope.split(",")}},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let r=t.openid;if(!r)return null;let i=new URLSearchParams({access_token:t.accessToken||"",openid:r,lang:"zh_CN"}),{data:a,error:o}=await (0,rK.f)("https://api.weixin.qq.com/sns/userinfo?"+i.toString(),{method:"GET"});if(o||!a||a.errcode)return null;let n=await e.mapProfileToUser?.(a),s=a.unionid||a.openid||r;return{user:{name:a.nickname,email:a.email||r5({identifier:s,namespace:"wechat"}),image:a.headimgurl,emailVerified:!1,...n},data:a}},options:e})},r7=Object.keys(r4),r8=E.enum(r7).or(E.string());function r9(e){return e?e.split(",").map(e=>e.trim()).filter(Boolean):[]}let ie=(0,s.g)("/list-accounts",{method:"GET",use:[p.Z],metadata:{openapi:{operationId:"listUserAccounts",description:"List all accounts linked to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"array",items:{type:"object",properties:{id:{type:"string"},providerId:{type:"string"},createdAt:{type:"string",format:"date-time"},updatedAt:{type:"string",format:"date-time"},accountId:{type:"string"},userId:{type:"string"},scopes:{type:"array",items:{type:"string"}}},required:["id","providerId","createdAt","updatedAt","accountId","userId","scopes"]}}}}}}}}},async e=>{let t=e.context.session,r=await e.context.internalAdapter.findAccounts(t.user.id);return e.json(r.map(t=>{let{scope:r,...i}=(0,w.s)(e.context.options,t);return{...i,scopes:r9(r)}}))}),it=(0,s.g)("/link-social",{method:"POST",requireHeaders:!0,body:E.object({callbackURL:E.string().meta({description:"The URL to redirect to after the user has signed in"}).optional(),provider:r8,idToken:E.object({token:E.string(),nonce:E.string().optional(),accessToken:E.string().optional(),refreshToken:E.string().optional()}).optional(),requestSignUp:E.boolean().optional(),scopes:E.array(E.string()).meta({description:"Additional scopes to request from the provider"}).optional(),errorCallbackURL:E.string().meta({description:"The URL to redirect to if there is an error during the link process"}).optional(),disableRedirect:E.boolean().meta({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),loginHint:E.string().meta({description:"The login hint to use for the authorization code request"}).optional(),additionalParams:rb,additionalData:E.record(E.string(),E.any()).optional()}),use:[p.i],metadata:{openapi:{description:"Link a social account to the user",operationId:"linkSocialAccount",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{url:{type:"string",description:"The authorization URL to redirect the user to"},redirect:{type:"boolean",description:"Indicates if the user should be redirected to the authorization URL"},status:{type:"boolean"}},required:["redirect"]}}}}}}}},async e=>{let t=e.context.session,r=await tu(e.context.socialProviders,{value:e.body.provider});if(!r)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),u.E.from("NOT_FOUND",tf.f.PROVIDER_NOT_FOUND);if(e.body.idToken){if(!rT(r))throw e.context.logger.error("Provider does not support id token verification",{provider:e.body.provider}),u.E.from("NOT_FOUND",tf.f.ID_TOKEN_NOT_SUPPORTED);let{token:i,nonce:a}=e.body.idToken;if(!await rv(r,i,a,e))throw e.context.logger.warn("Invalid id token",{provider:e.body.provider}),u.E.from("UNAUTHORIZED",tf.f.INVALID_TOKEN);let o={idToken:i,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken},n=r.getUserInfoFromIdToken?await r.getUserInfoFromIdToken(i):await r.getUserInfo(o);if(!n||!n?.user)throw e.context.logger.error("Failed to get user info",{provider:e.body.provider}),u.E.from("UNAUTHORIZED",tf.f.FAILED_TO_GET_USER_INFO);if(!n.user.email)throw e.context.logger.error(tJ(e.body.provider,{source:"id_token"}),{provider:e.body.provider}),u.E.from("UNAUTHORIZED",tf.f.USER_EMAIL_NOT_FOUND);let s=await tz(r,{idToken:i,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken},n.data),l=await e.context.internalAdapter.findAccountByKey(s);if(l?.userId===t.user.id){let a=Object.fromEntries(Object.entries({providerId:r.id,accessToken:await t0(e.body.idToken.accessToken,e.context),idToken:i,refreshToken:await t0(e.body.idToken.refreshToken,e.context)}).filter(([e,t])=>void 0!==t));return await e.context.internalAdapter.updateAccount(l.id,a),await rn(e,t.user.id,n.user),e.json({url:"",status:!0,redirect:!1})}if(l)throw u.E.from("CONFLICT",tf.f.SOCIAL_ACCOUNT_ALREADY_LINKED);if(!e.context.trustedProviders.includes(r.id)&&!tZ(n.user.emailVerified)||e.context.options.account?.accountLinking?.enabled===!1)throw u.E.from("UNAUTHORIZED",{message:"Account not linked - linking not allowed",code:"LINKING_NOT_ALLOWED"});if(n.user.email?.toLowerCase()!==t.user.email.toLowerCase()&&e.context.options.account?.accountLinking?.allowDifferentEmails!==!0)throw u.E.from("UNAUTHORIZED",{message:"Account not linked - different emails not allowed",code:"LINKING_DIFFERENT_EMAILS_NOT_ALLOWED"});try{await e.context.internalAdapter.createAccount({userId:t.user.id,...s,accessToken:await t0(e.body.idToken.accessToken,e.context),idToken:i,refreshToken:await t0(e.body.idToken.refreshToken,e.context)})}catch{throw u.E.from("EXPECTATION_FAILED",{message:"Account not linked - unable to create account",code:"LINKING_FAILED"})}return await rn(e,t.user.id,n.user),e.json({url:"",status:!0,redirect:!1})}let i=rf(r),a=await rm(e,{link:{userId:t.user.id,email:t.user.email,encryptedSessionToken:await (0,tC.M)({key:tF(e.context.secretConfig,"oauth-link-session-token"),data:t.session.token})},additionalData:e.body.additionalData,idTokenNonce:i}),o=await r.createAuthorizationURL({state:a.state,codeVerifier:a.codeVerifier,idTokenNonce:i,redirectURI:`${e.context.baseURL}${t1(r)}`,scopes:e.body.scopes,loginHint:e.body.loginHint,additionalParams:e.body.additionalParams});return e.body.disableRedirect||e.setHeader("Location",o.toString()),e.json({url:o.toString(),redirect:!e.body.disableRedirect})}),ir=(0,s.g)("/unlink-account",{method:"POST",body:E.object({accountId:E.string().meta({description:"The Better Auth account ID to unlink"})}),use:[p.h],metadata:{openapi:{description:"Unlink an account",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{let{accountId:t}=e.body,r=await e.context.internalAdapter.findAccounts(e.context.session.user.id);if(1===r.length&&!e.context.options.account?.accountLinking?.allowUnlinkingAll)throw u.E.from("BAD_REQUEST",tf.f.FAILED_TO_UNLINK_LAST_ACCOUNT);let i=r.find(e=>e.id===t);if(!i)throw u.E.from("BAD_REQUEST",tf.f.ACCOUNT_NOT_FOUND);return await e.context.internalAdapter.deleteAccount(i.id),e.json({status:!0})});async function ii(e,t){let r=await (0,p.D)(e,{disableCookieCache:(0,p.f)(e)});if(!r&&(e.request||e.headers))throw e.error("UNAUTHORIZED");let i=r?.user?.id||t;if(!i)throw u.E.from("BAD_REQUEST",{message:"Either userId or session is required",code:"USER_ID_OR_SESSION_REQUIRED"});return i}let ia=E.union([E.strictObject({accountId:E.string().meta({description:"The Better Auth account ID"}),userId:E.string().meta({description:"The user ID associated with the account"}).optional()}),E.strictObject({useAccountCookie:E.literal(!0).meta({description:"Select the current OAuth account from its signed cookie"}),userId:E.string().meta({description:"The user ID associated with the account"}).optional()})]);function io(e,t,{resolvedUserId:r,selection:i}){return(!(0,eJ.d)(e.context.options)||t.userId===r)&&(!("accountId"in i)||t.id===i.accountId)}async function is(e,{resolvedUserId:t,selection:r}){if("accountId"in r){let i=(await e.context.internalAdapter.findAccounts(t)).find(e=>e.id===r.accountId);if(i)return{account:i,accountCookie:null}}else if(e.context.options.account?.storeAccountCookie){let i=await (0,tq.q)(e);if(i&&io(e,i,{resolvedUserId:t,selection:r}))return{account:i,accountCookie:i}}throw u.E.from("BAD_REQUEST",tf.f.ACCOUNT_NOT_FOUND)}async function il(e,{resolvedUserId:t,selection:r,account:i}){let a=i??(await is(e,{resolvedUserId:t,selection:r})).account;if(!io(e,a,{resolvedUserId:t,selection:r}))throw u.E.from("BAD_REQUEST",tf.f.ACCOUNT_NOT_FOUND);let o=await tu(e.context.socialProviders,{value:a.providerId});if(!o)throw u.E.from("BAD_REQUEST",{message:`Provider ${a.providerId} is not supported.`,code:"PROVIDER_NOT_SUPPORTED"});try{let t=null,r=a.accessTokenExpiresAt&&new Date(a.accessTokenExpiresAt).getTime()-Date.now()<5e3;if(a.refreshToken&&r&&o.refreshAccessToken){let r=await tX(a.refreshToken,e.context);t=await o.refreshAccessToken(r,e);let i={accessToken:await t0(t?.accessToken,e.context),accessTokenExpiresAt:t?.accessTokenExpiresAt,refreshToken:t?.refreshToken?await t0(t.refreshToken,e.context):a.refreshToken,refreshTokenExpiresAt:t?.refreshTokenExpiresAt??a.refreshTokenExpiresAt,idToken:t?.idToken||a.idToken},n=null;a.id&&(n=await e.context.internalAdapter.updateAccount(a.id,i)),e.context.options.account?.storeAccountCookie&&await (0,tq.L)(e,{...a,...n??i})}let i=t?.accessTokenExpiresAt?"string"==typeof t.accessTokenExpiresAt?new Date(t.accessTokenExpiresAt):t.accessTokenExpiresAt:a.accessTokenExpiresAt?"string"==typeof a.accessTokenExpiresAt?new Date(a.accessTokenExpiresAt):a.accessTokenExpiresAt:void 0;return{accessToken:t?.accessToken??await tX(a.accessToken??"",e.context),accessTokenExpiresAt:i,scopes:r9(a.scope),idToken:t?.idToken??a.idToken??void 0}}catch(e){throw u.E.from("BAD_REQUEST",{message:"Failed to get a valid access token",code:"FAILED_TO_GET_ACCESS_TOKEN"})}}let ic=(0,s.g)("/get-access-token",{method:"POST",body:ia,metadata:{openapi:{description:"Get a valid access token, doing a refresh if needed",responses:{200:{description:"A Valid access token",content:{"application/json":{schema:{type:"object",properties:{tokenType:{type:"string"},idToken:{type:"string"},accessToken:{type:"string"},accessTokenExpiresAt:{type:"string",format:"date-time"}}}}}},400:{description:"Invalid refresh token or provider configuration"}}}}},async e=>{let{userId:t}=e.body,r=await il(e,{resolvedUserId:await ii(e,t),selection:e.body});return e.json(r)}),id=(0,s.g)("/refresh-token",{method:"POST",body:ia,metadata:{openapi:{description:"Refresh the access token using a refresh token",responses:{200:{description:"Access token refreshed successfully",content:{"application/json":{schema:{type:"object",properties:{tokenType:{type:"string"},idToken:{type:"string"},accessToken:{type:"string"},refreshToken:{type:"string"},accessTokenExpiresAt:{type:"string",format:"date-time"},refreshTokenExpiresAt:{type:"string",format:"date-time"}}}}}},400:{description:"Invalid refresh token or provider configuration"}}}}},async e=>{let{userId:t}=e.body,{account:r,accountCookie:i}=await is(e,{resolvedUserId:await ii(e,t),selection:e.body}),a=await tu(e.context.socialProviders,{value:r.providerId});if(!a)throw u.E.from("BAD_REQUEST",{message:`Provider ${r.providerId} is not supported.`,code:"PROVIDER_NOT_SUPPORTED"});if(!a.refreshAccessToken)throw u.E.from("BAD_REQUEST",{message:`Provider ${r.providerId} does not support token refreshing.`,code:"TOKEN_REFRESH_NOT_SUPPORTED"});let o=r.refreshToken??void 0;if(!o)throw u.E.from("BAD_REQUEST",{message:"Refresh token not found",code:"REFRESH_TOKEN_NOT_FOUND"});try{let t=await tX(o,e.context),n=await a.refreshAccessToken(t,e),s=n.refreshToken?await t0(n.refreshToken,e.context):o,l=n.refreshTokenExpiresAt??r.refreshTokenExpiresAt,c={accessToken:await t0(n.accessToken,e.context),refreshToken:s,accessTokenExpiresAt:n.accessTokenExpiresAt,refreshTokenExpiresAt:l,idToken:n.idToken||r.idToken},d=null;if(r.id&&(d=await e.context.internalAdapter.updateAccount(r.id,c)),i?.id===r.id&&e.context.options.account?.storeAccountCookie){let t={...i,...d??c};await (0,tq.L)(e,t)}let u=d?.scope??r.scope;return e.json({accessToken:n.accessToken,refreshToken:n.refreshToken??t,accessTokenExpiresAt:n.accessTokenExpiresAt,refreshTokenExpiresAt:l,scope:u,idToken:n.idToken||r.idToken,providerId:r.providerId,accountId:r.id})}catch(e){throw u.E.from("BAD_REQUEST",{message:"Failed to refresh access token",code:"FAILED_TO_REFRESH_ACCESS_TOKEN"})}}),iu=(0,s.g)("/account-info",{method:"GET",metadata:{openapi:{description:"Get the account info provided by the provider",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object",properties:{name:{type:"string"},email:{type:"string",nullable:!0},image:{type:"string"},emailVerified:{type:"boolean"}},required:["emailVerified"]},account:{type:"object",properties:{id:{type:"string"},providerId:{type:"string"},accountId:{type:"string"}},required:["id","providerId","accountId"],additionalProperties:!1},data:{type:"object",properties:{},additionalProperties:!0}},required:["user","data","account"],additionalProperties:!1}}}}}}},query:ia},async e=>{let{userId:t}=e.query,r=await ii(e,t),{account:i}=await is(e,{resolvedUserId:r,selection:e.query}),a=await tu(e.context.socialProviders,{value:i.providerId});if(!a)throw u.E.from("BAD_REQUEST",{message:"Account is not associated with a configured social provider.",code:"PROVIDER_NOT_CONFIGURED"});let o=await il(e,{resolvedUserId:r,selection:e.query,account:i});if(!o.accessToken)throw u.E.from("BAD_REQUEST",{message:"Access token not found",code:"ACCESS_TOKEN_NOT_FOUND"});let n=await a.getUserInfo({...o,accessToken:o.accessToken});if(!n)throw u.E.from("UNAUTHORIZED",tf.f.FAILED_TO_GET_USER_INFO);return e.json({...n,account:{id:i.id,providerId:i.providerId,accountId:i.accountId}})});async function ip(e,t,r){let i;if(r.iss&&t.issuer&&r.iss!==t.issuer)return e.context.logger.error("OAuth issuer mismatch",{expected:t.issuer,received:r.iss}),{error:"issuer_mismatch"};if(t.requiresIdTokenNonce&&!r.idTokenNonce)return e.context.logger.error("OAuth id_token nonce binding required but no expected nonce was found in state",{providerId:t.id}),{error:"nonce_binding_missing"};try{i=await t.validateAuthorizationCode({code:r.code,codeVerifier:r.codeVerifier,deviceId:r.deviceId,redirectURI:`${e.context.baseURL}${t1(t)}`})}catch(t){return e.context.logger.error("Failed to validate authorization code",t),{error:tH}}if(!i)return{error:tH};let a=await t.getUserInfo({...i,expectedIdTokenNonce:r.idTokenNonce,user:(0,b.f)(r.user)??void 0});if(!a?.user)return e.context.logger.error("Unable to get user info"),{error:tW};let o=await tK(t,i,a.data).catch(r=>(e.context.logger.error("Unable to derive provider account identity",{providerId:t.id,error:r}),null));return o?{tokens:i,userInfo:a.user,providerProfile:a.data,accountKey:o}:{error:tW}}let im={scope:"server"},ih=E.object({code:E.string().optional(),error:E.string().optional(),device_id:E.string().optional(),error_description:E.string().optional(),state:E.string().optional(),user:E.string().optional(),iss:E.string().optional()}),ig=(0,s.g)("/callback/:id",{method:["GET","POST"],operationId:"handleOAuthCallback",body:ih.optional(),query:ih.optional(),metadata:{...im,allowedMediaTypes:["application/x-www-form-urlencoded","application/json"]}},async e=>{let t,r,i,a=e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`;if("POST"===e.method){let t=e.body?ih.parse(e.body):{},r=e.query?ih.parse(e.query):{},i=ih.parse({...t,...r}),a=new URLSearchParams;for(let[e,t]of Object.entries(i))null!=t&&a.set(e,String(t));let o=`${e.context.baseURL}/callback/${e.params.id}?${a.toString()}`;throw e.redirect(o)}try{if("GET"===e.method)t=ih.parse(e.query);else if("POST"===e.method)t=ih.parse(e.body);else throw Error("Unsupported method")}catch(i){e.context.logger.error("INVALID_CALLBACK_REQUEST",i);let t=new URLSearchParams({error:"invalid_callback_request"}),r=(0,tE.M)(a,t);throw e.redirect(r)}let{code:o,error:n,state:s,error_description:l,device_id:c,user:d,iss:u}=t;if(void 0===s&&o){let t=await tu(e.context.socialProviders,{value:e.params.id});if(t?.allowIdpInitiated){let r=rf(t),{state:i,codeVerifier:a}=await rm(e,{idTokenNonce:r}),o=await t.createAuthorizationURL({state:i,codeVerifier:a,idTokenNonce:r,redirectURI:`${e.context.baseURL}${t1(t)}`});throw e.redirect(o.toString())}}if(!s){e.context.logger.error("State not found",n);let t=new URLSearchParams({error:"state_not_found"}),r=(0,tE.M)(a,t);throw e.redirect(r)}let{codeVerifier:p,callbackURL:f,link:m,errorURL:h,newUserURL:g,requestSignUp:w,idTokenNonce:y}=await rh(e);function b(t,r){let i=h??a,o=new URLSearchParams({error:t});r&&o.set("error_description",r);let n=(0,tE.M)(i,o);throw e.redirect(n)}if(n&&b(n,l),!o)throw e.context.logger.warn("Code not found"),b("no_code");let E=await tu(e.context.socialProviders,{value:e.params.id});if(!E)throw e.context.logger.warn("OAuth provider not found",{providerId:e.params.id}),b("oauth_provider_not_found");let A=await ip(e,E,{code:o,codeVerifier:p,iss:u,deviceId:c,user:d,idTokenNonce:y});if(A.error)throw b(A.error);let{tokens:I,userInfo:_,providerProfile:k,accountKey:T}=A,{accountId:v}=T;if(!f)throw e.context.logger.error("No callback URL found"),b("no_callback_url");let U={...T,...I,scope:I.scopes?.join(",")};if(m){let t=await ri(e,{link:m,userInfo:_,account:U,profile:k,scopes:I.scopes});if(!t.linked)return b(t.error.code,t.error.message);throw e.redirect(f)}if(!_.email)return e.context.logger.error(tJ(E.id)),b("email_not_found");try{r=await ra(e,{userInfo:{..._,id:v,email:_.email,name:_.name||""},account:U,callbackURL:f,disableSignUp:E.disableImplicitSignUp&&!w||E.options?.disableSignUp,overrideUserInfo:E.options?.overrideUserInfoOnSignIn,source:{method:"oauth",oauth:{providerId:E.id,profile:k}}})}catch(e){throw(0,tb.f)(e)&&e.body?.code&&b(e.body.code,e.body.message),e}if(r.error)return e.context.logger.error(r.error.split(" ").join("_")),b(r.error.split(" ").join("_"));let{session:R,user:x}=r.data;await (0,e0.V)(e,{session:R,user:x});try{i=(r.isRegister&&g||f).toString()}catch{i=r.isRegister&&g||f}throw e.redirect(i)});function iw(e){return e.replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'").replace(/&(?!amp;|lt;|gt;|quot;|#39;|#x[0-9a-fA-F]+;|#[0-9]+;)/g,"&")}let iy=(0,s.g)("/error",{method:"GET",metadata:{...im,openapi:{description:"Displays an error page",responses:{200:{description:"Success",content:{"text/html":{schema:{type:"string",description:"The HTML content of the error page"}}}}}}}},async e=>{let t=new URL(e.request?.url||""),r=t.searchParams.get("error")||"UNKNOWN",i=t.searchParams.get("error_description")||null,a=/^[\'A-Za-z0-9_-]+$/.test(r||"")?r:"UNKNOWN",o=i?iw(i):null,n=new URLSearchParams;n.set("error",a),i&&n.set("error_description",i);let s=e.context.options,l=s.onAPIError?.errorURL;return l?new Response(null,{status:302,headers:{Location:(0,tE.M)(l,n)}}):ta.C&&!s.onAPIError?.customizeDefaultErrorPage?new Response(null,{status:302,headers:{Location:`/?${n.toString()}`}}):new Response(((e,t="Unknown",r=null)=>{let i=e.onAPIError?.customizeDefaultErrorPage;return`<!DOCTYPE html>
|
|
106
|
+
`})});if(i||!r?.data?.viewer)return null;let a=r.data.viewer,o=await e.mapProfileToUser?.(a);return{user:{name:r.data.viewer.name,email:r.data.viewer.email,image:r.data.viewer.avatarUrl,emailVerified:!1,...o},data:a}},options:e}},linkedin:e=>{let t="https://www.linkedin.com/oauth/v2/accessToken";return{id:"linkedin",name:"Linkedin",accountSubject:({profile:e})=>e.sub,createAuthorizationURL:async({state:t,scopes:r,redirectURI:i,loginHint:a,additionalParams:o})=>{let n=e.disableDefaultScope?[]:["profile","email","openid"];return e.scope&&n.push(...e.scope),r&&n.push(...r),await ry({id:"linkedin",options:e,authorizationEndpoint:"https://www.linkedin.com/oauth/v2/authorization",scopes:n,state:t,loginHint:a,redirectURI:i,additionalParams:o})},validateAuthorizationCode:async({code:r,redirectURI:i})=>await rB({code:r,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>rj({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:i}=await (0,rK.f)("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(i)return null;let a=await e.mapProfileToUser?.(r);return{user:{name:r.name,email:r.email,emailVerified:r.email_verified??!1,image:r.picture,...a},data:r}},options:e}},gitlab:e=>{let t,{authorizationEndpoint:r,tokenEndpoint:i,userinfoEndpoint:a}=(t=e.issuer||"https://gitlab.com",{authorizationEndpoint:rG(`${t}/oauth/authorize`),tokenEndpoint:rG(`${t}/oauth/token`),userinfoEndpoint:rG(`${t}/api/v4/user`)}),o="gitlab";return{id:o,name:"Gitlab",accountSubject:({profile:e})=>e.id,createAuthorizationURL:async({state:t,scopes:i,codeVerifier:a,loginHint:n,redirectURI:s,additionalParams:l})=>{let c=e.disableDefaultScope?[]:["read_user"];return e.scope&&c.push(...e.scope),i&&c.push(...i),await ry({id:o,options:e,authorizationEndpoint:r,scopes:c,state:t,redirectURI:s,codeVerifier:a,loginHint:n,additionalParams:l})},validateAuthorizationCode:async({code:t,redirectURI:r,codeVerifier:a})=>rB({code:t,redirectURI:r,options:e,codeVerifier:a,tokenEndpoint:i}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>rj({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:i}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:i}=await (0,rK.f)(a,{headers:{authorization:`Bearer ${t.accessToken}`}});if(i||"active"!==r.state||r.locked)return null;let o=await e.mapProfileToUser?.(r);return{user:{name:r.name??r.username??"",email:r.email,image:r.avatar_url,emailVerified:r.email_verified??!1,...o},data:r}},options:e}},tiktok:e=>{let t="https://open.tiktokapis.com/v2/oauth/token/",r={method:"custom",customizeRequest({body:t}){t.set("client_key",e.clientKey),t.set("client_secret",e.clientSecret)}};return{id:"tiktok",name:"TikTok",accountSubject:({profile:e})=>e.data.user.open_id,createAuthorizationURL({state:t,scopes:r,redirectURI:i,additionalParams:a}){let o=e.disableDefaultScope?[]:["user.info.profile"];e.scope&&o.push(...e.scope),r&&o.push(...r);let n=new URL("https://www.tiktok.com/v2/auth/authorize");if(n.searchParams.set("scope",o.join(",")),n.searchParams.set("response_type","code"),n.searchParams.set("client_key",e.clientKey),n.searchParams.set("redirect_uri",e.redirectURI||i),n.searchParams.set("state",t),a)for(let[e,t]of Object.entries(a))rw.has(e)||"client_key"!==e&&n.searchParams.set(e,t);return n},validateAuthorizationCode:async({code:i,codeVerifier:a,redirectURI:o})=>rB({code:i,codeVerifier:a,redirectURI:e.redirectURI||o,options:{},tokenEndpoint:t,tokenEndpointAuth:r}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async e=>rj({refreshToken:e,options:{},tokenEndpoint:t,tokenEndpointAuth:r}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:i}=await (0,rK.f)("https://open.tiktokapis.com/v2/user/info/?fields=open_id,avatar_large_url,display_name,username",{headers:{authorization:`Bearer ${t.accessToken}`}});return i?null:{user:{email:r.data.user.email||r5({identifier:r.data.user.open_id,namespace:"tiktok"}),name:r.data.user.display_name||r.data.user.username||"",image:r.data.user.avatar_large_url,emailVerified:!1},data:r}},options:e}},reddit:e=>{let t="https://www.reddit.com/api/v1/access_token",r={clientId:e.clientId,clientSecret:e.clientSecret},i={method:"client_secret_basic"};return{id:"reddit",name:"Reddit",accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:r,redirectURI:i,additionalParams:a}){let o=e.disableDefaultScope?[]:["identity"];return e.scope&&o.push(...e.scope),r&&o.push(...r),ry({id:"reddit",options:e,authorizationEndpoint:"https://www.reddit.com/api/v1/authorize",scopes:o,state:t,redirectURI:i,duration:e.duration,additionalParams:a})},validateAuthorizationCode:async({code:a,redirectURI:o})=>rB({code:a,redirectURI:e.redirectURI||o,options:r,tokenEndpoint:t,tokenEndpointAuth:i,headers:{accept:"text/plain","user-agent":"better-auth"}}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async e=>rj({refreshToken:e,options:r,tokenEndpoint:t,tokenEndpointAuth:i}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:i}=await (0,rK.f)("https://oauth.reddit.com/api/v1/me",{headers:{Authorization:`Bearer ${t.accessToken}`,"User-Agent":"better-auth"}});if(i)return null;let a=await e.mapProfileToUser?.(r),o=a?.email||r5({identifier:r.id,namespace:"reddit"});return{user:{name:r.name,image:r.icon_img?.split("?")[0],...a,email:o,emailVerified:a?.emailVerified??!1},data:r}},options:e}},roblox:e=>{let t="https://apis.roblox.com/oauth/v1/token";return{id:"roblox",name:"Roblox",accountSubject:({profile:e})=>e.sub,createAuthorizationURL({state:t,scopes:r,redirectURI:i,additionalParams:a}){let o=e.disableDefaultScope?[]:["openid","profile"];return e.scope&&o.push(...e.scope),r&&o.push(...r),ry({id:"roblox",options:e,authorizationEndpoint:"https://apis.roblox.com/oauth/v1/authorize",scopes:o,state:t,redirectURI:i,prompt:e.prompt||"select_account consent",additionalParams:a})},validateAuthorizationCode:async({code:r,redirectURI:i})=>rB({code:r,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:t,authentication:"post"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>rj({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:i}=await (0,rK.f)("https://apis.roblox.com/oauth/v1/userinfo",{headers:{authorization:`Bearer ${t.accessToken}`}});if(i)return null;let a=await e.mapProfileToUser?.(r);return{user:{name:r.nickname||r.preferred_username||"",image:r.picture,email:r5({identifier:r.sub,namespace:"roblox"}),emailVerified:!1,...a},data:{...r}}},options:e}},salesforce:e=>{let t=(e.environment??"production")==="sandbox",r=e.loginUrl?`https://${e.loginUrl}/services/oauth2/authorize`:t?"https://test.salesforce.com/services/oauth2/authorize":"https://login.salesforce.com/services/oauth2/authorize",i=e.loginUrl?`https://${e.loginUrl}/services/oauth2/token`:t?"https://test.salesforce.com/services/oauth2/token":"https://login.salesforce.com/services/oauth2/token",a=e.loginUrl?`https://${e.loginUrl}/services/oauth2/userinfo`:t?"https://test.salesforce.com/services/oauth2/userinfo":"https://login.salesforce.com/services/oauth2/userinfo";return{id:"salesforce",name:"Salesforce",accountSubject:({profile:e})=>e.user_id,async createAuthorizationURL({state:t,scopes:i,codeVerifier:a,redirectURI:o,additionalParams:n}){if(!e.clientId||!e.clientSecret)throw eA.y.error("Client Id and Client Secret are required for Salesforce. Make sure to provide them in the options."),new u.p("CLIENT_ID_AND_SECRET_REQUIRED");if(!a)throw new u.p("codeVerifier is required for Salesforce");let s=e.disableDefaultScope?[]:["openid","email","profile"];return e.scope&&s.push(...e.scope),i&&s.push(...i),ry({id:"salesforce",options:e,authorizationEndpoint:r,scopes:s,state:t,codeVerifier:a,redirectURI:e.redirectURI||o,additionalParams:n})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:a})=>rB({code:t,codeVerifier:r,redirectURI:e.redirectURI||a,options:e,tokenEndpoint:i}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>rj({refreshToken:t,options:{clientId:e.clientId,clientSecret:e.clientSecret},tokenEndpoint:i}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);try{let{data:r}=await (0,rK.f)(a,{headers:{Authorization:`Bearer ${t.accessToken}`}});if(!r)return eA.y.error("Failed to fetch user info from Salesforce"),null;let i=await e.mapProfileToUser?.(r);return{user:{name:r.name,email:r.email,image:r.photos?.picture||r.photos?.thumbnail,emailVerified:r.email_verified??!1,...i},data:r}}catch(e){return eA.y.error("Failed to fetch user info from Salesforce:",e),null}},options:e}},vk:e=>{let t="https://id.vk.com/oauth2/auth";return{id:"vk",name:"VK",accountSubject:({profile:e})=>e.user.user_id,async createAuthorizationURL({state:t,scopes:r,codeVerifier:i,redirectURI:a,additionalParams:o}){let n=e.disableDefaultScope?[]:["email","phone"];return e.scope&&n.push(...e.scope),r&&n.push(...r),ry({id:"vk",options:e,authorizationEndpoint:"https://id.vk.com/authorize",scopes:n,state:t,redirectURI:a,codeVerifier:i,additionalParams:o})},validateAuthorizationCode:async({code:r,codeVerifier:i,redirectURI:a,deviceId:o})=>rB({code:r,codeVerifier:i,redirectURI:e.redirectURI||a,options:e,deviceId:o,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>rj({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.accessToken)return null;let r=new URLSearchParams({access_token:t.accessToken,client_id:e.clientId}).toString(),{data:i,error:a}=await (0,rK.f)("https://id.vk.com/oauth2/user_info",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r});if(a)return null;let o=await e.mapProfileToUser?.(i);return i.user.email||o?.email?{user:{first_name:i.user.first_name,last_name:i.user.last_name,email:i.user.email,image:i.user.avatar,emailVerified:!1,birthday:i.user.birthday,sex:i.user.sex,name:`${i.user.first_name} ${i.user.last_name}`,...o},data:i}:null},options:e}},zoom:e=>{let t={pkce:!0,...e};return{id:"zoom",name:"Zoom",accountSubject:({profile:e})=>e.id,createAuthorizationURL:async({state:e,redirectURI:r,codeVerifier:i,additionalParams:a})=>ry({id:"zoom",options:t,authorizationEndpoint:"https://zoom.us/oauth/authorize",state:e,redirectURI:r,codeVerifier:t.pkce?i:void 0,additionalParams:a}),validateAuthorizationCode:async({code:e,redirectURI:r,codeVerifier:i})=>rB({code:e,redirectURI:t.redirectURI||r,codeVerifier:i,options:t,tokenEndpoint:"https://zoom.us/oauth/token",authentication:"post"}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async e=>rj({refreshToken:e,options:{clientId:t.clientId,clientKey:t.clientKey,clientSecret:t.clientSecret},tokenEndpoint:"https://zoom.us/oauth/token"}),async getUserInfo(e){if(t.getUserInfo)return t.getUserInfo(e);let{data:r,error:i}=await (0,rK.f)("https://api.zoom.us/v2/users/me",{headers:{authorization:`Bearer ${e.accessToken}`}});if(i)return null;let a=await t.mapProfileToUser?.(r);return{user:{name:r.display_name,image:r.pic_url,email:r.email,emailVerified:!!r.verified,...a},data:{...r}}},options:t}},notion:e=>{let t="https://api.notion.com/v1/oauth/token";return{id:"notion",name:"Notion",accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:r,loginHint:i,redirectURI:a,additionalParams:o}){let n=(e.disableDefaultScope,[]);return e.scope&&n.push(...e.scope),r&&n.push(...r),ry({id:"notion",options:e,authorizationEndpoint:"https://api.notion.com/v1/oauth/authorize",scopes:n,state:t,redirectURI:a,loginHint:i,additionalParams:{...o??{},owner:"user"}})},validateAuthorizationCode:async({code:r,redirectURI:i})=>rB({code:r,redirectURI:i,options:e,tokenEndpoint:t,authentication:"basic"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>rj({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:i}=await (0,rK.f)("https://api.notion.com/v1/users/me",{headers:{Authorization:`Bearer ${t.accessToken}`,"Notion-Version":"2022-06-28"}});if(i||!r)return null;let a=r.bot?.owner?.user;if(!a)return null;let o=await e.mapProfileToUser?.(a);return{user:{name:a.name||"",email:a.person?.email||null,image:a.avatar_url,emailVerified:!1,...o},data:a}},options:e}},kakao:e=>{let t="https://kauth.kakao.com/oauth/token";return{id:"kakao",name:"Kakao",accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:r,redirectURI:i,loginHint:a,additionalParams:o}){let n=e.disableDefaultScope?[]:["account_email","profile_image","profile_nickname"];return e.scope&&n.push(...e.scope),r&&n.push(...r),ry({id:"kakao",options:e,authorizationEndpoint:"https://kauth.kakao.com/oauth/authorize",scopes:n,state:t,redirectURI:i,loginHint:a,additionalParams:o})},validateAuthorizationCode:async({code:r,redirectURI:i})=>rB({code:r,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>rj({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:i}=await (0,rK.f)("https://kapi.kakao.com/v2/user/me",{headers:{Authorization:`Bearer ${t.accessToken}`}});if(i||!r)return null;let a=await e.mapProfileToUser?.(r),o=r.kakao_account||{},n=o.profile||{};return{user:{name:n.nickname||o.name||"",email:o.email,image:n.profile_image_url||n.thumbnail_image_url,emailVerified:!!o.is_email_valid&&!!o.is_email_verified,...a},data:r}},options:e}},naver:e=>{let t="https://nid.naver.com/oauth2.0/token";return{id:"naver",name:"Naver",accountSubject:({profile:e})=>e.response.id,createAuthorizationURL({state:t,scopes:r,redirectURI:i,additionalParams:a}){let o=e.disableDefaultScope?[]:["profile","email"];return e.scope&&o.push(...e.scope),r&&o.push(...r),ry({id:"naver",options:e,authorizationEndpoint:"https://nid.naver.com/oauth2.0/authorize",scopes:o,state:t,redirectURI:i,additionalParams:a})},validateAuthorizationCode:async({code:r,redirectURI:i})=>rB({code:r,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>rj({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:i}=await (0,rK.f)("https://openapi.naver.com/v1/nid/me",{headers:{Authorization:`Bearer ${t.accessToken}`}});if(i||!r||"00"!==r.resultcode)return null;let a=await e.mapProfileToUser?.(r),o=r.response||{};return{user:{name:o.name||o.nickname||"",email:o.email,image:o.profile_image,emailVerified:!1,...a},data:r}},options:e}},line:e=>{let t="https://api.line.me/oauth2/v2.1/token";return{id:"line",name:"LINE",accountSubject:({profile:e})=>e.sub,async createAuthorizationURL({state:t,scopes:r,codeVerifier:i,redirectURI:a,loginHint:o,additionalParams:n}){let s=e.disableDefaultScope?[]:["openid","profile","email"];return e.scope&&s.push(...e.scope),r&&s.push(...r),await ry({id:"line",options:e,authorizationEndpoint:"https://access.line.me/oauth2/v2.1/authorize",scopes:s,state:t,codeVerifier:i,redirectURI:a,loginHint:o,additionalParams:n})},validateAuthorizationCode:async({code:r,codeVerifier:i,redirectURI:a})=>rB({code:r,codeVerifier:i,redirectURI:a,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>rj({refreshToken:r,options:{clientId:e.clientId,clientSecret:e.clientSecret},tokenEndpoint:t}),idToken:{verify:async(t,r)=>{let i=new URLSearchParams;i.set("id_token",t),i.set("client_id",e.clientId),r&&i.set("nonce",r);let{data:a,error:o}=await (0,rU.f)("https://api.line.me/oauth2/v2.1/verify",{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:i});return!o&&!!a&&a.aud===e.clientId&&(!a.nonce||a.nonce===r)}},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let r=null;if(t.idToken)try{r=(0,rV.f)(t.idToken)}catch{}if(!r){let{data:e}=await (0,rK.f)("https://api.line.me/oauth2/v2.1/userinfo",{headers:{authorization:`Bearer ${t.accessToken}`}});r=e||null}if(!r)return null;let i=await e.mapProfileToUser?.(r);return{user:{name:r.name||"",email:r.email,image:r.picture,emailVerified:!1,...i},data:r}},options:e}},paybin:e=>{let t=e.issuer||"https://idp.paybin.io",r=`${t}/oauth2/authorize`,i=`${t}/oauth2/token`;return{id:"paybin",name:"Paybin",accountSubject:({profile:e})=>e.sub,async createAuthorizationURL({state:t,scopes:i,codeVerifier:a,redirectURI:o,loginHint:n,additionalParams:s}){if(!e.clientId||!e.clientSecret)throw eA.y.error("Client Id and Client Secret is required for Paybin. Make sure to provide them in the options."),new u.p("CLIENT_ID_AND_SECRET_REQUIRED");if(!a)throw new u.p("codeVerifier is required for Paybin");let l=e.disableDefaultScope?[]:["openid","email","profile"];return e.scope&&l.push(...e.scope),i&&l.push(...i),await ry({id:"paybin",options:e,authorizationEndpoint:r,scopes:l,state:t,codeVerifier:a,redirectURI:o,prompt:e.prompt,loginHint:n,additionalParams:s})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:a})=>rB({code:t,codeVerifier:r,redirectURI:a,options:e,tokenEndpoint:i}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>rj({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:i}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let r=(0,rV.f)(t.idToken),i=await e.mapProfileToUser?.(r);return{user:{name:r.name||r.preferred_username||"",email:r.email,image:r.picture,emailVerified:r.email_verified||!1,...i},data:r}},options:e}},paypal:e=>{let t="sandbox"===(e.environment||"sandbox"),r=t?"https://www.sandbox.paypal.com/signin/authorize":"https://www.paypal.com/signin/authorize",i=t?"https://api-m.sandbox.paypal.com/v1/oauth2/token":"https://api-m.paypal.com/v1/oauth2/token",a=t?"https://api-m.sandbox.paypal.com/v1/identity/oauth2/userinfo":"https://api-m.paypal.com/v1/identity/oauth2/userinfo",o={clientId:e.clientId,clientSecret:e.clientSecret},n={method:"client_secret_basic"};return{id:"paypal",name:"PayPal",accountSubject:({profile:e})=>e.user_id,async createAuthorizationURL({state:t,codeVerifier:i,redirectURI:a,additionalParams:o}){if(!e.clientId||!e.clientSecret)throw eA.y.error("Client Id and Client Secret is required for PayPal. Make sure to provide them in the options."),new u.p("CLIENT_ID_AND_SECRET_REQUIRED");return await ry({id:"paypal",options:e,authorizationEndpoint:r,scopes:[],state:t,codeVerifier:i,redirectURI:a,prompt:e.prompt,additionalParams:o})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:a})=>{try{return await rB({code:t,codeVerifier:r,redirectURI:e.redirectURI||a,options:o,tokenEndpoint:i,tokenEndpointAuth:n})}catch(e){throw eA.y.error("PayPal token exchange failed:",e),new u.p("FAILED_TO_GET_ACCESS_TOKEN")}},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async e=>{try{return await rj({refreshToken:e,options:o,tokenEndpoint:i,tokenEndpointAuth:n})}catch(e){throw eA.y.error("PayPal token refresh failed:",e),new u.p("FAILED_TO_REFRESH_ACCESS_TOKEN")}},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.accessToken)return eA.y.error("Access token is required to fetch PayPal user info"),null;try{let r=await (0,rK.f)(`${a}?schema=paypalv1.1`,{headers:{Authorization:`Bearer ${t.accessToken}`,Accept:"application/json"}});if(!r.data)return eA.y.error("Failed to fetch user info from PayPal"),null;let i=r.data;if(t.idToken){let e;try{e=(0,rV.f)(t.idToken).sub}catch(e){return eA.y.error("Failed to decode PayPal ID token:",e),null}let r=i.sub??i.user_id;if(!e||r!==e)return eA.y.error("PayPal user info subject does not match ID token subject"),null}let o=await e.mapProfileToUser?.(i);return{user:{name:i.name,email:i.email,image:i.picture,emailVerified:i.email_verified,...o},data:i}}catch(e){return eA.y.error("Failed to fetch user info from PayPal:",e),null}},options:e}},polar:e=>{let t="https://api.polar.sh/v1/oauth2/token";return{id:"polar",name:"Polar",accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:r,codeVerifier:i,redirectURI:a,additionalParams:o}){let n=e.disableDefaultScope?[]:["openid","profile","email"];return e.scope&&n.push(...e.scope),r&&n.push(...r),ry({id:"polar",options:e,authorizationEndpoint:"https://polar.sh/oauth2/authorize",scopes:n,state:t,codeVerifier:i,redirectURI:a,prompt:e.prompt,additionalParams:o})},validateAuthorizationCode:async({code:r,codeVerifier:i,redirectURI:a})=>rB({code:r,codeVerifier:i,redirectURI:a,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>rj({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:i}=await (0,rK.f)("https://api.polar.sh/v1/oauth2/userinfo",{headers:{Authorization:`Bearer ${t.accessToken}`}});if(i)return null;let a=await e.mapProfileToUser?.(r);return{user:{name:r.public_name||r.username||"",email:r.email,image:r.avatar_url,emailVerified:r.email_verified??!1,...a},data:r}},options:e}},railway:e=>({id:"railway",name:"Railway",accountSubject:({profile:e})=>e.sub,createAuthorizationURL({state:t,scopes:r,codeVerifier:i,redirectURI:a,additionalParams:o}){let n=e.disableDefaultScope?[]:["openid","email","profile"];return e.scope&&n.push(...e.scope),r&&n.push(...r),ry({id:"railway",options:e,authorizationEndpoint:"https://backboard.railway.com/oauth/auth",scopes:n,state:t,codeVerifier:i,redirectURI:a,additionalParams:o})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:i})=>rB({code:t,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:r6,authentication:"basic"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>rj({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:r6,authentication:"basic"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:i}=await (0,rK.f)("https://backboard.railway.com/oauth/me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(i||!r)return null;let a=await e.mapProfileToUser?.(r);return{user:{name:r.name,email:r.email,image:r.picture,emailVerified:!1,...a},data:r}},options:e}),vercel:e=>{let t=e.tokenEndpointAuth?.method;if(e.clientSecret&&("private_key_jwt"===t||"none"===t))throw new u.p(`Vercel ${t} token endpoint authentication cannot be combined with clientSecret`);if(!e.clientSecret&&("client_secret_basic"===t||"client_secret_post"===t))throw new u.p(`Vercel ${t} token endpoint authentication requires clientSecret`);return{id:"vercel",name:"Vercel",accountSubject:({profile:e})=>e.sub,createAuthorizationURL({state:t,scopes:r,codeVerifier:i,redirectURI:a,additionalParams:o}){let n;if(!i)throw new u.p("codeVerifier is required for Vercel");return(void 0!==e.scope||void 0!==r)&&(n=[],e.scope&&n.push(...e.scope),r&&n.push(...r)),ry({id:"vercel",options:e,authorizationEndpoint:"https://vercel.com/oauth/authorize",scopes:n,state:t,codeVerifier:i,redirectURI:a,additionalParams:o})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:i})=>rB({code:t,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:"https://api.vercel.com/login/oauth/token",tokenEndpointAuth:e.tokenEndpointAuth}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:i}=await (0,rK.f)("https://api.vercel.com/login/oauth/userinfo",{headers:{Authorization:`Bearer ${t.accessToken}`}});if(i||!r)return null;let a=await e.mapProfileToUser?.(r);return{user:{name:r.name??r.preferred_username??"",email:r.email,image:r.picture,emailVerified:r.email_verified??!1,...a},data:r}},options:e}},wechat:e=>({id:"wechat",name:"WeChat",accountSubject:({profile:e})=>e.unionid||e.openid,createAuthorizationURL({state:t,scopes:r,redirectURI:i,additionalParams:a}){let o=e.disableDefaultScope?[]:["snsapi_login"];e.scope&&o.push(...e.scope),r&&o.push(...r);let n=new URL("https://open.weixin.qq.com/connect/qrconnect");if(n.searchParams.set("scope",o.join(",")),n.searchParams.set("response_type","code"),n.searchParams.set("appid",e.clientId),n.searchParams.set("redirect_uri",e.redirectURI||i),n.searchParams.set("state",t),n.searchParams.set("lang",e.lang||"cn"),a)for(let[e,t]of Object.entries(a))rw.has(e)||"appid"!==e&&n.searchParams.set(e,t);return n.hash="wechat_redirect",n},validateAuthorizationCode:async({code:t})=>{let{data:r,error:i}=await (0,rU.f)("https://api.weixin.qq.com/sns/oauth2/access_token",{method:"GET",query:{appid:e.clientId,secret:e.clientSecret,code:t,grant_type:"authorization_code"}});if(i||!r||r.errcode)throw Error(`Failed to validate authorization code: ${r?.errmsg||i?.message||"Unknown error"}`);return{tokenType:"Bearer",accessToken:r.access_token,refreshToken:r.refresh_token,accessTokenExpiresAt:new Date(Date.now()+1e3*r.expires_in),scopes:r.scope.split(","),openid:r.openid,unionid:r.unionid}},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>{let{data:r,error:i}=await (0,rU.f)("https://api.weixin.qq.com/sns/oauth2/refresh_token",{method:"GET",query:{appid:e.clientId,grant_type:"refresh_token",refresh_token:t}});if(i||!r||r.errcode)throw Error(`Failed to refresh access token: ${r?.errmsg||i?.message||"Unknown error"}`);return{tokenType:"Bearer",accessToken:r.access_token,refreshToken:r.refresh_token,accessTokenExpiresAt:new Date(Date.now()+1e3*r.expires_in),scopes:r.scope.split(",")}},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let r=t.openid;if(!r)return null;let i=new URLSearchParams({access_token:t.accessToken||"",openid:r,lang:"zh_CN"}),{data:a,error:o}=await (0,rK.f)("https://api.weixin.qq.com/sns/userinfo?"+i.toString(),{method:"GET"});if(o||!a||a.errcode)return null;let n=await e.mapProfileToUser?.(a),s=a.unionid||a.openid||r;return{user:{name:a.nickname,email:a.email||r5({identifier:s,namespace:"wechat"}),image:a.headimgurl,emailVerified:!1,...n},data:a}},options:e})},r7=Object.keys(r4),r8=E.enum(r7).or(E.string());function r9(e){return e?e.split(",").map(e=>e.trim()).filter(Boolean):[]}let ie=(0,s.g)("/list-accounts",{method:"GET",use:[p.Z],metadata:{openapi:{operationId:"listUserAccounts",description:"List all accounts linked to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"array",items:{type:"object",properties:{id:{type:"string"},providerId:{type:"string"},createdAt:{type:"string",format:"date-time"},updatedAt:{type:"string",format:"date-time"},accountId:{type:"string"},userId:{type:"string"},scopes:{type:"array",items:{type:"string"}}},required:["id","providerId","createdAt","updatedAt","accountId","userId","scopes"]}}}}}}}}},async e=>{let t=e.context.session,r=await e.context.internalAdapter.findAccounts(t.user.id);return e.json(r.map(t=>{let{scope:r,...i}=(0,w.s)(e.context.options,t);return{...i,scopes:r9(r)}}))}),it=(0,s.g)("/link-social",{method:"POST",requireHeaders:!0,body:E.object({callbackURL:E.string().meta({description:"The URL to redirect to after the user has signed in"}).optional(),provider:r8,idToken:E.object({token:E.string(),nonce:E.string().optional(),accessToken:E.string().optional(),refreshToken:E.string().optional()}).optional(),requestSignUp:E.boolean().optional(),scopes:E.array(E.string()).meta({description:"Additional scopes to request from the provider"}).optional(),errorCallbackURL:E.string().meta({description:"The URL to redirect to if there is an error during the link process"}).optional(),disableRedirect:E.boolean().meta({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),loginHint:E.string().meta({description:"The login hint to use for the authorization code request"}).optional(),additionalParams:rb,additionalData:E.record(E.string(),E.any()).optional()}),use:[p.i],metadata:{openapi:{description:"Link a social account to the user",operationId:"linkSocialAccount",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{url:{type:"string",description:"The authorization URL to redirect the user to"},redirect:{type:"boolean",description:"Indicates if the user should be redirected to the authorization URL"},status:{type:"boolean"}},required:["redirect"]}}}}}}}},async e=>{let t=e.context.session,r=await tu(e.context.socialProviders,{value:e.body.provider});if(!r)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),u.E.from("NOT_FOUND",tf.f.PROVIDER_NOT_FOUND);if(e.body.idToken){if(!rT(r))throw e.context.logger.error("Provider does not support id token verification",{provider:e.body.provider}),u.E.from("NOT_FOUND",tf.f.ID_TOKEN_NOT_SUPPORTED);let{token:i,nonce:a}=e.body.idToken;if(!await rv(r,i,a,e))throw e.context.logger.warn("Invalid id token",{provider:e.body.provider}),u.E.from("UNAUTHORIZED",tf.f.INVALID_TOKEN);let o={idToken:i,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken},n=r.getUserInfoFromIdToken?await r.getUserInfoFromIdToken(i):await r.getUserInfo(o);if(!n||!n?.user)throw e.context.logger.error("Failed to get user info",{provider:e.body.provider}),u.E.from("UNAUTHORIZED",tf.f.FAILED_TO_GET_USER_INFO);if(!n.user.email)throw e.context.logger.error(tJ(e.body.provider,{source:"id_token"}),{provider:e.body.provider}),u.E.from("UNAUTHORIZED",tf.f.USER_EMAIL_NOT_FOUND);let s=await tz(r,{idToken:i,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken},n.data),l=await e.context.internalAdapter.findAccountByKey(s);if(l?.userId===t.user.id){let a=Object.fromEntries(Object.entries({providerId:r.id,accessToken:await t0(e.body.idToken.accessToken,e.context),idToken:i,refreshToken:await t0(e.body.idToken.refreshToken,e.context)}).filter(([e,t])=>void 0!==t));return await e.context.internalAdapter.updateAccount(l.id,a),await rn(e,t.user.id,n.user),e.json({url:"",status:!0,redirect:!1})}if(l)throw u.E.from("CONFLICT",tf.f.SOCIAL_ACCOUNT_ALREADY_LINKED);if(!e.context.trustedProviders.includes(r.id)&&!tZ(n.user.emailVerified)||e.context.options.account?.accountLinking?.enabled===!1)throw u.E.from("UNAUTHORIZED",{message:"Account not linked - linking not allowed",code:"LINKING_NOT_ALLOWED"});if(n.user.email?.toLowerCase()!==t.user.email.toLowerCase()&&e.context.options.account?.accountLinking?.allowDifferentEmails!==!0)throw u.E.from("UNAUTHORIZED",{message:"Account not linked - different emails not allowed",code:"LINKING_DIFFERENT_EMAILS_NOT_ALLOWED"});try{await e.context.internalAdapter.createAccount({userId:t.user.id,...s,accessToken:await t0(e.body.idToken.accessToken,e.context),idToken:i,refreshToken:await t0(e.body.idToken.refreshToken,e.context)})}catch{throw u.E.from("EXPECTATION_FAILED",{message:"Account not linked - unable to create account",code:"LINKING_FAILED"})}return await rn(e,t.user.id,n.user),e.json({url:"",status:!0,redirect:!1})}let i=rf(r),a=await rm(e,{link:{userId:t.user.id,email:t.user.email,encryptedSessionToken:await (0,tC.M)({key:tF(e.context.secretConfig,"oauth-link-session-token"),data:t.session.token})},additionalData:e.body.additionalData,idTokenNonce:i}),o=await r.createAuthorizationURL({state:a.state,codeVerifier:a.codeVerifier,idTokenNonce:i,redirectURI:`${e.context.baseURL}${t1(r)}`,scopes:e.body.scopes,loginHint:e.body.loginHint,additionalParams:e.body.additionalParams});return e.body.disableRedirect||e.setHeader("Location",o.toString()),e.json({url:o.toString(),redirect:!e.body.disableRedirect})}),ir=(0,s.g)("/unlink-account",{method:"POST",body:E.object({accountId:E.string().meta({description:"The Better Auth account ID to unlink"})}),use:[p.h],metadata:{openapi:{description:"Unlink an account",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{let{accountId:t}=e.body,r=await e.context.internalAdapter.findAccounts(e.context.session.user.id);if(1===r.length&&!e.context.options.account?.accountLinking?.allowUnlinkingAll)throw u.E.from("BAD_REQUEST",tf.f.FAILED_TO_UNLINK_LAST_ACCOUNT);let i=r.find(e=>e.id===t);if(!i)throw u.E.from("BAD_REQUEST",tf.f.ACCOUNT_NOT_FOUND);return await e.context.internalAdapter.deleteAccount(i.id),e.json({status:!0})});async function ii(e,t){let r=await (0,p.D)(e,{disableCookieCache:(0,p.f)(e)});if(!r&&(e.request||e.headers))throw e.error("UNAUTHORIZED");let i=r?.user?.id||t;if(!i)throw u.E.from("BAD_REQUEST",{message:"Either userId or session is required",code:"USER_ID_OR_SESSION_REQUIRED"});return i}let ia=E.union([E.strictObject({accountId:E.string().meta({description:"The Better Auth account ID"}),userId:E.string().meta({description:"The user ID associated with the account"}).optional()}),E.strictObject({useAccountCookie:E.literal(!0).meta({description:"Select the current OAuth account from its signed cookie"}),userId:E.string().meta({description:"The user ID associated with the account"}).optional()})]);function io(e,t,{resolvedUserId:r,selection:i}){return(!(0,eJ.d)(e.context.options)||t.userId===r)&&(!("accountId"in i)||t.id===i.accountId)}async function is(e,{resolvedUserId:t,selection:r}){if("accountId"in r){let i=(await e.context.internalAdapter.findAccounts(t)).find(e=>e.id===r.accountId);if(i)return{account:i,accountCookie:null}}else if(e.context.options.account?.storeAccountCookie){let i=await (0,tq.q)(e);if(i&&io(e,i,{resolvedUserId:t,selection:r}))return{account:i,accountCookie:i}}throw u.E.from("BAD_REQUEST",tf.f.ACCOUNT_NOT_FOUND)}async function il(e,{resolvedUserId:t,selection:r,account:i}){let a=i??(await is(e,{resolvedUserId:t,selection:r})).account;if(!io(e,a,{resolvedUserId:t,selection:r}))throw u.E.from("BAD_REQUEST",tf.f.ACCOUNT_NOT_FOUND);let o=await tu(e.context.socialProviders,{value:a.providerId});if(!o)throw u.E.from("BAD_REQUEST",{message:`Provider ${a.providerId} is not supported.`,code:"PROVIDER_NOT_SUPPORTED"});try{let t=null,r=a.accessTokenExpiresAt&&new Date(a.accessTokenExpiresAt).getTime()-Date.now()<5e3;if(a.refreshToken&&r&&o.refreshAccessToken){let r=await tX(a.refreshToken,e.context);t=await o.refreshAccessToken(r,e);let i={accessToken:await t0(t?.accessToken,e.context),accessTokenExpiresAt:t?.accessTokenExpiresAt,refreshToken:t?.refreshToken?await t0(t.refreshToken,e.context):a.refreshToken,refreshTokenExpiresAt:t?.refreshTokenExpiresAt??a.refreshTokenExpiresAt,idToken:t?.idToken||a.idToken},n=null;a.id&&(n=await e.context.internalAdapter.updateAccount(a.id,i)),e.context.options.account?.storeAccountCookie&&await (0,tq.L)(e,{...a,...n??i})}let i=t?.accessTokenExpiresAt?"string"==typeof t.accessTokenExpiresAt?new Date(t.accessTokenExpiresAt):t.accessTokenExpiresAt:a.accessTokenExpiresAt?"string"==typeof a.accessTokenExpiresAt?new Date(a.accessTokenExpiresAt):a.accessTokenExpiresAt:void 0;return{accessToken:t?.accessToken??await tX(a.accessToken??"",e.context),accessTokenExpiresAt:i,scopes:r9(a.scope),idToken:t?.idToken??a.idToken??void 0}}catch(e){throw u.E.from("BAD_REQUEST",{message:"Failed to get a valid access token",code:"FAILED_TO_GET_ACCESS_TOKEN"})}}let ic=(0,s.g)("/get-access-token",{method:"POST",body:ia,metadata:{openapi:{description:"Get a valid access token, doing a refresh if needed",responses:{200:{description:"A Valid access token",content:{"application/json":{schema:{type:"object",properties:{tokenType:{type:"string"},idToken:{type:"string"},accessToken:{type:"string"},accessTokenExpiresAt:{type:"string",format:"date-time"}}}}}},400:{description:"Invalid refresh token or provider configuration"}}}}},async e=>{let{userId:t}=e.body,r=await il(e,{resolvedUserId:await ii(e,t),selection:e.body});return e.json(r)}),id=(0,s.g)("/refresh-token",{method:"POST",body:ia,metadata:{openapi:{description:"Refresh the access token using a refresh token",responses:{200:{description:"Access token refreshed successfully",content:{"application/json":{schema:{type:"object",properties:{tokenType:{type:"string"},idToken:{type:"string"},accessToken:{type:"string"},refreshToken:{type:"string"},accessTokenExpiresAt:{type:"string",format:"date-time"},refreshTokenExpiresAt:{type:"string",format:"date-time"}}}}}},400:{description:"Invalid refresh token or provider configuration"}}}}},async e=>{let{userId:t}=e.body,{account:r,accountCookie:i}=await is(e,{resolvedUserId:await ii(e,t),selection:e.body}),a=await tu(e.context.socialProviders,{value:r.providerId});if(!a)throw u.E.from("BAD_REQUEST",{message:`Provider ${r.providerId} is not supported.`,code:"PROVIDER_NOT_SUPPORTED"});if(!a.refreshAccessToken)throw u.E.from("BAD_REQUEST",{message:`Provider ${r.providerId} does not support token refreshing.`,code:"TOKEN_REFRESH_NOT_SUPPORTED"});let o=r.refreshToken??void 0;if(!o)throw u.E.from("BAD_REQUEST",{message:"Refresh token not found",code:"REFRESH_TOKEN_NOT_FOUND"});try{let t=await tX(o,e.context),n=await a.refreshAccessToken(t,e),s=n.refreshToken?await t0(n.refreshToken,e.context):o,l=n.refreshTokenExpiresAt??r.refreshTokenExpiresAt,c={accessToken:await t0(n.accessToken,e.context),refreshToken:s,accessTokenExpiresAt:n.accessTokenExpiresAt,refreshTokenExpiresAt:l,idToken:n.idToken||r.idToken},d=null;if(r.id&&(d=await e.context.internalAdapter.updateAccount(r.id,c)),i?.id===r.id&&e.context.options.account?.storeAccountCookie){let t={...i,...d??c};await (0,tq.L)(e,t)}let u=d?.scope??r.scope;return e.json({accessToken:n.accessToken,refreshToken:n.refreshToken??t,accessTokenExpiresAt:n.accessTokenExpiresAt,refreshTokenExpiresAt:l,scope:u,idToken:n.idToken||r.idToken,providerId:r.providerId,accountId:r.id})}catch(e){throw u.E.from("BAD_REQUEST",{message:"Failed to refresh access token",code:"FAILED_TO_REFRESH_ACCESS_TOKEN"})}}),iu=(0,s.g)("/account-info",{method:"GET",metadata:{openapi:{description:"Get the account info provided by the provider",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object",properties:{name:{type:"string"},email:{type:"string",nullable:!0},image:{type:"string"},emailVerified:{type:"boolean"}},required:["emailVerified"]},account:{type:"object",properties:{id:{type:"string"},providerId:{type:"string"},accountId:{type:"string"}},required:["id","providerId","accountId"],additionalProperties:!1},data:{type:"object",properties:{},additionalProperties:!0}},required:["user","data","account"],additionalProperties:!1}}}}}}},query:ia},async e=>{let{userId:t}=e.query,r=await ii(e,t),{account:i}=await is(e,{resolvedUserId:r,selection:e.query}),a=await tu(e.context.socialProviders,{value:i.providerId});if(!a)throw u.E.from("BAD_REQUEST",{message:"Account is not associated with a configured social provider.",code:"PROVIDER_NOT_CONFIGURED"});let o=await il(e,{resolvedUserId:r,selection:e.query,account:i});if(!o.accessToken)throw u.E.from("BAD_REQUEST",{message:"Access token not found",code:"ACCESS_TOKEN_NOT_FOUND"});let n=await a.getUserInfo({...o,accessToken:o.accessToken});if(!n)throw u.E.from("UNAUTHORIZED",tf.f.FAILED_TO_GET_USER_INFO);return e.json({...n,account:{id:i.id,providerId:i.providerId,accountId:i.accountId}})});async function ip(e,t,r){let i;if(r.iss&&t.issuer&&r.iss!==t.issuer)return e.context.logger.error("OAuth issuer mismatch",{expected:t.issuer,received:r.iss}),{error:"issuer_mismatch"};if(t.requiresIdTokenNonce&&!r.idTokenNonce)return e.context.logger.error("OAuth id_token nonce binding required but no expected nonce was found in state",{providerId:t.id}),{error:"nonce_binding_missing"};try{i=await t.validateAuthorizationCode({code:r.code,codeVerifier:r.codeVerifier,deviceId:r.deviceId,redirectURI:`${e.context.baseURL}${t1(t)}`})}catch(t){return e.context.logger.error("Failed to validate authorization code",t),{error:tH}}if(!i)return{error:tH};let a=await t.getUserInfo({...i,expectedIdTokenNonce:r.idTokenNonce,user:(0,b.f)(r.user)??void 0});if(!a?.user)return e.context.logger.error("Unable to get user info"),{error:tW};let o=await tK(t,i,a.data).catch(r=>(e.context.logger.error("Unable to derive provider account identity",{providerId:t.id,error:r}),null));return o?{tokens:i,userInfo:a.user,providerProfile:a.data,accountKey:o}:{error:tW}}let im={scope:"server"},ih=E.object({code:E.string().optional(),error:E.string().optional(),device_id:E.string().optional(),error_description:E.string().optional(),state:E.string().optional(),user:E.string().optional(),iss:E.string().optional()}),ig=(0,s.g)("/callback/:id",{method:["GET","POST"],operationId:"handleOAuthCallback",body:ih.optional(),query:ih.optional(),metadata:{...im,allowedMediaTypes:["application/x-www-form-urlencoded","application/json"]}},async e=>{let t,r,i,a=e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`;if("POST"===e.method){let t=e.body?ih.parse(e.body):{},r=e.query?ih.parse(e.query):{},i=ih.parse({...t,...r}),a=new URLSearchParams;for(let[e,t]of Object.entries(i))null!=t&&a.set(e,String(t));let o=`${e.context.baseURL}/callback/${e.params.id}?${a.toString()}`;throw e.redirect(o)}try{if("GET"===e.method)t=ih.parse(e.query);else if("POST"===e.method)t=ih.parse(e.body);else throw Error("Unsupported method")}catch(i){e.context.logger.error("INVALID_CALLBACK_REQUEST",i);let t=new URLSearchParams({error:"invalid_callback_request"}),r=(0,tE.M)(a,t);throw e.redirect(r)}let{code:o,error:n,state:s,error_description:l,device_id:c,user:d,iss:u}=t;if(void 0===s&&o){let t=await tu(e.context.socialProviders,{value:e.params.id});if(t?.allowIdpInitiated){let r=rf(t),{state:i,codeVerifier:a}=await rm(e,{idTokenNonce:r}),o=await t.createAuthorizationURL({state:i,codeVerifier:a,idTokenNonce:r,redirectURI:`${e.context.baseURL}${t1(t)}`});throw e.redirect(o.toString())}}if(!s){e.context.logger.error("State not found",n);let t=new URLSearchParams({error:"state_not_found"}),r=(0,tE.M)(a,t);throw e.redirect(r)}let{codeVerifier:p,callbackURL:f,link:m,errorURL:h,newUserURL:g,requestSignUp:w,idTokenNonce:y}=await rh(e);function b(t,r){let i=h??a,o=new URLSearchParams({error:t});r&&o.set("error_description",r);let n=(0,tE.M)(i,o);throw e.redirect(n)}if(n&&b(n,l),!o)throw e.context.logger.warn("Code not found"),b("no_code");let E=await tu(e.context.socialProviders,{value:e.params.id});if(!E)throw e.context.logger.warn("OAuth provider not found",{providerId:e.params.id}),b("oauth_provider_not_found");let A=await ip(e,E,{code:o,codeVerifier:p,iss:u,deviceId:c,user:d,idTokenNonce:y});if(A.error)throw b(A.error);let{tokens:I,userInfo:_,providerProfile:k,accountKey:T}=A,{accountId:v}=T;if(!f)throw e.context.logger.error("No callback URL found"),b("no_callback_url");let U={...T,...I,scope:I.scopes?.join(",")};if(m){let t=await ri(e,{link:m,userInfo:_,account:U,profile:k,scopes:I.scopes});if(!t.linked)return b(t.error.code,t.error.message);throw e.redirect(f)}if(!_.email)return e.context.logger.error(tJ(E.id)),b("email_not_found");try{r=await ra(e,{userInfo:{..._,id:v,email:_.email,name:_.name||""},account:U,callbackURL:f,disableSignUp:E.disableImplicitSignUp&&!w||E.options?.disableSignUp,overrideUserInfo:E.options?.overrideUserInfoOnSignIn,source:{method:"oauth",oauth:{providerId:E.id,profile:k}}})}catch(e){throw(0,tb.f)(e)&&e.body?.code&&b(e.body.code,e.body.message),e}if(r.error)return e.context.logger.error(r.error.split(" ").join("_")),b(r.error.split(" ").join("_"));let{session:R,user:S}=r.data;await (0,e0.V)(e,{session:R,user:S});try{i=(r.isRegister&&g||f).toString()}catch{i=r.isRegister&&g||f}throw e.redirect(i)});function iw(e){return e.replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'").replace(/&(?!amp;|lt;|gt;|quot;|#39;|#x[0-9a-fA-F]+;|#[0-9]+;)/g,"&")}let iy=(0,s.g)("/error",{method:"GET",metadata:{...im,openapi:{description:"Displays an error page",responses:{200:{description:"Success",content:{"text/html":{schema:{type:"string",description:"The HTML content of the error page"}}}}}}}},async e=>{let t=new URL(e.request?.url||""),r=t.searchParams.get("error")||"UNKNOWN",i=t.searchParams.get("error_description")||null,a=/^[\'A-Za-z0-9_-]+$/.test(r||"")?r:"UNKNOWN",o=i?iw(i):null,n=new URLSearchParams;n.set("error",a),i&&n.set("error_description",i);let s=e.context.options,l=s.onAPIError?.errorURL;return l?new Response(null,{status:302,headers:{Location:(0,tE.M)(l,n)}}):ta.C&&!s.onAPIError?.customizeDefaultErrorPage?new Response(null,{status:302,headers:{Location:`/?${n.toString()}`}}):new Response(((e,t="Unknown",r=null)=>{let i=e.onAPIError?.customizeDefaultErrorPage;return`<!DOCTYPE html>
|
|
107
107
|
<html lang="en">
|
|
108
108
|
<head>
|
|
109
109
|
<meta charset="UTF-8" />
|
|
@@ -437,7 +437,7 @@ ${i?.disableBackgroundGrid?"":`
|
|
|
437
437
|
</div>
|
|
438
438
|
</div>
|
|
439
439
|
</body>
|
|
440
|
-
</html>`})(e.context.options,a,o),{headers:{"Content-Type":"text/html"}})}),ib=(0,s.g)("/ok",{method:"GET",metadata:{...im,openapi:{description:"Check if the API is working",responses:{200:{description:"API is working",content:{"application/json":{schema:{type:"object",properties:{ok:{type:"boolean",description:"Indicates if the API is working"}},required:["ok"]}}}}}}}},async e=>e.json({ok:!0}));function iE(e,t,r){let i=t?new URL(t,e.baseURL):new URL(`${e.baseURL}/error`);return r&&Object.entries(r).forEach(([e,t])=>i.searchParams.set(e,t)),i.href}let iA=(0,s.g)("/request-password-reset",{method:"POST",body:E.object({email:E.email().meta({description:"The email address of the user to send a password reset email to"}),redirectTo:E.string().meta({description:"The URL to redirect the user to reset their password. If the token isn't valid or expired, it'll be redirected with a query parameter `?error=INVALID_TOKEN`. If the token is valid, it'll be redirected with a query parameter `?token=VALID_TOKEN"}).optional()}),metadata:{openapi:{operationId:"requestPasswordReset",description:"Send a password reset email to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"},message:{type:"string"}}}}}}}}},use:[tT(e=>e.body.redirectTo)]},async e=>{if(!e.context.options.emailAndPassword?.sendResetPassword)throw e.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPassword function in your auth config!"),u.E.from("BAD_REQUEST",{message:"Reset password isn't enabled",code:"RESET_PASSWORD_DISABLED"});let{email:t,redirectTo:r}=e.body,i=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!i)return(0,y.f)(24),await e.context.internalAdapter.findVerificationValue("dummy-verification-token"),e.context.logger.warn("Reset Password: User not found"),e.json({status:!0,message:"If this email exists in our system, check your email for the reset link"});let a=(0,e1.f)(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||3600,"sec"),o=(0,y.f)(24);await e.context.internalAdapter.createVerificationValue({value:i.user.id,identifier:`reset-password:${o}`,expiresAt:a});let n=r?encodeURIComponent(r):"",s=`${e.context.baseURL}/reset-password/${o}?callbackURL=${n}`;return await e.context.runInBackgroundOrAwait(e.context.options.emailAndPassword.sendResetPassword({user:i.user,url:s,token:o},e.request)),e.json({status:!0,message:"If this email exists in our system, check your email for the reset link"})}),iI=(0,s.g)("/reset-password/:token",{method:"GET",operationId:"resetPasswordCallback",query:E.object({callbackURL:E.string().meta({description:"The URL to redirect the user to reset their password"})}),use:[tT(e=>e.query.callbackURL)],metadata:{openapi:{operationId:"resetPasswordCallback",description:"Redirects the user to the callback URL with the token",parameters:[{name:"token",in:"path",required:!0,description:"The token to reset the password",schema:{type:"string"}},{name:"callbackURL",in:"query",required:!0,description:"The URL to redirect the user to reset their password",schema:{type:"string"}}],responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}}}}}}}}}},async e=>{var t,r;let i,{token:a}=e.params,{callbackURL:o}=e.query;if(!a||!o)throw e.redirect(iE(e.context,o,{error:"INVALID_TOKEN"}));let n=await e.context.internalAdapter.findVerificationValue(`reset-password:${a}`);if(!n||n.expiresAt<new Date)throw e.redirect(iE(e.context,o,{error:"INVALID_TOKEN"}));throw e.redirect((t=e.context,r={token:a},i=new URL(o,t.baseURL),r&&Object.entries(r).forEach(([e,t])=>i.searchParams.set(e,t)),i.href))}),i_=(0,s.g)("/reset-password",{method:"POST",operationId:"resetPassword",query:E.object({token:E.string().optional()}).optional(),body:E.object({newPassword:E.string().meta({description:"The new password to set"}),token:E.string().meta({description:"The token to reset the password"}).optional()}),metadata:{openapi:{operationId:"resetPassword",description:"Reset the password for a user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{let t=e.body.token||e.query?.token;if(!t)throw u.E.from("BAD_REQUEST",tf.f.INVALID_TOKEN);let{newPassword:r}=e.body;tm(e,r),th(e,r);let i=`reset-password:${t}`,a=await e.context.internalAdapter.findVerificationValue(i);if(!a||a.expiresAt<new Date)throw u.E.from("BAD_REQUEST",tf.f.INVALID_TOKEN);let o=a.value,n=await e.context.internalAdapter.findUserById(o);if(!n)throw u.E.from("BAD_REQUEST",tf.f.USER_NOT_FOUND);let s=await e.context.password.hash(r);return await tg(e,o,s,async()=>{if(!await e.context.internalAdapter.consumeVerificationValue(i))throw u.E.from("BAD_REQUEST",tf.f.INVALID_TOKEN)}),e.context.options.emailAndPassword?.onPasswordReset&&await e.context.options.emailAndPassword.onPasswordReset({user:n},e.request),e.json({status:!0})}),ik=(0,s.g)("/verify-password",{method:"POST",body:E.object({password:E.string().meta({description:"The password to verify"})}),metadata:{scope:"server",openapi:{operationId:"verifyPassword",description:"Verify the current user's password",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}},use:[p.i]},async e=>{let{password:t}=e.body,r=e.context.session;if(!await tw(e,{password:t,userId:r.user.id}))throw u.E.from("BAD_REQUEST",tf.f.INVALID_PASSWORD);return e.json({status:!0})}),iT=E.object({callbackURL:E.string().meta({description:"Callback URL to redirect to after the user has signed in"}).optional(),newUserCallbackURL:E.string().optional(),errorCallbackURL:E.string().meta({description:"Callback URL to redirect to if an error happens"}).optional(),provider:r8,disableRedirect:E.boolean().meta({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),idToken:E.optional(E.object({token:E.string().meta({description:"ID token from the provider"}),nonce:E.string().meta({description:"Nonce used to generate the token"}).optional(),accessToken:E.string().meta({description:"Access token from the provider"}).optional(),refreshToken:E.string().meta({description:"Refresh token from the provider"}).optional(),expiresAt:E.number().meta({description:"Expiry date of the token"}).optional(),user:E.object({name:E.object({firstName:E.string().optional(),lastName:E.string().optional()}).optional(),email:E.string().optional()}).meta({description:"The user object from the provider. Only available for some providers like Apple."}).optional()})),scopes:E.array(E.string()).meta({description:"Array of scopes to request from the provider. This will override the default scopes passed."}).optional(),requestSignUp:E.boolean().meta({description:"Explicitly request sign-up. Useful when disableImplicitSignUp is true for this provider"}).optional(),loginHint:E.string().meta({description:"The login hint to use for the authorization code request"}).optional(),additionalParams:rb,additionalData:E.record(E.string(),E.any()).optional().meta({description:"Additional data to be passed through the OAuth flow"})}),iv=E.object({callbackURL:E.string().meta({description:"The URL to redirect to after provider logout"}).optional(),disableRedirect:E.boolean().meta({description:"Return the provider logout URL without redirecting"}).optional(),state:E.string().meta({description:"State to pass to the provider logout endpoint"}).optional()}).optional(),iU=e=>({success:!0,url:e?.url,redirect:e?.redirect}),iR=(0,s.g)("/sign-out",{method:"POST",body:iv,operationId:"signOut",requireHeaders:!0,metadata:{openapi:{operationId:"signOut",description:"Sign out the current user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"},url:{type:"string",description:"Provider logout URL when RP-initiated logout is available"},redirect:{type:"boolean",description:"Whether the client should redirect to the provider logout URL"}}}}}}}}}},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret),r=null;if(t)try{r=await e.context.internalAdapter.findSession(t)}catch(t){e.context.logger.error("Failed to read session from database",t)}if(t)try{await e.context.internalAdapter.deleteSession(t)}catch(t){e.context.logger.error("Failed to delete session from database",t)}(0,e0.Q)(e);let i=await (async()=>{try{if(!r)return null;let t=await e.context.internalAdapter.findAccounts(r.user.id),i=new Map(e.context.socialProviders.map(e=>[e.id,e])),a=t.filter(e=>!!i.get(e.providerId)?.createEndSessionURL).sort((e,t)=>t.updatedAt.getTime()-e.updatedAt.getTime());if(0===a.length)return null;let o=new Set,n=e.body?.callbackURL?new URL(e.body.callbackURL,e.context.baseURL).toString():void 0;for(let t of a){if(o.has(t.providerId))continue;o.add(t.providerId);let r=i.get(t.providerId);try{let i=await r?.createEndSessionURL?.({idToken:t.idToken,postLogoutRedirectURI:n,state:e.body?.state});if(i)return i.toString()}catch(r){e.context.logger.error(`Failed to create logout URL for provider "${t.providerId}"`,r)}}return null}catch(t){return e.context.logger.error("Failed to create provider logout URL",t),null}})();if(i){let t=!e.body?.disableRedirect;return t&&e.setHeader("Location",i),e.json(iU({url:i,redirect:t}))}return e.json(iU())}),ix=E.object({name:E.string(),email:E.email(),password:E.string().nonempty(),image:E.string().optional(),callbackURL:E.string().optional(),rememberMe:E.boolean().optional()}).and(E.record(E.string(),E.any())),iS=E.record(E.string().meta({description:"Field name must be a string"}),E.any()),iO=E.record(E.string().meta({description:"Field name must be a string"}),E.any()),iD=(0,s.g)("/change-password",{method:"POST",operationId:"changePassword",body:E.object({newPassword:E.string().meta({description:"The new password to set"}),currentPassword:E.string().meta({description:"The current password is required"}),revokeOtherSessions:E.boolean().meta({description:"Must be a boolean value"}).optional()}),use:[p.i],metadata:{openapi:{operationId:"changePassword",description:"Change the password of the user",responses:{200:{description:"Password successfully changed",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string",nullable:!0,description:"New session token if other sessions were revoked"},user:{type:"object",properties:{id:{type:"string",description:"The unique identifier of the user"},email:{type:"string",format:"email",description:"The email address of the user"},name:{type:"string",description:"The name of the user"},image:{type:"string",format:"uri",nullable:!0,description:"The profile image URL of the user"},emailVerified:{type:"boolean",description:"Whether the email has been verified"},createdAt:{type:"string",format:"date-time",description:"When the user was created"},updatedAt:{type:"string",format:"date-time",description:"When the user was last updated"}},required:["id","email","name","emailVerified","createdAt","updatedAt"]}},required:["user"]}}}}}}}},async e=>{let{newPassword:t,currentPassword:r,revokeOtherSessions:i}=e.body,a=e.context.session;tm(e,t),th(e,t),th(e,r);let o=await e.context.internalAdapter.findCredentialAccount(a.user.id);if(!o||!o.password)throw u.E.from("BAD_REQUEST",tf.f.CREDENTIAL_ACCOUNT_NOT_FOUND);let n=await e.context.password.hash(t);if(!await e.context.password.verify({hash:o.password,password:r}))throw u.E.from("BAD_REQUEST",tf.f.INVALID_PASSWORD);let s=await (0,e7.n)(e.context.adapter,async()=>{if(i&&await e.context.internalAdapter.deleteUserSessions(a.user.id),await e.context.internalAdapter.updateAccount(o.id,{password:n}),!i)return null;let t=await e.context.internalAdapter.createSession(a.user.id,void 0,void 0,void 0,{deferSecondaryStorageWrites:!0});if(!t)throw u.E.from("INTERNAL_SERVER_ERROR",tf.f.FAILED_TO_GET_SESSION);return t}),l=null;return s&&(await (0,e0.V)(e,{session:s,user:a.user}),l=s.token),e.json({token:l,user:(0,w.$)(e.context.options,a.user)})}),iN=s.g.serverOnly({method:"POST",body:E.object({newPassword:E.string().meta({description:"The new password to set is required"})}),use:[p.i]},async e=>{let{newPassword:t}=e.body,r=e.context.session;tm(e,t),th(e,t);let i=await e.context.internalAdapter.findCredentialAccount(r.user.id),a=await e.context.password.hash(t);if(!i)return await e.context.internalAdapter.linkAccount({userId:r.user.id,providerId:"credential",accountId:r.user.id,password:a}),e.json({status:!0});if(!i.password)return await e.context.internalAdapter.updateAccount(i.id,{password:a}),e.json({status:!0});throw u.E.from("BAD_REQUEST",tf.f.PASSWORD_ALREADY_SET)}),iL=(0,s.g)("/delete-user",{method:"POST",use:[p.i],body:E.object({callbackURL:E.string().meta({description:"The callback URL to redirect to after the user is deleted"}).optional(),password:E.string().meta({description:"The password of the user is required to delete the user"}).optional(),token:E.string().meta({description:"The token to delete the user is required"}).optional()}),metadata:{openapi:{operationId:"deleteUser",description:"Delete the user",requestBody:{content:{"application/json":{schema:{type:"object",properties:{callbackURL:{type:"string",description:"The callback URL to redirect to after the user is deleted"},password:{type:"string",description:"The user's password. Required if session is not fresh"},token:{type:"string",description:"The deletion verification token"}}}}}},responses:{200:{description:"User deletion processed successfully",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",description:"Indicates if the operation was successful"},message:{type:"string",enum:["User deleted","Verification email sent"],description:"Status message of the deletion process"}},required:["success","message"]}}}}}}}},async e=>{if(!e.context.options.user?.deleteUser?.enabled)throw e.context.logger.error("Delete user is disabled. Enable it in the options"),u.E.fromStatus("NOT_FOUND");let t=e.context.session;if(e.body.password){th(e,e.body.password);let r=await e.context.internalAdapter.findCredentialAccount(t.user.id);if(!r||!r.password)throw u.E.from("BAD_REQUEST",tf.f.CREDENTIAL_ACCOUNT_NOT_FOUND);if(!await e.context.password.verify({hash:r.password,password:e.body.password}))throw u.E.from("BAD_REQUEST",tf.f.INVALID_PASSWORD)}if(e.body.token)return await iP({...e,query:{token:e.body.token}}),e.json({success:!0,message:"User deleted"});if(e.context.options.user.deleteUser?.sendDeleteAccountVerification){let r=(0,g.f)(32,"0-9","a-z");await e.context.internalAdapter.createVerificationValue({value:t.user.id,identifier:`delete-account-${r}`,expiresAt:new Date(Date.now()+1e3*(e.context.options.user.deleteUser?.deleteTokenExpiresIn||86400))});let i=`${e.context.baseURL}/delete-user/callback?token=${r}&callbackURL=${encodeURIComponent(e.body.callbackURL||"/")}`;return await e.context.runInBackgroundOrAwait(e.context.options.user.deleteUser.sendDeleteAccountVerification({user:t.user,url:i,token:r},e.request)),e.json({success:!0,message:"Verification email sent"})}if(!e.body.password&&0!==e.context.sessionConfig.freshAge){let r=new Date(t.session.createdAt).getTime(),i=1e3*e.context.sessionConfig.freshAge;if(Date.now()-r>=i)throw u.E.from("BAD_REQUEST",tf.f.SESSION_EXPIRED)}let r=e.context.options.user.deleteUser?.beforeDelete;r&&await r(t.user,e.request),await e.context.internalAdapter.deleteUser(t.user.id),await e.context.internalAdapter.deleteUserSessions(t.user.id),(0,e0.Q)(e);let i=e.context.options.user.deleteUser?.afterDelete;return i&&await i(t.user,e.request),e.json({success:!0,message:"User deleted"})}),iP=(0,s.g)("/delete-user/callback",{method:"GET",query:E.object({token:E.string().meta({description:"The token to verify the deletion request"}),callbackURL:E.string().meta({description:"The URL to redirect to after deletion"}).optional()}),use:[tT(e=>e.query.callbackURL)],metadata:{openapi:{description:"Callback to complete user deletion with verification token",responses:{200:{description:"User successfully deleted",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",description:"Indicates if the deletion was successful"},message:{type:"string",enum:["User deleted"],description:"Confirmation message"}},required:["success","message"]}}}}}}}},async e=>{if(!e.context.options.user?.deleteUser?.enabled)throw e.context.logger.error("Delete user is disabled. Enable it in the options"),u.E.from("NOT_FOUND",{message:"Not found",code:"NOT_FOUND"});let t=await (0,p.D)(e,{disableCookieCache:(0,p.f)(e)});if(!t)throw u.E.from("NOT_FOUND",tf.f.FAILED_TO_GET_USER_INFO);let r=await e.context.internalAdapter.consumeVerificationValue(`delete-account-${e.query.token}`);if(!r||r.value!==t.user.id)throw u.E.from("NOT_FOUND",tf.f.INVALID_TOKEN);let i=e.context.options.user.deleteUser?.beforeDelete;i&&await i(t.user,e.request),await e.context.internalAdapter.deleteUser(t.user.id),await e.context.internalAdapter.deleteUserSessions(t.user.id),await e.context.internalAdapter.deleteAccounts(t.user.id),(0,e0.Q)(e);let a=e.context.options.user.deleteUser?.afterDelete;if(a&&await a(t.user,e.request),e.query.callbackURL)throw e.redirect(e.query.callbackURL||"/");return e.json({success:!0,message:"User deleted"})}),iC=(0,s.g)("/change-email",{method:"POST",body:E.object({newEmail:E.email().meta({description:"The new email address to set must be a valid email address"}),callbackURL:E.string().meta({description:"The URL to redirect to after email verification"}).optional()}),use:[p.i],metadata:{openapi:{operationId:"changeEmail",responses:{200:{description:"Email change request processed successfully",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object",$ref:"#/components/schemas/User"},status:{type:"boolean",description:"Indicates if the request was successful"},message:{type:"string",enum:["Email updated","Verification email sent"],description:"Status message of the email change process",nullable:!0}},required:["status"]}}}}}}}},async e=>{if(!e.context.options.user?.changeEmail?.enabled)throw e.context.logger.error("Change email is disabled."),u.E.from("BAD_REQUEST",tf.f.CHANGE_EMAIL_DISABLED);let t=e.body.newEmail.toLowerCase();if(t===e.context.session.user.email)throw e.context.logger.warn("Email is the same"),u.E.fromStatus("BAD_REQUEST",{message:"Email is the same"});let r=!0!==e.context.session.user.emailVerified&&e.context.options.user.changeEmail.updateEmailWithoutVerification,i=e.context.options.emailVerification?.sendVerificationEmail,a=i&&e.context.session.user.emailVerified&&e.context.options.user.changeEmail.sendChangeEmailConfirmation;if(!r&&!a&&!i)throw e.context.logger.error("Verification email isn't enabled."),u.E.fromStatus("BAD_REQUEST",{message:"Verification email isn't enabled"});if(await e.context.internalAdapter.findUserByEmail(t))return await t4(e.context.secret,e.context.session.user.email,t,e.context.options.emailVerification?.expiresIn,{userId:e.context.session.user.id}),e.context.logger.info("Change email attempt for existing email"),e.json({status:!0});if(r){if(await e.context.internalAdapter.updateUser(e.context.session.user.id,{email:t}),await (0,e0.V)(e,{session:e.context.session.session,user:{...e.context.session.user,email:t}}),i){let r=await t4(e.context.secret,t,void 0,e.context.options.emailVerification?.expiresIn,{userId:e.context.session.user.id}),a=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${encodeURIComponent(e.body.callbackURL||"/")}`;await e.context.runInBackgroundOrAwait(i({user:{...e.context.session.user,email:t},url:a,token:r},e.request))}return e.json({status:!0})}if(a){let r=await t4(e.context.secret,e.context.session.user.email,t,e.context.options.emailVerification?.expiresIn,{requestType:"change-email-confirmation",userId:e.context.session.user.id}),i=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${encodeURIComponent(e.body.callbackURL||"/")}`;return await e.context.runInBackgroundOrAwait(a({user:e.context.session.user,newEmail:t,url:i,token:r},e.request)),e.json({status:!0})}if(!i)throw e.context.logger.error("Verification email isn't enabled."),u.E.fromStatus("BAD_REQUEST",{message:"Verification email isn't enabled"});let o=await t4(e.context.secret,e.context.session.user.email,t,e.context.options.emailVerification?.expiresIn,{requestType:"change-email-verification",userId:e.context.session.user.id}),n=`${e.context.baseURL}/verify-email?token=${o}&callbackURL=${encodeURIComponent(e.body.callbackURL||"/")}`;return await e.context.runInBackgroundOrAwait(i({user:{...e.context.session.user,email:t},url:n,token:o},e.request)),e.json({status:!0})});var iq=e.i(829302);async function ij(e,t){if(e.baseURL)return e;let r=function(e){if((0,eV.T)(e?.request))return e.request;if(!e?.headers)return;let t=e.headers instanceof Headers?e.headers:new Headers(e.headers);if(t.has("host")||t.has("x-forwarded-host"))return t}(t),i=e.options.baseURL,a=(0,eV._)(i)&&!!i.fallback;if(void 0===r&&!a)throw new u.E("INTERNAL_SERVER_ERROR",{message:"Dynamic baseURL could not be resolved for this direct auth.api call. Pass `headers: request.headers` (or `request`) to the call, or add `fallback` to your baseURL config."});try{return await td(e,r,tc(e.options))}catch(e){if(e instanceof u.p)throw new u.E("INTERNAL_SERVER_ERROR",{message:e.message});throw e}}e.i(418069);var i$=e.i(986097);function iB(e,t){let r=(0,te.f)(t),i=t.plugins?.reduce((e,t)=>({...e,...t.endpoints}),{})??{},a=t.plugins?.map(t=>t.middlewares?.map(i=>{let a=async a=>{let o=await e;return r(`middleware ${i.path} ${t.id}`,{[e9.A]:"middleware",[e9.F]:i.path,[e9.s]:`plugin:${t.id}`},()=>i.middleware({...a,context:{...o,...a.context}}))};return a.options=i.middleware.options,{path:i.path,middleware:a}})).filter(e=>void 0!==e).flat()||[];return{api:function(e,t){let r={};for(let[i,a]of Object.entries(e))r[i]=async e=>{let r=(0,iq.x)(a,i),o=async()=>{let i=await t,o=i.checkSchema?.();o&&await o;let n=(0,eV._)(i.options.baseURL)?await ij(i,e):i;return(0,iq.P)(a,{...e,context:n,operationId:r,asResponse:e?.asResponse??(0,eV.T)(e?.request)})};return await (0,f.B)()?o():(0,f.O)(new WeakMap,o)},r[i].path=a.path,r[i].options=a.options;return r}({signInSocial:(0,s.g)("/sign-in/social",{method:"POST",operationId:"socialSignIn",body:iT,metadata:{$Infer:{body:{},returned:{}},openapi:{description:"Sign in with a social provider",operationId:"socialSignIn",responses:{200:{description:"Success - Returns session details (idToken branch) or an authorize URL (redirect branch)",content:{"application/json":{schema:{type:"object",description:"Returns session details when idToken is provided, or an authorize URL otherwise",properties:{token:{type:"string"},user:{type:"object",$ref:"#/components/schemas/User"},url:{type:"string"},redirect:{type:"boolean"}},required:["redirect"]}}}}}}}},async e=>{let t=await tu(e.context.socialProviders,{value:e.body.provider});if(!t)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),u.E.from("NOT_FOUND",tf.f.PROVIDER_NOT_FOUND);if(e.body.idToken){if(!rT(t))throw e.context.logger.error("Provider does not support id token verification",{provider:e.body.provider}),u.E.from("NOT_FOUND",tf.f.ID_TOKEN_NOT_SUPPORTED);let{token:r,nonce:i}=e.body.idToken;if(!await rv(t,r,i,e))throw e.context.logger.warn("Invalid id token",{provider:e.body.provider}),u.E.from("UNAUTHORIZED",tf.f.INVALID_TOKEN);let a={idToken:r,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken,user:e.body.idToken.user},o=t.getUserInfoFromIdToken?await t.getUserInfoFromIdToken(r):await t.getUserInfo(a);if(!o||!o?.user)throw e.context.logger.error("Failed to get user info",{provider:e.body.provider}),u.E.from("UNAUTHORIZED",tf.f.FAILED_TO_GET_USER_INFO);if(!o.user.email)throw e.context.logger.error(tJ(e.body.provider,{source:"id_token"}),{provider:e.body.provider}),u.E.from("UNAUTHORIZED",tf.f.USER_EMAIL_NOT_FOUND);let n=await tz(t,a,o.data),s=o.data,l=await ra(e,{userInfo:{...o.user,email:o.user.email,id:n.accountId,name:o.user.name||"",image:o.user.image,emailVerified:o.user.emailVerified||!1},account:{...n,accessToken:e.body.idToken.accessToken,idToken:r},callbackURL:e.body.callbackURL,disableSignUp:t.disableImplicitSignUp&&!e.body.requestSignUp||t.options?.disableSignUp||t.disableSignUp,source:{method:"oauth",oauth:{providerId:t.id,profile:s}}});if(l.error){if(l.error===tQ)throw u.E.from("FORBIDDEN",tf.f.EMAIL_NOT_VERIFIED);throw u.E.from("UNAUTHORIZED",{message:l.error,code:"OAUTH_LINK_ERROR"})}return await (0,e0.V)(e,l.data),e.json({redirect:!1,token:l.data.session.token,url:void 0,user:(0,w.$)(e.context.options,l.data.user)})}let r=rf(t),{codeVerifier:i,state:a}=await rm(e,{additionalData:e.body.additionalData,idTokenNonce:r}),o=await t.createAuthorizationURL({state:a,codeVerifier:i,idTokenNonce:r,redirectURI:`${e.context.baseURL}${t1(t)}`,scopes:e.body.scopes,loginHint:e.body.loginHint,additionalParams:e.body.additionalParams});return e.body.disableRedirect||e.setHeader("Location",o.toString()),e.json({url:o.toString(),redirect:!e.body.disableRedirect})}),callbackOAuth:ig,getSession:(0,p.v)(),signOut:iR,signUpEmail:(0,s.g)("/sign-up/email",{method:"POST",operationId:"signUpWithEmailAndPassword",use:[tU],body:ix,cloneRequest:!0,metadata:{allowedMediaTypes:["application/x-www-form-urlencoded","application/json"],$Infer:{body:{},returned:{}},openapi:{operationId:"signUpWithEmailAndPassword",description:"Sign up a user using email and password",requestBody:{content:{"application/json":{schema:{type:"object",properties:{name:{type:"string",description:"The name of the user"},email:{type:"string",description:"The email of the user"},password:{type:"string",description:"The password of the user"},image:{type:"string",description:"The profile image URL of the user"},callbackURL:{type:"string",description:"The URL to use for email verification callback"},rememberMe:{type:"boolean",description:"If this is false, the session will not be remembered. Default is `true`."}},required:["name","email","password"]}}}},responses:{200:{description:"Successfully created user",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string",nullable:!0,description:"Authentication token for the session"},user:{type:"object",properties:{id:{type:"string",description:"The unique identifier of the user"},email:{type:"string",format:"email",description:"The email address of the user"},name:{type:"string",description:"The name of the user"},image:{type:"string",format:"uri",nullable:!0,description:"The profile image URL of the user"},emailVerified:{type:"boolean",description:"Whether the email has been verified"},createdAt:{type:"string",format:"date-time",description:"When the user was created"},updatedAt:{type:"string",format:"date-time",description:"When the user was last updated"}},required:["id","email","name","emailVerified","createdAt","updatedAt"]}},required:["user"]}}}},422:{description:"Unprocessable Entity. User already exists or failed to create user.",content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}}}}}}},async e=>(0,e7.n)(e.context.adapter,async()=>{let t;if(!e.context.options.emailAndPassword?.enabled||e.context.options.emailAndPassword?.disableSignUp)throw u.E.from("BAD_REQUEST",{message:"Email and password sign up is not enabled",code:"EMAIL_PASSWORD_SIGN_UP_DISABLED"});let r=e.body,{name:i,email:a,password:o,image:n,callbackURL:s,rememberMe:l,...c}=r;if(!E.email().safeParse(a).success)throw u.E.from("BAD_REQUEST",tf.f.INVALID_EMAIL);if(!o||"string"!=typeof o)throw u.E.from("BAD_REQUEST",tf.f.INVALID_PASSWORD);tm(e,o),th(e,o);let d=e.context.options.emailAndPassword.requireEmailVerification||!1===e.context.options.emailAndPassword.autoSignIn,p=!1===e.context.options.emailAndPassword.autoSignIn||d,f=(0,w.R)(e.context.options,c,"create"),m=a.toLowerCase(),h=()=>{let t,r=new Date,a=e.context.generateId({model:"user"})||(0,y.f)(),o={name:i,email:m,emailVerified:!1,image:n??null,createdAt:r,updatedAt:r},s=e.context.options.emailAndPassword?.customSyntheticUser;if(s){let r=Object.keys(e.context.options.user?.additionalFields??{}),i={};for(let e of r)e in f&&(i[e]=f[e]);let n=s({coreFields:o,additionalFields:i,id:a});t=(0,w.g)(e.context.options,n)}else t=(0,w.g)(e.context.options,{...o,...f,id:a});return e.json({token:null,user:(0,w.$)(e.context.options,t)})},g=await e.context.internalAdapter.findUserByEmail(m);if(g?.user){if(e.context.logger.info(`Sign-up attempt for existing email: ${a}`),d)return await e.context.password.hash(o),e.context.options.emailAndPassword?.onExistingUserSignUp&&await e.context.runInBackgroundOrAwait(e.context.options.emailAndPassword.onExistingUserSignUp({user:g.user},t3(e.request))),h();throw u.E.from("UNPROCESSABLE_ENTITY",tf.f.USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL)}let b=await e.context.password.hash(o);try{if(!(t=await e.context.internalAdapter.createUser({email:m,name:i,image:n,...f,emailVerified:!1},{method:"email-password"})))throw u.E.from("BAD_REQUEST",tf.f.FAILED_TO_CREATE_USER)}catch(t){if((0,tb.f)(t)){if(403===t.statusCode&&d)return h();throw t}throw(0,ta.o)()&&e.context.logger.error("Failed to create user",t),e.context.logger?.error("Failed to create user",t),u.E.from("UNPROCESSABLE_ENTITY",tf.f.FAILED_TO_CREATE_USER)}if(!t)throw u.E.from("UNPROCESSABLE_ENTITY",tf.f.FAILED_TO_CREATE_USER);if(await e.context.internalAdapter.linkAccount({userId:t.id,providerId:"credential",accountId:t.id,password:b}),e.context.options.emailVerification?.sendOnSignUp??e.context.options.emailAndPassword.requireEmailVerification){let i=await t4(e.context.secret,t.email,void 0,e.context.options.emailVerification?.expiresIn,{userId:t.id}),a=r.callbackURL?encodeURIComponent(r.callbackURL):encodeURIComponent("/"),o=`${e.context.baseURL}/verify-email?token=${i}&callbackURL=${a}`;e.context.options.emailVerification?.sendVerificationEmail&&await e.context.runInBackgroundOrAwait(e.context.options.emailVerification.sendVerificationEmail({user:t,url:o,token:i},t3(e.request)))}if(p)return e.json({token:null,user:(0,w.$)(e.context.options,t)});let A=await e.context.internalAdapter.createSession(t.id,!1===l,void 0,void 0,{deferSecondaryStorageWrites:!0});if(!A)throw u.E.from("BAD_REQUEST",tf.f.FAILED_TO_CREATE_SESSION);return await (0,e0.V)(e,{session:A,user:t},!1===l),e.json({token:A.token,user:(0,w.$)(e.context.options,t)})})),signInEmail:(0,s.g)("/sign-in/email",{method:"POST",operationId:"signInEmail",use:[tU],cloneRequest:!0,body:E.object({email:E.string().meta({description:"Email of the user"}),password:E.string().meta({description:"Password of the user"}),callbackURL:E.string().meta({description:"Callback URL to use as a redirect for email verification"}).optional(),rememberMe:E.boolean().meta({description:"If this is false, the session will not be remembered. Default is `true`."}).default(!0).optional()}),metadata:{allowedMediaTypes:["application/x-www-form-urlencoded","application/json"],$Infer:{body:{},returned:{}},openapi:{operationId:"signInEmail",description:"Sign in with email and password",responses:{200:{description:"Success - Returns either session details or redirect URL",content:{"application/json":{schema:{type:"object",description:"Session response when idToken is provided",properties:{redirect:{type:"boolean",enum:[!1]},token:{type:"string",description:"Session token"},url:{type:"string",nullable:!0},user:{type:"object",$ref:"#/components/schemas/User"}},required:["redirect","token","user"]}}}}}}}},async e=>{if(!e.context.options?.emailAndPassword?.enabled)throw e.context.logger.error("Email and password is not enabled. Make sure to enable it in the options on you `auth.ts` file. Check `https://better-auth.com/docs/authentication/email-password` for more!"),u.E.from("BAD_REQUEST",{code:"EMAIL_PASSWORD_DISABLED",message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!E.email().safeParse(t).success)throw u.E.from("BAD_REQUEST",tf.f.INVALID_EMAIL);th(e,r);let i=await e.context.internalAdapter.findUserByEmail(t.toLowerCase(),{includeAccounts:!0}),a=i?.accounts.find(e=>"credential"===e.providerId&&e.accountId===i.user.id);if(!i||!a)throw await e.context.password.hash(r),e.context.logger.warn("User not found"),u.E.from("UNAUTHORIZED",tf.f.INVALID_EMAIL_OR_PASSWORD);let o=i.user,n=a.password;if(!n)throw await e.context.password.hash(r),e.context.logger.warn("Password not found"),u.E.from("UNAUTHORIZED",tf.f.INVALID_EMAIL_OR_PASSWORD);if(!await e.context.password.verify({hash:n,password:r}))throw e.context.logger.warn("Invalid password"),u.E.from("UNAUTHORIZED",tf.f.INVALID_EMAIL_OR_PASSWORD);if(e.context.options?.emailAndPassword?.requireEmailVerification&&!o.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw u.E.from("FORBIDDEN",tf.f.EMAIL_NOT_VERIFIED);if(e.context.options?.emailVerification?.sendOnSignIn){let t=await t4(e.context.secret,o.email,void 0,e.context.options.emailVerification?.expiresIn,{userId:o.id}),r=e.body.callbackURL?encodeURIComponent(e.body.callbackURL):encodeURIComponent("/"),i=`${e.context.baseURL}/verify-email?token=${t}&callbackURL=${r}`;await e.context.runInBackgroundOrAwait(e.context.options.emailVerification.sendVerificationEmail({user:o,url:i,token:t},t3(e.request)))}throw u.E.from("FORBIDDEN",tf.f.EMAIL_NOT_VERIFIED)}let s=await e.context.internalAdapter.createSession(o.id,!1===e.body.rememberMe);if(!s)throw e.context.logger.error("Failed to create session"),u.E.from("UNAUTHORIZED",tf.f.FAILED_TO_CREATE_SESSION);return await (0,e0.V)(e,{session:s,user:o},!1===e.body.rememberMe),e.body.callbackURL&&e.setHeader("Location",e.body.callbackURL),e.json({redirect:!!e.body.callbackURL,token:s.token,url:e.body.callbackURL,user:(0,w.$)(e.context.options,o)})}),resetPassword:i_,verifyPassword:ik,verifyEmail:t9,sendVerificationEmail:t8,changeEmail:iC,changePassword:iD,setPassword:iN,updateSession:(0,s.g)("/update-session",{method:"POST",operationId:"updateSession",body:iS,use:[p.Z],metadata:{$Infer:{body:{}},openapi:{operationId:"updateSession",description:"Update the current session",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"object",$ref:"#/components/schemas/Session"}}}}}}}}}},async e=>{let t=e.body;if("object"!=typeof t||Array.isArray(t))throw u.E.from("BAD_REQUEST",tf.f.BODY_MUST_BE_AN_OBJECT);let r=e.context.session,i=(0,w.z)(e.context.options,t,"update");if(0===Object.keys(i).length)throw u.E.fromStatus("BAD_REQUEST",{message:"No fields to update"});let a=await e.context.internalAdapter.updateSession(r.session.token,{...i,updatedAt:new Date});if(!a&&(0,p.f)(e))throw(0,e0.Q)(e),u.E.from("UNAUTHORIZED",tf.f.FAILED_TO_GET_SESSION);let o=a??{...r.session,...i,updatedAt:new Date};return await (0,e0.V)(e,{session:o,user:r.user}),e.json({session:(0,w.Q)(e.context.options,o)})}),updateUser:(0,s.g)("/update-user",{method:"POST",operationId:"updateUser",body:iO,use:[p.Z],metadata:{$Infer:{body:{}},openapi:{operationId:"updateUser",description:"Update the current user",requestBody:{content:{"application/json":{schema:{type:"object",properties:{name:{type:"string",description:"The name of the user"},image:{type:"string",description:"The image of the user",nullable:!0}}}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object",$ref:"#/components/schemas/User"}}}}}}}}}},async e=>{let t=e.body;if("object"!=typeof t||Array.isArray(t))throw u.E.from("BAD_REQUEST",tf.f.BODY_MUST_BE_AN_OBJECT);if(t.email)throw u.E.from("BAD_REQUEST",tf.f.EMAIL_CAN_NOT_BE_UPDATED);let{name:r,image:i,...a}=t,o=e.context.session,n=(0,w.R)(e.context.options,a,"update");if(void 0===i&&void 0===r&&0===Object.keys(n).length)throw u.E.fromStatus("BAD_REQUEST",{message:"No fields to update"});let s=await e.context.internalAdapter.updateUser(o.user.id,{name:r,image:i,...n})??{...o.user,...void 0!==r&&{name:r},...void 0!==i&&{image:i},...n};return await (0,e0.V)(e,{session:o.session,user:s}),e.json({status:!0})}),deleteUser:iL,requestPasswordReset:iA,requestPasswordResetCallback:iI,listSessions:(0,p.T)(),revokeSession:p.G,revokeSessions:p.$,revokeOtherSessions:p.Y,linkSocialAccount:it,listUserAccounts:ie,deleteUserCallback:iP,unlinkAccount:ir,refreshToken:id,getAccessToken:ic,accountInfo:iu,...i,ok:ib,error:iy},e),middlewares:a}}var iV=e.i(114268),iM=e.i(902157),iF=e.i(912714),iK=e.i(660526),iz=e.i(750227),iH=e.i(339127);async function iW(e,t){return{database:t?.database,adapter:t?.adapter,emailVerification:{sendVerificationEmail:!!e.emailVerification?.sendVerificationEmail,sendOnSignUp:!!e.emailVerification?.sendOnSignUp,sendOnSignIn:!!e.emailVerification?.sendOnSignIn,autoSignInAfterVerification:!!e.emailVerification?.autoSignInAfterVerification,expiresIn:e.emailVerification?.expiresIn,beforeEmailVerification:!!e.emailVerification?.beforeEmailVerification,afterEmailVerification:!!e.emailVerification?.afterEmailVerification},emailAndPassword:{enabled:!!e.emailAndPassword?.enabled,disableSignUp:!!e.emailAndPassword?.disableSignUp,requireEmailVerification:!!e.emailAndPassword?.requireEmailVerification,maxPasswordLength:e.emailAndPassword?.maxPasswordLength,minPasswordLength:e.emailAndPassword?.minPasswordLength,sendResetPassword:!!e.emailAndPassword?.sendResetPassword,resetPasswordTokenExpiresIn:e.emailAndPassword?.resetPasswordTokenExpiresIn,onPasswordReset:!!e.emailAndPassword?.onPasswordReset,password:{hash:!!e.emailAndPassword?.password?.hash,verify:!!e.emailAndPassword?.password?.verify},autoSignIn:!!e.emailAndPassword?.autoSignIn,revokeSessionsOnPasswordReset:!!e.emailAndPassword?.revokeSessionsOnPasswordReset},socialProviders:await Promise.all(Object.keys(e.socialProviders||{}).map(async t=>{let r=e.socialProviders?.[t];if(!r)return{};let i="function"==typeof r?await r():r;return{id:t,mapProfileToUser:!!i.mapProfileToUser,disableDefaultScope:!!i.disableDefaultScope,disableIdTokenSignIn:!!i.disableIdTokenSignIn,disableImplicitSignUp:i.disableImplicitSignUp,disableSignUp:i.disableSignUp,getUserInfo:!!i.getUserInfo,overrideUserInfoOnSignIn:!!i.overrideUserInfoOnSignIn,prompt:i.prompt,verifyIdToken:!!i.verifyIdToken,scope:i.scope,refreshAccessToken:!!i.refreshAccessToken}})),plugins:e.plugins?.map(e=>e.id.toString()),user:{modelName:e.user?.modelName,fields:e.user?.fields,additionalFields:e.user?.additionalFields,changeEmail:{enabled:e.user?.changeEmail?.enabled,sendChangeEmailConfirmation:!!e.user?.changeEmail?.sendChangeEmailConfirmation}},verification:{modelName:e.verification?.modelName,disableCleanup:e.verification?.disableCleanup,fields:e.verification?.fields},session:{modelName:e.session?.modelName,additionalFields:e.session?.additionalFields,cookieCache:{enabled:e.session?.cookieCache?.enabled,maxAge:e.session?.cookieCache?.maxAge,strategy:e.session?.cookieCache?.strategy},disableSessionRefresh:e.session?.disableSessionRefresh,expiresIn:e.session?.expiresIn,fields:e.session?.fields,freshAge:e.session?.freshAge,preserveSessionInDatabase:e.session?.preserveSessionInDatabase,storeSessionInDatabase:e.session?.storeSessionInDatabase,updateAge:e.session?.updateAge},account:{modelName:e.account?.modelName,fields:e.account?.fields,encryptOAuthTokens:e.account?.encryptOAuthTokens,updateAccountOnSignIn:e.account?.updateAccountOnSignIn,accountLinking:{enabled:e.account?.accountLinking?.enabled,trustedProviders:e.account?.accountLinking?.trustedProviders,updateUserInfoOnLink:e.account?.accountLinking?.updateUserInfoOnLink,allowUnlinkingAll:e.account?.accountLinking?.allowUnlinkingAll}},hooks:{after:!!e.hooks?.after,before:!!e.hooks?.before},secondaryStorage:!!e.secondaryStorage,advanced:{cookiePrefix:!!e.advanced?.cookiePrefix,cookies:!!e.advanced?.cookies,crossSubDomainCookies:{domain:!!e.advanced?.crossSubDomainCookies?.domain,enabled:e.advanced?.crossSubDomainCookies?.enabled,additionalCookies:e.advanced?.crossSubDomainCookies?.additionalCookies},database:{generateId:e.advanced?.database?.generateId,defaultFindManyLimit:e.advanced?.database?.defaultFindManyLimit},useSecureCookies:e.advanced?.useSecureCookies,ipAddress:{disableIpTracking:e.advanced?.ipAddress?.disableIpTracking,ipAddressHeaders:e.advanced?.ipAddress?.ipAddressHeaders},disableCSRFCheck:e.advanced?.disableCSRFCheck,cookieAttributes:{expires:e.advanced?.defaultCookieAttributes?.expires,secure:e.advanced?.defaultCookieAttributes?.secure,sameSite:e.advanced?.defaultCookieAttributes?.sameSite,domain:!!e.advanced?.defaultCookieAttributes?.domain,path:e.advanced?.defaultCookieAttributes?.path,httpOnly:e.advanced?.defaultCookieAttributes?.httpOnly}},trustedOrigins:e.trustedOrigins?.length,rateLimit:{storage:e.rateLimit?.storage,modelName:e.rateLimit?.modelName,window:e.rateLimit?.window,customStorage:!!e.rateLimit?.customStorage,enabled:e.rateLimit?.enabled,max:e.rateLimit?.max},onAPIError:{errorURL:e.onAPIError?.errorURL,onError:!!e.onAPIError?.onError,throw:e.onAPIError?.throw},logger:{disabled:e.logger?.disabled,level:e.logger?.level,log:!!e.logger?.log},databaseHooks:{user:{create:{after:!!e.databaseHooks?.user?.create?.after,before:!!e.databaseHooks?.user?.create?.before},update:{after:!!e.databaseHooks?.user?.update?.after,before:!!e.databaseHooks?.user?.update?.before}},session:{create:{after:!!e.databaseHooks?.session?.create?.after,before:!!e.databaseHooks?.session?.create?.before},update:{after:!!e.databaseHooks?.session?.update?.after,before:!!e.databaseHooks?.session?.update?.before}},account:{create:{after:!!e.databaseHooks?.account?.create?.after,before:!!e.databaseHooks?.account?.create?.before},update:{after:!!e.databaseHooks?.account?.update?.after,before:!!e.databaseHooks?.account?.update?.before}},verification:{create:{after:!!e.databaseHooks?.verification?.create?.after,before:!!e.databaseHooks?.verification?.create?.before},update:{after:!!e.databaseHooks?.verification?.update?.after,before:!!e.databaseHooks?.verification?.update?.before}}}}}async function iY(e){let t=await (0,d.f)("SHA-256").digest(e);return c.t.encode(t)}async function iQ(){if(t)return t;try{let e=process.cwd();if(!e)return;let r=await iF.default.readFile(iz.default.join(e,"package.json"),"utf-8");return t=JSON.parse(r)}catch{}}async function iG(e){if(t)return t.dependencies?.[e]||t.devDependencies?.[e]||t.peerDependencies?.[e];try{let t=process.cwd();if(!t)throw Error("no-cwd");let r=iz.default.join(t,"node_modules",e,"package.json"),i=await iF.default.readFile(r,"utf-8");return JSON.parse(i).version||await iJ(e)||void 0}catch{}return iJ(e)}async function iJ(e){let t=await iQ();if(t)return({...t.dependencies,...t.devDependencies,...t.peerDependencies})[e]}async function iZ(){return(await iQ())?.name}async function iX(){try{let e,t,r=iK.default.cpus();return{deploymentVendor:(e=process.env,(t=(...t)=>t.some(t=>!!e[t]))("CF_PAGES","CF_PAGES_URL","CF_ACCOUNT_ID")||"u">typeof navigator&&"Cloudflare-Workers"===navigator.userAgent?"cloudflare":t("VERCEL","VERCEL_URL","VERCEL_ENV")?"vercel":t("NETLIFY","NETLIFY_URL")?"netlify":t("RENDER","RENDER_URL","RENDER_INTERNAL_HOSTNAME","RENDER_SERVICE_ID")?"render":t("AWS_LAMBDA_FUNCTION_NAME","AWS_EXECUTION_ENV","LAMBDA_TASK_ROOT")?"aws":t("GOOGLE_CLOUD_FUNCTION_NAME","GOOGLE_CLOUD_PROJECT","GCP_PROJECT","K_SERVICE")?"gcp":t("AZURE_FUNCTION_NAME","FUNCTIONS_WORKER_RUNTIME","WEBSITE_INSTANCE_ID","WEBSITE_SITE_NAME")?"azure":t("DENO_DEPLOYMENT_ID","DENO_REGION")?"deno-deploy":t("FLY_APP_NAME","FLY_REGION","FLY_ALLOC_ID")?"fly-io":t("RAILWAY_STATIC_URL","RAILWAY_ENVIRONMENT_NAME")?"railway":t("DYNO","HEROKU_APP_NAME")?"heroku":t("DO_DEPLOYMENT_ID","DO_APP_NAME","DIGITALOCEAN")?"digitalocean":t("KOYEB","KOYEB_DEPLOYMENT_ID","KOYEB_APP_NAME")?"koyeb":null),systemPlatform:iK.default.platform(),systemRelease:iK.default.release(),systemArchitecture:iK.default.arch(),cpuCount:r.length,cpuModel:r.length?r[0].model:null,cpuSpeed:r.length?r[0].speed:null,memory:iK.default.totalmem(),isWSL:await i5(),isDocker:await i2(),isTTY:process.stdout?process.stdout.isTTY:null}}catch{return{systemPlatform:null,systemRelease:null,systemArchitecture:null,cpuCount:null,cpuModel:null,cpuSpeed:null,memory:null,isWSL:null,isDocker:null,isTTY:null}}}async function i0(){try{return iM.default.statSync("/.dockerenv"),!0}catch{return!1}}async function i1(){try{return iM.default.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}async function i2(){return void 0===r&&(r=await i0()||await i1()),r}let i3=async()=>{try{return iM.default.statSync("/run/.containerenv"),!0}catch{return!1}};async function i6(){return void 0===i&&(i=await i3()||await i2()),i}async function i5(){try{if(iK.default.release().toLowerCase().includes("microsoft")){if(await i6())return!1;return!0}return!!iM.default.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft")&&!await i6()}catch{return!1}}let i4=null;async function i7(e){if(i4)return i4;let t=await iZ();return i4=t?await iY(e?e+t:t):e?await iY(e):(0,iH.f)("a-z","A-Z","0-9")(32)}async function i8(){for(let[e,t]of Object.entries({pg:"postgresql",mysql:"mysql",mariadb:"mariadb",sqlite3:"sqlite","better-sqlite3":"sqlite","@prisma/client":"prisma",mongoose:"mongodb",mongodb:"mongodb","drizzle-orm":"drizzle"})){let r=await iG(e);if(r)return{name:t,version:r}}}async function i9(){for(let[e,t]of Object.entries({next:"next",nuxt:"nuxt","react-router":"react-router",astro:"astro","@sveltejs/kit":"sveltekit","solid-start":"solid-start","tanstack-start":"tanstack-start",hono:"hono",express:"express",elysia:"elysia",expo:"expo"})){let r=await iG(e);if(r)return{name:t,version:r}}}let ae=async function(){};async function at(e,t){let r,i=e.telemetry?.debug||(0,ta.O)("BETTER_AUTH_TELEMETRY_DEBUG",!1),a=ta.w.BETTER_AUTH_TELEMETRY_ENDPOINT;if(!a&&!t?.customTrack)return{publish:ae};let o=async e=>{t?.customTrack?await t.customTrack(e).catch(eA.y.error):a&&(i?eA.y.info("telemetry event",JSON.stringify(e,null,2)):await (0,rK.f)(a,{method:"POST",body:e}).catch(eA.y.error))},n=async()=>{let r=e.telemetry?.enabled!==void 0&&e.telemetry.enabled;return((0,ta.O)("BETTER_AUTH_TELEMETRY",!1)||r)&&(t?.skipTestCheck||!(0,ta.s)())},s=await n();return s&&(r=await i7("string"==typeof e.baseURL?e.baseURL:void 0),o({type:"init",payload:{config:await iW(e,t),runtime:"u">typeof Deno?{name:"deno",version:Deno?.version?.deno??null}:"u">typeof Bun?{name:"bun",version:Bun?.version??null}:"u">typeof process&&process?.versions?.node?{name:"node",version:process.versions.node??null}:{name:"edge",version:null},database:await i8(),framework:await i9(),environment:"production"===(0,ta.B)("NODE_ENV")?"production":"false"!==ta.$.CI&&("BUILD_ID"in ta.$||"BUILD_NUMBER"in ta.$||"CI"in ta.$||"CI_APP_ID"in ta.$||"CI_BUILD_ID"in ta.$||"CI_BUILD_NUMBER"in ta.$||"CI_NAME"in ta.$||"CONTINUOUS_INTEGRATION"in ta.$||"RUN_ID"in ta.$)?"ci":(0,ta.s)()?"test":"development",systemInfo:await iX(),packageManager:function(){let e=ta.$.npm_config_user_agent;if(!e)return;let t=e.split(" ")[0],r=t.lastIndexOf("/"),i=t.substring(0,r);return{name:"npminstall"===i?"cnpm":i,version:t.substring(r+1)}}()},anonymousId:r})),{publish:async t=>{s&&(r||(r=await i7("string"==typeof e.baseURL?e.baseURL:void 0)),await o({type:t.type,payload:t.payload,anonymousId:r}))}}}async function ar(e,t,r){let i,a,o,n,s=(0,eJ.z)(t);s||(t=(0,to.U)(t,{session:{cookieCache:{enabled:!0,strategy:"jwe",refreshCache:!0,maxAge:t.session?.expiresIn||604800}}})),t.database||(t=(0,to.U)(t,{account:{storeAccountCookie:!0}}));let c=t.plugins||[],d=(w=t,w.advanced?.crossSubDomainCookies?.enabled,[]),p=(0,eA.J)(t.logger),f=(0,eV._)(t.baseURL);if((0,eV._)(t.baseURL)){let{allowedHosts:e}=t.baseURL;if(!e||0===e.length)throw new u.p('baseURL.allowedHosts cannot be empty. Provide at least one allowed host pattern (e.g., ["myapp.com", "*.vercel.app"]).')}let m=f?void 0:(0,eV.X)("string"==typeof t.baseURL?t.baseURL:void 0,t.basePath);m||f||p.warn("[better-auth] Base URL is not set. Set the baseURL option or BETTER_AUTH_URL env, or use a dynamic baseURL with allowedHosts for multi-host setups. Without it the origin is derived from the incoming request, and callbacks and redirects may not work correctly."),"memory"===e.id&&t.advanced?.database?.generateId===!1&&p.error(`[better-auth] Misconfiguration detected.
|
|
440
|
+
</html>`})(e.context.options,a,o),{headers:{"Content-Type":"text/html"}})}),ib=(0,s.g)("/ok",{method:"GET",metadata:{...im,openapi:{description:"Check if the API is working",responses:{200:{description:"API is working",content:{"application/json":{schema:{type:"object",properties:{ok:{type:"boolean",description:"Indicates if the API is working"}},required:["ok"]}}}}}}}},async e=>e.json({ok:!0}));function iE(e,t,r){let i=t?new URL(t,e.baseURL):new URL(`${e.baseURL}/error`);return r&&Object.entries(r).forEach(([e,t])=>i.searchParams.set(e,t)),i.href}let iA=(0,s.g)("/request-password-reset",{method:"POST",body:E.object({email:E.email().meta({description:"The email address of the user to send a password reset email to"}),redirectTo:E.string().meta({description:"The URL to redirect the user to reset their password. If the token isn't valid or expired, it'll be redirected with a query parameter `?error=INVALID_TOKEN`. If the token is valid, it'll be redirected with a query parameter `?token=VALID_TOKEN"}).optional()}),metadata:{openapi:{operationId:"requestPasswordReset",description:"Send a password reset email to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"},message:{type:"string"}}}}}}}}},use:[tT(e=>e.body.redirectTo)]},async e=>{if(!e.context.options.emailAndPassword?.sendResetPassword)throw e.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPassword function in your auth config!"),u.E.from("BAD_REQUEST",{message:"Reset password isn't enabled",code:"RESET_PASSWORD_DISABLED"});let{email:t,redirectTo:r}=e.body,i=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!i)return(0,y.f)(24),await e.context.internalAdapter.findVerificationValue("dummy-verification-token"),e.context.logger.warn("Reset Password: User not found"),e.json({status:!0,message:"If this email exists in our system, check your email for the reset link"});let a=(0,e1.f)(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||3600,"sec"),o=(0,y.f)(24);await e.context.internalAdapter.createVerificationValue({value:i.user.id,identifier:`reset-password:${o}`,expiresAt:a});let n=r?encodeURIComponent(r):"",s=`${e.context.baseURL}/reset-password/${o}?callbackURL=${n}`;return await e.context.runInBackgroundOrAwait(e.context.options.emailAndPassword.sendResetPassword({user:i.user,url:s,token:o},e.request)),e.json({status:!0,message:"If this email exists in our system, check your email for the reset link"})}),iI=(0,s.g)("/reset-password/:token",{method:"GET",operationId:"resetPasswordCallback",query:E.object({callbackURL:E.string().meta({description:"The URL to redirect the user to reset their password"})}),use:[tT(e=>e.query.callbackURL)],metadata:{openapi:{operationId:"resetPasswordCallback",description:"Redirects the user to the callback URL with the token",parameters:[{name:"token",in:"path",required:!0,description:"The token to reset the password",schema:{type:"string"}},{name:"callbackURL",in:"query",required:!0,description:"The URL to redirect the user to reset their password",schema:{type:"string"}}],responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}}}}}}}}}},async e=>{var t,r;let i,{token:a}=e.params,{callbackURL:o}=e.query;if(!a||!o)throw e.redirect(iE(e.context,o,{error:"INVALID_TOKEN"}));let n=await e.context.internalAdapter.findVerificationValue(`reset-password:${a}`);if(!n||n.expiresAt<new Date)throw e.redirect(iE(e.context,o,{error:"INVALID_TOKEN"}));throw e.redirect((t=e.context,r={token:a},i=new URL(o,t.baseURL),r&&Object.entries(r).forEach(([e,t])=>i.searchParams.set(e,t)),i.href))}),i_=(0,s.g)("/reset-password",{method:"POST",operationId:"resetPassword",query:E.object({token:E.string().optional()}).optional(),body:E.object({newPassword:E.string().meta({description:"The new password to set"}),token:E.string().meta({description:"The token to reset the password"}).optional()}),metadata:{openapi:{operationId:"resetPassword",description:"Reset the password for a user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{let t=e.body.token||e.query?.token;if(!t)throw u.E.from("BAD_REQUEST",tf.f.INVALID_TOKEN);let{newPassword:r}=e.body;tm(e,r),th(e,r);let i=`reset-password:${t}`,a=await e.context.internalAdapter.findVerificationValue(i);if(!a||a.expiresAt<new Date)throw u.E.from("BAD_REQUEST",tf.f.INVALID_TOKEN);let o=a.value,n=await e.context.internalAdapter.findUserById(o);if(!n)throw u.E.from("BAD_REQUEST",tf.f.USER_NOT_FOUND);let s=await e.context.password.hash(r);return await tg(e,o,s,async()=>{if(!await e.context.internalAdapter.consumeVerificationValue(i))throw u.E.from("BAD_REQUEST",tf.f.INVALID_TOKEN)}),e.context.options.emailAndPassword?.onPasswordReset&&await e.context.options.emailAndPassword.onPasswordReset({user:n},e.request),e.json({status:!0})}),ik=(0,s.g)("/verify-password",{method:"POST",body:E.object({password:E.string().meta({description:"The password to verify"})}),metadata:{scope:"server",openapi:{operationId:"verifyPassword",description:"Verify the current user's password",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}},use:[p.i]},async e=>{let{password:t}=e.body,r=e.context.session;if(!await tw(e,{password:t,userId:r.user.id}))throw u.E.from("BAD_REQUEST",tf.f.INVALID_PASSWORD);return e.json({status:!0})}),iT=E.object({callbackURL:E.string().meta({description:"Callback URL to redirect to after the user has signed in"}).optional(),newUserCallbackURL:E.string().optional(),errorCallbackURL:E.string().meta({description:"Callback URL to redirect to if an error happens"}).optional(),provider:r8,disableRedirect:E.boolean().meta({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),idToken:E.optional(E.object({token:E.string().meta({description:"ID token from the provider"}),nonce:E.string().meta({description:"Nonce used to generate the token"}).optional(),accessToken:E.string().meta({description:"Access token from the provider"}).optional(),refreshToken:E.string().meta({description:"Refresh token from the provider"}).optional(),expiresAt:E.number().meta({description:"Expiry date of the token"}).optional(),user:E.object({name:E.object({firstName:E.string().optional(),lastName:E.string().optional()}).optional(),email:E.string().optional()}).meta({description:"The user object from the provider. Only available for some providers like Apple."}).optional()})),scopes:E.array(E.string()).meta({description:"Array of scopes to request from the provider. This will override the default scopes passed."}).optional(),requestSignUp:E.boolean().meta({description:"Explicitly request sign-up. Useful when disableImplicitSignUp is true for this provider"}).optional(),loginHint:E.string().meta({description:"The login hint to use for the authorization code request"}).optional(),additionalParams:rb,additionalData:E.record(E.string(),E.any()).optional().meta({description:"Additional data to be passed through the OAuth flow"})}),iv=E.object({callbackURL:E.string().meta({description:"The URL to redirect to after provider logout"}).optional(),disableRedirect:E.boolean().meta({description:"Return the provider logout URL without redirecting"}).optional(),state:E.string().meta({description:"State to pass to the provider logout endpoint"}).optional()}).optional(),iU=e=>({success:!0,url:e?.url,redirect:e?.redirect}),iR=(0,s.g)("/sign-out",{method:"POST",body:iv,operationId:"signOut",requireHeaders:!0,metadata:{openapi:{operationId:"signOut",description:"Sign out the current user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"},url:{type:"string",description:"Provider logout URL when RP-initiated logout is available"},redirect:{type:"boolean",description:"Whether the client should redirect to the provider logout URL"}}}}}}}}}},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret),r=null;if(t)try{r=await e.context.internalAdapter.findSession(t)}catch(t){e.context.logger.error("Failed to read session from database",t)}if(t)try{await e.context.internalAdapter.deleteSession(t)}catch(t){e.context.logger.error("Failed to delete session from database",t)}(0,e0.Q)(e);let i=await (async()=>{try{if(!r)return null;let t=await e.context.internalAdapter.findAccounts(r.user.id),i=new Map(e.context.socialProviders.map(e=>[e.id,e])),a=t.filter(e=>!!i.get(e.providerId)?.createEndSessionURL).sort((e,t)=>t.updatedAt.getTime()-e.updatedAt.getTime());if(0===a.length)return null;let o=new Set,n=e.body?.callbackURL?new URL(e.body.callbackURL,e.context.baseURL).toString():void 0;for(let t of a){if(o.has(t.providerId))continue;o.add(t.providerId);let r=i.get(t.providerId);try{let i=await r?.createEndSessionURL?.({idToken:t.idToken,postLogoutRedirectURI:n,state:e.body?.state});if(i)return i.toString()}catch(r){e.context.logger.error(`Failed to create logout URL for provider "${t.providerId}"`,r)}}return null}catch(t){return e.context.logger.error("Failed to create provider logout URL",t),null}})();if(i){let t=!e.body?.disableRedirect;return t&&e.setHeader("Location",i),e.json(iU({url:i,redirect:t}))}return e.json(iU())}),iS=E.object({name:E.string(),email:E.email(),password:E.string().nonempty(),image:E.string().optional(),callbackURL:E.string().optional(),rememberMe:E.boolean().optional()}).and(E.record(E.string(),E.any())),ix=E.record(E.string().meta({description:"Field name must be a string"}),E.any()),iO=E.record(E.string().meta({description:"Field name must be a string"}),E.any()),iD=(0,s.g)("/change-password",{method:"POST",operationId:"changePassword",body:E.object({newPassword:E.string().meta({description:"The new password to set"}),currentPassword:E.string().meta({description:"The current password is required"}),revokeOtherSessions:E.boolean().meta({description:"Must be a boolean value"}).optional()}),use:[p.i],metadata:{openapi:{operationId:"changePassword",description:"Change the password of the user",responses:{200:{description:"Password successfully changed",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string",nullable:!0,description:"New session token if other sessions were revoked"},user:{type:"object",properties:{id:{type:"string",description:"The unique identifier of the user"},email:{type:"string",format:"email",description:"The email address of the user"},name:{type:"string",description:"The name of the user"},image:{type:"string",format:"uri",nullable:!0,description:"The profile image URL of the user"},emailVerified:{type:"boolean",description:"Whether the email has been verified"},createdAt:{type:"string",format:"date-time",description:"When the user was created"},updatedAt:{type:"string",format:"date-time",description:"When the user was last updated"}},required:["id","email","name","emailVerified","createdAt","updatedAt"]}},required:["user"]}}}}}}}},async e=>{let{newPassword:t,currentPassword:r,revokeOtherSessions:i}=e.body,a=e.context.session;tm(e,t),th(e,t),th(e,r);let o=await e.context.internalAdapter.findCredentialAccount(a.user.id);if(!o||!o.password)throw u.E.from("BAD_REQUEST",tf.f.CREDENTIAL_ACCOUNT_NOT_FOUND);let n=await e.context.password.hash(t);if(!await e.context.password.verify({hash:o.password,password:r}))throw u.E.from("BAD_REQUEST",tf.f.INVALID_PASSWORD);let s=await (0,e7.n)(e.context.adapter,async()=>{if(i&&await e.context.internalAdapter.deleteUserSessions(a.user.id),await e.context.internalAdapter.updateAccount(o.id,{password:n}),!i)return null;let t=await e.context.internalAdapter.createSession(a.user.id,void 0,void 0,void 0,{deferSecondaryStorageWrites:!0});if(!t)throw u.E.from("INTERNAL_SERVER_ERROR",tf.f.FAILED_TO_GET_SESSION);return t}),l=null;return s&&(await (0,e0.V)(e,{session:s,user:a.user}),l=s.token),e.json({token:l,user:(0,w.$)(e.context.options,a.user)})}),iN=s.g.serverOnly({method:"POST",body:E.object({newPassword:E.string().meta({description:"The new password to set is required"})}),use:[p.i]},async e=>{let{newPassword:t}=e.body,r=e.context.session;tm(e,t),th(e,t);let i=await e.context.internalAdapter.findCredentialAccount(r.user.id),a=await e.context.password.hash(t);if(!i)return await e.context.internalAdapter.linkAccount({userId:r.user.id,providerId:"credential",accountId:r.user.id,password:a}),e.json({status:!0});if(!i.password)return await e.context.internalAdapter.updateAccount(i.id,{password:a}),e.json({status:!0});throw u.E.from("BAD_REQUEST",tf.f.PASSWORD_ALREADY_SET)}),iL=(0,s.g)("/delete-user",{method:"POST",use:[p.i],body:E.object({callbackURL:E.string().meta({description:"The callback URL to redirect to after the user is deleted"}).optional(),password:E.string().meta({description:"The password of the user is required to delete the user"}).optional(),token:E.string().meta({description:"The token to delete the user is required"}).optional()}),metadata:{openapi:{operationId:"deleteUser",description:"Delete the user",requestBody:{content:{"application/json":{schema:{type:"object",properties:{callbackURL:{type:"string",description:"The callback URL to redirect to after the user is deleted"},password:{type:"string",description:"The user's password. Required if session is not fresh"},token:{type:"string",description:"The deletion verification token"}}}}}},responses:{200:{description:"User deletion processed successfully",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",description:"Indicates if the operation was successful"},message:{type:"string",enum:["User deleted","Verification email sent"],description:"Status message of the deletion process"}},required:["success","message"]}}}}}}}},async e=>{if(!e.context.options.user?.deleteUser?.enabled)throw e.context.logger.error("Delete user is disabled. Enable it in the options"),u.E.fromStatus("NOT_FOUND");let t=e.context.session;if(e.body.password){th(e,e.body.password);let r=await e.context.internalAdapter.findCredentialAccount(t.user.id);if(!r||!r.password)throw u.E.from("BAD_REQUEST",tf.f.CREDENTIAL_ACCOUNT_NOT_FOUND);if(!await e.context.password.verify({hash:r.password,password:e.body.password}))throw u.E.from("BAD_REQUEST",tf.f.INVALID_PASSWORD)}if(e.body.token)return await iP({...e,query:{token:e.body.token}}),e.json({success:!0,message:"User deleted"});if(e.context.options.user.deleteUser?.sendDeleteAccountVerification){let r=(0,g.f)(32,"0-9","a-z");await e.context.internalAdapter.createVerificationValue({value:t.user.id,identifier:`delete-account-${r}`,expiresAt:new Date(Date.now()+1e3*(e.context.options.user.deleteUser?.deleteTokenExpiresIn||86400))});let i=`${e.context.baseURL}/delete-user/callback?token=${r}&callbackURL=${encodeURIComponent(e.body.callbackURL||"/")}`;return await e.context.runInBackgroundOrAwait(e.context.options.user.deleteUser.sendDeleteAccountVerification({user:t.user,url:i,token:r},e.request)),e.json({success:!0,message:"Verification email sent"})}if(!e.body.password&&0!==e.context.sessionConfig.freshAge){let r=new Date(t.session.createdAt).getTime(),i=1e3*e.context.sessionConfig.freshAge;if(Date.now()-r>=i)throw u.E.from("BAD_REQUEST",tf.f.SESSION_EXPIRED)}let r=e.context.options.user.deleteUser?.beforeDelete;r&&await r(t.user,e.request),await e.context.internalAdapter.deleteUser(t.user.id),await e.context.internalAdapter.deleteUserSessions(t.user.id),(0,e0.Q)(e);let i=e.context.options.user.deleteUser?.afterDelete;return i&&await i(t.user,e.request),e.json({success:!0,message:"User deleted"})}),iP=(0,s.g)("/delete-user/callback",{method:"GET",query:E.object({token:E.string().meta({description:"The token to verify the deletion request"}),callbackURL:E.string().meta({description:"The URL to redirect to after deletion"}).optional()}),use:[tT(e=>e.query.callbackURL)],metadata:{openapi:{description:"Callback to complete user deletion with verification token",responses:{200:{description:"User successfully deleted",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",description:"Indicates if the deletion was successful"},message:{type:"string",enum:["User deleted"],description:"Confirmation message"}},required:["success","message"]}}}}}}}},async e=>{if(!e.context.options.user?.deleteUser?.enabled)throw e.context.logger.error("Delete user is disabled. Enable it in the options"),u.E.from("NOT_FOUND",{message:"Not found",code:"NOT_FOUND"});let t=await (0,p.D)(e,{disableCookieCache:(0,p.f)(e)});if(!t)throw u.E.from("NOT_FOUND",tf.f.FAILED_TO_GET_USER_INFO);let r=await e.context.internalAdapter.consumeVerificationValue(`delete-account-${e.query.token}`);if(!r||r.value!==t.user.id)throw u.E.from("NOT_FOUND",tf.f.INVALID_TOKEN);let i=e.context.options.user.deleteUser?.beforeDelete;i&&await i(t.user,e.request),await e.context.internalAdapter.deleteUser(t.user.id),await e.context.internalAdapter.deleteUserSessions(t.user.id),await e.context.internalAdapter.deleteAccounts(t.user.id),(0,e0.Q)(e);let a=e.context.options.user.deleteUser?.afterDelete;if(a&&await a(t.user,e.request),e.query.callbackURL)throw e.redirect(e.query.callbackURL||"/");return e.json({success:!0,message:"User deleted"})}),iC=(0,s.g)("/change-email",{method:"POST",body:E.object({newEmail:E.email().meta({description:"The new email address to set must be a valid email address"}),callbackURL:E.string().meta({description:"The URL to redirect to after email verification"}).optional()}),use:[p.i],metadata:{openapi:{operationId:"changeEmail",responses:{200:{description:"Email change request processed successfully",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object",$ref:"#/components/schemas/User"},status:{type:"boolean",description:"Indicates if the request was successful"},message:{type:"string",enum:["Email updated","Verification email sent"],description:"Status message of the email change process",nullable:!0}},required:["status"]}}}}}}}},async e=>{if(!e.context.options.user?.changeEmail?.enabled)throw e.context.logger.error("Change email is disabled."),u.E.from("BAD_REQUEST",tf.f.CHANGE_EMAIL_DISABLED);let t=e.body.newEmail.toLowerCase();if(t===e.context.session.user.email)throw e.context.logger.warn("Email is the same"),u.E.fromStatus("BAD_REQUEST",{message:"Email is the same"});let r=!0!==e.context.session.user.emailVerified&&e.context.options.user.changeEmail.updateEmailWithoutVerification,i=e.context.options.emailVerification?.sendVerificationEmail,a=i&&e.context.session.user.emailVerified&&e.context.options.user.changeEmail.sendChangeEmailConfirmation;if(!r&&!a&&!i)throw e.context.logger.error("Verification email isn't enabled."),u.E.fromStatus("BAD_REQUEST",{message:"Verification email isn't enabled"});if(await e.context.internalAdapter.findUserByEmail(t))return await t4(e.context.secret,e.context.session.user.email,t,e.context.options.emailVerification?.expiresIn,{userId:e.context.session.user.id}),e.context.logger.info("Change email attempt for existing email"),e.json({status:!0});if(r){if(await e.context.internalAdapter.updateUser(e.context.session.user.id,{email:t}),await (0,e0.V)(e,{session:e.context.session.session,user:{...e.context.session.user,email:t}}),i){let r=await t4(e.context.secret,t,void 0,e.context.options.emailVerification?.expiresIn,{userId:e.context.session.user.id}),a=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${encodeURIComponent(e.body.callbackURL||"/")}`;await e.context.runInBackgroundOrAwait(i({user:{...e.context.session.user,email:t},url:a,token:r},e.request))}return e.json({status:!0})}if(a){let r=await t4(e.context.secret,e.context.session.user.email,t,e.context.options.emailVerification?.expiresIn,{requestType:"change-email-confirmation",userId:e.context.session.user.id}),i=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${encodeURIComponent(e.body.callbackURL||"/")}`;return await e.context.runInBackgroundOrAwait(a({user:e.context.session.user,newEmail:t,url:i,token:r},e.request)),e.json({status:!0})}if(!i)throw e.context.logger.error("Verification email isn't enabled."),u.E.fromStatus("BAD_REQUEST",{message:"Verification email isn't enabled"});let o=await t4(e.context.secret,e.context.session.user.email,t,e.context.options.emailVerification?.expiresIn,{requestType:"change-email-verification",userId:e.context.session.user.id}),n=`${e.context.baseURL}/verify-email?token=${o}&callbackURL=${encodeURIComponent(e.body.callbackURL||"/")}`;return await e.context.runInBackgroundOrAwait(i({user:{...e.context.session.user,email:t},url:n,token:o},e.request)),e.json({status:!0})});var iq=e.i(829302);async function ij(e,t){if(e.baseURL)return e;let r=function(e){if((0,eV.T)(e?.request))return e.request;if(!e?.headers)return;let t=e.headers instanceof Headers?e.headers:new Headers(e.headers);if(t.has("host")||t.has("x-forwarded-host"))return t}(t),i=e.options.baseURL,a=(0,eV._)(i)&&!!i.fallback;if(void 0===r&&!a)throw new u.E("INTERNAL_SERVER_ERROR",{message:"Dynamic baseURL could not be resolved for this direct auth.api call. Pass `headers: request.headers` (or `request`) to the call, or add `fallback` to your baseURL config."});try{return await td(e,r,tc(e.options))}catch(e){if(e instanceof u.p)throw new u.E("INTERNAL_SERVER_ERROR",{message:e.message});throw e}}e.i(418069);var i$=e.i(986097);function iB(e,t){let r=(0,te.f)(t),i=t.plugins?.reduce((e,t)=>({...e,...t.endpoints}),{})??{},a=t.plugins?.map(t=>t.middlewares?.map(i=>{let a=async a=>{let o=await e;return r(`middleware ${i.path} ${t.id}`,{[e9.A]:"middleware",[e9.F]:i.path,[e9.s]:`plugin:${t.id}`},()=>i.middleware({...a,context:{...o,...a.context}}))};return a.options=i.middleware.options,{path:i.path,middleware:a}})).filter(e=>void 0!==e).flat()||[];return{api:function(e,t){let r={};for(let[i,a]of Object.entries(e))r[i]=async e=>{let r=(0,iq.x)(a,i),o=async()=>{let i=await t,o=i.checkSchema?.();o&&await o;let n=(0,eV._)(i.options.baseURL)?await ij(i,e):i;return(0,iq.P)(a,{...e,context:n,operationId:r,asResponse:e?.asResponse??(0,eV.T)(e?.request)})};return await (0,f.B)()?o():(0,f.O)(new WeakMap,o)},r[i].path=a.path,r[i].options=a.options;return r}({signInSocial:(0,s.g)("/sign-in/social",{method:"POST",operationId:"socialSignIn",body:iT,metadata:{$Infer:{body:{},returned:{}},openapi:{description:"Sign in with a social provider",operationId:"socialSignIn",responses:{200:{description:"Success - Returns session details (idToken branch) or an authorize URL (redirect branch)",content:{"application/json":{schema:{type:"object",description:"Returns session details when idToken is provided, or an authorize URL otherwise",properties:{token:{type:"string"},user:{type:"object",$ref:"#/components/schemas/User"},url:{type:"string"},redirect:{type:"boolean"}},required:["redirect"]}}}}}}}},async e=>{let t=await tu(e.context.socialProviders,{value:e.body.provider});if(!t)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),u.E.from("NOT_FOUND",tf.f.PROVIDER_NOT_FOUND);if(e.body.idToken){if(!rT(t))throw e.context.logger.error("Provider does not support id token verification",{provider:e.body.provider}),u.E.from("NOT_FOUND",tf.f.ID_TOKEN_NOT_SUPPORTED);let{token:r,nonce:i}=e.body.idToken;if(!await rv(t,r,i,e))throw e.context.logger.warn("Invalid id token",{provider:e.body.provider}),u.E.from("UNAUTHORIZED",tf.f.INVALID_TOKEN);let a={idToken:r,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken,user:e.body.idToken.user},o=t.getUserInfoFromIdToken?await t.getUserInfoFromIdToken(r):await t.getUserInfo(a);if(!o||!o?.user)throw e.context.logger.error("Failed to get user info",{provider:e.body.provider}),u.E.from("UNAUTHORIZED",tf.f.FAILED_TO_GET_USER_INFO);if(!o.user.email)throw e.context.logger.error(tJ(e.body.provider,{source:"id_token"}),{provider:e.body.provider}),u.E.from("UNAUTHORIZED",tf.f.USER_EMAIL_NOT_FOUND);let n=await tz(t,a,o.data),s=o.data,l=await ra(e,{userInfo:{...o.user,email:o.user.email,id:n.accountId,name:o.user.name||"",image:o.user.image,emailVerified:o.user.emailVerified||!1},account:{...n,accessToken:e.body.idToken.accessToken,idToken:r},callbackURL:e.body.callbackURL,disableSignUp:t.disableImplicitSignUp&&!e.body.requestSignUp||t.options?.disableSignUp||t.disableSignUp,source:{method:"oauth",oauth:{providerId:t.id,profile:s}}});if(l.error){if(l.error===tQ)throw u.E.from("FORBIDDEN",tf.f.EMAIL_NOT_VERIFIED);throw u.E.from("UNAUTHORIZED",{message:l.error,code:"OAUTH_LINK_ERROR"})}return await (0,e0.V)(e,l.data),e.json({redirect:!1,token:l.data.session.token,url:void 0,user:(0,w.$)(e.context.options,l.data.user)})}let r=rf(t),{codeVerifier:i,state:a}=await rm(e,{additionalData:e.body.additionalData,idTokenNonce:r}),o=await t.createAuthorizationURL({state:a,codeVerifier:i,idTokenNonce:r,redirectURI:`${e.context.baseURL}${t1(t)}`,scopes:e.body.scopes,loginHint:e.body.loginHint,additionalParams:e.body.additionalParams});return e.body.disableRedirect||e.setHeader("Location",o.toString()),e.json({url:o.toString(),redirect:!e.body.disableRedirect})}),callbackOAuth:ig,getSession:(0,p.v)(),signOut:iR,signUpEmail:(0,s.g)("/sign-up/email",{method:"POST",operationId:"signUpWithEmailAndPassword",use:[tU],body:iS,cloneRequest:!0,metadata:{allowedMediaTypes:["application/x-www-form-urlencoded","application/json"],$Infer:{body:{},returned:{}},openapi:{operationId:"signUpWithEmailAndPassword",description:"Sign up a user using email and password",requestBody:{content:{"application/json":{schema:{type:"object",properties:{name:{type:"string",description:"The name of the user"},email:{type:"string",description:"The email of the user"},password:{type:"string",description:"The password of the user"},image:{type:"string",description:"The profile image URL of the user"},callbackURL:{type:"string",description:"The URL to use for email verification callback"},rememberMe:{type:"boolean",description:"If this is false, the session will not be remembered. Default is `true`."}},required:["name","email","password"]}}}},responses:{200:{description:"Successfully created user",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string",nullable:!0,description:"Authentication token for the session"},user:{type:"object",properties:{id:{type:"string",description:"The unique identifier of the user"},email:{type:"string",format:"email",description:"The email address of the user"},name:{type:"string",description:"The name of the user"},image:{type:"string",format:"uri",nullable:!0,description:"The profile image URL of the user"},emailVerified:{type:"boolean",description:"Whether the email has been verified"},createdAt:{type:"string",format:"date-time",description:"When the user was created"},updatedAt:{type:"string",format:"date-time",description:"When the user was last updated"}},required:["id","email","name","emailVerified","createdAt","updatedAt"]}},required:["user"]}}}},422:{description:"Unprocessable Entity. User already exists or failed to create user.",content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}}}}}}},async e=>(0,e7.n)(e.context.adapter,async()=>{let t;if(!e.context.options.emailAndPassword?.enabled||e.context.options.emailAndPassword?.disableSignUp)throw u.E.from("BAD_REQUEST",{message:"Email and password sign up is not enabled",code:"EMAIL_PASSWORD_SIGN_UP_DISABLED"});let r=e.body,{name:i,email:a,password:o,image:n,callbackURL:s,rememberMe:l,...c}=r;if(!E.email().safeParse(a).success)throw u.E.from("BAD_REQUEST",tf.f.INVALID_EMAIL);if(!o||"string"!=typeof o)throw u.E.from("BAD_REQUEST",tf.f.INVALID_PASSWORD);tm(e,o),th(e,o);let d=e.context.options.emailAndPassword.requireEmailVerification||!1===e.context.options.emailAndPassword.autoSignIn,p=!1===e.context.options.emailAndPassword.autoSignIn||d,f=(0,w.R)(e.context.options,c,"create"),m=a.toLowerCase(),h=()=>{let t,r=new Date,a=e.context.generateId({model:"user"})||(0,y.f)(),o={name:i,email:m,emailVerified:!1,image:n??null,createdAt:r,updatedAt:r},s=e.context.options.emailAndPassword?.customSyntheticUser;if(s){let r=Object.keys(e.context.options.user?.additionalFields??{}),i={};for(let e of r)e in f&&(i[e]=f[e]);let n=s({coreFields:o,additionalFields:i,id:a});t=(0,w.g)(e.context.options,n)}else t=(0,w.g)(e.context.options,{...o,...f,id:a});return e.json({token:null,user:(0,w.$)(e.context.options,t)})},g=await e.context.internalAdapter.findUserByEmail(m);if(g?.user){if(e.context.logger.info(`Sign-up attempt for existing email: ${a}`),d)return await e.context.password.hash(o),e.context.options.emailAndPassword?.onExistingUserSignUp&&await e.context.runInBackgroundOrAwait(e.context.options.emailAndPassword.onExistingUserSignUp({user:g.user},t3(e.request))),h();throw u.E.from("UNPROCESSABLE_ENTITY",tf.f.USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL)}let b=await e.context.password.hash(o);try{if(!(t=await e.context.internalAdapter.createUser({email:m,name:i,image:n,...f,emailVerified:!1},{method:"email-password"})))throw u.E.from("BAD_REQUEST",tf.f.FAILED_TO_CREATE_USER)}catch(t){if((0,tb.f)(t)){if(403===t.statusCode&&d)return h();throw t}throw(0,ta.o)()&&e.context.logger.error("Failed to create user",t),e.context.logger?.error("Failed to create user",t),u.E.from("UNPROCESSABLE_ENTITY",tf.f.FAILED_TO_CREATE_USER)}if(!t)throw u.E.from("UNPROCESSABLE_ENTITY",tf.f.FAILED_TO_CREATE_USER);if(await e.context.internalAdapter.linkAccount({userId:t.id,providerId:"credential",accountId:t.id,password:b}),e.context.options.emailVerification?.sendOnSignUp??e.context.options.emailAndPassword.requireEmailVerification){let i=await t4(e.context.secret,t.email,void 0,e.context.options.emailVerification?.expiresIn,{userId:t.id}),a=r.callbackURL?encodeURIComponent(r.callbackURL):encodeURIComponent("/"),o=`${e.context.baseURL}/verify-email?token=${i}&callbackURL=${a}`;e.context.options.emailVerification?.sendVerificationEmail&&await e.context.runInBackgroundOrAwait(e.context.options.emailVerification.sendVerificationEmail({user:t,url:o,token:i},t3(e.request)))}if(p)return e.json({token:null,user:(0,w.$)(e.context.options,t)});let A=await e.context.internalAdapter.createSession(t.id,!1===l,void 0,void 0,{deferSecondaryStorageWrites:!0});if(!A)throw u.E.from("BAD_REQUEST",tf.f.FAILED_TO_CREATE_SESSION);return await (0,e0.V)(e,{session:A,user:t},!1===l),e.json({token:A.token,user:(0,w.$)(e.context.options,t)})})),signInEmail:(0,s.g)("/sign-in/email",{method:"POST",operationId:"signInEmail",use:[tU],cloneRequest:!0,body:E.object({email:E.string().meta({description:"Email of the user"}),password:E.string().meta({description:"Password of the user"}),callbackURL:E.string().meta({description:"Callback URL to use as a redirect for email verification"}).optional(),rememberMe:E.boolean().meta({description:"If this is false, the session will not be remembered. Default is `true`."}).default(!0).optional()}),metadata:{allowedMediaTypes:["application/x-www-form-urlencoded","application/json"],$Infer:{body:{},returned:{}},openapi:{operationId:"signInEmail",description:"Sign in with email and password",responses:{200:{description:"Success - Returns either session details or redirect URL",content:{"application/json":{schema:{type:"object",description:"Session response when idToken is provided",properties:{redirect:{type:"boolean",enum:[!1]},token:{type:"string",description:"Session token"},url:{type:"string",nullable:!0},user:{type:"object",$ref:"#/components/schemas/User"}},required:["redirect","token","user"]}}}}}}}},async e=>{if(!e.context.options?.emailAndPassword?.enabled)throw e.context.logger.error("Email and password is not enabled. Make sure to enable it in the options on you `auth.ts` file. Check `https://better-auth.com/docs/authentication/email-password` for more!"),u.E.from("BAD_REQUEST",{code:"EMAIL_PASSWORD_DISABLED",message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!E.email().safeParse(t).success)throw u.E.from("BAD_REQUEST",tf.f.INVALID_EMAIL);th(e,r);let i=await e.context.internalAdapter.findUserByEmail(t.toLowerCase(),{includeAccounts:!0}),a=i?.accounts.find(e=>"credential"===e.providerId&&e.accountId===i.user.id);if(!i||!a)throw await e.context.password.hash(r),e.context.logger.warn("User not found"),u.E.from("UNAUTHORIZED",tf.f.INVALID_EMAIL_OR_PASSWORD);let o=i.user,n=a.password;if(!n)throw await e.context.password.hash(r),e.context.logger.warn("Password not found"),u.E.from("UNAUTHORIZED",tf.f.INVALID_EMAIL_OR_PASSWORD);if(!await e.context.password.verify({hash:n,password:r}))throw e.context.logger.warn("Invalid password"),u.E.from("UNAUTHORIZED",tf.f.INVALID_EMAIL_OR_PASSWORD);if(e.context.options?.emailAndPassword?.requireEmailVerification&&!o.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw u.E.from("FORBIDDEN",tf.f.EMAIL_NOT_VERIFIED);if(e.context.options?.emailVerification?.sendOnSignIn){let t=await t4(e.context.secret,o.email,void 0,e.context.options.emailVerification?.expiresIn,{userId:o.id}),r=e.body.callbackURL?encodeURIComponent(e.body.callbackURL):encodeURIComponent("/"),i=`${e.context.baseURL}/verify-email?token=${t}&callbackURL=${r}`;await e.context.runInBackgroundOrAwait(e.context.options.emailVerification.sendVerificationEmail({user:o,url:i,token:t},t3(e.request)))}throw u.E.from("FORBIDDEN",tf.f.EMAIL_NOT_VERIFIED)}let s=await e.context.internalAdapter.createSession(o.id,!1===e.body.rememberMe);if(!s)throw e.context.logger.error("Failed to create session"),u.E.from("UNAUTHORIZED",tf.f.FAILED_TO_CREATE_SESSION);return await (0,e0.V)(e,{session:s,user:o},!1===e.body.rememberMe),e.body.callbackURL&&e.setHeader("Location",e.body.callbackURL),e.json({redirect:!!e.body.callbackURL,token:s.token,url:e.body.callbackURL,user:(0,w.$)(e.context.options,o)})}),resetPassword:i_,verifyPassword:ik,verifyEmail:t9,sendVerificationEmail:t8,changeEmail:iC,changePassword:iD,setPassword:iN,updateSession:(0,s.g)("/update-session",{method:"POST",operationId:"updateSession",body:ix,use:[p.Z],metadata:{$Infer:{body:{}},openapi:{operationId:"updateSession",description:"Update the current session",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"object",$ref:"#/components/schemas/Session"}}}}}}}}}},async e=>{let t=e.body;if("object"!=typeof t||Array.isArray(t))throw u.E.from("BAD_REQUEST",tf.f.BODY_MUST_BE_AN_OBJECT);let r=e.context.session,i=(0,w.z)(e.context.options,t,"update");if(0===Object.keys(i).length)throw u.E.fromStatus("BAD_REQUEST",{message:"No fields to update"});let a=await e.context.internalAdapter.updateSession(r.session.token,{...i,updatedAt:new Date});if(!a&&(0,p.f)(e))throw(0,e0.Q)(e),u.E.from("UNAUTHORIZED",tf.f.FAILED_TO_GET_SESSION);let o=a??{...r.session,...i,updatedAt:new Date};return await (0,e0.V)(e,{session:o,user:r.user}),e.json({session:(0,w.Q)(e.context.options,o)})}),updateUser:(0,s.g)("/update-user",{method:"POST",operationId:"updateUser",body:iO,use:[p.Z],metadata:{$Infer:{body:{}},openapi:{operationId:"updateUser",description:"Update the current user",requestBody:{content:{"application/json":{schema:{type:"object",properties:{name:{type:"string",description:"The name of the user"},image:{type:"string",description:"The image of the user",nullable:!0}}}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object",$ref:"#/components/schemas/User"}}}}}}}}}},async e=>{let t=e.body;if("object"!=typeof t||Array.isArray(t))throw u.E.from("BAD_REQUEST",tf.f.BODY_MUST_BE_AN_OBJECT);if(t.email)throw u.E.from("BAD_REQUEST",tf.f.EMAIL_CAN_NOT_BE_UPDATED);let{name:r,image:i,...a}=t,o=e.context.session,n=(0,w.R)(e.context.options,a,"update");if(void 0===i&&void 0===r&&0===Object.keys(n).length)throw u.E.fromStatus("BAD_REQUEST",{message:"No fields to update"});let s=await e.context.internalAdapter.updateUser(o.user.id,{name:r,image:i,...n})??{...o.user,...void 0!==r&&{name:r},...void 0!==i&&{image:i},...n};return await (0,e0.V)(e,{session:o.session,user:s}),e.json({status:!0})}),deleteUser:iL,requestPasswordReset:iA,requestPasswordResetCallback:iI,listSessions:(0,p.T)(),revokeSession:p.G,revokeSessions:p.$,revokeOtherSessions:p.Y,linkSocialAccount:it,listUserAccounts:ie,deleteUserCallback:iP,unlinkAccount:ir,refreshToken:id,getAccessToken:ic,accountInfo:iu,...i,ok:ib,error:iy},e),middlewares:a}}var iV=e.i(114268),iM=e.i(902157),iF=e.i(912714),iK=e.i(660526),iz=e.i(750227),iH=e.i(339127);async function iW(e,t){return{database:t?.database,adapter:t?.adapter,emailVerification:{sendVerificationEmail:!!e.emailVerification?.sendVerificationEmail,sendOnSignUp:!!e.emailVerification?.sendOnSignUp,sendOnSignIn:!!e.emailVerification?.sendOnSignIn,autoSignInAfterVerification:!!e.emailVerification?.autoSignInAfterVerification,expiresIn:e.emailVerification?.expiresIn,beforeEmailVerification:!!e.emailVerification?.beforeEmailVerification,afterEmailVerification:!!e.emailVerification?.afterEmailVerification},emailAndPassword:{enabled:!!e.emailAndPassword?.enabled,disableSignUp:!!e.emailAndPassword?.disableSignUp,requireEmailVerification:!!e.emailAndPassword?.requireEmailVerification,maxPasswordLength:e.emailAndPassword?.maxPasswordLength,minPasswordLength:e.emailAndPassword?.minPasswordLength,sendResetPassword:!!e.emailAndPassword?.sendResetPassword,resetPasswordTokenExpiresIn:e.emailAndPassword?.resetPasswordTokenExpiresIn,onPasswordReset:!!e.emailAndPassword?.onPasswordReset,password:{hash:!!e.emailAndPassword?.password?.hash,verify:!!e.emailAndPassword?.password?.verify},autoSignIn:!!e.emailAndPassword?.autoSignIn,revokeSessionsOnPasswordReset:!!e.emailAndPassword?.revokeSessionsOnPasswordReset},socialProviders:await Promise.all(Object.keys(e.socialProviders||{}).map(async t=>{let r=e.socialProviders?.[t];if(!r)return{};let i="function"==typeof r?await r():r;return{id:t,mapProfileToUser:!!i.mapProfileToUser,disableDefaultScope:!!i.disableDefaultScope,disableIdTokenSignIn:!!i.disableIdTokenSignIn,disableImplicitSignUp:i.disableImplicitSignUp,disableSignUp:i.disableSignUp,getUserInfo:!!i.getUserInfo,overrideUserInfoOnSignIn:!!i.overrideUserInfoOnSignIn,prompt:i.prompt,verifyIdToken:!!i.verifyIdToken,scope:i.scope,refreshAccessToken:!!i.refreshAccessToken}})),plugins:e.plugins?.map(e=>e.id.toString()),user:{modelName:e.user?.modelName,fields:e.user?.fields,additionalFields:e.user?.additionalFields,changeEmail:{enabled:e.user?.changeEmail?.enabled,sendChangeEmailConfirmation:!!e.user?.changeEmail?.sendChangeEmailConfirmation}},verification:{modelName:e.verification?.modelName,disableCleanup:e.verification?.disableCleanup,fields:e.verification?.fields},session:{modelName:e.session?.modelName,additionalFields:e.session?.additionalFields,cookieCache:{enabled:e.session?.cookieCache?.enabled,maxAge:e.session?.cookieCache?.maxAge,strategy:e.session?.cookieCache?.strategy},disableSessionRefresh:e.session?.disableSessionRefresh,expiresIn:e.session?.expiresIn,fields:e.session?.fields,freshAge:e.session?.freshAge,preserveSessionInDatabase:e.session?.preserveSessionInDatabase,storeSessionInDatabase:e.session?.storeSessionInDatabase,updateAge:e.session?.updateAge},account:{modelName:e.account?.modelName,fields:e.account?.fields,encryptOAuthTokens:e.account?.encryptOAuthTokens,updateAccountOnSignIn:e.account?.updateAccountOnSignIn,accountLinking:{enabled:e.account?.accountLinking?.enabled,trustedProviders:e.account?.accountLinking?.trustedProviders,updateUserInfoOnLink:e.account?.accountLinking?.updateUserInfoOnLink,allowUnlinkingAll:e.account?.accountLinking?.allowUnlinkingAll}},hooks:{after:!!e.hooks?.after,before:!!e.hooks?.before},secondaryStorage:!!e.secondaryStorage,advanced:{cookiePrefix:!!e.advanced?.cookiePrefix,cookies:!!e.advanced?.cookies,crossSubDomainCookies:{domain:!!e.advanced?.crossSubDomainCookies?.domain,enabled:e.advanced?.crossSubDomainCookies?.enabled,additionalCookies:e.advanced?.crossSubDomainCookies?.additionalCookies},database:{generateId:e.advanced?.database?.generateId,defaultFindManyLimit:e.advanced?.database?.defaultFindManyLimit},useSecureCookies:e.advanced?.useSecureCookies,ipAddress:{disableIpTracking:e.advanced?.ipAddress?.disableIpTracking,ipAddressHeaders:e.advanced?.ipAddress?.ipAddressHeaders},disableCSRFCheck:e.advanced?.disableCSRFCheck,cookieAttributes:{expires:e.advanced?.defaultCookieAttributes?.expires,secure:e.advanced?.defaultCookieAttributes?.secure,sameSite:e.advanced?.defaultCookieAttributes?.sameSite,domain:!!e.advanced?.defaultCookieAttributes?.domain,path:e.advanced?.defaultCookieAttributes?.path,httpOnly:e.advanced?.defaultCookieAttributes?.httpOnly}},trustedOrigins:e.trustedOrigins?.length,rateLimit:{storage:e.rateLimit?.storage,modelName:e.rateLimit?.modelName,window:e.rateLimit?.window,customStorage:!!e.rateLimit?.customStorage,enabled:e.rateLimit?.enabled,max:e.rateLimit?.max},onAPIError:{errorURL:e.onAPIError?.errorURL,onError:!!e.onAPIError?.onError,throw:e.onAPIError?.throw},logger:{disabled:e.logger?.disabled,level:e.logger?.level,log:!!e.logger?.log},databaseHooks:{user:{create:{after:!!e.databaseHooks?.user?.create?.after,before:!!e.databaseHooks?.user?.create?.before},update:{after:!!e.databaseHooks?.user?.update?.after,before:!!e.databaseHooks?.user?.update?.before}},session:{create:{after:!!e.databaseHooks?.session?.create?.after,before:!!e.databaseHooks?.session?.create?.before},update:{after:!!e.databaseHooks?.session?.update?.after,before:!!e.databaseHooks?.session?.update?.before}},account:{create:{after:!!e.databaseHooks?.account?.create?.after,before:!!e.databaseHooks?.account?.create?.before},update:{after:!!e.databaseHooks?.account?.update?.after,before:!!e.databaseHooks?.account?.update?.before}},verification:{create:{after:!!e.databaseHooks?.verification?.create?.after,before:!!e.databaseHooks?.verification?.create?.before},update:{after:!!e.databaseHooks?.verification?.update?.after,before:!!e.databaseHooks?.verification?.update?.before}}}}}async function iY(e){let t=await (0,d.f)("SHA-256").digest(e);return c.t.encode(t)}async function iQ(){if(t)return t;try{let e=process.cwd();if(!e)return;let r=await iF.default.readFile(iz.default.join(e,"package.json"),"utf-8");return t=JSON.parse(r)}catch{}}async function iG(e){if(t)return t.dependencies?.[e]||t.devDependencies?.[e]||t.peerDependencies?.[e];try{let t=process.cwd();if(!t)throw Error("no-cwd");let r=iz.default.join(t,"node_modules",e,"package.json"),i=await iF.default.readFile(r,"utf-8");return JSON.parse(i).version||await iJ(e)||void 0}catch{}return iJ(e)}async function iJ(e){let t=await iQ();if(t)return({...t.dependencies,...t.devDependencies,...t.peerDependencies})[e]}async function iZ(){return(await iQ())?.name}async function iX(){try{let e,t,r=iK.default.cpus();return{deploymentVendor:(e=process.env,(t=(...t)=>t.some(t=>!!e[t]))("CF_PAGES","CF_PAGES_URL","CF_ACCOUNT_ID")||"u">typeof navigator&&"Cloudflare-Workers"===navigator.userAgent?"cloudflare":t("VERCEL","VERCEL_URL","VERCEL_ENV")?"vercel":t("NETLIFY","NETLIFY_URL")?"netlify":t("RENDER","RENDER_URL","RENDER_INTERNAL_HOSTNAME","RENDER_SERVICE_ID")?"render":t("AWS_LAMBDA_FUNCTION_NAME","AWS_EXECUTION_ENV","LAMBDA_TASK_ROOT")?"aws":t("GOOGLE_CLOUD_FUNCTION_NAME","GOOGLE_CLOUD_PROJECT","GCP_PROJECT","K_SERVICE")?"gcp":t("AZURE_FUNCTION_NAME","FUNCTIONS_WORKER_RUNTIME","WEBSITE_INSTANCE_ID","WEBSITE_SITE_NAME")?"azure":t("DENO_DEPLOYMENT_ID","DENO_REGION")?"deno-deploy":t("FLY_APP_NAME","FLY_REGION","FLY_ALLOC_ID")?"fly-io":t("RAILWAY_STATIC_URL","RAILWAY_ENVIRONMENT_NAME")?"railway":t("DYNO","HEROKU_APP_NAME")?"heroku":t("DO_DEPLOYMENT_ID","DO_APP_NAME","DIGITALOCEAN")?"digitalocean":t("KOYEB","KOYEB_DEPLOYMENT_ID","KOYEB_APP_NAME")?"koyeb":null),systemPlatform:iK.default.platform(),systemRelease:iK.default.release(),systemArchitecture:iK.default.arch(),cpuCount:r.length,cpuModel:r.length?r[0].model:null,cpuSpeed:r.length?r[0].speed:null,memory:iK.default.totalmem(),isWSL:await i5(),isDocker:await i2(),isTTY:process.stdout?process.stdout.isTTY:null}}catch{return{systemPlatform:null,systemRelease:null,systemArchitecture:null,cpuCount:null,cpuModel:null,cpuSpeed:null,memory:null,isWSL:null,isDocker:null,isTTY:null}}}async function i0(){try{return iM.default.statSync("/.dockerenv"),!0}catch{return!1}}async function i1(){try{return iM.default.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}async function i2(){return void 0===r&&(r=await i0()||await i1()),r}let i3=async()=>{try{return iM.default.statSync("/run/.containerenv"),!0}catch{return!1}};async function i6(){return void 0===i&&(i=await i3()||await i2()),i}async function i5(){try{if(iK.default.release().toLowerCase().includes("microsoft")){if(await i6())return!1;return!0}return!!iM.default.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft")&&!await i6()}catch{return!1}}let i4=null;async function i7(e){if(i4)return i4;let t=await iZ();return i4=t?await iY(e?e+t:t):e?await iY(e):(0,iH.f)("a-z","A-Z","0-9")(32)}async function i8(){for(let[e,t]of Object.entries({pg:"postgresql",mysql:"mysql",mariadb:"mariadb",sqlite3:"sqlite","better-sqlite3":"sqlite","@prisma/client":"prisma",mongoose:"mongodb",mongodb:"mongodb","drizzle-orm":"drizzle"})){let r=await iG(e);if(r)return{name:t,version:r}}}async function i9(){for(let[e,t]of Object.entries({next:"next",nuxt:"nuxt","react-router":"react-router",astro:"astro","@sveltejs/kit":"sveltekit","solid-start":"solid-start","tanstack-start":"tanstack-start",hono:"hono",express:"express",elysia:"elysia",expo:"expo"})){let r=await iG(e);if(r)return{name:t,version:r}}}let ae=async function(){};async function at(e,t){let r,i=e.telemetry?.debug||(0,ta.O)("BETTER_AUTH_TELEMETRY_DEBUG",!1),a=ta.w.BETTER_AUTH_TELEMETRY_ENDPOINT;if(!a&&!t?.customTrack)return{publish:ae};let o=async e=>{t?.customTrack?await t.customTrack(e).catch(eA.y.error):a&&(i?eA.y.info("telemetry event",JSON.stringify(e,null,2)):await (0,rK.f)(a,{method:"POST",body:e}).catch(eA.y.error))},n=async()=>{let r=e.telemetry?.enabled!==void 0&&e.telemetry.enabled;return((0,ta.O)("BETTER_AUTH_TELEMETRY",!1)||r)&&(t?.skipTestCheck||!(0,ta.s)())},s=await n();return s&&(r=await i7("string"==typeof e.baseURL?e.baseURL:void 0),o({type:"init",payload:{config:await iW(e,t),runtime:"u">typeof Deno?{name:"deno",version:Deno?.version?.deno??null}:"u">typeof Bun?{name:"bun",version:Bun?.version??null}:"u">typeof process&&process?.versions?.node?{name:"node",version:process.versions.node??null}:{name:"edge",version:null},database:await i8(),framework:await i9(),environment:"production"===(0,ta.B)("NODE_ENV")?"production":"false"!==ta.$.CI&&("BUILD_ID"in ta.$||"BUILD_NUMBER"in ta.$||"CI"in ta.$||"CI_APP_ID"in ta.$||"CI_BUILD_ID"in ta.$||"CI_BUILD_NUMBER"in ta.$||"CI_NAME"in ta.$||"CONTINUOUS_INTEGRATION"in ta.$||"RUN_ID"in ta.$)?"ci":(0,ta.s)()?"test":"development",systemInfo:await iX(),packageManager:function(){let e=ta.$.npm_config_user_agent;if(!e)return;let t=e.split(" ")[0],r=t.lastIndexOf("/"),i=t.substring(0,r);return{name:"npminstall"===i?"cnpm":i,version:t.substring(r+1)}}()},anonymousId:r})),{publish:async t=>{s&&(r||(r=await i7("string"==typeof e.baseURL?e.baseURL:void 0)),await o({type:t.type,payload:t.payload,anonymousId:r}))}}}async function ar(e,t,r){let i,a,o,n,s=(0,eJ.z)(t);s||(t=(0,to.U)(t,{session:{cookieCache:{enabled:!0,strategy:"jwe",refreshCache:!0,maxAge:t.session?.expiresIn||604800}}})),t.database||(t=(0,to.U)(t,{account:{storeAccountCookie:!0}}));let c=t.plugins||[],d=(w=t,w.advanced?.crossSubDomainCookies?.enabled,[]),p=(0,eA.J)(t.logger),f=(0,eV._)(t.baseURL);if((0,eV._)(t.baseURL)){let{allowedHosts:e}=t.baseURL;if(!e||0===e.length)throw new u.p('baseURL.allowedHosts cannot be empty. Provide at least one allowed host pattern (e.g., ["myapp.com", "*.vercel.app"]).')}let m=f?void 0:(0,eV.X)("string"==typeof t.baseURL?t.baseURL:void 0,t.basePath);m||f||p.warn("[better-auth] Base URL is not set. Set the baseURL option or BETTER_AUTH_URL env, or use a dynamic baseURL with allowedHosts for multi-host setups. Without it the origin is derived from the incoming request, and callbacks and redirects may not work correctly."),"memory"===e.id&&t.advanced?.database?.generateId===!1&&p.error(`[better-auth] Misconfiguration detected.
|
|
441
441
|
You are using the memory DB with generateId: false.
|
|
442
442
|
This will cause no id to be generated for any model.
|
|
443
443
|
Most of the features of Better Auth will not work correctly.`);let h=t.secrets??((b=ta.$.BETTER_AUTH_SECRETS)?b.split(",").map((e,t)=>{let r=(e=e.trim()).indexOf(":");if(-1===r)throw new u.p(`Invalid BETTER_AUTH_SECRETS entry at position ${t+1}. Expected format: "<version>:<secret>"`);let i=parseInt(e.slice(0,r),10);if(!Number.isInteger(i)||i<0)throw new u.p(`Invalid version in BETTER_AUTH_SECRETS entry at position ${t+1}. Version must be a non-negative integer.`);let a=e.slice(r+1).trim();if(!a)throw new u.p(`Empty secret value for version ${i} in BETTER_AUTH_SECRETS.`);return{version:i,value:a}}):null),g=t.secret||ta.$.BETTER_AUTH_SECRET||ta.$.AUTH_SECRET||"";if(h)!function(e,t){var r;let i;if(0===e.length)throw new u.p("`secrets` array must contain at least one entry.");let a=new Set;for(let t of e){let e=parseInt(String(t.version),10);if(!Number.isInteger(e)||e<0||String(e)!==String(t.version).trim())throw new u.p(`Invalid version ${t.version} in \`secrets\`. Version must be a non-negative integer.`);if(!t.value)throw new u.p(`Empty secret value for version ${e} in \`secrets\`.`);if(a.has(e))throw new u.p(`Duplicate version ${e} in \`secrets\`. Each version must be unique.`);a.add(e)}let o=e[0];o.value.length<32&&t.warn(`[better-auth] Warning: the current secret (version ${o.version}) should be at least 32 characters long for adequate security.`),120>(0===(i=new Set(r=o.value).size)?0:Math.log2(Math.pow(i,r.length)))&&t.warn("[better-auth] Warning: the current secret appears low-entropy. Use a randomly generated secret for production.")}(h,p),i=h[0].value,a=function(e,t){let r=new Map;for(let t of e)r.set(parseInt(String(t.version),10),t.value);return{keys:r,currentVersion:parseInt(String(e[0].version),10),legacySecret:t&&"better-auth-secret-12345678901234567890"!==t?t:void 0}}(h,g);else{var w,b,E=i=g||"better-auth-secret-12345678901234567890";let e="better-auth-secret-12345678901234567890"===E;if(!(0,ta.s)()){let t;if(e&&ta.C)throw new u.p("You are using the default secret. Please set `BETTER_AUTH_SECRET` in your environment variables or pass `secret` in your auth config.");if(!E)throw new u.p("BETTER_AUTH_SECRET is missing. Set it in your environment or pass `secret` to betterAuth({ secret }).");E.length<32&&p.warn("[better-auth] Warning: your BETTER_AUTH_SECRET should be at least 32 characters long for adequate security. Generate one with `npx auth secret` or `openssl rand -base64 32`."),120>(0===(t=new Set(E).size)?0:Math.log2(Math.pow(t,E.length)))&&p.warn("[better-auth] Warning: your BETTER_AUTH_SECRET appears low-entropy. Use a randomly generated secret for production.")}a=i}!function(e,t){let r=new Map;e.plugins?.forEach(e=>{if(e.endpoints){for(let[t,i]of Object.entries(e.endpoints))if(i&&"path"in i&&"string"==typeof i.path){let a=i.path,o=[];i.options&&"method"in i.options&&(Array.isArray(i.options.method)?o=i.options.method:"string"==typeof i.options.method&&(o=[i.options.method])),0===o.length&&(o=["*"]),r.has(a)||r.set(a,[]),r.get(a).push({pluginId:e.id,endpointKey:t,methods:o})}}});let i=[];for(let[e,t]of r.entries())if(t.length>1){let r=new Map,a=!1;for(let e of t)for(let i of e.methods)r.has(i)||r.set(i,[]),r.get(i).push(e.pluginId),r.get(i).length>1&&(a=!0),"*"===i&&t.length>1?a=!0:"*"!==i&&r.has("*")&&(a=!0);if(a){let a=[...new Set(t.map(e=>e.pluginId))],o=[];for(let[e,i]of r.entries())(i.length>1||"*"===e&&t.length>1||"*"!==e&&r.has("*"))&&o.push(e);i.push({path:e,plugins:a,conflictingMethods:o})}}if(i.length>0){let e=i.map(e=>` - "${e.path}" [${e.conflictingMethods.join(", ")}] used by plugins: ${e.plugins.join(", ")}`).join("\n");t.error(`Endpoint path conflicts detected! Multiple plugins are trying to use the same endpoint paths with conflicting HTTP methods:
|
|
@@ -447,10 +447,10 @@ To resolve this, you can:
|
|
|
447
447
|
1. Use only one of the conflicting plugins
|
|
448
448
|
2. Configure the plugins to use different paths (if supported)
|
|
449
449
|
3. Ensure plugins use different HTTP methods for the same path
|
|
450
|
-
`)}}(t={...t,secret:i,baseURL:f?t.baseURL:m?new URL(m).origin:"",basePath:t.basePath||"/api/auth",plugins:c.concat(d)},p);let A=t.advanced?.ipAddress?.trustedProxies;if(A&&A.length>0){let e=(0,l.p)(A);e.length>0&&p.warn(`Ignoring invalid \`advanced.ipAddress.trustedProxies\` entries: ${e.join(", ")}. Each entry must be an IP address or CIDR range.`)}let I=(0,e0.e)(t),_=(0,eE.R)(t),k=(await Promise.all(Object.entries(t.socialProviders||{}).map(async([e,t])=>{let r="function"==typeof t?await t():t;if(null==r||!1===r.enabled)return null;r.clientId||p.warn(`Social provider ${e} is missing clientId or clientSecret`);let i=r4[e](r);return i.disableImplicitSignUp=r.disableImplicitSignUp,i}))).filter(e=>null!==e),T=({model:e,size:r})=>{if("function"==typeof t.advanced?.generateId)return t.advanced.generateId({model:e,size:r});let i=t?.advanced?.database?.generateId;return"function"==typeof i?i({model:e,size:r}):"uuid"===i?crypto.randomUUID():"serial"!==i&&!1!==i&&(0,y.f)(r)},{publish:v}=await at(t,{adapter:e.id,database:"function"==typeof t.database?"adapter":r(t.database)}),U=new Set(t.plugins.map(e=>e.id)),R=await tl(t),x=await tp(t),S={appName:t.appName||"Better Auth",baseURL:m||"",version:(0,iV.I)(),socialProviders:k,options:t,oauthConfig:{storeStateStrategy:t.account?.storeStateStrategy||(s?"database":"cookie"),skipStateCookieCheck:!!t.account?.skipStateCookieCheck},tables:_,trustedOrigins:R,trustedProviders:x,isTrustedOrigin(e,t){return this.trustedOrigins.some(r=>eG(e,r,t))},sessionConfig:{updateAge:t.session?.updateAge!==void 0?t.session.updateAge:86400,expiresIn:t.session?.expiresIn||604800,freshAge:t.session?.freshAge===void 0?86400:t.session.freshAge,cookieRefreshCache:(o=t.session?.cookieCache?.refreshCache,n=t.session?.cookieCache?.maxAge||300,s&&o?(p.warn("[better-auth] `session.cookieCache.refreshCache` is enabled while `database` or `secondaryStorage` is configured. `refreshCache` is meant for stateless (DB-less) setups. Disabling `refreshCache` — remove it from your config to silence this warning."),!1):!1!==o&&void 0!==o&&(!0===o?{enabled:!0,updateAge:Math.floor(.2*n)}:{enabled:!0,updateAge:void 0!==o.updateAge?o.updateAge:Math.floor(.2*n)}))},secret:i,secretConfig:a,rateLimit:{...t.rateLimit,enabled:t.rateLimit?.enabled??ta.C,window:t.rateLimit?.window||10,max:t.rateLimit?.max||100,storage:t.rateLimit?.storage||(t.secondaryStorage?"secondary-storage":"memory")},authCookies:I,logger:p,generateId:T,session:null,secondaryStorage:t.secondaryStorage,password:{hash:t.emailAndPassword?.password?.hash||eX.Z,verify:t.emailAndPassword?.password?.verify||eX.B,config:{minPasswordLength:t.emailAndPassword?.minPasswordLength||8,maxPasswordLength:t.emailAndPassword?.maxPasswordLength||128},checkPassword:ty},setNewSession(e){this.newSession=e},newSession:null,adapter:e,internalAdapter:ti(e,{options:t,logger:p,hooks:t.databaseHooks?[{source:"user",hooks:t.databaseHooks}]:[],generateId:T}),createAuthCookie:(0,e0.g)(t),async runMigrations(){throw new u.p("runMigrations will be set by the specific init implementation")},publishTelemetry:v,skipCSRFCheck:!!t.advanced?.disableCSRFCheck,skipOriginCheck:t.advanced?.disableOriginCheck!==void 0?t.advanced.disableOriginCheck:!!(0,ta.s)(),runInBackground:t.advanced?.backgroundTasks?.handler??(e=>{e.catch(()=>{})}),async runInBackgroundOrAwait(e){try{t.advanced?.backgroundTasks?.handler?e instanceof Promise&&t.advanced.backgroundTasks.handler(e.catch(e=>{p.error("Failed to run background task:",e)})):await e}catch(e){p.error("Failed to run background task:",e)}},getPlugin:e=>t.plugins.find(t=>t.id===e)??null,hasPlugin:e=>U.has(e)},O=ts(S);return(0,eZ.f)(O)&&await O,S.checkSchema=(0,eg.f)(S.adapter),S.explicitSchemaCheck=(0,eg.j)(S.adapter),S}let ai=async e=>{let t=await e_(e),r=await ar(t,e,e=>(0,eT.getKyselyDatabaseType)(e)||"unknown");return r.runMigrations=async function(){if(!e.database||"updateMany"in e.database)throw new u.p("Database is not provided or it's an adapter. Migrations are only supported with a database instance.");let{runMigrations:t}=await eB(e);await t()},r};e.s(["f",0,e=>((e,t)=>{let r=t(e).then(e=>{let t=e.options.advanced?.database?.validateSchema;e.checkSchema||!1===t||e.logger[!0===t?"warn":"debug"](`Schema validation is not available for adapter "${e.adapter.id}". Skipping schema validation. Database operations will proceed normally.`);let r=e.checkSchema?.();return r&&r.catch(t=>{e.logger.error(t instanceof ew._?t.message:"Could not validate the database schema. Check your database connection.")}),e}),{api:i}=iB(r,e),a=e.plugins?.reduce((e,t)=>t.$ERROR_CODES?{...e,...t.$ERROR_CODES}:e,{}),o=async t=>{let i,a=await r,o=a.options.basePath||"/api/auth";if((0,eV._)(e.baseURL))i=await td(a,t,tc(a.options));else{i=Object.create(Object.getPrototypeOf(a),Object.getOwnPropertyDescriptors(a));let e=a.options;if(!a.options.baseURL){let r=(0,eV.X)(void 0,o,t,void 0,a.options.advanced?.trustedProxyHeaders);if(!r)throw new u.p("Could not get base URL from request. Please provide a valid base URL.");i.baseURL=r,i.options={...a.options,baseURL:(0,eV.H)(r)||void 0},e=i.options}i.trustedOrigins=await tl(e,t),i.trustedProviders=await tp(e,t)}let{handler:n}=((e,t)=>{let r=(0,te.f)(t),{api:i,middlewares:a}=iB(e,t),o=new URL(e.baseURL).pathname;return(0,i$.f)(i,{routerContext:e,openapi:{disabled:!0},basePath:o,routerMiddleware:[{path:"/**",middleware:tk},...a],allowedMediaTypes:["application/json"],skipTrailingSlashes:t.advanced?.skipTrailingSlashes??!1,async onRequest(t){let i=e.options.disabledPaths||[],a=(0,tE.s)(t.url,o);if(i.includes(a))return new Response("Not Found",{status:404});let n=e.checkSchema?.();n&&await n;let s=t,l=await tN(s,e);if(l)return l;for(let t of e.options.plugins||[])if(t.onRequest){let i=await r(`onRequest ${t.id}`,{[e9.A]:"onRequest",[e9.s]:`plugin:${t.id}`},()=>t.onRequest(s,e));if(i&&"response"in i)return i.response;i&&"request"in i&&(s=i.request)}return s},async onResponse(t,i){for(let i of e.options.plugins||[])if(i.onResponse){let a=await r(`onResponse ${i.id}`,{[e9.A]:"onResponse",[e9.s]:`plugin:${i.id}`,[e9.h]:t.status},()=>i.onResponse(t,e));if(a)return a.response}return t},async onError(r){if((0,tb.f)(r)&&"FOUND"===r.status)return;if(t.onAPIError?.throw)throw r;if(t.onAPIError?.onError){try{await t.onAPIError.onError(r,e)}catch(t){e.logger.error("onAPIError.onError threw",t)}return}let i=t.logger?.level,a="error"===i||"warn"===i||"debug"===i?eA.y:void 0;if(t.logger?.disabled!==!0){if(r&&"object"==typeof r&&"message"in r&&"string"==typeof r.message&&(r.message.includes("no column")||r.message.includes("column")||r.message.includes("relation")||r.message.includes("table")||r.message.includes("does not exist")))return void e.logger?.error(r.message);(0,tb.f)(r)?("INTERNAL_SERVER_ERROR"===r.status&&e.logger.error(r.status,r),a?.error(r.message)):e.logger?.error(r&&"object"==typeof r&&"name"in r?r.name:"",r)}}})})(i,e);return(0,e7.Q)(i.adapter,()=>n(t))};return{handler:o,fetch:o,api:i,options:e,$context:r,$ERROR_CODES:{...a,...tf.f}}})(e,ai)],204721)},413417,e=>{"use strict";var t=e.i(786198);e.i(418069);var r=e.i(455659),i=e.i(704199),a=e.i(728895);let o=new Set(["invalid_dpop_proof"]),n=/^[\x21\x23-\x5b\x5d-\x7e]+$/,s=/^[\x20-\x21\x23-\x5b\x5d-\x7e]+$/;function l(e){if(/[\x00-\x1f\x7f]/.test(e))throw TypeError("invalid WWW-Authenticate parameter");return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function c(e){if("string"!=typeof e||!s.test(e))throw TypeError("invalid error_description");return e}function d(e){let t=e.body;return{errorCode:"string"==typeof t?.error?t.error:void 0,description:"string"==typeof t?.error_description?t.error_description:"string"==typeof t?.message?t.message:e.message}}function u(e,t,i){return(Array.isArray(e)?e:[e]).map(e=>`Bearer ${i(function(e,t){let i=URL.canParse?.(e)?new URL(e):null;if(i&&"null"!==i.origin){let e=i.pathname.endsWith("/")?i.pathname.slice(0,-1):i.pathname;return`${i.origin}/.well-known/oauth-protected-resource${e}${i.search}`}let a=t?.resourceMetadataMappings?.[e];if(!a)throw new r.E("INTERNAL_SERVER_ERROR",{message:`missing resource_metadata mapping for ${e}`});return a}(e,t)).filter(e=>!!e).join(", ")}`).join(", ")}var p=e.i(252524),p=p,f=p,m=p;function h(e){var t;let r,i,a;if("string"!=typeof e)throw TypeError("MCP resource must be a single URL string");try{r=new URL(e)}catch{throw TypeError("MCP resource must be an absolute URL")}if(r.username||r.password)throw TypeError("MCP resource URL must not contain credentials");if(e.includes("#"))throw TypeError("MCP resource URL must not contain a fragment");if(e.includes("?"))throw TypeError("MCP resource URL must not contain a query; to protect a query-carrying resource, verify tokens with verifyAccessTokenRequest and build challenges with createResourceServerChallenge");if("https:"!==r.protocol&&!("http:"===r.protocol&&(a=4===(i=(t=r.hostname).split(".")).length&&"127"===i[0]&&i.every(e=>/^\d+$/.test(e)&&255>=Number(e)),"localhost"===t||"[::1]"===t||a)))throw TypeError("MCP resource URL must use HTTPS, except for localhost or loopback IP development URLs");return e}function g(e,s,p){let f=function(e,s,p){let f=function(e){if(e){for(let t of e)if(!n.test(t))throw TypeError(`invalid challenge scope: ${JSON.stringify(t)}`);return[...new Set(e)].join(" ")}}(p?.challengeScopes);if((0,t.f)(e)&&"UNAUTHORIZED"===e.status)return!function(e){let{errorCode:t,description:r}=d(e);return!!t&&(o.has(t)||"invalid_token"===t&&r.includes("DPoP"))}(e)?new r.E("UNAUTHORIZED",{message:e.message},{"WWW-Authenticate":u(s,p,e=>[`resource_metadata="${l(e)}"`,f&&`scope="${l(f)}"`])}):new r.E("UNAUTHORIZED",{message:e.message},{"WWW-Authenticate":function(e,t){let{errorCode:r,description:a}=d(e),o=t?.dpopSigningAlgorithms??i.G;return`DPoP error="${l(r??"invalid_dpop_proof")}", error_description="${c(a)}", algs="${l(o.join(" "))}"`}(e,p)});if((0,a.p)(e)){let t,i=(t=e.body,{scope:t?.scope,description:t?.error_description!==void 0?t.error_description:e.message}),a=c(i.description),o=i.scope||f;return new r.E("FORBIDDEN",{message:a},{"WWW-Authenticate":u(s,p,e=>['error="insufficient_scope"',o&&`scope="${l(o)}"`,`resource_metadata="${l(e)}"`,`error_description="${a}"`])})}}(e,s,p);if(!f)throw e;let m=new Headers(f.headers);return m.set("Content-Type","application/json"),new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:f.message},id:null}),{status:f.statusCode,headers:m})}let w="/.well-known/oauth-protected-resource",y=new Set(["openid","profile","email","phone","address","offline_access"]),b=e=>"string"==typeof e?e:e.identifier;e.s(["V",0,(e,t)=>{let r=h(e.audience),i={challengeScopes:e.challengeScopes??e.requiredScopes,dpopSigningAlgorithms:e.dpop?.signingAlgorithms},o={verifyOptions:{...e.jwtVerifyOptions,issuer:e.issuer,audience:e.audience},jwksUrl:e.jwksUrl,remoteVerify:e.remoteVerify,requiredScopes:e.requiredScopes,isScopeSatisfied:e.isScopeSatisfied,dpop:e.dpop};return async e=>{let n;try{n=await (0,a.x)((0,a.z)(e),o)}catch(e){return g(e,r,i)}try{return await t(e,n)}catch(e){if((0,a.p)(e))return g(e,r,i);throw e}}},"B",0,e=>{var t;let r,a,{resource:o,refreshTokenReuseInterval:n=30,...s}=e,l=h(o),c=(0,m.i)({refreshTokenReuseInterval:n,...s,resources:(t=s.resources,(r=t??[]).some(e=>b(e)===l)?r:[...r,l]),clientRegistrationDefaultResources:(a=s.clientRegistrationDefaultResources,a?.includes(l)?a:[...a??[],l])}),d=c.onRequest;return{...c,onRequest:async(e,t)=>{var r;let a,o,n,c,u=await d?.(e,t);if(u)return u;let m=new URL(e.url).pathname,h=t.options.advanced?.skipTrailingSlashes?m.replace(/\/+$/,"")||"/":m,g="";try{g=new URL(l).pathname.replace(/\/$/,"")}catch{g=""}if(!(new Set([w,`${w}${g}`])).has(h))return;if("GET"!==e.method&&"HEAD"!==e.method)return{response:new Response(null,{status:405,headers:{Allow:"GET, HEAD"}})};let E=(0,f.d)((r={context:t},a=(s.advertisedMetadata?.scopes_supported??s.scopes??[]).filter(e=>!y.has(e)),n="object"==typeof(o=s.resources?.find(e=>b(e)===l))&&!0===o.dpopBoundAccessTokensRequired,c={resource:l,authorization_servers:[(0,p.t)(r,s)],bearer_methods_supported:["header"],dpop_signing_alg_values_supported:[...s.dpop?.signingAlgorithms??i.G]},n&&(c.dpop_bound_access_tokens_required=!0),a.length&&(c.scopes_supported=[...a]),c));return"HEAD"===e.method?{response:new Response(null,{status:E.status,headers:E.headers})}:{response:E}}}}],413417)},749599,e=>{"use strict";let t;var r=e.i(46754),i=e.i(682868),a=e.i(272003),o=e.i(890659);let n=()=>t??=e.A(6878).catch(e=>{throw t=void 0,e});e.s(["A",0,()=>{let e=!1;return{id:"next-cookies",version:a.f,hooks:{before:[{matcher:e=>"/get-session"===e.path,handler:(0,o.a)(async t=>{let r;if(e||(!function(e,t){let r=e.options.plugins||[];if(0===r.length)return;let i=r.findIndex(e=>e.id===t);-1===i||r.slice(i+1).some(e=>e.hooks&&Array.isArray(e.hooks.after)&&e.hooks.after.length>0)&&e.logger.warn(`[better-auth] Cookie integration plugin "${t}" should be placed last in the plugins array. Plugins with \`hooks.after\` running after it may set cookies that are not forwarded to the framework cookie store. Move your cookie integration plugin to the end of the \`plugins\` array to avoid missing \`Set-Cookie\` headers.`)}(t.context,"next-cookies"),e=!0),"_flag"in t&&"router"===t._flag)return;try{let{headers:e}=await n();r=await e()}catch{return}let a="1"===r.get("RSC"),o=!!r.get("next-action");a&&!o&&await (0,i.w)(!0)})}],after:[{matcher:e=>!0,handler:(0,o.a)(async e=>{let t=e.context.responseHeaders;if((!("_flag"in e)||"router"!==e._flag)&&t instanceof Headers){let e,i=t?.get("set-cookie");if(!i)return;let a=(0,r.p)(i);try{let{cookies:t}=await n();e=await t()}catch(e){if(e instanceof Error&&(e.message.startsWith("`cookies` was called outside a request scope.")||e.message.includes("Cannot find module")))return;throw e}a.forEach((t,i)=>{if(i)try{e.set(i,t.value,(0,r.n)(t))}catch{}});return}})}]}}},"z",0,function(e){let t=async t=>"handler"in e?e.handler(t):e(t);return{GET:t,POST:t,PATCH:t,PUT:t,DELETE:t}}],749599)},483052,13681,58260,292243,169040,789714,782393,464661,320170,100642,781615,e=>{"use strict";var t=e.i(756023),r=e.i(272003);let i=(0,e.i(483319).y)({user:["create","list","set-role","ban","impersonate","impersonate-admins","delete","set-password","set-email","set-phone","get","update"],session:["list","revoke","delete"]}),a={admin:i.newRole({user:["create","list","set-role","ban","impersonate","delete","set-password","set-email","set-phone","get","update"],session:["list","revoke","delete"]}),user:i.newRole({user:[],session:[]})};var o=e.i(672823);let n=(0,o.f)({FAILED_TO_CREATE_USER:"Failed to create user",USER_ALREADY_EXISTS:"User already exists.",USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL:"User already exists. Use another email.",YOU_CANNOT_BAN_YOURSELF:"You cannot ban yourself",YOU_ARE_NOT_ALLOWED_TO_CHANGE_USERS_ROLE:"You are not allowed to change users role",YOU_ARE_NOT_ALLOWED_TO_CREATE_USERS:"You are not allowed to create users",YOU_ARE_NOT_ALLOWED_TO_LIST_USERS:"You are not allowed to list users",YOU_ARE_NOT_ALLOWED_TO_LIST_USERS_SESSIONS:"You are not allowed to list users sessions",YOU_ARE_NOT_ALLOWED_TO_BAN_USERS:"You are not allowed to ban users",YOU_ARE_NOT_ALLOWED_TO_IMPERSONATE_USERS:"You are not allowed to impersonate users",YOU_ARE_NOT_ALLOWED_TO_REVOKE_USERS_SESSIONS:"You are not allowed to revoke users sessions",YOU_ARE_NOT_ALLOWED_TO_DELETE_USERS:"You are not allowed to delete users",YOU_ARE_NOT_ALLOWED_TO_SET_USERS_PASSWORD:"You are not allowed to set users password",BANNED_USER:"You have been banned from this application",YOU_ARE_NOT_ALLOWED_TO_GET_USER:"You are not allowed to get user",NO_DATA_TO_UPDATE:"No data to update",YOU_ARE_NOT_ALLOWED_TO_UPDATE_USERS:"You are not allowed to update users",YOU_CANNOT_REMOVE_YOURSELF:"You cannot remove yourself",YOU_ARE_NOT_ALLOWED_TO_SET_NON_EXISTENT_VALUE:"You are not allowed to set a non-existent role value",YOU_CANNOT_IMPERSONATE_ADMINS:"You cannot impersonate admins",INVALID_ROLE_TYPE:"Invalid role type",YOU_ARE_NOT_ALLOWED_TO_SET_USERS_EMAIL:"You are not allowed to update users email",YOU_ARE_NOT_ALLOWED_TO_SET_USERS_PHONE_NUMBER:"You are not allowed to update users phone number",PASSWORD_CANNOT_BE_UPDATED_VIA_UPDATE_USER:"Password cannot be updated through update-user. Use the set-user-password endpoint instead",USER_ID_CANNOT_BE_UPDATED:"User id cannot be updated"});var s=e.i(786198);let l=async e=>{let t=e.context.returned;return t?t instanceof Response?200!==t.status?null:await t.clone().json():(0,s.f)(t)?null:t:null};var c=e.i(542158),d=e.i(370728),u=e.i(112996),p=e.i(950551);let f=e=>{if(e.userId&&e.options?.adminUserIds?.includes(e.userId))return!0;if(!e.permissions)return!1;let t=(e.role||e.options?.defaultRole||"user").split(","),r=e.options?.roles||a;for(let i of t)if(r[i]?.authorize(e.permissions)?.success)return!0;return!1};var m=e.i(71616),h=e.i(910228),g=e.i(776757),w=e.i(890659),y=e.i(907855),b=e.i(754257);let E=(0,w.a)(async e=>{let t=await (0,u.M)(e);if(!t)throw m.E.fromStatus("UNAUTHORIZED");return{session:t}});function A(e){return Array.isArray(e)?e.join(","):e}let I=y.object({userId:b.f.string().meta({description:"The user id"}),role:y.union([y.string().meta({description:"The role to set. `admin` or `user` by default"}),y.array(y.string().meta({description:"The roles to set. `admin` or `user` by default"}))]).meta({description:"The role to set, this can be a string or an array of strings. Eg: `admin` or `[admin, user]`"})}),_=y.object({id:y.string().meta({description:"The id of the User"})}),k=y.object({email:y.string().meta({description:"The email of the user"}),password:y.string().optional().meta({description:"The password of the user. If not provided, the user will be created without a credential account (useful for magic link or social login only users)."}),name:y.string().meta({description:"The name of the user"}),role:y.union([y.string().meta({description:"The role of the user"}),y.array(y.string().meta({description:"The roles of user"}))]).optional().meta({description:'A string or array of strings representing the roles to apply to the new user. Eg: "user"'}),data:y.record(y.string(),y.any()).optional().meta({description:"Extra fields for the user. Including custom additional fields."})}),T=y.object({userId:b.f.string().meta({description:"The user id"}),data:y.record(y.any(),y.any()).meta({description:"The user data to update"})}),v=y.object({searchValue:y.string().optional().meta({description:'The value to search for. Eg: "some name"'}),searchField:y.enum(["email","name"]).meta({description:'The field to search in, defaults to email. Can be `email` or `name`. Eg: "name"'}).optional(),searchOperator:y.enum(["contains","starts_with","ends_with"]).meta({description:'The operator to use for the search. Can be `contains`, `starts_with` or `ends_with`. Eg: "contains"'}).optional(),limit:y.string().meta({description:"The number of users to return"}).or(y.number()).optional(),offset:y.string().meta({description:"The offset to start from"}).or(y.number()).optional(),sortBy:y.string().meta({description:"The field to sort by"}).optional(),sortDirection:y.enum(["asc","desc"]).meta({description:"The direction to sort by"}).optional(),filterField:y.string().meta({description:"The field to filter by"}).optional(),filterValue:y.string().meta({description:"The value to filter by"}).or(y.number()).or(y.boolean()).or(y.array(y.string())).or(y.array(y.number())).optional(),filterOperator:y.enum(g.f).meta({description:"The operator to use for the filter"}).optional()}),U=y.object({userId:b.f.string().meta({description:"The user id"})}),R=y.object({userId:b.f.string().meta({description:"The user id"})}),x=y.object({userId:b.f.string().meta({description:"The user id"}),banReason:y.string().meta({description:"The reason for the ban"}).optional(),banExpiresIn:y.number().meta({description:"The number of seconds until the ban expires"}).optional()}),S=y.object({userId:b.f.string().meta({description:"The user id"})}),O=y.object({sessionToken:y.string().meta({description:"The session token"})}),D=y.object({userId:b.f.string().meta({description:"The user id"})}),N=y.object({userId:b.f.string().meta({description:"The user id"})}),L=y.object({newPassword:y.string().nonempty("newPassword cannot be empty").meta({description:"The new password"}),userId:b.f.string().nonempty("userId cannot be empty").meta({description:"The user id"})}),P=y.object({userId:b.f.string().optional().meta({description:'The user id. Eg: "user-id"'}),role:y.string().optional().meta({description:'The role to check permission for. Eg: "admin"'})}).and(y.xor([y.object({permission:y.record(y.string(),y.array(y.string()))}),y.object({permissions:y.record(y.string(),y.array(y.string()))})])),C={user:{fields:{role:{type:"string",required:!1,input:!1},banned:{type:"boolean",defaultValue:!1,required:!1,input:!1},banReason:{type:"string",required:!1,input:!1},banExpires:{type:"date",required:!1,input:!1}}},session:{fields:{impersonatedBy:{type:"string",required:!1,input:!1}}}};e.s(["f",0,e=>{let i={...e||{},defaultRole:e?.defaultRole??"user",adminRoles:e?.adminRoles??["admin"],bannedUserMessage:e?.bannedUserMessage??"You have been banned from this application. Please contact support if you believe this is an error."};if(e?.adminRoles){let t=(Array.isArray(e.adminRoles)?e.adminRoles:[...e.adminRoles.split(",")]).filter(t=>!Object.keys(e?.roles||a).map(e=>e.toLowerCase()).includes(t.toLowerCase()));if(t.length>0)throw new m.p(`Invalid admin roles: ${t.join(", ")}. Admin roles must be defined in the 'roles' configuration.`)}return{id:"admin",version:r.f,init:t=>({options:{databaseHooks:{user:{create:{before:async t=>({data:{role:e?.defaultRole??"user",...t}})}},session:{create:{async before(e,r){let a=r?.context.internalAdapter??t.internalAdapter,o=await a.findUserById(e.userId);if(o?.banned){if(o.banExpires&&new Date(o.banExpires).getTime()<Date.now())return void await a.updateUser(e.userId,{banned:!1,banReason:null,banExpires:null});let t=i.bannedUserMessage,r="function"==typeof t?await t(o):t;throw m.E.from("FORBIDDEN",{message:r,code:"BANNED_USER"})}}}}}}}),hooks:{after:[{matcher:e=>"/list-sessions"===e.path,handler:(0,w.a)(async e=>{let t=await l(e);if(!t)return;let r=t.filter(e=>!e.impersonatedBy);return e.json(r)})}]},endpoints:{setRole:(0,w.g)("/admin/set-role",{method:"POST",body:I,requireHeaders:!0,use:[E],metadata:{openapi:{operationId:"setUserRole",summary:"Set the role of a user",description:"Set the role of a user",responses:{200:{description:"User role updated",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"}}}}}}}},$Infer:{body:{}}}},async e=>{if(!f({userId:e.context.session.user.id,role:e.context.session.user.role,options:i,permissions:{user:["set-role"]}}))throw m.E.from("FORBIDDEN",n.YOU_ARE_NOT_ALLOWED_TO_CHANGE_USERS_ROLE);let r=i.roles;if(r){for(let t of Array.isArray(e.body.role)?e.body.role:[e.body.role])if(!r[t])throw m.E.from("BAD_REQUEST",n.YOU_ARE_NOT_ALLOWED_TO_SET_NON_EXISTENT_VALUE)}if(!await e.context.internalAdapter.findUserById(e.body.userId))throw m.E.from("NOT_FOUND",h.f.USER_NOT_FOUND);let a=await e.context.internalAdapter.updateUser(e.body.userId,{role:A(e.body.role)});return e.json({user:(0,t.$)(e.context.options,a)})}),getUser:(0,w.g)("/admin/get-user",{method:"GET",query:_,use:[E],metadata:{openapi:{operationId:"getUser",summary:"Get an existing user",description:"Get an existing user",responses:{200:{description:"User",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"}}}}}}}}}},async e=>{let{id:r}=e.query;if(!f({userId:e.context.session.user.id,role:e.context.session.user.role,options:i,permissions:{user:["get"]}}))throw m.E.from("FORBIDDEN",n.YOU_ARE_NOT_ALLOWED_TO_GET_USER);let a=await e.context.internalAdapter.findUserById(r);if(!a)throw m.E.from("NOT_FOUND",h.f.USER_NOT_FOUND);return(0,t.$)(e.context.options,a)}),createUser:(0,w.g)("/admin/create-user",{method:"POST",body:k,metadata:{openapi:{operationId:"createUser",summary:"Create a new user",description:"Create a new user",responses:{200:{description:"User created",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"}}}}}}}},$Infer:{body:{}}}},async e=>{let r=await (0,u.M)(e);if(!r&&(e.request||e.headers))throw e.error("UNAUTHORIZED");if(r&&!f({userId:r.user.id,role:r.user.role,options:i,permissions:{user:["create"]}}))throw m.E.from("FORBIDDEN",n.YOU_ARE_NOT_ALLOWED_TO_CREATE_USERS);let{role:a,...o}=e.body.data??{},s=e.body.role??a;if(void 0!==s){if(r&&!f({userId:r.user.id,role:r.user.role,options:i,permissions:{user:["set-role"]}}))throw m.E.from("FORBIDDEN",n.YOU_ARE_NOT_ALLOWED_TO_CHANGE_USERS_ROLE);for(let e of Array.isArray(s)?s:[s]){if("string"!=typeof e)throw m.E.from("BAD_REQUEST",n.INVALID_ROLE_TYPE);if(i.roles&&!i.roles[e])throw m.E.from("BAD_REQUEST",n.YOU_ARE_NOT_ALLOWED_TO_SET_NON_EXISTENT_VALUE)}}if(r&&["banned","banReason","banExpires"].some(e=>Object.prototype.hasOwnProperty.call(o,e))&&!f({userId:r.user.id,role:r.user.role,options:i,permissions:{user:["ban"]}}))throw m.E.from("FORBIDDEN",n.YOU_ARE_NOT_ALLOWED_TO_BAN_USERS);let l=e.body.email.toLowerCase();if(!y.email().safeParse(l).success)throw m.E.from("BAD_REQUEST",h.f.INVALID_EMAIL);if(e.body.password&&(0,p.a)(e,e.body.password),await e.context.internalAdapter.findUserByEmail(l))throw m.E.from("BAD_REQUEST",n.USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL);let c=await e.context.internalAdapter.createUser({...o,email:l,name:e.body.name,role:void 0!==s?A(s):i?.defaultRole??"user"},{method:"admin"});if(!c)throw m.E.from("INTERNAL_SERVER_ERROR",n.FAILED_TO_CREATE_USER);if(e.body.password){let t=await e.context.password.hash(e.body.password);await e.context.internalAdapter.linkAccount({providerId:"credential",accountId:c.id,password:t,userId:c.id})}return e.json({user:(0,t.$)(e.context.options,c)})}),adminUpdateUser:(0,w.g)("/admin/update-user",{method:"POST",body:T,use:[E],metadata:{openapi:{operationId:"adminUpdateUser",summary:"Update a user",description:"Update a user's details",responses:{200:{description:"User updated",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"}}}}}}}}}},async e=>{if(!f({userId:e.context.session.user.id,role:e.context.session.user.role,options:i,permissions:{user:["update"]}}))throw m.E.from("FORBIDDEN",n.YOU_ARE_NOT_ALLOWED_TO_UPDATE_USERS);if(0===Object.keys(e.body.data).length)throw m.E.from("BAD_REQUEST",n.NO_DATA_TO_UPDATE);let r=e.body.data,a=e=>Object.prototype.hasOwnProperty.call(r,e);if(a("password"))throw m.E.from("BAD_REQUEST",n.PASSWORD_CANNOT_BE_UPDATED_VIA_UPDATE_USER);if(a("id"))throw m.E.from("BAD_REQUEST",n.USER_ID_CANNOT_BE_UPDATED);if(Object.prototype.hasOwnProperty.call(e.body.data,"role")){if(!f({userId:e.context.session.user.id,role:e.context.session.user.role,options:i,permissions:{user:["set-role"]}}))throw m.E.from("FORBIDDEN",n.YOU_ARE_NOT_ALLOWED_TO_CHANGE_USERS_ROLE);let t=e.body.data.role,r=Array.isArray(t)?t:[t];for(let e of r){if("string"!=typeof e)throw m.E.from("BAD_REQUEST",n.INVALID_ROLE_TYPE);if(i.roles&&!i.roles[e])throw m.E.from("BAD_REQUEST",n.YOU_ARE_NOT_ALLOWED_TO_SET_NON_EXISTENT_VALUE)}e.body.data.role=A(r)}if(["banned","banReason","banExpires"].some(a)){if(!f({userId:e.context.session.user.id,role:e.context.session.user.role,options:i,permissions:{user:["ban"]}}))throw m.E.from("FORBIDDEN",n.YOU_ARE_NOT_ALLOWED_TO_BAN_USERS);if(!0===r.banned&&e.body.userId===e.context.session.user.id)throw m.E.from("BAD_REQUEST",n.YOU_CANNOT_BAN_YOURSELF)}if(a("email")||a("emailVerified")){if(!f({userId:e.context.session.user.id,role:e.context.session.user.role,options:i,permissions:{user:["set-email"]}}))throw m.E.from("FORBIDDEN",n.YOU_ARE_NOT_ALLOWED_TO_SET_USERS_EMAIL);if(a("email")){let t=String(r.email).toLowerCase();if(!y.email().safeParse(t).success)throw m.E.from("BAD_REQUEST",h.f.INVALID_EMAIL);let i=await e.context.internalAdapter.findUserByEmail(t);if(i&&i.user.id!==e.body.userId)throw m.E.from("BAD_REQUEST",n.USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL);r.email=t}}if((a("phoneNumber")||a("phoneNumberVerified"))&&!f({userId:e.context.session.user.id,role:e.context.session.user.role,options:i,permissions:{user:["set-phone"]}}))throw m.E.from("FORBIDDEN",n.YOU_ARE_NOT_ALLOWED_TO_SET_USERS_PHONE_NUMBER);if(!await e.context.internalAdapter.findUserById(e.body.userId))throw m.E.from("NOT_FOUND",h.f.USER_NOT_FOUND);let o=await e.context.internalAdapter.updateUser(e.body.userId,e.body.data);return!0===r.banned&&await e.context.internalAdapter.deleteUserSessions(e.body.userId),e.json((0,t.$)(e.context.options,o))}),listUsers:(0,w.g)("/admin/list-users",{method:"GET",use:[E],query:v,metadata:{openapi:{operationId:"listUsers",summary:"List users",description:"List users",responses:{200:{description:"List of users",content:{"application/json":{schema:{type:"object",properties:{users:{type:"array",items:{$ref:"#/components/schemas/User"}},total:{type:"number"},limit:{type:"number"},offset:{type:"number"}},required:["users","total"]}}}}}}}},async e=>{let r=e.context.session;if(!f({userId:e.context.session.user.id,role:r.user.role,options:i,permissions:{user:["list"]}}))throw m.E.from("FORBIDDEN",n.YOU_ARE_NOT_ALLOWED_TO_LIST_USERS);let a=[];e.query?.searchValue&&a.push({field:e.query.searchField||"email",operator:e.query.searchOperator||"contains",value:e.query.searchValue}),e.query?.filterValue!==void 0&&a.push({field:e.query.filterField||"email",operator:e.query.filterOperator||"eq",value:e.query.filterValue});try{let r=await e.context.internalAdapter.listUsers(Number(e.query?.limit)||void 0,Number(e.query?.offset)||void 0,e.query?.sortBy?{field:e.query.sortBy,direction:e.query.sortDirection||"asc"}:void 0,a.length?a:void 0),i=await e.context.internalAdapter.countTotalUsers(a.length?a:void 0);return e.json({users:r.map(r=>(0,t.$)(e.context.options,r)),total:i,limit:Number(e.query?.limit)||void 0,offset:Number(e.query?.offset)||void 0})}catch{return e.json({users:[],total:0})}}),listUserSessions:(0,w.g)("/admin/list-user-sessions",{method:"POST",use:[E],body:U,metadata:{openapi:{operationId:"adminListUserSessions",summary:"List user sessions",description:"List user sessions",responses:{200:{description:"List of user sessions",content:{"application/json":{schema:{type:"object",properties:{sessions:{type:"array",items:{$ref:"#/components/schemas/Session"}}}}}}}}}}},async e=>{let r=e.context.session;if(!f({userId:e.context.session.user.id,role:r.user.role,options:i,permissions:{session:["list"]}}))throw m.E.from("FORBIDDEN",n.YOU_ARE_NOT_ALLOWED_TO_LIST_USERS_SESSIONS);let a=await e.context.internalAdapter.listSessions(e.body.userId);return e.json({sessions:a.map(r=>(0,t.Q)(e.context.options,r))})}),unbanUser:(0,w.g)("/admin/unban-user",{method:"POST",body:R,use:[E],metadata:{openapi:{operationId:"unbanUser",summary:"Unban a user",description:"Unban a user",responses:{200:{description:"User unbanned",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"}}}}}}}}}},async e=>{let r=e.context.session;if(!f({userId:e.context.session.user.id,role:r.user.role,options:i,permissions:{user:["ban"]}}))throw m.E.from("FORBIDDEN",n.YOU_ARE_NOT_ALLOWED_TO_BAN_USERS);if(!await e.context.internalAdapter.findUserById(e.body.userId))throw m.E.from("NOT_FOUND",h.f.USER_NOT_FOUND);let a=await e.context.internalAdapter.updateUser(e.body.userId,{banned:!1,banExpires:null,banReason:null,updatedAt:new Date});return e.json({user:(0,t.$)(e.context.options,a)})}),banUser:(0,w.g)("/admin/ban-user",{method:"POST",body:x,use:[E],metadata:{openapi:{operationId:"banUser",summary:"Ban a user",description:"Ban a user",responses:{200:{description:"User banned",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"}}}}}}}}}},async e=>{let r=e.context.session;if(!f({userId:e.context.session.user.id,role:r.user.role,options:i,permissions:{user:["ban"]}}))throw m.E.from("FORBIDDEN",n.YOU_ARE_NOT_ALLOWED_TO_BAN_USERS);if(!await e.context.internalAdapter.findUserById(e.body.userId))throw m.E.from("NOT_FOUND",h.f.USER_NOT_FOUND);if(e.body.userId===e.context.session.user.id)throw m.E.from("BAD_REQUEST",n.YOU_CANNOT_BAN_YOURSELF);let a=await e.context.internalAdapter.updateUser(e.body.userId,{banned:!0,banReason:e.body.banReason||i?.defaultBanReason||"No reason",banExpires:e.body.banExpiresIn?(0,c.f)(e.body.banExpiresIn,"sec"):i?.defaultBanExpiresIn?(0,c.f)(i.defaultBanExpiresIn,"sec"):null,updatedAt:new Date});return await e.context.internalAdapter.deleteUserSessions(e.body.userId),e.json({user:(0,t.$)(e.context.options,a)})}),impersonateUser:(0,w.g)("/admin/impersonate-user",{method:"POST",body:S,use:[E],metadata:{openapi:{operationId:"impersonateUser",summary:"Impersonate a user",description:"Impersonate a user",responses:{200:{description:"Impersonation session created",content:{"application/json":{schema:{type:"object",properties:{session:{$ref:"#/components/schemas/Session"},user:{$ref:"#/components/schemas/User"}}}}}}}}}},async e=>{if(!f({userId:e.context.session.user.id,role:e.context.session.user.role,options:i,permissions:{user:["impersonate"]}}))throw m.E.from("FORBIDDEN",n.YOU_ARE_NOT_ALLOWED_TO_IMPERSONATE_USERS);let r=await e.context.internalAdapter.findUserById(e.body.userId);if(!r)throw m.E.from("NOT_FOUND",h.f.USER_NOT_FOUND);let a=(Array.isArray(i.adminRoles)?i.adminRoles:i.adminRoles?.split(",")||[]).map(e=>e.trim());if(((r.role||i.defaultRole||"user").split(",").some(e=>a.includes(e))||i.adminUserIds?.includes(r.id))&&!(!0===i.allowImpersonatingAdmins||f({userId:e.context.session.user.id,role:e.context.session.user.role,options:i,permissions:{user:["impersonate-admins"]}})))throw m.E.from("FORBIDDEN",n.YOU_CANNOT_IMPERSONATE_ADMINS);let o=await e.context.internalAdapter.createSession(r.id,!0,{impersonatedBy:e.context.session.user.id,expiresAt:i?.impersonationSessionDuration?(0,c.f)(i.impersonationSessionDuration,"sec"):(0,c.f)(3600,"sec")},!0);if(!o)throw m.E.from("INTERNAL_SERVER_ERROR",n.FAILED_TO_CREATE_USER);let s=e.context.authCookies;(0,d.Q)(e);let l=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret),u=e.context.createAuthCookie("admin_session");return await e.setSignedCookie(u.name,`${e.context.session.session.token}:${l||""}`,e.context.secret,s.sessionToken.attributes),await (0,d.V)(e,{session:o,user:r},!0),e.json({session:o,user:(0,t.$)(e.context.options,r)})}),stopImpersonating:(0,w.g)("/admin/stop-impersonating",{method:"POST",requireHeaders:!0},async e=>{let r=await (0,u.D)(e);if(!r)throw m.E.fromStatus("UNAUTHORIZED");if(!r.session.impersonatedBy)throw m.E.fromStatus("BAD_REQUEST",{message:"You are not impersonating anyone"});let i=await e.context.internalAdapter.findUserById(r.session.impersonatedBy);if(!i)throw m.E.fromStatus("INTERNAL_SERVER_ERROR",{message:"Failed to find user"});let a=e.context.createAuthCookie("admin_session"),o=await e.getSignedCookie(a.name,e.context.secret);if(!o)throw m.E.fromStatus("INTERNAL_SERVER_ERROR",{message:"Failed to find admin session"});let[n,s]=o?.split(":"),l=await e.context.internalAdapter.findSession(n);if(!l||l.session.userId!==i.id)throw m.E.fromStatus("INTERNAL_SERVER_ERROR",{message:"Failed to find admin session"});return await e.context.internalAdapter.deleteSession(r.session.token),await (0,d.V)(e,l,!!s),(0,d.c)(e,a),e.json({session:(0,t.Q)(e.context.options,l.session),user:(0,t.$)(e.context.options,l.user)})}),revokeUserSession:(0,w.g)("/admin/revoke-user-session",{method:"POST",body:O,use:[E],metadata:{openapi:{operationId:"revokeUserSession",summary:"Revoke a user session",description:"Revoke a user session",responses:{200:{description:"Session revoked",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async e=>{let t=e.context.session;if(!f({userId:e.context.session.user.id,role:t.user.role,options:i,permissions:{session:["revoke"]}}))throw m.E.from("FORBIDDEN",n.YOU_ARE_NOT_ALLOWED_TO_REVOKE_USERS_SESSIONS);return await e.context.internalAdapter.deleteSession(e.body.sessionToken),e.json({success:!0})}),revokeUserSessions:(0,w.g)("/admin/revoke-user-sessions",{method:"POST",body:D,use:[E],metadata:{openapi:{operationId:"revokeUserSessions",summary:"Revoke all user sessions",description:"Revoke all user sessions",responses:{200:{description:"Sessions revoked",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async e=>{let t=e.context.session;if(!f({userId:e.context.session.user.id,role:t.user.role,options:i,permissions:{session:["revoke"]}}))throw m.E.from("FORBIDDEN",n.YOU_ARE_NOT_ALLOWED_TO_REVOKE_USERS_SESSIONS);return await e.context.internalAdapter.deleteUserSessions(e.body.userId),e.json({success:!0})}),removeUser:(0,w.g)("/admin/remove-user",{method:"POST",body:N,use:[E],metadata:{openapi:{operationId:"removeUser",summary:"Remove a user",description:"Delete a user and all their sessions and accounts. Cannot be undone.",responses:{200:{description:"User removed",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async e=>{let t=e.context.session;if(!f({userId:e.context.session.user.id,role:t.user.role,options:i,permissions:{user:["delete"]}}))throw m.E.from("FORBIDDEN",n.YOU_ARE_NOT_ALLOWED_TO_DELETE_USERS);if(e.body.userId===e.context.session.user.id)throw m.E.from("BAD_REQUEST",n.YOU_CANNOT_REMOVE_YOURSELF);if(!await e.context.internalAdapter.findUserById(e.body.userId))throw m.E.from("NOT_FOUND",h.f.USER_NOT_FOUND);return await e.context.internalAdapter.deleteUserSessions(e.body.userId),await e.context.internalAdapter.deleteUser(e.body.userId),e.json({success:!0})}),setUserPassword:(0,w.g)("/admin/set-user-password",{method:"POST",body:L,use:[E],metadata:{openapi:{operationId:"setUserPassword",summary:"Set a user's password",description:"Set a user's password",responses:{200:{description:"Password set",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{if(!f({userId:e.context.session.user.id,role:e.context.session.user.role,options:i,permissions:{user:["set-password"]}}))throw m.E.from("FORBIDDEN",n.YOU_ARE_NOT_ALLOWED_TO_SET_USERS_PASSWORD);let{newPassword:t,userId:r}=e.body;(0,p.b)(e,t),(0,p.a)(e,t);let a=await e.context.internalAdapter.findUserById(r);if(!a)throw m.E.from("NOT_FOUND",h.f.USER_NOT_FOUND);let o=await e.context.password.hash(t);return await e.context.internalAdapter.findCredentialAccount(r)?await e.context.internalAdapter.updatePassword(r,o):await e.context.internalAdapter.createAccount({userId:r,providerId:"credential",accountId:a.id,password:o}),e.json({status:!0})}),userHasPermission:(0,w.g)("/admin/has-permission",{method:"POST",body:P,metadata:{openapi:{description:"Check if the user has permission",requestBody:{content:{"application/json":{schema:{type:"object",properties:{permissions:{type:"object",description:"The permission to check"}},required:["permissions"]}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{error:{type:"string"},success:{type:"boolean"}},required:["success"]}}}}}},$Infer:{body:{}}}},async e=>{if(!e.body?.permissions)throw new m.E("BAD_REQUEST",{message:"invalid permission check. no permission(s) were passed."});let t=await (0,u.M)(e);if(!t&&(e.request||e.headers))throw new m.E("UNAUTHORIZED");if(!t&&!e.body.userId&&!e.body.role)throw new m.E("BAD_REQUEST",{message:"user id or role is required"});let r=t?.user||(e.body.role?{id:e.body.userId||"",role:e.body.role}:null)||(e.body.userId?await e.context.internalAdapter.findUserById(e.body.userId):null);if(!r)throw new m.E("BAD_REQUEST",{message:"user not found"});let a=f({userId:r.id,role:r.role,options:i,permissions:e.body.permissions});return e.json({error:null,success:a})})},$ERROR_CODES:n,schema:(0,t.C)(C,i.schema),options:e}}],483052);var q=e.i(46754);e.i(418069);var j=e.i(444336),$=e.i(35972);function B(e){try{return decodeURIComponent(e)}catch{return e}}e.s(["f",0,e=>({id:"bearer",version:r.f,hooks:{before:[{matcher:e=>!!(e.request?.headers.get("authorization")||e.headers?.get("authorization")),handler:(0,w.a)(async t=>{let r,i=t.request?.headers.get("authorization")||t.headers?.get("Authorization");if(!i||"bearer "!==i.slice(0,7).toLowerCase())return;let a=i.slice(7).trim();if(!a)return;if(a.includes("."))r=a.includes("%")?B(a):a;else{if(e?.requireSignature)return;r=B((await (0,j.k)("",a,t.context.secret)).replace("=",""))}try{if(!await (0,$.f)("SHA-256","base64urlnopad").verify(t.context.secret,r.split(".")[0],r.split(".")[1]))return}catch{return}let o=t.request?.headers||t.headers,n=new Headers({...Object.fromEntries(o?.entries())});return(0,q.K)(n,t.context.authCookies.sessionToken.name,r),{context:{headers:n}}})}],after:[{matcher:e=>!0,handler:(0,w.a)(async e=>{let t=e.context.responseHeaders?.get("set-cookie");if(!t)return;let r=(0,q.p)(t),i=e.context.authCookies.sessionToken.name,a=r.get(i);if(!a||!a.value||0===a["max-age"])return;let o=a.value,n=new Set((e.context.responseHeaders?.get("access-control-expose-headers")||"").split(",").map(e=>e.trim()).filter(Boolean));n.add("set-auth-token"),e.setHeader("set-auth-token",o),e.setHeader("Access-Control-Expose-Headers",Array.from(n).join(", "))})}]},options:e})],13681);var V=e.i(342e3);let M=(0,o.f)({INVALID_OAUTH_CONFIGURATION:"Invalid OAuth configuration",TOKEN_URL_NOT_FOUND:"Invalid OAuth configuration. Token URL not found."});var F=e.i(533078),K=e.i(878175);e.i(339507);var z=e.i(945e3),H=e.i(729522),W=e.i(661372),Y=e.i(374091),Q=e.i(100762),G=e.i(550064);let J=e=>{try{return(0,K.f)(e)}catch{return null}};async function Z(e,t,r){let i=await (0,F.f)(e,{method:"GET",headers:t,signal:r?AbortSignal.timeout(r):void 0});if(i.error||!i.data)return null;if(i.data.issuer)try{new URL(i.data.issuer)}catch{return null}return i.data}async function X(e,t,r){if(e.idToken){let t=r??J(e.idToken);if(t?.sub&&t?.email)return{id:t.sub,emailVerified:(0,V.f)(t.email_verified),image:t.picture,...t}}if(!t||!e.accessToken)return null;let i=await (0,F.f)(t,{method:"GET",headers:{Authorization:`Bearer ${e.accessToken}`}});return i.error||!i.data?null:{...i.data,email:i.data.email,emailVerified:(0,V.f)(i.data.email_verified),image:i.data.picture,name:i.data.name}}e.s(["f",0,e=>{let t=new Set,i=new Set;for(let r of e.config){let e=r.providerId;t.has(e)&&i.add(e),t.add(e)}i.size>0&&console.warn(`Duplicate provider IDs found: ${Array.from(i).join(", ")}`);let a=async(e,t,r)=>{let i=[];for(let a of e){let e,o,n=a.authorizationUrl,s=a.tokenUrl,l=a.userInfoUrl,c=a.endSessionEndpoint,d=!1;if(a.discoveryUrl){let i=await Z(a.discoveryUrl,a.discoveryHeaders,r).catch(e=>(t.logger.error(`Discovery fetch failed for "${a.providerId}": ${e}`),null));if(i){n??=i.authorization_endpoint,s??=i.token_endpoint,l??=i.userinfo_endpoint,c??=i.end_session_endpoint,e=i.issuer;let r=i.id_token_signing_alg_values_supported;if(d=Array.isArray(r)&&r.length>0,i.jwks_uri&&i.issuer){let e;try{e=new URL(i.jwks_uri,a.discoveryUrl)}catch{t.logger.error(`Provider "${a.providerId}": invalid jwks_uri "${i.jwks_uri}" in discovery document. Provider skipped.`);continue}o={jwks:(0,G.R)(e),issuer:i.issuer,audience:a.clientId,algorithms:d?r:void 0}}}if(!n||!s&&!a.getToken){t.logger.error(`Provider "${a.providerId}": discovery left no usable authorization endpoint or token exchange. Provider skipped.`);continue}}if(a.requireIdTokenVerification&&!o){if(a.discoveryUrl){t.logger.error(`Provider "${a.providerId}": requires verified ID tokens, but discovery did not provide a usable issuer and jwks_uri. Provider skipped.`);continue}throw Error(`Provider "${a.providerId}": requires verified ID tokens, but discovery did not provide a usable issuer and jwks_uri.`)}let u=a.tokenEndpointAuth;if(a.clientSecret&&(u?.method==="private_key_jwt"||u?.method==="none"))throw Error(`Provider "${a.providerId}": tokenEndpointAuth.method "${u?.method}" cannot be combined with clientSecret`);if(!a.clientSecret&&(u?.method==="client_secret_basic"||u?.method==="client_secret_post"))throw Error(`Provider "${a.providerId}": tokenEndpointAuth.method "${u?.method}" requires clientSecret`);if(!a.clientSecret&&!u&&"basic"===a.authentication)throw Error(`Provider "${a.providerId}": authentication "basic" requires clientSecret`);let p=async(e,t)=>{let r=a.getUserInfo?await a.getUserInfo(e):await X(e,l,t);if(!r)return null;let i=!a.getUserInfo||null!=r.sub;if(t?.sub!==void 0&&i&&String(r.sub)!==t.sub)return null;let o=a.mapProfileToUser?await a.mapProfileToUser(r):{},n={email:r.email,emailVerified:(0,V.f)(r.emailVerified),image:r.image,name:r.name,...o};return{user:{...n,image:n.image??void 0},data:r}},f=a.accountSubject,h={id:a.providerId,name:a.name??a.providerId,issuer:e,accountSubject:({tokens:e,profile:t})=>f?f({tokens:e,profile:t}):d?o&&e.idToken?J(e.idToken)?.sub??"":t.sub??"":t.id??"",idToken:o,requiresIdTokenNonce:void 0!==o&&!0!==a.disableIdTokenNonceBinding,allowIdpInitiated:a.allowIdpInitiated,async createEndSessionURL(e){let r;if(a.disableProviderLogout||!c)return null;try{r=new URL(c)}catch{return null}e.idToken&&r.searchParams.set("id_token_hint",e.idToken);let i=e.postLogoutRedirectURI??a.postLogoutRedirectURI,o=i?new URL(i,t.baseURL).toString():void 0;return o?(r.searchParams.set("post_logout_redirect_uri",o),r.searchParams.set("client_id",a.clientId),e.state&&r.searchParams.set("state",e.state)):e.idToken||r.searchParams.set("client_id",a.clientId),r},createAuthorizationURL(e){if(!n)throw m.E.from("BAD_REQUEST",M.INVALID_OAUTH_CONFIGURATION);return(0,H.V)({id:a.providerId,options:{clientId:a.clientId,clientSecret:a.clientSecret,redirectURI:a.redirectURI},authorizationEndpoint:n,state:e.state,codeVerifier:a.pkce??!0?e.codeVerifier:void 0,scopes:(()=>{let t=[...e.scopes??[],...a.scopes??[]];return d&&!t.includes("openid")&&t.unshift("openid"),t})(),redirectURI:e.redirectURI,prompt:a.prompt,accessType:a.accessType,responseType:a.responseType,responseMode:a.responseMode,nonce:e.idTokenNonce,additionalParams:{...a.authorizationUrlParams??{},...e.additionalParams??{}},loginHint:e.loginHint})},async validateAuthorizationCode(e){if(a.getToken)return(0,z.O)(await a.getToken(e),a.accessTokenExpiresIn);if(!s)throw m.E.from("BAD_REQUEST",M.TOKEN_URL_NOT_FOUND);let t=await (0,Y.M)({headers:a.authorizationHeaders,code:e.code,codeVerifier:a.pkce??!0?e.codeVerifier:void 0,redirectURI:e.redirectURI,options:{clientId:a.clientId,clientSecret:a.clientSecret,redirectURI:a.redirectURI},tokenEndpoint:s,authentication:a.authentication,tokenEndpointAuth:u,additionalParams:a.tokenUrlParams});return(0,z.O)(t,a.accessTokenExpiresIn)},async getUserInfoFromIdToken(e){let t=h.idToken?J(e):void 0;return null===t?null:p({idToken:e},t)},async getUserInfo(e){let{expectedIdTokenNonce:r,...i}=e;if(!i.idToken||!h.idToken)return p(i);let o=await (0,Q.n)(h,i.idToken,r)?J(i.idToken):null;return o?p(i,o):(t.logger.error(`Provider "${a.providerId}": id_token failed verification against the discovery JWKS or expected nonce`),null)},async refreshAccessToken(e,t){if(!s)throw m.E.from("BAD_REQUEST",M.TOKEN_URL_NOT_FOUND);let r="function"==typeof a.refreshTokenParams?await a.refreshTokenParams(t):a.refreshTokenParams,i=await (0,W.f)({refreshToken:e,options:{clientId:a.clientId,clientSecret:a.clientSecret},authentication:a.authentication,tokenEndpointAuth:u,tokenEndpoint:s,extraParams:r});return(0,z.O)(i,a.accessTokenExpiresIn)},disableImplicitSignUp:a.disableImplicitSignUp,disableSignUp:a.disableSignUp,options:{disableSignUp:a.disableSignUp,overrideUserInfoOnSignIn:a.overrideUserInfo,requireEmailVerification:a.requireEmailVerification}};i.push(h)}return i},o=e=>{let t=e.body?.provider??e.body?.providerId??e.query?.provider??e.params?.id;return"string"==typeof t?t:void 0};return{id:"generic-oauth",version:r.f,init:async t=>{let r=await a(e.config,t),i=new Set(r.map(e=>e.id)),o=new Map(e.config.filter(e=>!i.has(e.providerId)).map(e=>[e.providerId,{config:e}])),n=new Set(t.socialProviders.map(e=>e.id));for(let e of r)n.has(e.id)&&t.logger.warn(`Generic OAuth provider "${e.id}" shadows a built-in social provider with the same ID`);return{context:{socialProviders:r.concat(t.socialProviders),genericOAuthPendingDiscovery:o}}},hooks:{before:[{matcher:e=>e.context.genericOAuthPendingDiscovery?.has(o(e)??"")===!0,handler:(0,w.a)(async e=>{await ((e,t)=>{let r=e.genericOAuthPendingDiscovery,i=r?.get(t);if(i)return i.attempt??=a([i.config],e,1e4).then(([i])=>{i&&(r?.delete(t),e.socialProviders.unshift(i))}).finally(()=>{i.attempt=void 0}),i.attempt})(e.context,o(e)??"")})}]},options:e,$ERROR_CODES:M}}],58260);var ee=e.i(51144),et=e.i(530501),er=e.i(282318);let ei=async e=>{let t=await (0,er.f)("SHA-256").digest(new TextEncoder().encode(e));return et.W.encode(new Uint8Array(t),{padding:!1})},ea=y.object({token:y.string().meta({description:'The token to verify. Eg: "some-token"'})});e.s(["f",0,e=>{let t={storeToken:"plain",...e};async function i(e,r){return"hashed"===t.storeToken?await ei(r):"object"==typeof t.storeToken&&"type"in t.storeToken&&"custom-hasher"===t.storeToken.type?await t.storeToken.hash(r):r}async function a(e,r){let a=t?.generateToken?await t.generateToken(r,e):(0,ee.f)(32),o=new Date(Date.now()+(t?.expiresIn??3)*6e4),n=await i(e,a);return await e.context.internalAdapter.createVerificationValue({value:r.session.token,identifier:`one-time-token:${n}`,expiresAt:o}),a}return{id:"one-time-token",version:r.f,endpoints:{generateOneTimeToken:(0,w.g)("/one-time-token/generate",{method:"GET",use:[u.Z]},async e=>{if(t?.disableClientRequest&&e.request)throw e.error("BAD_REQUEST",{message:"Client requests are disabled"});let r=e.context.session,i=await a(e,r);return e.json({token:i})}),verifyOneTimeToken:(0,w.g)("/one-time-token/verify",{method:"POST",body:ea},async e=>{let{token:r}=e.body,a=await i(e,r),o=await e.context.internalAdapter.consumeVerificationValue(`one-time-token:${a}`);if(!o)throw e.error("BAD_REQUEST",{message:"Invalid token"});let n=await e.context.internalAdapter.findSession(o.value);if(!n)throw e.error("BAD_REQUEST",{message:"Session not found"});if(t?.disableSetSessionCookie||await (0,d.V)(e,n),n.session.expiresAt<new Date)throw e.error("BAD_REQUEST",{message:"Session expired"});return e.json(n)})},hooks:{after:[{matcher:()=>!0,handler:(0,w.a)(async e=>{if(e.context.newSession){if(!t?.setOttHeaderOnNewSession)return;let r=new Set((e.context.responseHeaders?.get("access-control-expose-headers")||"").split(",").map(e=>e.trim()).filter(Boolean));r.add("set-ott");let i=await a(e,e.context.newSession);e.setHeader("set-ott",i),e.setHeader("Access-Control-Expose-Headers",Array.from(r).join(", "))}})}]},options:e}}],292243);var eo=e.i(303361),en=e.i(187126);function es(e,t){return e[t]?.trim()||void 0}function el(e,t){let r=es(e,t);if(!r)throw Error(`${t} is required for AUTH_MODE.`);return r}e.s(["L",0,function(e=process.env){let t=function(e){let t=es(e,"AUTH_MODE")??"password";if("password"!==t&&"oidc"!==t&&"both"!==t)throw Error('AUTH_MODE must be "password", "oidc", or "both".');return t}(e),r=(0,eo.U)(e);return{secret:(0,en.h)(e).authSecret,origins:r,baseURL:r.canonical,trustProxyHeaders:function(e){let t=es(e,"TRUST_PROXY_HEADERS")?.toLowerCase();if(!t||"false"===t||"0"===t)return!1;if("true"===t||"1"===t)return!0;throw Error("TRUST_PROXY_HEADERS must be true, false, 1, or 0.")}(e),mode:t,provider:function(e,t){if("password"===t)return null;let r=es(e,"AUTH_OAUTH_DISCOVERY_URL"),i=es(e,"AUTH_OAUTH_AUTHORIZATION_URL"),a=es(e,"AUTH_OAUTH_TOKEN_URL"),o=es(e,"AUTH_OAUTH_USER_INFO_URL"),n=es(e,"AUTH_OAUTH_ISSUER"),s=!!(i||a||o),l=i&&a&&o;if(r&&s)throw Error("OIDC configuration must use either discovery or explicit endpoints, not both.");if(!r&&!l)throw Error("OIDC authentication requires AUTH_OAUTH_DISCOVERY_URL or all of AUTH_OAUTH_AUTHORIZATION_URL, AUTH_OAUTH_TOKEN_URL, and AUTH_OAUTH_USER_INFO_URL.");if(s&&!l)throw Error("Explicit OAuth configuration must include authorization, token, and user-info URLs.");if(l&&!n)throw Error("AUTH_OAUTH_ISSUER is required with explicit OAuth endpoints.");let c=el(e,"AUTH_OAUTH_SCOPES").split(",").map(e=>e.trim()).filter(Boolean);if(0===c.length)throw Error("AUTH_OAUTH_SCOPES must contain at least one scope.");return{providerId:el(e,"AUTH_OAUTH_PROVIDER_ID"),displayName:el(e,"AUTH_OAUTH_PROVIDER_NAME"),clientId:el(e,"AUTH_OAUTH_CLIENT_ID"),clientSecret:el(e,"AUTH_OAUTH_CLIENT_SECRET"),scopes:c,requireIssuerValidation:function(e){let t=es(e,"AUTH_OAUTH_REQUIRE_ISSUER_VALIDATION")?.toLowerCase();if(!t||"false"===t||"0"===t)return!1;if("true"===t||"1"===t)return!0;throw Error("AUTH_OAUTH_REQUIRE_ISSUER_VALIDATION must be true, false, 1, or 0.")}(e),discoveryUrl:r,issuer:n,authorizationUrl:i,tokenUrl:a,userInfoUrl:o}}(e,t)}},"_",0,function(e){return"oidc"===e||"both"===e},"Z",0,function(e){return"password"===e||"both"===e}],169040);var ec=e.i(812057);let ed=RegExp(String.raw`((?:"?(?:authorization|password|access[_-]?token|refresh[_-]?token|id[_-]?token|session[_-]?token|client[_-]?secret|client_assertion|code_verifier|code|token|secret|privateKey)"?)\s*:\s*)(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^,\n}\]]+)`,"gi");function eu(e){return e.replace(ed,'$1"[REDACTED]"').replace(/\b(Bearer|DPoP)\s+[A-Za-z0-9._~+\/-]+/gi,"$1 [REDACTED]").replace(/([?&](?:access_token|refresh_token|client_secret|code|code_verifier)=)[^&\s]+/gi,"$1[REDACTED]")}function ep(e){return"string"==typeof e&&e.length>0?e:void 0}async function ef(e,t){try{return await fetch(e,{headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${t}`,"User-Agent":"AI-Development-Environment"}})}catch{return null}}async function em(e,t){let r,i=await ef(e,t);if(!i?.ok)return null;let a=await i.json(),o=ep(a.email),n=await ef(((r=new URL(e)).pathname=`${r.pathname.replace(/\/$/,"")}/emails`,r.toString()),t),s=n?.ok?await n.json():[],l=Array.isArray(s)?s:[],c=l.find(e=>!0===e.primary)??l[0],d=o??ep(c?.email),u=l.find(e=>ep(e.email)===d);return{...a,email:d,emailVerified:u?.verified===!0,image:ep(a.avatar_url),name:ep(a.name)??ep(a.login)??""}}e.s(["f",0,function(e,t,...r){let i=[`${new Date().toISOString()} ${e.toUpperCase()} [Better Auth]: ${t}`,...r.map(e=>"string"==typeof e?e:(0,ec.inspect)(e,{depth:6,breakLength:120}))].map(eu);"error"===e?console.error(...i):"warn"===e?console.warn(...i):console.log(...i)}],789714),e.s(["f",0,em],782393);var eh=e.i(666680),eg=e.i(243783);let ew="default";async function ey(){let e=await (0,eg.U)();return await e.authSettings.findUnique({where:{id:ew}})??await e.authSettings.upsert({where:{id:ew},create:{id:ew},update:{}})}async function eb(){let e=await (0,eg.U)(),[t,r]=await Promise.all([ey(),e.user.count()]);return t.bootstrapCompleted||0!==r?!t.bootstrapCompleted&&r>0?(await e.authSettings.update({where:{id:ew},data:{bootstrapCompleted:!0,registrationEnabled:!1,bootstrapClaimId:null,bootstrapClaimedAt:null}}),{enabled:!1,setupRequired:!1}):{enabled:t.registrationEnabled,setupRequired:!1}:{enabled:!0,setupRequired:!0}}async function eE(e){let t=await (0,eg.U)();if(0===await t.user.count())throw new m.E("BAD_REQUEST",{message:"Create the initial account before changing registration."});await t.authSettings.upsert({where:{id:ew},create:{id:ew,bootstrapCompleted:!0,registrationEnabled:e},update:{registrationEnabled:e}})}async function eA(e,t){if(e===t)throw new m.E("BAD_REQUEST",{message:"You cannot delete the account you are currently using."});let r=await (0,eg.U)();if(1!==await r.$executeRaw`
|
|
450
|
+
`)}}(t={...t,secret:i,baseURL:f?t.baseURL:m?new URL(m).origin:"",basePath:t.basePath||"/api/auth",plugins:c.concat(d)},p);let A=t.advanced?.ipAddress?.trustedProxies;if(A&&A.length>0){let e=(0,l.p)(A);e.length>0&&p.warn(`Ignoring invalid \`advanced.ipAddress.trustedProxies\` entries: ${e.join(", ")}. Each entry must be an IP address or CIDR range.`)}let I=(0,e0.e)(t),_=(0,eE.R)(t),k=(await Promise.all(Object.entries(t.socialProviders||{}).map(async([e,t])=>{let r="function"==typeof t?await t():t;if(null==r||!1===r.enabled)return null;r.clientId||p.warn(`Social provider ${e} is missing clientId or clientSecret`);let i=r4[e](r);return i.disableImplicitSignUp=r.disableImplicitSignUp,i}))).filter(e=>null!==e),T=({model:e,size:r})=>{if("function"==typeof t.advanced?.generateId)return t.advanced.generateId({model:e,size:r});let i=t?.advanced?.database?.generateId;return"function"==typeof i?i({model:e,size:r}):"uuid"===i?crypto.randomUUID():"serial"!==i&&!1!==i&&(0,y.f)(r)},{publish:v}=await at(t,{adapter:e.id,database:"function"==typeof t.database?"adapter":r(t.database)}),U=new Set(t.plugins.map(e=>e.id)),R=await tl(t),S=await tp(t),x={appName:t.appName||"Better Auth",baseURL:m||"",version:(0,iV.I)(),socialProviders:k,options:t,oauthConfig:{storeStateStrategy:t.account?.storeStateStrategy||(s?"database":"cookie"),skipStateCookieCheck:!!t.account?.skipStateCookieCheck},tables:_,trustedOrigins:R,trustedProviders:S,isTrustedOrigin(e,t){return this.trustedOrigins.some(r=>eG(e,r,t))},sessionConfig:{updateAge:t.session?.updateAge!==void 0?t.session.updateAge:86400,expiresIn:t.session?.expiresIn||604800,freshAge:t.session?.freshAge===void 0?86400:t.session.freshAge,cookieRefreshCache:(o=t.session?.cookieCache?.refreshCache,n=t.session?.cookieCache?.maxAge||300,s&&o?(p.warn("[better-auth] `session.cookieCache.refreshCache` is enabled while `database` or `secondaryStorage` is configured. `refreshCache` is meant for stateless (DB-less) setups. Disabling `refreshCache` — remove it from your config to silence this warning."),!1):!1!==o&&void 0!==o&&(!0===o?{enabled:!0,updateAge:Math.floor(.2*n)}:{enabled:!0,updateAge:void 0!==o.updateAge?o.updateAge:Math.floor(.2*n)}))},secret:i,secretConfig:a,rateLimit:{...t.rateLimit,enabled:t.rateLimit?.enabled??ta.C,window:t.rateLimit?.window||10,max:t.rateLimit?.max||100,storage:t.rateLimit?.storage||(t.secondaryStorage?"secondary-storage":"memory")},authCookies:I,logger:p,generateId:T,session:null,secondaryStorage:t.secondaryStorage,password:{hash:t.emailAndPassword?.password?.hash||eX.Z,verify:t.emailAndPassword?.password?.verify||eX.B,config:{minPasswordLength:t.emailAndPassword?.minPasswordLength||8,maxPasswordLength:t.emailAndPassword?.maxPasswordLength||128},checkPassword:ty},setNewSession(e){this.newSession=e},newSession:null,adapter:e,internalAdapter:ti(e,{options:t,logger:p,hooks:t.databaseHooks?[{source:"user",hooks:t.databaseHooks}]:[],generateId:T}),createAuthCookie:(0,e0.g)(t),async runMigrations(){throw new u.p("runMigrations will be set by the specific init implementation")},publishTelemetry:v,skipCSRFCheck:!!t.advanced?.disableCSRFCheck,skipOriginCheck:t.advanced?.disableOriginCheck!==void 0?t.advanced.disableOriginCheck:!!(0,ta.s)(),runInBackground:t.advanced?.backgroundTasks?.handler??(e=>{e.catch(()=>{})}),async runInBackgroundOrAwait(e){try{t.advanced?.backgroundTasks?.handler?e instanceof Promise&&t.advanced.backgroundTasks.handler(e.catch(e=>{p.error("Failed to run background task:",e)})):await e}catch(e){p.error("Failed to run background task:",e)}},getPlugin:e=>t.plugins.find(t=>t.id===e)??null,hasPlugin:e=>U.has(e)},O=ts(x);return(0,eZ.f)(O)&&await O,x.checkSchema=(0,eg.f)(x.adapter),x.explicitSchemaCheck=(0,eg.j)(x.adapter),x}let ai=async e=>{let t=await e_(e),r=await ar(t,e,e=>(0,eT.getKyselyDatabaseType)(e)||"unknown");return r.runMigrations=async function(){if(!e.database||"updateMany"in e.database)throw new u.p("Database is not provided or it's an adapter. Migrations are only supported with a database instance.");let{runMigrations:t}=await eB(e);await t()},r};e.s(["f",0,e=>((e,t)=>{let r=t(e).then(e=>{let t=e.options.advanced?.database?.validateSchema;e.checkSchema||!1===t||e.logger[!0===t?"warn":"debug"](`Schema validation is not available for adapter "${e.adapter.id}". Skipping schema validation. Database operations will proceed normally.`);let r=e.checkSchema?.();return r&&r.catch(t=>{e.logger.error(t instanceof ew._?t.message:"Could not validate the database schema. Check your database connection.")}),e}),{api:i}=iB(r,e),a=e.plugins?.reduce((e,t)=>t.$ERROR_CODES?{...e,...t.$ERROR_CODES}:e,{}),o=async t=>{let i,a=await r,o=a.options.basePath||"/api/auth";if((0,eV._)(e.baseURL))i=await td(a,t,tc(a.options));else{i=Object.create(Object.getPrototypeOf(a),Object.getOwnPropertyDescriptors(a));let e=a.options;if(!a.options.baseURL){let r=(0,eV.X)(void 0,o,t,void 0,a.options.advanced?.trustedProxyHeaders);if(!r)throw new u.p("Could not get base URL from request. Please provide a valid base URL.");i.baseURL=r,i.options={...a.options,baseURL:(0,eV.H)(r)||void 0},e=i.options}i.trustedOrigins=await tl(e,t),i.trustedProviders=await tp(e,t)}let{handler:n}=((e,t)=>{let r=(0,te.f)(t),{api:i,middlewares:a}=iB(e,t),o=new URL(e.baseURL).pathname;return(0,i$.f)(i,{routerContext:e,openapi:{disabled:!0},basePath:o,routerMiddleware:[{path:"/**",middleware:tk},...a],allowedMediaTypes:["application/json"],skipTrailingSlashes:t.advanced?.skipTrailingSlashes??!1,async onRequest(t){let i=e.options.disabledPaths||[],a=(0,tE.s)(t.url,o);if(i.includes(a))return new Response("Not Found",{status:404});let n=e.checkSchema?.();n&&await n;let s=t,l=await tN(s,e);if(l)return l;for(let t of e.options.plugins||[])if(t.onRequest){let i=await r(`onRequest ${t.id}`,{[e9.A]:"onRequest",[e9.s]:`plugin:${t.id}`},()=>t.onRequest(s,e));if(i&&"response"in i)return i.response;i&&"request"in i&&(s=i.request)}return s},async onResponse(t,i){for(let i of e.options.plugins||[])if(i.onResponse){let a=await r(`onResponse ${i.id}`,{[e9.A]:"onResponse",[e9.s]:`plugin:${i.id}`,[e9.h]:t.status},()=>i.onResponse(t,e));if(a)return a.response}return t},async onError(r){if((0,tb.f)(r)&&"FOUND"===r.status)return;if(t.onAPIError?.throw)throw r;if(t.onAPIError?.onError){try{await t.onAPIError.onError(r,e)}catch(t){e.logger.error("onAPIError.onError threw",t)}return}let i=t.logger?.level,a="error"===i||"warn"===i||"debug"===i?eA.y:void 0;if(t.logger?.disabled!==!0){if(r&&"object"==typeof r&&"message"in r&&"string"==typeof r.message&&(r.message.includes("no column")||r.message.includes("column")||r.message.includes("relation")||r.message.includes("table")||r.message.includes("does not exist")))return void e.logger?.error(r.message);(0,tb.f)(r)?("INTERNAL_SERVER_ERROR"===r.status&&e.logger.error(r.status,r),a?.error(r.message)):e.logger?.error(r&&"object"==typeof r&&"name"in r?r.name:"",r)}}})})(i,e);return(0,e7.Q)(i.adapter,()=>n(t))};return{handler:o,fetch:o,api:i,options:e,$context:r,$ERROR_CODES:{...a,...tf.f}}})(e,ai)],204721)},413417,e=>{"use strict";var t=e.i(786198);e.i(418069);var r=e.i(455659),i=e.i(704199),a=e.i(728895);let o=new Set(["invalid_dpop_proof"]),n=/^[\x21\x23-\x5b\x5d-\x7e]+$/,s=/^[\x20-\x21\x23-\x5b\x5d-\x7e]+$/;function l(e){if(/[\x00-\x1f\x7f]/.test(e))throw TypeError("invalid WWW-Authenticate parameter");return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function c(e){if("string"!=typeof e||!s.test(e))throw TypeError("invalid error_description");return e}function d(e){let t=e.body;return{errorCode:"string"==typeof t?.error?t.error:void 0,description:"string"==typeof t?.error_description?t.error_description:"string"==typeof t?.message?t.message:e.message}}function u(e,t,i){return(Array.isArray(e)?e:[e]).map(e=>`Bearer ${i(function(e,t){let i=URL.canParse?.(e)?new URL(e):null;if(i&&"null"!==i.origin){let e=i.pathname.endsWith("/")?i.pathname.slice(0,-1):i.pathname;return`${i.origin}/.well-known/oauth-protected-resource${e}${i.search}`}let a=t?.resourceMetadataMappings?.[e];if(!a)throw new r.E("INTERNAL_SERVER_ERROR",{message:`missing resource_metadata mapping for ${e}`});return a}(e,t)).filter(e=>!!e).join(", ")}`).join(", ")}var p=e.i(252524),p=p,f=p,m=p;function h(e){var t;let r,i,a;if("string"!=typeof e)throw TypeError("MCP resource must be a single URL string");try{r=new URL(e)}catch{throw TypeError("MCP resource must be an absolute URL")}if(r.username||r.password)throw TypeError("MCP resource URL must not contain credentials");if(e.includes("#"))throw TypeError("MCP resource URL must not contain a fragment");if(e.includes("?"))throw TypeError("MCP resource URL must not contain a query; to protect a query-carrying resource, verify tokens with verifyAccessTokenRequest and build challenges with createResourceServerChallenge");if("https:"!==r.protocol&&!("http:"===r.protocol&&(a=4===(i=(t=r.hostname).split(".")).length&&"127"===i[0]&&i.every(e=>/^\d+$/.test(e)&&255>=Number(e)),"localhost"===t||"[::1]"===t||a)))throw TypeError("MCP resource URL must use HTTPS, except for localhost or loopback IP development URLs");return e}function g(e,s,p){let f=function(e,s,p){let f=function(e){if(e){for(let t of e)if(!n.test(t))throw TypeError(`invalid challenge scope: ${JSON.stringify(t)}`);return[...new Set(e)].join(" ")}}(p?.challengeScopes);if((0,t.f)(e)&&"UNAUTHORIZED"===e.status)return!function(e){let{errorCode:t,description:r}=d(e);return!!t&&(o.has(t)||"invalid_token"===t&&r.includes("DPoP"))}(e)?new r.E("UNAUTHORIZED",{message:e.message},{"WWW-Authenticate":u(s,p,e=>[`resource_metadata="${l(e)}"`,f&&`scope="${l(f)}"`])}):new r.E("UNAUTHORIZED",{message:e.message},{"WWW-Authenticate":function(e,t){let{errorCode:r,description:a}=d(e),o=t?.dpopSigningAlgorithms??i.G;return`DPoP error="${l(r??"invalid_dpop_proof")}", error_description="${c(a)}", algs="${l(o.join(" "))}"`}(e,p)});if((0,a.p)(e)){let t,i=(t=e.body,{scope:t?.scope,description:t?.error_description!==void 0?t.error_description:e.message}),a=c(i.description),o=i.scope||f;return new r.E("FORBIDDEN",{message:a},{"WWW-Authenticate":u(s,p,e=>['error="insufficient_scope"',o&&`scope="${l(o)}"`,`resource_metadata="${l(e)}"`,`error_description="${a}"`])})}}(e,s,p);if(!f)throw e;let m=new Headers(f.headers);return m.set("Content-Type","application/json"),new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:f.message},id:null}),{status:f.statusCode,headers:m})}let w="/.well-known/oauth-protected-resource",y=new Set(["openid","profile","email","phone","address","offline_access"]),b=e=>"string"==typeof e?e:e.identifier;e.s(["V",0,(e,t)=>{let r=h(e.audience),i={challengeScopes:e.challengeScopes??e.requiredScopes,dpopSigningAlgorithms:e.dpop?.signingAlgorithms},o={verifyOptions:{...e.jwtVerifyOptions,issuer:e.issuer,audience:e.audience},jwksUrl:e.jwksUrl,remoteVerify:e.remoteVerify,requiredScopes:e.requiredScopes,isScopeSatisfied:e.isScopeSatisfied,dpop:e.dpop};return async e=>{let n;try{n=await (0,a.x)((0,a.z)(e),o)}catch(e){return g(e,r,i)}try{return await t(e,n)}catch(e){if((0,a.p)(e))return g(e,r,i);throw e}}},"B",0,e=>{var t;let r,a,{resource:o,refreshTokenReuseInterval:n=30,...s}=e,l=h(o),c=(0,m.i)({refreshTokenReuseInterval:n,...s,resources:(t=s.resources,(r=t??[]).some(e=>b(e)===l)?r:[...r,l]),clientRegistrationDefaultResources:(a=s.clientRegistrationDefaultResources,a?.includes(l)?a:[...a??[],l])}),d=c.onRequest;return{...c,onRequest:async(e,t)=>{var r;let a,o,n,c,u=await d?.(e,t);if(u)return u;let m=new URL(e.url).pathname,h=t.options.advanced?.skipTrailingSlashes?m.replace(/\/+$/,"")||"/":m,g="";try{g=new URL(l).pathname.replace(/\/$/,"")}catch{g=""}if(!(new Set([w,`${w}${g}`])).has(h))return;if("GET"!==e.method&&"HEAD"!==e.method)return{response:new Response(null,{status:405,headers:{Allow:"GET, HEAD"}})};let E=(0,f.d)((r={context:t},a=(s.advertisedMetadata?.scopes_supported??s.scopes??[]).filter(e=>!y.has(e)),n="object"==typeof(o=s.resources?.find(e=>b(e)===l))&&!0===o.dpopBoundAccessTokensRequired,c={resource:l,authorization_servers:[(0,p.t)(r,s)],bearer_methods_supported:["header"],dpop_signing_alg_values_supported:[...s.dpop?.signingAlgorithms??i.G]},n&&(c.dpop_bound_access_tokens_required=!0),a.length&&(c.scopes_supported=[...a]),c));return"HEAD"===e.method?{response:new Response(null,{status:E.status,headers:E.headers})}:{response:E}}}}],413417)},749599,e=>{"use strict";let t;var r=e.i(46754),i=e.i(682868),a=e.i(272003),o=e.i(890659);let n=()=>t??=e.A(6878).catch(e=>{throw t=void 0,e});e.s(["A",0,()=>{let e=!1;return{id:"next-cookies",version:a.f,hooks:{before:[{matcher:e=>"/get-session"===e.path,handler:(0,o.a)(async t=>{let r;if(e||(!function(e,t){let r=e.options.plugins||[];if(0===r.length)return;let i=r.findIndex(e=>e.id===t);-1===i||r.slice(i+1).some(e=>e.hooks&&Array.isArray(e.hooks.after)&&e.hooks.after.length>0)&&e.logger.warn(`[better-auth] Cookie integration plugin "${t}" should be placed last in the plugins array. Plugins with \`hooks.after\` running after it may set cookies that are not forwarded to the framework cookie store. Move your cookie integration plugin to the end of the \`plugins\` array to avoid missing \`Set-Cookie\` headers.`)}(t.context,"next-cookies"),e=!0),"_flag"in t&&"router"===t._flag)return;try{let{headers:e}=await n();r=await e()}catch{return}let a="1"===r.get("RSC"),o=!!r.get("next-action");a&&!o&&await (0,i.w)(!0)})}],after:[{matcher:e=>!0,handler:(0,o.a)(async e=>{let t=e.context.responseHeaders;if((!("_flag"in e)||"router"!==e._flag)&&t instanceof Headers){let e,i=t?.get("set-cookie");if(!i)return;let a=(0,r.p)(i);try{let{cookies:t}=await n();e=await t()}catch(e){if(e instanceof Error&&(e.message.startsWith("`cookies` was called outside a request scope.")||e.message.includes("Cannot find module")))return;throw e}a.forEach((t,i)=>{if(i)try{e.set(i,t.value,(0,r.n)(t))}catch{}});return}})}]}}},"z",0,function(e){let t=async t=>"handler"in e?e.handler(t):e(t);return{GET:t,POST:t,PATCH:t,PUT:t,DELETE:t}}],749599)},483052,13681,58260,292243,169040,789714,782393,464661,320170,100642,781615,e=>{"use strict";var t=e.i(756023),r=e.i(272003);let i=(0,e.i(483319).y)({user:["create","list","set-role","ban","impersonate","impersonate-admins","delete","set-password","set-email","set-phone","get","update"],session:["list","revoke","delete"]}),a={admin:i.newRole({user:["create","list","set-role","ban","impersonate","delete","set-password","set-email","set-phone","get","update"],session:["list","revoke","delete"]}),user:i.newRole({user:[],session:[]})};var o=e.i(672823);let n=(0,o.f)({FAILED_TO_CREATE_USER:"Failed to create user",USER_ALREADY_EXISTS:"User already exists.",USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL:"User already exists. Use another email.",YOU_CANNOT_BAN_YOURSELF:"You cannot ban yourself",YOU_ARE_NOT_ALLOWED_TO_CHANGE_USERS_ROLE:"You are not allowed to change users role",YOU_ARE_NOT_ALLOWED_TO_CREATE_USERS:"You are not allowed to create users",YOU_ARE_NOT_ALLOWED_TO_LIST_USERS:"You are not allowed to list users",YOU_ARE_NOT_ALLOWED_TO_LIST_USERS_SESSIONS:"You are not allowed to list users sessions",YOU_ARE_NOT_ALLOWED_TO_BAN_USERS:"You are not allowed to ban users",YOU_ARE_NOT_ALLOWED_TO_IMPERSONATE_USERS:"You are not allowed to impersonate users",YOU_ARE_NOT_ALLOWED_TO_REVOKE_USERS_SESSIONS:"You are not allowed to revoke users sessions",YOU_ARE_NOT_ALLOWED_TO_DELETE_USERS:"You are not allowed to delete users",YOU_ARE_NOT_ALLOWED_TO_SET_USERS_PASSWORD:"You are not allowed to set users password",BANNED_USER:"You have been banned from this application",YOU_ARE_NOT_ALLOWED_TO_GET_USER:"You are not allowed to get user",NO_DATA_TO_UPDATE:"No data to update",YOU_ARE_NOT_ALLOWED_TO_UPDATE_USERS:"You are not allowed to update users",YOU_CANNOT_REMOVE_YOURSELF:"You cannot remove yourself",YOU_ARE_NOT_ALLOWED_TO_SET_NON_EXISTENT_VALUE:"You are not allowed to set a non-existent role value",YOU_CANNOT_IMPERSONATE_ADMINS:"You cannot impersonate admins",INVALID_ROLE_TYPE:"Invalid role type",YOU_ARE_NOT_ALLOWED_TO_SET_USERS_EMAIL:"You are not allowed to update users email",YOU_ARE_NOT_ALLOWED_TO_SET_USERS_PHONE_NUMBER:"You are not allowed to update users phone number",PASSWORD_CANNOT_BE_UPDATED_VIA_UPDATE_USER:"Password cannot be updated through update-user. Use the set-user-password endpoint instead",USER_ID_CANNOT_BE_UPDATED:"User id cannot be updated"});var s=e.i(786198);let l=async e=>{let t=e.context.returned;return t?t instanceof Response?200!==t.status?null:await t.clone().json():(0,s.f)(t)?null:t:null};var c=e.i(542158),d=e.i(370728),u=e.i(112996),p=e.i(950551);let f=e=>{if(e.userId&&e.options?.adminUserIds?.includes(e.userId))return!0;if(!e.permissions)return!1;let t=(e.role||e.options?.defaultRole||"user").split(","),r=e.options?.roles||a;for(let i of t)if(r[i]?.authorize(e.permissions)?.success)return!0;return!1};var m=e.i(71616),h=e.i(910228),g=e.i(776757),w=e.i(890659),y=e.i(907855),b=e.i(754257);let E=(0,w.a)(async e=>{let t=await (0,u.M)(e);if(!t)throw m.E.fromStatus("UNAUTHORIZED");return{session:t}});function A(e){return Array.isArray(e)?e.join(","):e}let I=y.object({userId:b.f.string().meta({description:"The user id"}),role:y.union([y.string().meta({description:"The role to set. `admin` or `user` by default"}),y.array(y.string().meta({description:"The roles to set. `admin` or `user` by default"}))]).meta({description:"The role to set, this can be a string or an array of strings. Eg: `admin` or `[admin, user]`"})}),_=y.object({id:y.string().meta({description:"The id of the User"})}),k=y.object({email:y.string().meta({description:"The email of the user"}),password:y.string().optional().meta({description:"The password of the user. If not provided, the user will be created without a credential account (useful for magic link or social login only users)."}),name:y.string().meta({description:"The name of the user"}),role:y.union([y.string().meta({description:"The role of the user"}),y.array(y.string().meta({description:"The roles of user"}))]).optional().meta({description:'A string or array of strings representing the roles to apply to the new user. Eg: "user"'}),data:y.record(y.string(),y.any()).optional().meta({description:"Extra fields for the user. Including custom additional fields."})}),T=y.object({userId:b.f.string().meta({description:"The user id"}),data:y.record(y.any(),y.any()).meta({description:"The user data to update"})}),v=y.object({searchValue:y.string().optional().meta({description:'The value to search for. Eg: "some name"'}),searchField:y.enum(["email","name"]).meta({description:'The field to search in, defaults to email. Can be `email` or `name`. Eg: "name"'}).optional(),searchOperator:y.enum(["contains","starts_with","ends_with"]).meta({description:'The operator to use for the search. Can be `contains`, `starts_with` or `ends_with`. Eg: "contains"'}).optional(),limit:y.string().meta({description:"The number of users to return"}).or(y.number()).optional(),offset:y.string().meta({description:"The offset to start from"}).or(y.number()).optional(),sortBy:y.string().meta({description:"The field to sort by"}).optional(),sortDirection:y.enum(["asc","desc"]).meta({description:"The direction to sort by"}).optional(),filterField:y.string().meta({description:"The field to filter by"}).optional(),filterValue:y.string().meta({description:"The value to filter by"}).or(y.number()).or(y.boolean()).or(y.array(y.string())).or(y.array(y.number())).optional(),filterOperator:y.enum(g.f).meta({description:"The operator to use for the filter"}).optional()}),U=y.object({userId:b.f.string().meta({description:"The user id"})}),R=y.object({userId:b.f.string().meta({description:"The user id"})}),S=y.object({userId:b.f.string().meta({description:"The user id"}),banReason:y.string().meta({description:"The reason for the ban"}).optional(),banExpiresIn:y.number().meta({description:"The number of seconds until the ban expires"}).optional()}),x=y.object({userId:b.f.string().meta({description:"The user id"})}),O=y.object({sessionToken:y.string().meta({description:"The session token"})}),D=y.object({userId:b.f.string().meta({description:"The user id"})}),N=y.object({userId:b.f.string().meta({description:"The user id"})}),L=y.object({newPassword:y.string().nonempty("newPassword cannot be empty").meta({description:"The new password"}),userId:b.f.string().nonempty("userId cannot be empty").meta({description:"The user id"})}),P=y.object({userId:b.f.string().optional().meta({description:'The user id. Eg: "user-id"'}),role:y.string().optional().meta({description:'The role to check permission for. Eg: "admin"'})}).and(y.xor([y.object({permission:y.record(y.string(),y.array(y.string()))}),y.object({permissions:y.record(y.string(),y.array(y.string()))})])),C={user:{fields:{role:{type:"string",required:!1,input:!1},banned:{type:"boolean",defaultValue:!1,required:!1,input:!1},banReason:{type:"string",required:!1,input:!1},banExpires:{type:"date",required:!1,input:!1}}},session:{fields:{impersonatedBy:{type:"string",required:!1,input:!1}}}};e.s(["f",0,e=>{let i={...e||{},defaultRole:e?.defaultRole??"user",adminRoles:e?.adminRoles??["admin"],bannedUserMessage:e?.bannedUserMessage??"You have been banned from this application. Please contact support if you believe this is an error."};if(e?.adminRoles){let t=(Array.isArray(e.adminRoles)?e.adminRoles:[...e.adminRoles.split(",")]).filter(t=>!Object.keys(e?.roles||a).map(e=>e.toLowerCase()).includes(t.toLowerCase()));if(t.length>0)throw new m.p(`Invalid admin roles: ${t.join(", ")}. Admin roles must be defined in the 'roles' configuration.`)}return{id:"admin",version:r.f,init:t=>({options:{databaseHooks:{user:{create:{before:async t=>({data:{role:e?.defaultRole??"user",...t}})}},session:{create:{async before(e,r){let a=r?.context.internalAdapter??t.internalAdapter,o=await a.findUserById(e.userId);if(o?.banned){if(o.banExpires&&new Date(o.banExpires).getTime()<Date.now())return void await a.updateUser(e.userId,{banned:!1,banReason:null,banExpires:null});let t=i.bannedUserMessage,r="function"==typeof t?await t(o):t;throw m.E.from("FORBIDDEN",{message:r,code:"BANNED_USER"})}}}}}}}),hooks:{after:[{matcher:e=>"/list-sessions"===e.path,handler:(0,w.a)(async e=>{let t=await l(e);if(!t)return;let r=t.filter(e=>!e.impersonatedBy);return e.json(r)})}]},endpoints:{setRole:(0,w.g)("/admin/set-role",{method:"POST",body:I,requireHeaders:!0,use:[E],metadata:{openapi:{operationId:"setUserRole",summary:"Set the role of a user",description:"Set the role of a user",responses:{200:{description:"User role updated",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"}}}}}}}},$Infer:{body:{}}}},async e=>{if(!f({userId:e.context.session.user.id,role:e.context.session.user.role,options:i,permissions:{user:["set-role"]}}))throw m.E.from("FORBIDDEN",n.YOU_ARE_NOT_ALLOWED_TO_CHANGE_USERS_ROLE);let r=i.roles;if(r){for(let t of Array.isArray(e.body.role)?e.body.role:[e.body.role])if(!r[t])throw m.E.from("BAD_REQUEST",n.YOU_ARE_NOT_ALLOWED_TO_SET_NON_EXISTENT_VALUE)}if(!await e.context.internalAdapter.findUserById(e.body.userId))throw m.E.from("NOT_FOUND",h.f.USER_NOT_FOUND);let a=await e.context.internalAdapter.updateUser(e.body.userId,{role:A(e.body.role)});return e.json({user:(0,t.$)(e.context.options,a)})}),getUser:(0,w.g)("/admin/get-user",{method:"GET",query:_,use:[E],metadata:{openapi:{operationId:"getUser",summary:"Get an existing user",description:"Get an existing user",responses:{200:{description:"User",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"}}}}}}}}}},async e=>{let{id:r}=e.query;if(!f({userId:e.context.session.user.id,role:e.context.session.user.role,options:i,permissions:{user:["get"]}}))throw m.E.from("FORBIDDEN",n.YOU_ARE_NOT_ALLOWED_TO_GET_USER);let a=await e.context.internalAdapter.findUserById(r);if(!a)throw m.E.from("NOT_FOUND",h.f.USER_NOT_FOUND);return(0,t.$)(e.context.options,a)}),createUser:(0,w.g)("/admin/create-user",{method:"POST",body:k,metadata:{openapi:{operationId:"createUser",summary:"Create a new user",description:"Create a new user",responses:{200:{description:"User created",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"}}}}}}}},$Infer:{body:{}}}},async e=>{let r=await (0,u.M)(e);if(!r&&(e.request||e.headers))throw e.error("UNAUTHORIZED");if(r&&!f({userId:r.user.id,role:r.user.role,options:i,permissions:{user:["create"]}}))throw m.E.from("FORBIDDEN",n.YOU_ARE_NOT_ALLOWED_TO_CREATE_USERS);let{role:a,...o}=e.body.data??{},s=e.body.role??a;if(void 0!==s){if(r&&!f({userId:r.user.id,role:r.user.role,options:i,permissions:{user:["set-role"]}}))throw m.E.from("FORBIDDEN",n.YOU_ARE_NOT_ALLOWED_TO_CHANGE_USERS_ROLE);for(let e of Array.isArray(s)?s:[s]){if("string"!=typeof e)throw m.E.from("BAD_REQUEST",n.INVALID_ROLE_TYPE);if(i.roles&&!i.roles[e])throw m.E.from("BAD_REQUEST",n.YOU_ARE_NOT_ALLOWED_TO_SET_NON_EXISTENT_VALUE)}}if(r&&["banned","banReason","banExpires"].some(e=>Object.prototype.hasOwnProperty.call(o,e))&&!f({userId:r.user.id,role:r.user.role,options:i,permissions:{user:["ban"]}}))throw m.E.from("FORBIDDEN",n.YOU_ARE_NOT_ALLOWED_TO_BAN_USERS);let l=e.body.email.toLowerCase();if(!y.email().safeParse(l).success)throw m.E.from("BAD_REQUEST",h.f.INVALID_EMAIL);if(e.body.password&&(0,p.a)(e,e.body.password),await e.context.internalAdapter.findUserByEmail(l))throw m.E.from("BAD_REQUEST",n.USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL);let c=await e.context.internalAdapter.createUser({...o,email:l,name:e.body.name,role:void 0!==s?A(s):i?.defaultRole??"user"},{method:"admin"});if(!c)throw m.E.from("INTERNAL_SERVER_ERROR",n.FAILED_TO_CREATE_USER);if(e.body.password){let t=await e.context.password.hash(e.body.password);await e.context.internalAdapter.linkAccount({providerId:"credential",accountId:c.id,password:t,userId:c.id})}return e.json({user:(0,t.$)(e.context.options,c)})}),adminUpdateUser:(0,w.g)("/admin/update-user",{method:"POST",body:T,use:[E],metadata:{openapi:{operationId:"adminUpdateUser",summary:"Update a user",description:"Update a user's details",responses:{200:{description:"User updated",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"}}}}}}}}}},async e=>{if(!f({userId:e.context.session.user.id,role:e.context.session.user.role,options:i,permissions:{user:["update"]}}))throw m.E.from("FORBIDDEN",n.YOU_ARE_NOT_ALLOWED_TO_UPDATE_USERS);if(0===Object.keys(e.body.data).length)throw m.E.from("BAD_REQUEST",n.NO_DATA_TO_UPDATE);let r=e.body.data,a=e=>Object.prototype.hasOwnProperty.call(r,e);if(a("password"))throw m.E.from("BAD_REQUEST",n.PASSWORD_CANNOT_BE_UPDATED_VIA_UPDATE_USER);if(a("id"))throw m.E.from("BAD_REQUEST",n.USER_ID_CANNOT_BE_UPDATED);if(Object.prototype.hasOwnProperty.call(e.body.data,"role")){if(!f({userId:e.context.session.user.id,role:e.context.session.user.role,options:i,permissions:{user:["set-role"]}}))throw m.E.from("FORBIDDEN",n.YOU_ARE_NOT_ALLOWED_TO_CHANGE_USERS_ROLE);let t=e.body.data.role,r=Array.isArray(t)?t:[t];for(let e of r){if("string"!=typeof e)throw m.E.from("BAD_REQUEST",n.INVALID_ROLE_TYPE);if(i.roles&&!i.roles[e])throw m.E.from("BAD_REQUEST",n.YOU_ARE_NOT_ALLOWED_TO_SET_NON_EXISTENT_VALUE)}e.body.data.role=A(r)}if(["banned","banReason","banExpires"].some(a)){if(!f({userId:e.context.session.user.id,role:e.context.session.user.role,options:i,permissions:{user:["ban"]}}))throw m.E.from("FORBIDDEN",n.YOU_ARE_NOT_ALLOWED_TO_BAN_USERS);if(!0===r.banned&&e.body.userId===e.context.session.user.id)throw m.E.from("BAD_REQUEST",n.YOU_CANNOT_BAN_YOURSELF)}if(a("email")||a("emailVerified")){if(!f({userId:e.context.session.user.id,role:e.context.session.user.role,options:i,permissions:{user:["set-email"]}}))throw m.E.from("FORBIDDEN",n.YOU_ARE_NOT_ALLOWED_TO_SET_USERS_EMAIL);if(a("email")){let t=String(r.email).toLowerCase();if(!y.email().safeParse(t).success)throw m.E.from("BAD_REQUEST",h.f.INVALID_EMAIL);let i=await e.context.internalAdapter.findUserByEmail(t);if(i&&i.user.id!==e.body.userId)throw m.E.from("BAD_REQUEST",n.USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL);r.email=t}}if((a("phoneNumber")||a("phoneNumberVerified"))&&!f({userId:e.context.session.user.id,role:e.context.session.user.role,options:i,permissions:{user:["set-phone"]}}))throw m.E.from("FORBIDDEN",n.YOU_ARE_NOT_ALLOWED_TO_SET_USERS_PHONE_NUMBER);if(!await e.context.internalAdapter.findUserById(e.body.userId))throw m.E.from("NOT_FOUND",h.f.USER_NOT_FOUND);let o=await e.context.internalAdapter.updateUser(e.body.userId,e.body.data);return!0===r.banned&&await e.context.internalAdapter.deleteUserSessions(e.body.userId),e.json((0,t.$)(e.context.options,o))}),listUsers:(0,w.g)("/admin/list-users",{method:"GET",use:[E],query:v,metadata:{openapi:{operationId:"listUsers",summary:"List users",description:"List users",responses:{200:{description:"List of users",content:{"application/json":{schema:{type:"object",properties:{users:{type:"array",items:{$ref:"#/components/schemas/User"}},total:{type:"number"},limit:{type:"number"},offset:{type:"number"}},required:["users","total"]}}}}}}}},async e=>{let r=e.context.session;if(!f({userId:e.context.session.user.id,role:r.user.role,options:i,permissions:{user:["list"]}}))throw m.E.from("FORBIDDEN",n.YOU_ARE_NOT_ALLOWED_TO_LIST_USERS);let a=[];e.query?.searchValue&&a.push({field:e.query.searchField||"email",operator:e.query.searchOperator||"contains",value:e.query.searchValue}),e.query?.filterValue!==void 0&&a.push({field:e.query.filterField||"email",operator:e.query.filterOperator||"eq",value:e.query.filterValue});try{let r=await e.context.internalAdapter.listUsers(Number(e.query?.limit)||void 0,Number(e.query?.offset)||void 0,e.query?.sortBy?{field:e.query.sortBy,direction:e.query.sortDirection||"asc"}:void 0,a.length?a:void 0),i=await e.context.internalAdapter.countTotalUsers(a.length?a:void 0);return e.json({users:r.map(r=>(0,t.$)(e.context.options,r)),total:i,limit:Number(e.query?.limit)||void 0,offset:Number(e.query?.offset)||void 0})}catch{return e.json({users:[],total:0})}}),listUserSessions:(0,w.g)("/admin/list-user-sessions",{method:"POST",use:[E],body:U,metadata:{openapi:{operationId:"adminListUserSessions",summary:"List user sessions",description:"List user sessions",responses:{200:{description:"List of user sessions",content:{"application/json":{schema:{type:"object",properties:{sessions:{type:"array",items:{$ref:"#/components/schemas/Session"}}}}}}}}}}},async e=>{let r=e.context.session;if(!f({userId:e.context.session.user.id,role:r.user.role,options:i,permissions:{session:["list"]}}))throw m.E.from("FORBIDDEN",n.YOU_ARE_NOT_ALLOWED_TO_LIST_USERS_SESSIONS);let a=await e.context.internalAdapter.listSessions(e.body.userId);return e.json({sessions:a.map(r=>(0,t.Q)(e.context.options,r))})}),unbanUser:(0,w.g)("/admin/unban-user",{method:"POST",body:R,use:[E],metadata:{openapi:{operationId:"unbanUser",summary:"Unban a user",description:"Unban a user",responses:{200:{description:"User unbanned",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"}}}}}}}}}},async e=>{let r=e.context.session;if(!f({userId:e.context.session.user.id,role:r.user.role,options:i,permissions:{user:["ban"]}}))throw m.E.from("FORBIDDEN",n.YOU_ARE_NOT_ALLOWED_TO_BAN_USERS);if(!await e.context.internalAdapter.findUserById(e.body.userId))throw m.E.from("NOT_FOUND",h.f.USER_NOT_FOUND);let a=await e.context.internalAdapter.updateUser(e.body.userId,{banned:!1,banExpires:null,banReason:null,updatedAt:new Date});return e.json({user:(0,t.$)(e.context.options,a)})}),banUser:(0,w.g)("/admin/ban-user",{method:"POST",body:S,use:[E],metadata:{openapi:{operationId:"banUser",summary:"Ban a user",description:"Ban a user",responses:{200:{description:"User banned",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"}}}}}}}}}},async e=>{let r=e.context.session;if(!f({userId:e.context.session.user.id,role:r.user.role,options:i,permissions:{user:["ban"]}}))throw m.E.from("FORBIDDEN",n.YOU_ARE_NOT_ALLOWED_TO_BAN_USERS);if(!await e.context.internalAdapter.findUserById(e.body.userId))throw m.E.from("NOT_FOUND",h.f.USER_NOT_FOUND);if(e.body.userId===e.context.session.user.id)throw m.E.from("BAD_REQUEST",n.YOU_CANNOT_BAN_YOURSELF);let a=await e.context.internalAdapter.updateUser(e.body.userId,{banned:!0,banReason:e.body.banReason||i?.defaultBanReason||"No reason",banExpires:e.body.banExpiresIn?(0,c.f)(e.body.banExpiresIn,"sec"):i?.defaultBanExpiresIn?(0,c.f)(i.defaultBanExpiresIn,"sec"):null,updatedAt:new Date});return await e.context.internalAdapter.deleteUserSessions(e.body.userId),e.json({user:(0,t.$)(e.context.options,a)})}),impersonateUser:(0,w.g)("/admin/impersonate-user",{method:"POST",body:x,use:[E],metadata:{openapi:{operationId:"impersonateUser",summary:"Impersonate a user",description:"Impersonate a user",responses:{200:{description:"Impersonation session created",content:{"application/json":{schema:{type:"object",properties:{session:{$ref:"#/components/schemas/Session"},user:{$ref:"#/components/schemas/User"}}}}}}}}}},async e=>{if(!f({userId:e.context.session.user.id,role:e.context.session.user.role,options:i,permissions:{user:["impersonate"]}}))throw m.E.from("FORBIDDEN",n.YOU_ARE_NOT_ALLOWED_TO_IMPERSONATE_USERS);let r=await e.context.internalAdapter.findUserById(e.body.userId);if(!r)throw m.E.from("NOT_FOUND",h.f.USER_NOT_FOUND);let a=(Array.isArray(i.adminRoles)?i.adminRoles:i.adminRoles?.split(",")||[]).map(e=>e.trim());if(((r.role||i.defaultRole||"user").split(",").some(e=>a.includes(e))||i.adminUserIds?.includes(r.id))&&!(!0===i.allowImpersonatingAdmins||f({userId:e.context.session.user.id,role:e.context.session.user.role,options:i,permissions:{user:["impersonate-admins"]}})))throw m.E.from("FORBIDDEN",n.YOU_CANNOT_IMPERSONATE_ADMINS);let o=await e.context.internalAdapter.createSession(r.id,!0,{impersonatedBy:e.context.session.user.id,expiresAt:i?.impersonationSessionDuration?(0,c.f)(i.impersonationSessionDuration,"sec"):(0,c.f)(3600,"sec")},!0);if(!o)throw m.E.from("INTERNAL_SERVER_ERROR",n.FAILED_TO_CREATE_USER);let s=e.context.authCookies;(0,d.Q)(e);let l=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret),u=e.context.createAuthCookie("admin_session");return await e.setSignedCookie(u.name,`${e.context.session.session.token}:${l||""}`,e.context.secret,s.sessionToken.attributes),await (0,d.V)(e,{session:o,user:r},!0),e.json({session:o,user:(0,t.$)(e.context.options,r)})}),stopImpersonating:(0,w.g)("/admin/stop-impersonating",{method:"POST",requireHeaders:!0},async e=>{let r=await (0,u.D)(e);if(!r)throw m.E.fromStatus("UNAUTHORIZED");if(!r.session.impersonatedBy)throw m.E.fromStatus("BAD_REQUEST",{message:"You are not impersonating anyone"});let i=await e.context.internalAdapter.findUserById(r.session.impersonatedBy);if(!i)throw m.E.fromStatus("INTERNAL_SERVER_ERROR",{message:"Failed to find user"});let a=e.context.createAuthCookie("admin_session"),o=await e.getSignedCookie(a.name,e.context.secret);if(!o)throw m.E.fromStatus("INTERNAL_SERVER_ERROR",{message:"Failed to find admin session"});let[n,s]=o?.split(":"),l=await e.context.internalAdapter.findSession(n);if(!l||l.session.userId!==i.id)throw m.E.fromStatus("INTERNAL_SERVER_ERROR",{message:"Failed to find admin session"});return await e.context.internalAdapter.deleteSession(r.session.token),await (0,d.V)(e,l,!!s),(0,d.c)(e,a),e.json({session:(0,t.Q)(e.context.options,l.session),user:(0,t.$)(e.context.options,l.user)})}),revokeUserSession:(0,w.g)("/admin/revoke-user-session",{method:"POST",body:O,use:[E],metadata:{openapi:{operationId:"revokeUserSession",summary:"Revoke a user session",description:"Revoke a user session",responses:{200:{description:"Session revoked",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async e=>{let t=e.context.session;if(!f({userId:e.context.session.user.id,role:t.user.role,options:i,permissions:{session:["revoke"]}}))throw m.E.from("FORBIDDEN",n.YOU_ARE_NOT_ALLOWED_TO_REVOKE_USERS_SESSIONS);return await e.context.internalAdapter.deleteSession(e.body.sessionToken),e.json({success:!0})}),revokeUserSessions:(0,w.g)("/admin/revoke-user-sessions",{method:"POST",body:D,use:[E],metadata:{openapi:{operationId:"revokeUserSessions",summary:"Revoke all user sessions",description:"Revoke all user sessions",responses:{200:{description:"Sessions revoked",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async e=>{let t=e.context.session;if(!f({userId:e.context.session.user.id,role:t.user.role,options:i,permissions:{session:["revoke"]}}))throw m.E.from("FORBIDDEN",n.YOU_ARE_NOT_ALLOWED_TO_REVOKE_USERS_SESSIONS);return await e.context.internalAdapter.deleteUserSessions(e.body.userId),e.json({success:!0})}),removeUser:(0,w.g)("/admin/remove-user",{method:"POST",body:N,use:[E],metadata:{openapi:{operationId:"removeUser",summary:"Remove a user",description:"Delete a user and all their sessions and accounts. Cannot be undone.",responses:{200:{description:"User removed",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async e=>{let t=e.context.session;if(!f({userId:e.context.session.user.id,role:t.user.role,options:i,permissions:{user:["delete"]}}))throw m.E.from("FORBIDDEN",n.YOU_ARE_NOT_ALLOWED_TO_DELETE_USERS);if(e.body.userId===e.context.session.user.id)throw m.E.from("BAD_REQUEST",n.YOU_CANNOT_REMOVE_YOURSELF);if(!await e.context.internalAdapter.findUserById(e.body.userId))throw m.E.from("NOT_FOUND",h.f.USER_NOT_FOUND);return await e.context.internalAdapter.deleteUserSessions(e.body.userId),await e.context.internalAdapter.deleteUser(e.body.userId),e.json({success:!0})}),setUserPassword:(0,w.g)("/admin/set-user-password",{method:"POST",body:L,use:[E],metadata:{openapi:{operationId:"setUserPassword",summary:"Set a user's password",description:"Set a user's password",responses:{200:{description:"Password set",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{if(!f({userId:e.context.session.user.id,role:e.context.session.user.role,options:i,permissions:{user:["set-password"]}}))throw m.E.from("FORBIDDEN",n.YOU_ARE_NOT_ALLOWED_TO_SET_USERS_PASSWORD);let{newPassword:t,userId:r}=e.body;(0,p.b)(e,t),(0,p.a)(e,t);let a=await e.context.internalAdapter.findUserById(r);if(!a)throw m.E.from("NOT_FOUND",h.f.USER_NOT_FOUND);let o=await e.context.password.hash(t);return await e.context.internalAdapter.findCredentialAccount(r)?await e.context.internalAdapter.updatePassword(r,o):await e.context.internalAdapter.createAccount({userId:r,providerId:"credential",accountId:a.id,password:o}),e.json({status:!0})}),userHasPermission:(0,w.g)("/admin/has-permission",{method:"POST",body:P,metadata:{openapi:{description:"Check if the user has permission",requestBody:{content:{"application/json":{schema:{type:"object",properties:{permissions:{type:"object",description:"The permission to check"}},required:["permissions"]}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{error:{type:"string"},success:{type:"boolean"}},required:["success"]}}}}}},$Infer:{body:{}}}},async e=>{if(!e.body?.permissions)throw new m.E("BAD_REQUEST",{message:"invalid permission check. no permission(s) were passed."});let t=await (0,u.M)(e);if(!t&&(e.request||e.headers))throw new m.E("UNAUTHORIZED");if(!t&&!e.body.userId&&!e.body.role)throw new m.E("BAD_REQUEST",{message:"user id or role is required"});let r=t?.user||(e.body.role?{id:e.body.userId||"",role:e.body.role}:null)||(e.body.userId?await e.context.internalAdapter.findUserById(e.body.userId):null);if(!r)throw new m.E("BAD_REQUEST",{message:"user not found"});let a=f({userId:r.id,role:r.role,options:i,permissions:e.body.permissions});return e.json({error:null,success:a})})},$ERROR_CODES:n,schema:(0,t.C)(C,i.schema),options:e}}],483052);var q=e.i(46754);e.i(418069);var j=e.i(444336),$=e.i(35972);function B(e){try{return decodeURIComponent(e)}catch{return e}}e.s(["f",0,e=>({id:"bearer",version:r.f,hooks:{before:[{matcher:e=>!!(e.request?.headers.get("authorization")||e.headers?.get("authorization")),handler:(0,w.a)(async t=>{let r,i=t.request?.headers.get("authorization")||t.headers?.get("Authorization");if(!i||"bearer "!==i.slice(0,7).toLowerCase())return;let a=i.slice(7).trim();if(!a)return;if(a.includes("."))r=a.includes("%")?B(a):a;else{if(e?.requireSignature)return;r=B((await (0,j.k)("",a,t.context.secret)).replace("=",""))}try{if(!await (0,$.f)("SHA-256","base64urlnopad").verify(t.context.secret,r.split(".")[0],r.split(".")[1]))return}catch{return}let o=t.request?.headers||t.headers,n=new Headers({...Object.fromEntries(o?.entries())});return(0,q.K)(n,t.context.authCookies.sessionToken.name,r),{context:{headers:n}}})}],after:[{matcher:e=>!0,handler:(0,w.a)(async e=>{let t=e.context.responseHeaders?.get("set-cookie");if(!t)return;let r=(0,q.p)(t),i=e.context.authCookies.sessionToken.name,a=r.get(i);if(!a||!a.value||0===a["max-age"])return;let o=a.value,n=new Set((e.context.responseHeaders?.get("access-control-expose-headers")||"").split(",").map(e=>e.trim()).filter(Boolean));n.add("set-auth-token"),e.setHeader("set-auth-token",o),e.setHeader("Access-Control-Expose-Headers",Array.from(n).join(", "))})}]},options:e})],13681);var V=e.i(342e3);let M=(0,o.f)({INVALID_OAUTH_CONFIGURATION:"Invalid OAuth configuration",TOKEN_URL_NOT_FOUND:"Invalid OAuth configuration. Token URL not found."});var F=e.i(533078),K=e.i(878175);e.i(339507);var z=e.i(945e3),H=e.i(729522),W=e.i(661372),Y=e.i(374091),Q=e.i(100762),G=e.i(550064);let J=e=>{try{return(0,K.f)(e)}catch{return null}};async function Z(e,t,r){let i=await (0,F.f)(e,{method:"GET",headers:t,signal:r?AbortSignal.timeout(r):void 0});if(i.error||!i.data)return null;if(i.data.issuer)try{new URL(i.data.issuer)}catch{return null}return i.data}async function X(e,t,r){if(e.idToken){let t=r??J(e.idToken);if(t?.sub&&t?.email)return{id:t.sub,emailVerified:(0,V.f)(t.email_verified),image:t.picture,...t}}if(!t||!e.accessToken)return null;let i=await (0,F.f)(t,{method:"GET",headers:{Authorization:`Bearer ${e.accessToken}`}});return i.error||!i.data?null:{...i.data,email:i.data.email,emailVerified:(0,V.f)(i.data.email_verified),image:i.data.picture,name:i.data.name}}e.s(["f",0,e=>{let t=new Set,i=new Set;for(let r of e.config){let e=r.providerId;t.has(e)&&i.add(e),t.add(e)}i.size>0&&console.warn(`Duplicate provider IDs found: ${Array.from(i).join(", ")}`);let a=async(e,t,r)=>{let i=[];for(let a of e){let e,o,n=a.authorizationUrl,s=a.tokenUrl,l=a.userInfoUrl,c=a.endSessionEndpoint,d=!1;if(a.discoveryUrl){let i=await Z(a.discoveryUrl,a.discoveryHeaders,r).catch(e=>(t.logger.error(`Discovery fetch failed for "${a.providerId}": ${e}`),null));if(i){n??=i.authorization_endpoint,s??=i.token_endpoint,l??=i.userinfo_endpoint,c??=i.end_session_endpoint,e=i.issuer;let r=i.id_token_signing_alg_values_supported;if(d=Array.isArray(r)&&r.length>0,i.jwks_uri&&i.issuer){let e;try{e=new URL(i.jwks_uri,a.discoveryUrl)}catch{t.logger.error(`Provider "${a.providerId}": invalid jwks_uri "${i.jwks_uri}" in discovery document. Provider skipped.`);continue}o={jwks:(0,G.R)(e),issuer:i.issuer,audience:a.clientId,algorithms:d?r:void 0}}}if(!n||!s&&!a.getToken){t.logger.error(`Provider "${a.providerId}": discovery left no usable authorization endpoint or token exchange. Provider skipped.`);continue}}if(a.requireIdTokenVerification&&!o){if(a.discoveryUrl){t.logger.error(`Provider "${a.providerId}": requires verified ID tokens, but discovery did not provide a usable issuer and jwks_uri. Provider skipped.`);continue}throw Error(`Provider "${a.providerId}": requires verified ID tokens, but discovery did not provide a usable issuer and jwks_uri.`)}let u=a.tokenEndpointAuth;if(a.clientSecret&&(u?.method==="private_key_jwt"||u?.method==="none"))throw Error(`Provider "${a.providerId}": tokenEndpointAuth.method "${u?.method}" cannot be combined with clientSecret`);if(!a.clientSecret&&(u?.method==="client_secret_basic"||u?.method==="client_secret_post"))throw Error(`Provider "${a.providerId}": tokenEndpointAuth.method "${u?.method}" requires clientSecret`);if(!a.clientSecret&&!u&&"basic"===a.authentication)throw Error(`Provider "${a.providerId}": authentication "basic" requires clientSecret`);let p=async(e,t)=>{let r=a.getUserInfo?await a.getUserInfo(e):await X(e,l,t);if(!r)return null;let i=!a.getUserInfo||null!=r.sub;if(t?.sub!==void 0&&i&&String(r.sub)!==t.sub)return null;let o=a.mapProfileToUser?await a.mapProfileToUser(r):{},n={email:r.email,emailVerified:(0,V.f)(r.emailVerified),image:r.image,name:r.name,...o};return{user:{...n,image:n.image??void 0},data:r}},f=a.accountSubject,h={id:a.providerId,name:a.name??a.providerId,issuer:e,accountSubject:({tokens:e,profile:t})=>f?f({tokens:e,profile:t}):d?o&&e.idToken?J(e.idToken)?.sub??"":t.sub??"":t.id??"",idToken:o,requiresIdTokenNonce:void 0!==o&&!0!==a.disableIdTokenNonceBinding,allowIdpInitiated:a.allowIdpInitiated,async createEndSessionURL(e){let r;if(a.disableProviderLogout||!c)return null;try{r=new URL(c)}catch{return null}e.idToken&&r.searchParams.set("id_token_hint",e.idToken);let i=e.postLogoutRedirectURI??a.postLogoutRedirectURI,o=i?new URL(i,t.baseURL).toString():void 0;return o?(r.searchParams.set("post_logout_redirect_uri",o),r.searchParams.set("client_id",a.clientId),e.state&&r.searchParams.set("state",e.state)):e.idToken||r.searchParams.set("client_id",a.clientId),r},createAuthorizationURL(e){if(!n)throw m.E.from("BAD_REQUEST",M.INVALID_OAUTH_CONFIGURATION);return(0,H.V)({id:a.providerId,options:{clientId:a.clientId,clientSecret:a.clientSecret,redirectURI:a.redirectURI},authorizationEndpoint:n,state:e.state,codeVerifier:a.pkce??!0?e.codeVerifier:void 0,scopes:(()=>{let t=[...e.scopes??[],...a.scopes??[]];return d&&!t.includes("openid")&&t.unshift("openid"),t})(),redirectURI:e.redirectURI,prompt:a.prompt,accessType:a.accessType,responseType:a.responseType,responseMode:a.responseMode,nonce:e.idTokenNonce,additionalParams:{...a.authorizationUrlParams??{},...e.additionalParams??{}},loginHint:e.loginHint})},async validateAuthorizationCode(e){if(a.getToken)return(0,z.O)(await a.getToken(e),a.accessTokenExpiresIn);if(!s)throw m.E.from("BAD_REQUEST",M.TOKEN_URL_NOT_FOUND);let t=await (0,Y.M)({headers:a.authorizationHeaders,code:e.code,codeVerifier:a.pkce??!0?e.codeVerifier:void 0,redirectURI:e.redirectURI,options:{clientId:a.clientId,clientSecret:a.clientSecret,redirectURI:a.redirectURI},tokenEndpoint:s,authentication:a.authentication,tokenEndpointAuth:u,additionalParams:a.tokenUrlParams});return(0,z.O)(t,a.accessTokenExpiresIn)},async getUserInfoFromIdToken(e){let t=h.idToken?J(e):void 0;return null===t?null:p({idToken:e},t)},async getUserInfo(e){let{expectedIdTokenNonce:r,...i}=e;if(!i.idToken||!h.idToken)return p(i);let o=await (0,Q.n)(h,i.idToken,r)?J(i.idToken):null;return o?p(i,o):(t.logger.error(`Provider "${a.providerId}": id_token failed verification against the discovery JWKS or expected nonce`),null)},async refreshAccessToken(e,t){if(!s)throw m.E.from("BAD_REQUEST",M.TOKEN_URL_NOT_FOUND);let r="function"==typeof a.refreshTokenParams?await a.refreshTokenParams(t):a.refreshTokenParams,i=await (0,W.f)({refreshToken:e,options:{clientId:a.clientId,clientSecret:a.clientSecret},authentication:a.authentication,tokenEndpointAuth:u,tokenEndpoint:s,extraParams:r});return(0,z.O)(i,a.accessTokenExpiresIn)},disableImplicitSignUp:a.disableImplicitSignUp,disableSignUp:a.disableSignUp,options:{disableSignUp:a.disableSignUp,overrideUserInfoOnSignIn:a.overrideUserInfo,requireEmailVerification:a.requireEmailVerification}};i.push(h)}return i},o=e=>{let t=e.body?.provider??e.body?.providerId??e.query?.provider??e.params?.id;return"string"==typeof t?t:void 0};return{id:"generic-oauth",version:r.f,init:async t=>{let r=await a(e.config,t),i=new Set(r.map(e=>e.id)),o=new Map(e.config.filter(e=>!i.has(e.providerId)).map(e=>[e.providerId,{config:e}])),n=new Set(t.socialProviders.map(e=>e.id));for(let e of r)n.has(e.id)&&t.logger.warn(`Generic OAuth provider "${e.id}" shadows a built-in social provider with the same ID`);return{context:{socialProviders:r.concat(t.socialProviders),genericOAuthPendingDiscovery:o}}},hooks:{before:[{matcher:e=>e.context.genericOAuthPendingDiscovery?.has(o(e)??"")===!0,handler:(0,w.a)(async e=>{await ((e,t)=>{let r=e.genericOAuthPendingDiscovery,i=r?.get(t);if(i)return i.attempt??=a([i.config],e,1e4).then(([i])=>{i&&(r?.delete(t),e.socialProviders.unshift(i))}).finally(()=>{i.attempt=void 0}),i.attempt})(e.context,o(e)??"")})}]},options:e,$ERROR_CODES:M}}],58260);var ee=e.i(51144),et=e.i(530501),er=e.i(282318);let ei=async e=>{let t=await (0,er.f)("SHA-256").digest(new TextEncoder().encode(e));return et.W.encode(new Uint8Array(t),{padding:!1})},ea=y.object({token:y.string().meta({description:'The token to verify. Eg: "some-token"'})});e.s(["f",0,e=>{let t={storeToken:"plain",...e};async function i(e,r){return"hashed"===t.storeToken?await ei(r):"object"==typeof t.storeToken&&"type"in t.storeToken&&"custom-hasher"===t.storeToken.type?await t.storeToken.hash(r):r}async function a(e,r){let a=t?.generateToken?await t.generateToken(r,e):(0,ee.f)(32),o=new Date(Date.now()+(t?.expiresIn??3)*6e4),n=await i(e,a);return await e.context.internalAdapter.createVerificationValue({value:r.session.token,identifier:`one-time-token:${n}`,expiresAt:o}),a}return{id:"one-time-token",version:r.f,endpoints:{generateOneTimeToken:(0,w.g)("/one-time-token/generate",{method:"GET",use:[u.Z]},async e=>{if(t?.disableClientRequest&&e.request)throw e.error("BAD_REQUEST",{message:"Client requests are disabled"});let r=e.context.session,i=await a(e,r);return e.json({token:i})}),verifyOneTimeToken:(0,w.g)("/one-time-token/verify",{method:"POST",body:ea},async e=>{let{token:r}=e.body,a=await i(e,r),o=await e.context.internalAdapter.consumeVerificationValue(`one-time-token:${a}`);if(!o)throw e.error("BAD_REQUEST",{message:"Invalid token"});let n=await e.context.internalAdapter.findSession(o.value);if(!n)throw e.error("BAD_REQUEST",{message:"Session not found"});if(t?.disableSetSessionCookie||await (0,d.V)(e,n),n.session.expiresAt<new Date)throw e.error("BAD_REQUEST",{message:"Session expired"});return e.json(n)})},hooks:{after:[{matcher:()=>!0,handler:(0,w.a)(async e=>{if(e.context.newSession){if(!t?.setOttHeaderOnNewSession)return;let r=new Set((e.context.responseHeaders?.get("access-control-expose-headers")||"").split(",").map(e=>e.trim()).filter(Boolean));r.add("set-ott");let i=await a(e,e.context.newSession);e.setHeader("set-ott",i),e.setHeader("Access-Control-Expose-Headers",Array.from(r).join(", "))}})}]},options:e}}],292243);var eo=e.i(303361),en=e.i(187126);function es(e,t){return e[t]?.trim()||void 0}function el(e,t){let r=es(e,t);if(!r)throw Error(`${t} is required for AUTH_MODE.`);return r}e.s(["L",0,function(e=process.env){let t=function(e){let t=es(e,"AUTH_MODE")??"password";if("password"!==t&&"oidc"!==t&&"both"!==t)throw Error('AUTH_MODE must be "password", "oidc", or "both".');return t}(e),r=(0,eo.U)(e);return{secret:(0,en.h)(e).authSecret,origins:r,baseURL:r.canonical,trustProxyHeaders:function(e){let t=es(e,"TRUST_PROXY_HEADERS")?.toLowerCase();if(!t||"false"===t||"0"===t)return!1;if("true"===t||"1"===t)return!0;throw Error("TRUST_PROXY_HEADERS must be true, false, 1, or 0.")}(e),mode:t,provider:function(e,t){if("password"===t)return null;let r=es(e,"AUTH_OAUTH_DISCOVERY_URL"),i=es(e,"AUTH_OAUTH_AUTHORIZATION_URL"),a=es(e,"AUTH_OAUTH_TOKEN_URL"),o=es(e,"AUTH_OAUTH_USER_INFO_URL"),n=es(e,"AUTH_OAUTH_ISSUER"),s=!!(i||a||o),l=i&&a&&o;if(r&&s)throw Error("OIDC configuration must use either discovery or explicit endpoints, not both.");if(!r&&!l)throw Error("OIDC authentication requires AUTH_OAUTH_DISCOVERY_URL or all of AUTH_OAUTH_AUTHORIZATION_URL, AUTH_OAUTH_TOKEN_URL, and AUTH_OAUTH_USER_INFO_URL.");if(s&&!l)throw Error("Explicit OAuth configuration must include authorization, token, and user-info URLs.");if(l&&!n)throw Error("AUTH_OAUTH_ISSUER is required with explicit OAuth endpoints.");let c=el(e,"AUTH_OAUTH_SCOPES").split(",").map(e=>e.trim()).filter(Boolean);if(0===c.length)throw Error("AUTH_OAUTH_SCOPES must contain at least one scope.");return{providerId:el(e,"AUTH_OAUTH_PROVIDER_ID"),displayName:el(e,"AUTH_OAUTH_PROVIDER_NAME"),clientId:el(e,"AUTH_OAUTH_CLIENT_ID"),clientSecret:el(e,"AUTH_OAUTH_CLIENT_SECRET"),scopes:c,requireIssuerValidation:function(e){let t=es(e,"AUTH_OAUTH_REQUIRE_ISSUER_VALIDATION")?.toLowerCase();if(!t||"false"===t||"0"===t)return!1;if("true"===t||"1"===t)return!0;throw Error("AUTH_OAUTH_REQUIRE_ISSUER_VALIDATION must be true, false, 1, or 0.")}(e),discoveryUrl:r,issuer:n,authorizationUrl:i,tokenUrl:a,userInfoUrl:o}}(e,t)}},"_",0,function(e){return"oidc"===e||"both"===e},"Z",0,function(e){return"password"===e||"both"===e}],169040);var ec=e.i(812057);let ed=RegExp(String.raw`((?:"?(?:authorization|password|access[_-]?token|refresh[_-]?token|id[_-]?token|session[_-]?token|client[_-]?secret|client_assertion|code_verifier|code|token|secret|privateKey)"?)\s*:\s*)(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^,\n}\]]+)`,"gi");function eu(e){return e.replace(ed,'$1"[REDACTED]"').replace(/\b(Bearer|DPoP)\s+[A-Za-z0-9._~+\/-]+/gi,"$1 [REDACTED]").replace(/([?&](?:access_token|refresh_token|client_secret|code|code_verifier)=)[^&\s]+/gi,"$1[REDACTED]")}function ep(e){return"string"==typeof e&&e.length>0?e:void 0}async function ef(e,t){try{return await fetch(e,{headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${t}`,"User-Agent":"AI-Development-Environment"}})}catch{return null}}async function em(e,t){let r,i=await ef(e,t);if(!i?.ok)return null;let a=await i.json(),o=ep(a.email),n=await ef(((r=new URL(e)).pathname=`${r.pathname.replace(/\/$/,"")}/emails`,r.toString()),t),s=n?.ok?await n.json():[],l=Array.isArray(s)?s:[],c=l.find(e=>!0===e.primary)??l[0],d=o??ep(c?.email),u=l.find(e=>ep(e.email)===d);return{...a,email:d,emailVerified:u?.verified===!0,image:ep(a.avatar_url),name:ep(a.name)??ep(a.login)??""}}e.s(["f",0,function(e,t,...r){let i=[`${new Date().toISOString()} ${e.toUpperCase()} [Better Auth]: ${t}`,...r.map(e=>"string"==typeof e?e:(0,ec.inspect)(e,{depth:6,breakLength:120}))].map(eu);"error"===e?console.error(...i):"warn"===e?console.warn(...i):console.log(...i)}],789714),e.s(["f",0,em],782393);var eh=e.i(666680),eg=e.i(243783);let ew="default";async function ey(){let e=await (0,eg.U)();return await e.authSettings.findUnique({where:{id:ew}})??await e.authSettings.upsert({where:{id:ew},create:{id:ew},update:{}})}async function eb(){let e=await (0,eg.U)(),[t,r]=await Promise.all([ey(),e.user.count()]);return t.bootstrapCompleted||0!==r?!t.bootstrapCompleted&&r>0?(await e.authSettings.update({where:{id:ew},data:{bootstrapCompleted:!0,registrationEnabled:!1,bootstrapClaimId:null,bootstrapClaimedAt:null}}),{enabled:!1,setupRequired:!1}):{enabled:t.registrationEnabled,setupRequired:!1}:{enabled:!0,setupRequired:!0}}async function eE(e){let t=await (0,eg.U)();if(0===await t.user.count())throw new m.E("BAD_REQUEST",{message:"Create the initial account before changing registration."});await t.authSettings.upsert({where:{id:ew},create:{id:ew,bootstrapCompleted:!0,registrationEnabled:e},update:{registrationEnabled:e}})}async function eA(e,t){if(e===t)throw new m.E("BAD_REQUEST",{message:"You cannot delete the account you are currently using."});let r=await (0,eg.U)();if(1!==await r.$executeRaw`
|
|
451
451
|
DELETE FROM "user"
|
|
452
452
|
WHERE "id" = ${e}
|
|
453
453
|
AND (SELECT COUNT(*) FROM "user") > 1
|
|
454
|
-
`){if(!await r.user.findUnique({where:{id:e},select:{id:!0}}))throw new m.E("NOT_FOUND",{message:"User not found."});throw new m.E("BAD_REQUEST",{message:"The final account cannot be deleted."})}}async function eI({allowWhenRegistrationClosed:e=!1}={}){let t=await (0,eg.U)(),r=await ey();if(r.bootstrapCompleted){if(!r.registrationEnabled&&!e)throw new m.E("FORBIDDEN",{message:"Account registration is disabled."});return}if(await t.user.count()>0){if(await t.authSettings.update({where:{id:ew},data:{bootstrapCompleted:!0,registrationEnabled:!1,bootstrapClaimId:null,bootstrapClaimedAt:null}}),e)return;throw new m.E("FORBIDDEN",{message:"Account registration is disabled."})}let i=new Date(Date.now()-18e4),a=(0,eh.randomUUID)();if(1!==(await t.authSettings.updateMany({where:{id:ew,bootstrapCompleted:!1,OR:[{bootstrapClaimedAt:null},{bootstrapClaimedAt:{lt:i}}]},data:{bootstrapClaimId:a,bootstrapClaimedAt:new Date}})).count)throw new m.E("CONFLICT",{message:"The initial account is already being created. Try again shortly."})}async function e_(){let e=await (0,eg.U)();await e.authSettings.updateMany({where:{id:ew,bootstrapCompleted:!1},data:{bootstrapCompleted:!0,registrationEnabled:!1,bootstrapClaimId:null,bootstrapClaimedAt:null}})}function ek(e,t){let r=e[t]?.trim().toLowerCase();if(!r||"false"===r||"0"===r)return!1;if("true"===r||"1"===r)return!0;throw Error(`${t} must be true, false, 1, or 0.`)}e.s(["x",0,{user:{create:{before:async(e,t)=>(await eI({allowWhenRegistrationClosed:t?.path?.includes("/admin/create-user")??!1}),{data:{...e,role:"user",banned:!1,banReason:null,banExpires:null}}),after:async()=>{await e_()}},update:{before:async e=>({data:{...e,role:"user",banned:!1,banReason:null,banExpires:null}})},delete:{before:async()=>{throw new m.E("BAD_REQUEST",{message:"Accounts must be deleted through the management API."})}}}},"J",0,eA,"w",0,eb,"T",0,eE],464661),e.s(["f",0,function(e=process.env){if(!ek(e,"MCP_OAUTH_ENABLED"))return null;if(!e.PUBLIC_BASE_URL?.trim()&&!e.APP_ORIGINS?.trim())throw Error("MCP OAuth requires a configured canonical PUBLIC_BASE_URL or APP_ORIGINS.");let t=(0,eo.U)(e),r=e.APP_ORIGINS?.split(",").map(e=>e.trim()).filter(Boolean).map(eo.Y).find(e=>!e.wildcard),i=e.PUBLIC_BASE_URL?.trim()?t.canonical:r?`${r.protocol??(r.loopback?"http:":"https:")}//${r.host}`:null;if(!i)throw Error("MCP OAuth requires an exact canonical origin.");let a=new URL(i),o="localhost"===a.hostname||a.hostname.endsWith(".localhost")||"[::1]"===a.hostname||/^127\./.test(a.hostname);if("https:"!==a.protocol&&!("http:"===a.protocol&&o))throw Error("MCP OAuth requires HTTPS except on loopback development origins.");return{origin:a.origin,issuer:`${a.origin}/api/auth`,resource:`${a.origin}/api/mcp`,dcrEnabled:ek(e,"MCP_OAUTH_DCR_ENABLED")}}],320170);var eT=e.i(278706),eT=eT,ev=e.i(252524),ev=ev,eU=ev,eR=ev,ex=ev,eS=e.i(455659),eO=e.i(783968),eD=e.i(661573),eN=e.i(947448);let eL=/\/(?:\.|%2e)(?:\.|%2e)?(?:\/|$|#|\?)/i,eP=new Set(["client_secret_post","client_secret_basic","client_secret_jwt"]);function eC(e){let t;try{t=new URL(e)}catch{return!1}return"https:"===t.protocol}let eq=/^application\/(?:[-\w.]+\+)?json\s*(?:;|$)/i,ej="Failed to fetch metadata document (network error or redirect blocked)",e$="cimd";function eB(e){return new eS.E("BAD_REQUEST",{error:"invalid_client",error_description:e})}function eV(){return eB("Metadata document exceeds 5KB size limit")}async function eM(e,t,r){let i,a=e.body?.getReader();if(!a){let r=await e.text();if(new TextEncoder().encode(r).byteLength>t)throw eV();return r}let o=[],n=0,s=new Promise((e,t)=>{i=t}),l=()=>{i?.(Error("Metadata document body read aborted")),a.cancel().catch(()=>{})};r.aborted?l():r.addEventListener("abort",l,{once:!0});try{for(;;){let{done:e,value:r}=await Promise.race([a.read(),s]);if(e)break;if((n+=r.byteLength)>t)throw await a.cancel(),eV();o.push(r)}}finally{r.removeEventListener("abort",l),a.releaseLock()}let c=new Uint8Array(n),d=0;for(let e of o)c.set(e,d),d+=e.byteLength;return new TextDecoder().decode(c)}async function eF(e,t,r,i){let a,o=function(e){let t;if(eL.test(e))return"client_id URL MUST NOT contain dot segments";if(e.includes("#"))return"client_id URL MUST NOT contain a fragment";try{t=new URL(e)}catch{return"client_id is not a valid URL"}if("https:"!==t.protocol)return"client_id URL must use HTTPS";let r=/^https:\/\//i.exec(e);if(!r||e.includes("\\"))return"client_id URL MUST use an explicit HTTPS authority form";let i=e.slice(r[0].length),a=i.search(/[/?#]/);return 0===a?"client_id URL MUST use an explicit HTTPS authority form":a<0||"/"!==i[a]?"client_id URL MUST contain an explicit path component":t.username||t.password?"client_id URL MUST NOT contain credentials":(0,eO.$)(t.hostname)?null:"client_id URL must not target a private or reserved address"}(t);if(o)throw eB(o);if(r.isMetadataDocumentUrlAllowed&&!await r.isMetadataDocumentUrlAllowed(t,e))throw eB("client_id URL is not permitted by the server's fetch policy");let n=new Headers({Accept:"application/json"});i?.etag&&n.set("If-None-Match",i.etag),i?.lastModified&&n.set("If-Modified-Since",i.lastModified);let s=new AbortController,l=!1,c=setTimeout(()=>{l=!0,s.abort()},5e3);try{var d;let o,c;try{a=await r.fetchClientMetadataResource(t,{headers:n,redirect:"error",signal:s.signal})}catch{throw eB(l?"Metadata document fetch timed out after 5000ms":ej)}if(a.redirected)throw eB("Metadata document fetch must not follow redirects");let u={cacheControl:(d=a.headers).get("cache-control")??void 0,vary:d.get("vary")??void 0,expires:d.get("expires")??void 0,date:d.get("date")??void 0,age:d.get("age")??void 0,etag:d.get("etag")??void 0,lastModified:d.get("last-modified")??void 0};if(304===a.status){if(!i?.etag&&!i?.lastModified)throw eB("Metadata document returned 304 without a conditional validator");return{status:"not-modified",cacheHeaders:u}}if(200!==a.status)throw eB(`Metadata document fetch returned HTTP ${a.status}`);let p=a.headers.get("content-type")??"";if(!eq.test(p))throw eB(`Metadata document must be JSON (got Content-Type "${p||"(none)"}")`);try{let e=a.headers.get("content-length");if(e){let t=Number.parseInt(e,10);if(Number.isFinite(t)&&t>5120)throw await a.body?.cancel(),eV()}o=await eM(a,5120,s.signal)}catch(e){if(l)throw eB("Metadata document fetch timed out after 5000ms");if(e instanceof eS.E)throw e;throw eB(ej)}try{c=JSON.parse(o)}catch{throw eB("Metadata document is not valid JSON")}let f=function(e,t,r={}){let i;if(!t||"object"!=typeof t)return{valid:!1,error:"metadata document is not a JSON object"};for(let e of Object.keys(t))if((0,eU.c)(e))return{valid:!1,error:`metadata document MUST NOT contain "${e}"`};let a=ev.b.strip().safeParse(t);if(!a.success){let e=a.error.issues[0];return{valid:!1,error:`${e?.path.join(".")||"metadata document"}: ${e?.message??"invalid client metadata"}`}}let o=a.data,n=[];if(o.client_id!==e)return{valid:!1,error:`client_id "${String(o.client_id)}" does not match the metadata document URL`};if("mcp-2026-07-28"===r.metadataProfile&&!o.client_name?.trim())return{valid:!1,error:"client_name must be a non-empty string"};for(let e of["backchannel_logout_uri","backchannel_logout_session_required"])if(void 0!==o[e])return{valid:!1,error:`metadata document MUST NOT contain "${e}"`};let s=new Set(["none","private_key_jwt"]);if("string"==typeof o.token_endpoint_auth_method){if(eP.has(o.token_endpoint_auth_method))return{valid:!1,error:`symmetric auth method "${o.token_endpoint_auth_method}" is prohibited for Client ID Metadata Document clients`};if(!s.has(o.token_endpoint_auth_method))return{valid:!1,error:'token_endpoint_auth_method must be "none" or "private_key_jwt" for Client ID Metadata Document clients'};if("private_key_jwt"===o.token_endpoint_auth_method&&!o.jwks&&!o.jwks_uri)return{valid:!1,error:"private_key_jwt requires either jwks or jwks_uri in the metadata document"}}if(o.jwks&&!(0,ex.l)(o.jwks).valid)return{valid:!1,error:"jwks must contain only structurally valid public keys"};if(o.jwks_uri)try{let e=new URL(o.jwks_uri);if(e.username||e.password)return{valid:!1,error:"jwks_uri must not contain credentials"};if(o.jwks_uri.includes("#"))return{valid:!1,error:"jwks_uri must not contain a fragment"}}catch{return{valid:!1,error:"jwks_uri must be a valid URL"}}if("mcp-2026-07-28"===r.metadataProfile&&!o.redirect_uris||o.redirect_uris&&!o.redirect_uris.every(e=>(function(e){try{let t=new URL(e);return"http:"===t.protocol||"https:"===t.protocol||(0,eD.Y)(t)}catch{return!1}})(e)))return{valid:!1,error:"redirect_uris must be a non-empty array of absolute HTTP(S) or private-use URIs"};for(let e of["client_uri","logo_uri","tos_uri","policy_uri"]){if(void 0!==o[e]&&"string"!=typeof o[e])return{valid:!1,error:`${e} must be a string`};if("string"==typeof o[e])try{let t=new URL(o[e]);if("https:"!==t.protocol&&"http:"!==t.protocol)return{valid:!1,error:`${e} must use HTTP(S)`};if(t.username||t.password)return{valid:!1,error:`${e} must not contain credentials`};if(!(0,eO.$)(t.hostname))return{valid:!1,error:`${e} must not point to a private or reserved address`}}catch{return{valid:!1,error:`${e} is not a valid URL`}}}let l=r.originBoundFields??["post_logout_redirect_uris","client_uri"];try{i=new URL(e).origin}catch{return{valid:!1,error:"client_id is not a valid URL"}}for(let e of l){let t,r=o[e];if(void 0!==r){if("string"==typeof r)t=[r];else{if(!Array.isArray(r)||!r.every(e=>"string"==typeof e))return{valid:!1,error:`${e} must be a string or an array of strings`};t=r}for(let r of t){let t;try{t=new URL(r)}catch{return{valid:!1,error:`${e} contains an invalid URL: "${r}"`}}let a="redirect_uris"===e||"post_logout_redirect_uris"===e,o=a&&(0,eD.Y)(t);if("https:"!==t.protocol&&"http:"!==t.protocol&&!o)return{valid:!1,error:`all values for ${e} must use HTTP(S) or a private-use scheme`};if(o&&("redirect_uris"===e||(0,eD.a)(t)))continue;let n=a&&("http:"===t.protocol||"https:"===t.protocol)&&(0,eO.g)(t.hostname);if(t.origin!==i&&!n)return{valid:!1,error:`${e} value "${r}" must have the same origin as client_id (${i})`}}}}return n.push(...function(e){let t=[];try{let r=new URL(e);"/"===r.pathname&&t.push("client_id URL path / is NOT RECOMMENDED (§3)"),r.search&&t.push("client_id URL SHOULD NOT contain a query string (§3)")}catch{}return t}(e)),{valid:!0,metadata:{...o,token_endpoint_auth_method:o.token_endpoint_auth_method??"none"},...n.length>0?{warnings:n}:{}}}(t,c,{originBoundFields:r.originBoundFields,metadataProfile:r.metadataProfile});if(!f.valid)throw eB(f.error);for(let t of f.warnings??[])e.context.logger.warn(`cimd metadata document warning: ${t}`);return{status:"modified",metadata:f.metadata,cacheHeaders:u}}finally{clearTimeout(c)}}async function eK(e,t,r,i,a,o){let n=o?{...o}:void 0,s=await (0,eR.a)(e,a,{clientId:t,clientDiscoveryId:e$,metadata:{...r,client_id:r.client_id,redirect_uris:r.redirect_uris??[]},existingClient:o});if(s.created)try{await i.onClientCreated?.({client:s.client,clientMetadataDocument:r,context:e})}catch(t){e.context.logger.error("cimd onClientCreated notification failed",t)}else try{n&&await i.onClientRefreshed?.({client:s.client,previousClient:n,clientMetadataDocument:r,context:e})}catch(t){e.context.logger.error("cimd onClientRefreshed notification failed",t)}return s.client}function ez(e){return new eS.E("TOO_MANY_REQUESTS",{error:"temporarily_unavailable",error_description:e})}function eH(e,t){if(!Number.isInteger(e)||e<1)throw new m.p(`cimd metadataFetchPolicy.${t} must be a positive integer`);return e}function eW(e,t){let r=t-6e4,i=0;for(;i<e.length&&e[i]<=r;)i+=1;i>0&&e.splice(0,i)}function eY(e){if("string"!=typeof e||!/^\d+$/.test(e))return null;let t=Number(e);return Number.isSafeInteger(t)?t:null}e.s(["f",0,e=>{let t,r=(t=function(e){let t,r=e.metadataRevalidationInterval??"60m",i=e.maxCacheEntries??1e3;if(!Number.isInteger(i)||i<1)throw new m.p("cimd maxCacheEntries must be a positive integer");let a=(t=e.metadataFetchPolicy,{minimumFetchIntervalMs:function(e,t){if("number"==typeof e){if(!Number.isFinite(e)||e<0)throw new m.p(`cimd metadataFetchPolicy.${t} must be a non-negative number of seconds or duration string`);return 1e3*e}try{let t=Math.floor(Date.now()/1e3),r=((0,eN.x)(e,t)-t)*1e3;if(!Number.isFinite(r)||r<0)throw Error("negative duration");return r}catch{throw new m.p(`cimd metadataFetchPolicy.${t} must be a non-negative number of seconds or duration string`)}}(t?.minimumFetchInterval??1,"minimumFetchInterval"),maximumConcurrentFetches:eH(t?.maximumConcurrentFetches??16,"maximumConcurrentFetches"),maximumConcurrentFetchesPerOrigin:eH(t?.maximumConcurrentFetchesPerOrigin??4,"maximumConcurrentFetchesPerOrigin"),maximumFetchesPerMinute:eH(t?.maximumFetchesPerMinute??120,"maximumFetchesPerMinute"),maximumFetchesPerOriginPerMinute:eH(t?.maximumFetchesPerOriginPerMinute??30,"maximumFetchesPerOriginPerMinute")}),o=new Map,n=new Map,s=new Map,l=new Map,c=[],d=0;return async(t,u,p)=>{if(!eC(u))return null;let f=t.context.getPlugin("oauth-provider");if(!f)throw new m.p("cimd discovery invoked without the oauth-provider plugin installed");let h=f.options,g=(e=>{let t=o.get(e);if(t)return o.delete(e),o.set(e,t),t})(u),w=Date.now();if(g&&g.expiresAt>w)return p||eK(t,u,g.metadata,e,h);let y=n.get(u);if(void 0!==y)return y;let b=(e=>{let t=Date.now(),r=s.get(e);if(a.minimumFetchIntervalMs>0&&void 0!==r&&t-r<a.minimumFetchIntervalMs)throw ez("metadata document fetch is within the per-client minimum interval");if(!s.has(e))for(;s.size>=i;){let e=!1;for(let[r,i]of s)if(!n.has(r)&&(!(a.minimumFetchIntervalMs>0)||!(t-i<a.minimumFetchIntervalMs))){s.delete(r),e=!0;break}if(!e)throw ez("metadata fetch client state is at capacity")}let o=((e,t)=>{let r=l.get(e);if(r)return eW(r.fetchStartTimesMs,t),l.delete(e),l.set(e,r),r;for(;l.size>=i;){let e=!1;for(let[r,i]of l)if(eW(i.fetchStartTimesMs,t),!(i.activeFetchCount>0)&&!(i.fetchStartTimesMs.length>0)){l.delete(r),e=!0;break}if(!e)throw ez("metadata fetch origin state is at capacity")}let a={activeFetchCount:0,fetchStartTimesMs:[]};return l.set(e,a),a})(new URL(e).origin,t);if(eW(c,t),d>=a.maximumConcurrentFetches)throw ez("global metadata fetch concurrency limit exceeded");if(o.activeFetchCount>=a.maximumConcurrentFetchesPerOrigin)throw ez("metadata fetch concurrency limit exceeded for client origin");if(c.length>=a.maximumFetchesPerMinute)throw ez("global metadata fetch rate limit exceeded");if(o.fetchStartTimesMs.length>=a.maximumFetchesPerOriginPerMinute)throw ez("metadata fetch rate limit exceeded for client origin");s.delete(e),s.set(e,t),c.push(t),o.fetchStartTimesMs.push(t),d+=1,o.activeFetchCount+=1;let u=!1;return()=>{u||(u=!0,d-=1,o.activeFetchCount-=1)}})(u),E=(async()=>{let a,n=await eF(t,u,e,g?{etag:g.etag,lastModified:g.lastModified}:void 0);if("not-modified"===n.status&&!g)throw f="Metadata document returned 304 without a validated cached document",new eS.E("BAD_REQUEST",{error:"invalid_client",error_description:f});let l="modified"===n.status?n.metadata:g.metadata,c=await eK(t,u,l,e,h,p??void 0),d=(a=function(e,t,r){let{directives:i,duplicates:a}=function(e){let t=new Map,r=new Set;for(let i of e?.split(",")??[]){let[e,...a]=i.trim().split("="),o=e?.toLowerCase();if(!o)continue;t.has(o)&&r.add(o);let n=a.join("=").trim();t.set(o,!n||n.replace(/^"|"$/g,""))}return{directives:t,duplicates:r}}(e.cacheControl),o=e.vary?.split(",").some(e=>"*"===e.trim());if(i.has("no-store")||i.has("private")||o)return{cacheable:!1,expiresAt:r};let n=function(e,t){if("number"==typeof e)return Math.max(0,1e3*e);let r=Math.floor(t/1e3);return Math.max(0,((0,eN.x)(e,r)-r)*1e3)}(t,r);if(i.has("no-cache"))return{cacheable:!0,expiresAt:r};let s=eY(e.age)??0,l=e.date?Date.parse(e.date):r,c=Math.max(Number.isFinite(l)?Math.max(0,r-l):0,1e3*s),d=null,u=i.has("s-maxage"),p=eY(i.get("s-maxage")),f=i.has("max-age"),m=eY(i.get("max-age")),h=u?null===p||a.has("s-maxage"):f&&(null===m||a.has("max-age")),g=u?p:m;if(h)d=0;else if(null!==g)d=Math.max(0,1e3*g-c);else if(e.expires){let t=Date.parse(e.expires);Number.isFinite(t)&&(d=Math.max(0,t-(Number.isFinite(l)?l:r)-c))}return{cacheable:!0,expiresAt:r+Math.min(n,d??n)}}(y="modified"===n.status?n.cacheHeaders:(m=g.responseCacheHeaders,{cacheControl:(w=n.cacheHeaders).cacheControl??m.cacheControl,vary:w.vary??m.vary,expires:w.expires??m.expires,date:w.date??m.date,age:w.age??m.age,etag:w.etag??m.etag,lastModified:w.lastModified??m.lastModified}),r,Date.now())).cacheable?{metadata:l,expiresAt:a.expiresAt,etag:y.etag,lastModified:y.lastModified,responseCacheHeaders:y}:null;if(d){var f,m,w,y;for(o.delete(u);o.size>=i;){let e=o.keys().next().value;if("string"!=typeof e)break;o.delete(e)}o.set(u,d)}else o.delete(u);return s.delete(u),c})();n.set(u,E);try{return await E}catch(e){throw s.delete(u),s.set(u,Date.now()),e}finally{n.get(u)===E&&n.delete(u),b()}}}(e),{id:e$,matches:eC,resolve:t,fetchClientMetadataResource:e.fetchClientMetadataResource,discoveryMetadata:{client_id_metadata_document_supported:!0}});return{id:"cimd",version:"1.7.16",init(e){(0,eT.L)(e,{clientDiscovery:r})}}}],100642);var eQ=e.i(300794),eG=e.i(743698),eJ=e.i(761095),eZ=e.i(81111);let eX=new Set([204,205,304]),e0=async(e,t)=>{let r=new Request(e,t),i=new URL(r.url);if("https:"!==i.protocol)throw TypeError("CIMD Node transport requires an HTTPS URL");if("GET"!==r.method&&"HEAD"!==r.method)throw TypeError("CIMD Node transport supports only GET and HEAD");let a=await (0,eQ.lookup)(i.hostname,{all:!0,verbatim:!0});if(0===a.length)throw TypeError("metadata hostname returned no DNS addresses");for(let e of a)if(!(0,eO.$)(e.address))throw TypeError("metadata hostname must resolve only to public-routable addresses");let o=a[0],n=Object.fromEntries(r.headers.entries());n.host=i.host;let s=t?.signal??(e instanceof Request?e.signal:r.signal);return new Promise((e,t)=>{let a=(0,eG.request)(i,{agent:!1,headers:n,method:r.method,servername:0===(0,eJ.isIP)(i.hostname.replace(/^\[|\]$/g,""))?i.hostname:void 0,signal:s,lookup:(e,t,r)=>{t.all?r(null,[o]):r(null,o.address,o.family)}},i=>{let a=i.statusCode??500,o="HEAD"===r.method||eX.has(a)?null:eZ.Readable.toWeb(i);try{e(new Response(o,{headers:function(e){let t=new Headers;for(let[r,i]of Object.entries(e))if(Array.isArray(i))for(let e of i)t.append(r,e);else void 0!==i&&t.append(r,i);return t}(i.headers),status:a,statusText:i.statusMessage}))}catch(e){i.destroy(),t(e)}});a.once("error",t),a.end()})};e.s(["f",0,e0],781615)},303361,e=>{"use strict";let t=new Set(["localhost","127.0.0.1","::1","[::1]"]);function r(e){let r,i=e.trim();if(!i)throw Error("APP_ORIGINS contains an empty entry.");if(/[\s/\\]/.test(i.replace(/^https?:\/\//,"")))throw Error(`APP_ORIGINS entry "${i}" must be a bare host or an origin, with no path.`);if(i.includes("@"))throw Error(`APP_ORIGINS entry "${i}" must not contain credentials.`);let a=/^(https?):\/\/(.+)$/.exec(i),o=a?"https"===a[1]?"https:":"http:":null,n=a?a[2]:i,s=/^(\[[^\]]+\]|[^:]+)(?::(\d+))?$/.exec(n);if(!s)throw Error(`APP_ORIGINS entry "${i}" is not a valid host.`);let l=s[1].toLowerCase(),c=s[2]??null;if(!l||"."===l)throw Error(`APP_ORIGINS entry "${i}" is not a valid host.`);let d=l.includes("*");return d&&function(e,t){let r=e.split(".");if(r.slice(1).some(e=>e.includes("*")))throw Error(`APP_ORIGINS entry "${t}" may only use a wildcard in its leftmost label.`);if("*"!==r[0])throw Error(`APP_ORIGINS entry "${t}" must use "*" as a whole label, for example "*.example.com".`);if(r.length<3)throw Error(`APP_ORIGINS entry "${t}" is too broad; a wildcard needs at least two literal labels after it.`)}(l,i),{hostname:l,host:c?`${l}:${c}`:l,port:c,protocol:o,wildcard:d,loopback:(r=l.toLowerCase().replace(/^\[|\]$/g,""),!!(t.has(r)||"::1"===r||r.endsWith(".localhost"))||/^127\./.test(r))}}function i(e,t){return e.protocol?e.protocol:e.loopback?"http:":t?"https:":"http:"}let a=!1;function o(e){let t=e.trim().toLowerCase();return!(!t||/[\s/\\@]/.test(t))&&/^(\[[^\]]+\]|[^:]+)(?::\d+)?$/.test(t)}function n(e,t){let r=e.trim().toLowerCase();if(!r)return!1;let i=/^(\[[^\]]+\]|[^:]+)(?::(\d+))?$/.exec(r);if(!i)return!1;let a=i[1],o=i[2]??null;return(!t.port||t.port===o)&&function(e,t){let r=e.trim().toLowerCase();if(!r)return!1;if(!t.wildcard)return t.hostname===r;let i=t.hostname.slice(1);return r.endsWith(i)&&r.length>i.length}(a,t)}function s(e,t){let r=t=>{let r=e.headers.get(t)?.split(",")[0]?.trim();return r&&!/[\s/\\@]/.test(r)?r:null},i=t?r("x-forwarded-host"):null,a=t?r("x-forwarded-proto"):null,n=i??r("host");if(n&&o(n)){let t="https"===a||"http"===a?a:new URL(e.url).protocol.replace(":","");return`${t}://${n.toLowerCase()}`}try{return new URL(e.url).origin}catch{return null}}e.s(["J",0,function(e){if("inferred"!==e.mode)return"single"===e.mode?e.canonical:{allowedHosts:e.patterns.flatMap(e=>e.port?[e.host]:[e.host,`${e.host}:*`]),protocol:e.allHttps?"https":"auto",fallback:e.canonical}},"K",0,function(e,t){let r=e.headers.get("sec-fetch-site");if(r)return"same-origin"===r||"none"===r;let i=e.headers.get("origin");if(!i)return!0;let a=s(e,t);return!!a&&i.trim().toLowerCase()===a},"L",0,function(e,t){let r=t.trim();if(!r)return!1;let i=r;if(/^https?:\/\//i.test(r))try{i=new URL(r).host}catch{return!1}return"inferred"===e.mode?o(i):e.patterns.some(e=>n(i,e))},"v",0,s,"Y",0,r,"U",0,function(e=process.env){let t,o="phase-production-build"===e.NEXT_PHASE,s="production"===e.NODE_ENV&&!o,l=e.APP_ORIGINS?.trim(),c=function(e){let t,r=e.PUBLIC_BASE_URL?.trim();if(!r)return null;try{t=new URL(r)}catch{throw Error("PUBLIC_BASE_URL must be an absolute http or https URL.")}if("http:"!==t.protocol&&"https:"!==t.protocol)throw Error("PUBLIC_BASE_URL must use http or https.");return t}(e),d=l?l.split(",").map(e=>e.trim()).filter(Boolean).map(r):[];if(s&&0===d.length&&!c)return a||(a=!0,console.warn("[origins] Neither APP_ORIGINS nor PUBLIC_BASE_URL is set. Each request's own Host header will be trusted, so absolute URLs this server generates — OAuth callbacks, iOS enrollment and install links, the GitHub webhook URL — follow whatever host the caller asked for. Set APP_ORIGINS to the hostname(s) this server is reached at to pin them.")),{patterns:[],canonical:null,mode:"inferred",allHttps:!1};let u=s?d:function(e){let t=new Map;for(let r of e){let e=t.get(r.host);e?"http:"===r.protocol&&t.set(r.host,{...e,protocol:"http:"}):t.set(r.host,r)}return[...t.values()]}([...(t=e.PORT?.trim()||"3000",["localhost","127.0.0.1","[::1]"].map(e=>r(`http://${e}:${t}`))),...d]);if(0===u.length&&c&&(u=[r(c.origin)]),s){let e=u.filter(e=>e.wildcard);if(e.length>0)throw Error(`APP_ORIGINS may not use wildcards in production (${e.map(e=>e.hostname).join(", ")}). A wildcard trusts every host under it for CSRF and for post-login redirects; list exact hosts instead.`)}c&&!u.some(e=>n(c.host,e))&&(u=[...u,r(c.origin)]);let p=u.find(e=>!e.wildcard);if(!p&&!c)throw Error("APP_ORIGINS must include at least one exact origin; a wildcard alone gives this server no address to put in the links it generates.");return{patterns:u,canonical:c?.origin??`${i(p,s)}//${p.host}`,mode:1!==u.length||u[0].wildcard?"multi":"single",allHttps:u.every(e=>e.loopback||"https:"===i(e,s))}}])},435387,e=>{"use strict";let t=["mcp:read","mcp:write","mcp:destructive"],r={read:["mcp:read"],write:["mcp:read","mcp:write"],destructive:[...t]};e.s(["v",0,r,"n",0,t])},576257,434402,e=>{"use strict";var t=e.i(363004),r=e.i(931129),i=e.i(204721),a=e.i(890659),o=e.i(370728),n=e.i(749599),s=e.i(483052),l=e.i(13681),c=e.i(483319),d=e.i(58260),u=e.i(292243),p=e.i(303361),f=e.i(243783),m=e.i(169040),h=e.i(789714),g=e.i(782393),w=e.i(464661),y=e.i(320170),b=e.i(666680),E=e.i(100642),A=e.i(781615),I=e.i(413417),_=e.i(71616),k=e.i(756023),T=e.i(112996),v=e.i(272003),U=e.i(287292),R=e.i(947448),x=e.i(762542),S=e.i(21568),O=e.i(827957),D=e.i(741242),N=e.i(397554),L=e.i(709939);function P(e){let t=e.context.options.baseURL;return"string"==typeof t?t||"better-auth:session-cache":e.context.baseURL||"better-auth:session-cache"}async function C(e,t,r){let i=(0,D.f)(t).kid;if(!i)return e.context.logger.debug("Cookie-cache JWT missing kid in header"),null;let a=await (0,U.i)(e.context.adapter,r).getAllKeys(e);if(!a?.length)return e.context.logger.debug("No JWKS keys available for cookie-cache JWT"),null;let o=a.find(e=>e.id===i);if(!o)return e.context.logger.debug(`No JWKS key found for cookie-cache JWT kid: ${i}`),null;let n=o.alg??(0,U.V)(r);return{alg:n,publicKey:await (0,N.g)(JSON.parse(o.publicKey),n)}}async function q(e,t,r,i){let a=await (0,x.L)(e,i);if(!a)throw new _.p("`jwt({ sessionCookieCache: true })` requires locally managed JWT plugin keys and does not support `jwt.sign`.");return await new O.f({...t,sid:t.session.token}).setProtectedHeader({alg:a.alg,kid:a.kid,typ:S.Y}).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+r).setIssuer(P(e)).setAudience(S.H).setSubject(t.user.id).sign(a.privateKey)}async function j(e,t,r){try{if("better-auth.session-cache+jwt"!==(0,D.f)(t).typ)return null;let i=await C(e,t,r);if(!i)return null;let{payload:a}=await (0,L.f)(t,i.publicKey,{...(0,S.V)({issuer:P(e)}),algorithms:[i.alg]}),o=(0,S.R)(a);if(!o)return null;return{payload:o,expiresAt:o.exp?1e3*o.exp:Date.now()}}catch(t){return e.context.logger.debug("Cookie-cache JWT verification failed",t),null}}let $={jwks:{fields:{publicKey:{type:"string",required:!0},privateKey:{type:"string",required:!0},createdAt:{type:"date",required:!0},expiresAt:{type:"date",required:!1},alg:{type:"string",required:!1},crv:{type:"string",required:!1}}}};var B=e.i(497515),V=e.i(530501);async function M(e,t){let r=(0,B.g)();try{let i=e.split(".");if(3!==i.length)return null;let a=new TextDecoder().decode(V.t.decode(i[0])),o=JSON.parse(a).kid;if(!o)return r.context.logger.debug("JWT missing kid in header"),null;let n=await (0,U.i)(r.context.adapter,t).getAllKeys(r);if(!n||0===n.length)return r.context.logger.debug("No JWKS keys available"),null;let s=n.find(e=>e.id===o);if(!s)return r.context.logger.debug(`No JWKS key found for kid: ${o}`),null;let l=JSON.parse(s.publicKey),c=s.alg??(0,U.V)(t),d=await (0,N.g)(l,c),u="string"==typeof r.context.options.baseURL?r.context.options.baseURL:void 0,p=t?.jwt?.issuer??u,f=t?.jwt?.audience??u;p&&f||r.context.logger.warn("[better-auth] The JWT plugin is verifying a JWT without checking its issuer or audience because no base URL was resolved for this call. Set `baseURL`, or `jwt.issuer` and `jwt.audience` in the JWT plugin options.");let{payload:m}=await (0,L.f)(e,d,{issuer:p,audience:f,algorithms:[c]});if(!m.sub||!m.aud)return null;return m}catch(e){return r.context.logger.debug("JWT verification failed",e),null}}var F=e.i(907855);let K=F.object({payload:F.record(F.string(),F.any()),overrideOptions:F.record(F.string(),F.any()).optional()}),z=F.object({token:F.string(),issuer:F.string().optional()});var H=e.i(435387);let W="aide_mcp_authorization_id";function Y(){throw new _.E("BAD_REQUEST",{error:"invalid_grant",error_description:"The MCP authorization is inactive. Authorize this application again."})}function Q(e,t){return async r=>{let i;try{i=JSON.parse(r.value)}catch{return}if(i?.type!=="authorization_code")return;let a=i.resource??i.query?.resource;(Array.isArray(a)?a.includes(t.resource):a===t.resource)||Y(),("string"!=typeof i.userId||"string"!=typeof i.query?.client_id)&&Y();let o=await e.oauthClient.findUnique({where:{clientId:i.query.client_id}}),n=await e.mcpAuthorization.create({data:{id:(0,b.randomUUID)(),authorizationCodeId:r.identifier,userId:i.userId,clientId:i.query.client_id,clientName:o?.name??i.query.client_id,scopes:i.query.scope??""}});return{data:{...r,value:JSON.stringify({...i,referenceId:n.id})}}}}function G(e,t){let r=[...H.n,"offline_access"];return[(e=>{if(e?.jwt?.sign&&!e.jwks?.remoteUrl)throw new _.p("options.jwks.remoteUrl must be set when using options.jwt.sign");if(e?.jwks?.remoteUrl&&!e.jwks?.keyPairConfig?.alg)throw new _.p("options.jwks.keyPairConfig.alg must be specified when options.jwks.remoteUrl is used for OpenID metadata");let t=e?.jwks?.jwksPath??"/jwks";if("string"!=typeof t||0===t.length||!t.startsWith("/")||t.includes(".."))throw new _.p("options.jwks.jwksPath must be a non-empty string starting with '/' and not contain '..'");return{id:"jwt",version:v.f,options:e,init(t){if(!e?.sessionCookieCache)return;if(t.options.session?.cookieCache?.strategy!=="jwt")throw new _.p('`jwt({ sessionCookieCache: true })` requires `session.cookieCache.strategy = "jwt"`.');if(e.jwt?.sign)throw new _.p("`jwt({ sessionCookieCache: true })` requires locally managed JWT plugin keys and does not support `jwt.sign`.");let r=e.jwks?.gracePeriod,i=t.options.session.cookieCache.maxAge||300;return void 0!==r&&i>r&&t.logger.warn(`[better-auth] \`session.cookieCache.maxAge\` (${i}s) exceeds the JWT plugin JWKS grace period (${r}s). Rotated keys may stop verifying cookie-cache JWTs before the cookie expires.`),{context:{sessionConfig:{...t.sessionConfig,cookieCacheSigner:{sign:(t,r,i)=>q(t,r,i,e),verify:(t,r)=>j(t,r,e)}}}}},endpoints:{getJwks:(0,a.g)(t,{method:"GET",metadata:{openapi:{operationId:"getJSONWebKeySet",description:"Get the JSON Web Key Set",responses:{200:{description:"JSON Web Key Set retrieved successfully",content:{"application/json":{schema:{type:"object",properties:{keys:{type:"array",description:"Array of public JSON Web Keys",items:{type:"object",properties:{kid:{type:"string",description:"Key ID uniquely identifying the key, corresponds to the 'id' from the stored Jwk"},kty:{type:"string",description:"Key type (e.g., 'RSA', 'EC', 'OKP')"},alg:{type:"string",description:"Algorithm intended for use with the key (e.g., 'EdDSA', 'RS256')"},use:{type:"string",description:"Intended use of the public key (e.g., 'sig' for signature)",enum:["sig"],nullable:!0},n:{type:"string",description:"Modulus for RSA keys (base64url-encoded)",nullable:!0},e:{type:"string",description:"Exponent for RSA keys (base64url-encoded)",nullable:!0},crv:{type:"string",description:"Curve name for elliptic curve keys (e.g., 'Ed25519', 'P-256')",nullable:!0},x:{type:"string",description:"X coordinate for elliptic curve keys (base64url-encoded)",nullable:!0},y:{type:"string",description:"Y coordinate for elliptic curve keys (base64url-encoded)",nullable:!0}},required:["kid","kty","alg"]}}},required:["keys"]}}}}}}}},async t=>{if(e?.jwks?.remoteUrl)throw new _.E("NOT_FOUND");let r=(0,U.i)(t.context.adapter,e),i=await r.getAllKeys(t);if(i&&i?.length!==0||(await (0,R.K)(t,e),i=await r.getAllKeys(t)),!i?.length)throw new _.p("No key sets found. Make sure you have a key in your database.");let a=Date.now(),o=(e?.jwks?.gracePeriod??2592e3)*1e3,n=i.filter(e=>!e.expiresAt||e.expiresAt.getTime()+o>a),s=e?.jwks?.keyPairConfig,l=s&&"crv"in s?s.crv:void 0;return t.json({keys:n.map(t=>({alg:t.alg??(0,U.V)(e),crv:t.crv??l,...JSON.parse(t.publicKey),kid:t.id}))})}),getToken:(0,a.g)("/token",{method:"GET",requireHeaders:!0,use:[T.Z],metadata:{openapi:{operationId:"getJSONWebToken",description:"Get a JWT token",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}}}}}}}}}},async t=>{let r=await (0,x.d)(t,e);return t.json({token:r})}),signJWT:a.g.serverOnly({method:"POST",metadata:{$Infer:{body:{}}},body:K},async t=>{let r=await (0,x.X)(t,{options:{...e,...t.body.overrideOptions},payload:t.body.payload});return t.json({token:r})}),verifyJWT:a.g.serverOnly({method:"POST",metadata:{$Infer:{body:{},response:{}}},body:z},async t=>{let r=t.body.issuer?{...e,jwt:{...e?.jwt,issuer:t.body.issuer}}:e,i=await M(t.body.token,r);return t.json({payload:i})})},hooks:{after:[{matcher:e=>"/get-session"===e.path,handler:(0,a.a)(async t=>{if(e?.disableSettingJwtHeader)return;let r=t.context.session||t.context.newSession;if(r&&r.session){let r=await (0,x.d)(t,e),i=new Set((t.context.responseHeaders?.get("access-control-expose-headers")||"").split(",").map(e=>e.trim()).filter(Boolean));i.add("set-auth-jwt"),t.setHeader("set-auth-jwt",r),t.setHeader("Access-Control-Expose-Headers",Array.from(i).join(", "))}})}]},schema:(0,k.C)($,e?.schema)}})({jwt:{issuer:t.issuer,audience:t.resource}}),(0,I.B)({loginPage:"/mcp/sign-in",consentPage:"/mcp/consent",resource:t.resource,scopes:r,resources:[{identifier:t.resource,allowedScopes:r,accessTokenTtl:300,refreshTokenTtl:2592e3}],grantTypes:["authorization_code","refresh_token"],accessTokenExpiresIn:300,refreshTokenExpiresIn:2592e3,refreshTokenReuseInterval:0,clientRegistrationDefaultScopes:["mcp:read"],clientRegistrationAllowedScopes:r,allowDynamicClientRegistration:t.dcrEnabled,allowUnauthenticatedClientRegistration:t.dcrEnabled,clientRegistrationDefaultApplicationType:"infer",extensions:[{claims:{accessToken:async({user:r,client:i,referenceId:a,resources:o,scopes:n})=>{r&&a&&o?.includes(t.resource)||Y();let s=await e.mcpAuthorization.findFirst({where:{id:a,userId:r.id,clientId:i.clientId,revokedAt:null,user:{is:{id:r.id}}}});return(!s||n.some(e=>!s.scopes.split(" ").includes(e)))&&Y(),{[W]:s.id}}}}]}),(0,E.f)({fetchClientMetadataResource:A.f,metadataProfile:"mcp-2026-07-28"})]}e.s(["P",0,W,"y",0,G,"K",0,Q],434402);let J={user:["create","list","set-password","set-email","get","update"],session:["list","revoke","delete"]},Z=(0,c.y)(J),X=Z.newRole(J),ee=null;e.s(["f",0,function(){return ee||(ee=(0,f.U)().then(e=>(function(e,c=(0,m.L)(),f=(0,y.f)()){let b=c.provider,E=(0,p.J)(c.origins),A=b?.providerId.toLowerCase()==="github"?b.userInfoUrl:void 0,I=(0,m._)(c.mode)&&b?(0,d.f)({config:[{providerId:b.providerId,clientId:b.clientId,clientSecret:b.clientSecret,scopes:b.scopes,discoveryUrl:b.discoveryUrl,authorizationUrl:b.authorizationUrl,tokenUrl:b.tokenUrl,userInfoUrl:b.userInfoUrl,getUserInfo:A?async e=>e.accessToken?(0,g.f)(A,e.accessToken):null:void 0,pkce:!0,requireIdTokenVerification:b.requireIssuerValidation,disableImplicitSignUp:!1}]}):null;return(0,i.f)({appName:"AI Development Environment",baseURL:"object"==typeof E?{...E,protocol:"auto"}:E,disabledPaths:f?["/token"]:[],trustedOrigins:e=>{if(!e)return[];let t=(0,p.v)(e,c.trustProxyHeaders);return t&&(0,p.L)(c.origins,t)?[t]:[]},secret:c.secret,logger:{log:h.f},hooks:{before:(0,a.a)(async e=>{let t=e.request?(0,p.v)(e.request,c.trustProxyHeaders):null,r=e.headers?.get("cookie")??"",i=t?"https:"===new URL(t).protocol:!!/(?:^|;\s*)__Secure-better-auth\.session_token=/.test(r)||!/(?:^|;\s*)better-auth\.session_token=/.test(r)&&void 0,a={...e.context.options,advanced:{...e.context.options.advanced,useSecureCookies:i}};e.context.authCookies=(0,o.e)(a),e.context.createAuthCookie=(0,o.g)(a)})},advanced:{trustedProxyHeaders:c.trustProxyHeaders},database:(0,r.f)(e,{provider:"sqlite"}),emailAndPassword:{enabled:(0,m.Z)(c.mode),requireEmailVerification:!1},account:{accountLinking:{enabled:!0,disableImplicitLinking:!0,allowDifferentEmails:!1}},databaseHooks:{...w.x,...f?{verification:{create:{before:Q(e,f)}}}:{}},plugins:[function(){let e=(0,s.f)({ac:Z,roles:{user:X},defaultRole:"user",adminRoles:["user"]}),{setRole:t,banUser:r,unbanUser:i,impersonateUser:a,stopImpersonating:o,removeUser:n,...l}=e.endpoints;return{...e,endpoints:l}}(),(0,t.f)({schema:{apikey:{modelName:"apiKey"}},defaultPrefix:"aide_",requireName:!0,startingCharactersConfig:{shouldStore:!0,charactersLength:12},keyExpiration:{defaultExpiresIn:null,disableCustomExpiresTime:!1,minExpiresIn:1,maxExpiresIn:3650},rateLimit:{enabled:!1},enableSessionForAPIKeys:!1}),(0,l.f)(),(0,u.f)({disableClientRequest:!0,expiresIn:1,storeToken:"hashed"}),...I?[I]:[],...f?G(e,f):[],(0,n.A)()]})})(e))),ee}],576257)}];
|
|
454
|
+
`){if(!await r.user.findUnique({where:{id:e},select:{id:!0}}))throw new m.E("NOT_FOUND",{message:"User not found."});throw new m.E("BAD_REQUEST",{message:"The final account cannot be deleted."})}}async function eI({allowWhenRegistrationClosed:e=!1}={}){let t=await (0,eg.U)(),r=await ey();if(r.bootstrapCompleted){if(!r.registrationEnabled&&!e)throw new m.E("FORBIDDEN",{message:"Account registration is disabled."});return}if(await t.user.count()>0){if(await t.authSettings.update({where:{id:ew},data:{bootstrapCompleted:!0,registrationEnabled:!1,bootstrapClaimId:null,bootstrapClaimedAt:null}}),e)return;throw new m.E("FORBIDDEN",{message:"Account registration is disabled."})}let i=new Date(Date.now()-18e4),a=(0,eh.randomUUID)();if(1!==(await t.authSettings.updateMany({where:{id:ew,bootstrapCompleted:!1,OR:[{bootstrapClaimedAt:null},{bootstrapClaimedAt:{lt:i}}]},data:{bootstrapClaimId:a,bootstrapClaimedAt:new Date}})).count)throw new m.E("CONFLICT",{message:"The initial account is already being created. Try again shortly."})}async function e_(){let e=await (0,eg.U)();await e.authSettings.updateMany({where:{id:ew,bootstrapCompleted:!1},data:{bootstrapCompleted:!0,registrationEnabled:!1,bootstrapClaimId:null,bootstrapClaimedAt:null}})}function ek(e,t){let r=e[t]?.trim().toLowerCase();if(!r||"false"===r||"0"===r)return!1;if("true"===r||"1"===r)return!0;throw Error(`${t} must be true, false, 1, or 0.`)}e.s(["x",0,{user:{create:{before:async(e,t)=>(await eI({allowWhenRegistrationClosed:t?.path?.includes("/admin/create-user")??!1}),{data:{...e,role:"user",banned:!1,banReason:null,banExpires:null}}),after:async()=>{await e_()}},update:{before:async e=>({data:{...e,role:"user",banned:!1,banReason:null,banExpires:null}})},delete:{before:async()=>{throw new m.E("BAD_REQUEST",{message:"Accounts must be deleted through the management API."})}}}},"J",0,eA,"w",0,eb,"T",0,eE],464661),e.s(["f",0,function(e=process.env){if(!ek(e,"MCP_OAUTH_ENABLED"))return null;if(!e.PUBLIC_BASE_URL?.trim()&&!e.APP_ORIGINS?.trim())throw Error("MCP OAuth requires a configured canonical PUBLIC_BASE_URL or APP_ORIGINS.");let t=(0,eo.U)(e),r=e.APP_ORIGINS?.split(",").map(e=>e.trim()).filter(Boolean).map(eo.Y).find(e=>!e.wildcard),i=e.PUBLIC_BASE_URL?.trim()?t.canonical:r?`${r.protocol??(r.loopback?"http:":"https:")}//${r.host}`:null;if(!i)throw Error("MCP OAuth requires an exact canonical origin.");let a=new URL(i),o="localhost"===a.hostname||a.hostname.endsWith(".localhost")||"[::1]"===a.hostname||/^127\./.test(a.hostname);if("https:"!==a.protocol&&!("http:"===a.protocol&&o))throw Error("MCP OAuth requires HTTPS except on loopback development origins.");return{origin:a.origin,issuer:`${a.origin}/api/auth`,resource:`${a.origin}/api/mcp`,dcrEnabled:ek(e,"MCP_OAUTH_DCR_ENABLED")}}],320170);var eT=e.i(278706),eT=eT,ev=e.i(252524),ev=ev,eU=ev,eR=ev,eS=ev,ex=e.i(455659),eO=e.i(783968),eD=e.i(661573),eN=e.i(947448);let eL=/\/(?:\.|%2e)(?:\.|%2e)?(?:\/|$|#|\?)/i,eP=new Set(["client_secret_post","client_secret_basic","client_secret_jwt"]);function eC(e){let t;try{t=new URL(e)}catch{return!1}return"https:"===t.protocol}let eq=/^application\/(?:[-\w.]+\+)?json\s*(?:;|$)/i,ej="Failed to fetch metadata document (network error or redirect blocked)",e$="cimd";function eB(e){return new ex.E("BAD_REQUEST",{error:"invalid_client",error_description:e})}function eV(){return eB("Metadata document exceeds 5KB size limit")}async function eM(e,t,r){let i,a=e.body?.getReader();if(!a){let r=await e.text();if(new TextEncoder().encode(r).byteLength>t)throw eV();return r}let o=[],n=0,s=new Promise((e,t)=>{i=t}),l=()=>{i?.(Error("Metadata document body read aborted")),a.cancel().catch(()=>{})};r.aborted?l():r.addEventListener("abort",l,{once:!0});try{for(;;){let{done:e,value:r}=await Promise.race([a.read(),s]);if(e)break;if((n+=r.byteLength)>t)throw await a.cancel(),eV();o.push(r)}}finally{r.removeEventListener("abort",l),a.releaseLock()}let c=new Uint8Array(n),d=0;for(let e of o)c.set(e,d),d+=e.byteLength;return new TextDecoder().decode(c)}async function eF(e,t,r,i){let a,o=function(e){let t;if(eL.test(e))return"client_id URL MUST NOT contain dot segments";if(e.includes("#"))return"client_id URL MUST NOT contain a fragment";try{t=new URL(e)}catch{return"client_id is not a valid URL"}if("https:"!==t.protocol)return"client_id URL must use HTTPS";let r=/^https:\/\//i.exec(e);if(!r||e.includes("\\"))return"client_id URL MUST use an explicit HTTPS authority form";let i=e.slice(r[0].length),a=i.search(/[/?#]/);return 0===a?"client_id URL MUST use an explicit HTTPS authority form":a<0||"/"!==i[a]?"client_id URL MUST contain an explicit path component":t.username||t.password?"client_id URL MUST NOT contain credentials":(0,eO.$)(t.hostname)?null:"client_id URL must not target a private or reserved address"}(t);if(o)throw eB(o);if(r.isMetadataDocumentUrlAllowed&&!await r.isMetadataDocumentUrlAllowed(t,e))throw eB("client_id URL is not permitted by the server's fetch policy");let n=new Headers({Accept:"application/json"});i?.etag&&n.set("If-None-Match",i.etag),i?.lastModified&&n.set("If-Modified-Since",i.lastModified);let s=new AbortController,l=!1,c=setTimeout(()=>{l=!0,s.abort()},5e3);try{var d;let o,c;try{a=await r.fetchClientMetadataResource(t,{headers:n,redirect:"error",signal:s.signal})}catch{throw eB(l?"Metadata document fetch timed out after 5000ms":ej)}if(a.redirected)throw eB("Metadata document fetch must not follow redirects");let u={cacheControl:(d=a.headers).get("cache-control")??void 0,vary:d.get("vary")??void 0,expires:d.get("expires")??void 0,date:d.get("date")??void 0,age:d.get("age")??void 0,etag:d.get("etag")??void 0,lastModified:d.get("last-modified")??void 0};if(304===a.status){if(!i?.etag&&!i?.lastModified)throw eB("Metadata document returned 304 without a conditional validator");return{status:"not-modified",cacheHeaders:u}}if(200!==a.status)throw eB(`Metadata document fetch returned HTTP ${a.status}`);let p=a.headers.get("content-type")??"";if(!eq.test(p))throw eB(`Metadata document must be JSON (got Content-Type "${p||"(none)"}")`);try{let e=a.headers.get("content-length");if(e){let t=Number.parseInt(e,10);if(Number.isFinite(t)&&t>5120)throw await a.body?.cancel(),eV()}o=await eM(a,5120,s.signal)}catch(e){if(l)throw eB("Metadata document fetch timed out after 5000ms");if(e instanceof ex.E)throw e;throw eB(ej)}try{c=JSON.parse(o)}catch{throw eB("Metadata document is not valid JSON")}let f=function(e,t,r={}){let i;if(!t||"object"!=typeof t)return{valid:!1,error:"metadata document is not a JSON object"};for(let e of Object.keys(t))if((0,eU.c)(e))return{valid:!1,error:`metadata document MUST NOT contain "${e}"`};let a=ev.b.strip().safeParse(t);if(!a.success){let e=a.error.issues[0];return{valid:!1,error:`${e?.path.join(".")||"metadata document"}: ${e?.message??"invalid client metadata"}`}}let o=a.data,n=[];if(o.client_id!==e)return{valid:!1,error:`client_id "${String(o.client_id)}" does not match the metadata document URL`};if("mcp-2026-07-28"===r.metadataProfile&&!o.client_name?.trim())return{valid:!1,error:"client_name must be a non-empty string"};for(let e of["backchannel_logout_uri","backchannel_logout_session_required"])if(void 0!==o[e])return{valid:!1,error:`metadata document MUST NOT contain "${e}"`};let s=new Set(["none","private_key_jwt"]);if("string"==typeof o.token_endpoint_auth_method){if(eP.has(o.token_endpoint_auth_method))return{valid:!1,error:`symmetric auth method "${o.token_endpoint_auth_method}" is prohibited for Client ID Metadata Document clients`};if(!s.has(o.token_endpoint_auth_method))return{valid:!1,error:'token_endpoint_auth_method must be "none" or "private_key_jwt" for Client ID Metadata Document clients'};if("private_key_jwt"===o.token_endpoint_auth_method&&!o.jwks&&!o.jwks_uri)return{valid:!1,error:"private_key_jwt requires either jwks or jwks_uri in the metadata document"}}if(o.jwks&&!(0,eS.l)(o.jwks).valid)return{valid:!1,error:"jwks must contain only structurally valid public keys"};if(o.jwks_uri)try{let e=new URL(o.jwks_uri);if(e.username||e.password)return{valid:!1,error:"jwks_uri must not contain credentials"};if(o.jwks_uri.includes("#"))return{valid:!1,error:"jwks_uri must not contain a fragment"}}catch{return{valid:!1,error:"jwks_uri must be a valid URL"}}if("mcp-2026-07-28"===r.metadataProfile&&!o.redirect_uris||o.redirect_uris&&!o.redirect_uris.every(e=>(function(e){try{let t=new URL(e);return"http:"===t.protocol||"https:"===t.protocol||(0,eD.Y)(t)}catch{return!1}})(e)))return{valid:!1,error:"redirect_uris must be a non-empty array of absolute HTTP(S) or private-use URIs"};for(let e of["client_uri","logo_uri","tos_uri","policy_uri"]){if(void 0!==o[e]&&"string"!=typeof o[e])return{valid:!1,error:`${e} must be a string`};if("string"==typeof o[e])try{let t=new URL(o[e]);if("https:"!==t.protocol&&"http:"!==t.protocol)return{valid:!1,error:`${e} must use HTTP(S)`};if(t.username||t.password)return{valid:!1,error:`${e} must not contain credentials`};if(!(0,eO.$)(t.hostname))return{valid:!1,error:`${e} must not point to a private or reserved address`}}catch{return{valid:!1,error:`${e} is not a valid URL`}}}let l=r.originBoundFields??["post_logout_redirect_uris","client_uri"];try{i=new URL(e).origin}catch{return{valid:!1,error:"client_id is not a valid URL"}}for(let e of l){let t,r=o[e];if(void 0!==r){if("string"==typeof r)t=[r];else{if(!Array.isArray(r)||!r.every(e=>"string"==typeof e))return{valid:!1,error:`${e} must be a string or an array of strings`};t=r}for(let r of t){let t;try{t=new URL(r)}catch{return{valid:!1,error:`${e} contains an invalid URL: "${r}"`}}let a="redirect_uris"===e||"post_logout_redirect_uris"===e,o=a&&(0,eD.Y)(t);if("https:"!==t.protocol&&"http:"!==t.protocol&&!o)return{valid:!1,error:`all values for ${e} must use HTTP(S) or a private-use scheme`};if(o&&("redirect_uris"===e||(0,eD.a)(t)))continue;let n=a&&("http:"===t.protocol||"https:"===t.protocol)&&(0,eO.g)(t.hostname);if(t.origin!==i&&!n)return{valid:!1,error:`${e} value "${r}" must have the same origin as client_id (${i})`}}}}return n.push(...function(e){let t=[];try{let r=new URL(e);"/"===r.pathname&&t.push("client_id URL path / is NOT RECOMMENDED (§3)"),r.search&&t.push("client_id URL SHOULD NOT contain a query string (§3)")}catch{}return t}(e)),{valid:!0,metadata:{...o,token_endpoint_auth_method:o.token_endpoint_auth_method??"none"},...n.length>0?{warnings:n}:{}}}(t,c,{originBoundFields:r.originBoundFields,metadataProfile:r.metadataProfile});if(!f.valid)throw eB(f.error);for(let t of f.warnings??[])e.context.logger.warn(`cimd metadata document warning: ${t}`);return{status:"modified",metadata:f.metadata,cacheHeaders:u}}finally{clearTimeout(c)}}async function eK(e,t,r,i,a,o){let n=o?{...o}:void 0,s=await (0,eR.a)(e,a,{clientId:t,clientDiscoveryId:e$,metadata:{...r,client_id:r.client_id,redirect_uris:r.redirect_uris??[]},existingClient:o});if(s.created)try{await i.onClientCreated?.({client:s.client,clientMetadataDocument:r,context:e})}catch(t){e.context.logger.error("cimd onClientCreated notification failed",t)}else try{n&&await i.onClientRefreshed?.({client:s.client,previousClient:n,clientMetadataDocument:r,context:e})}catch(t){e.context.logger.error("cimd onClientRefreshed notification failed",t)}return s.client}function ez(e){return new ex.E("TOO_MANY_REQUESTS",{error:"temporarily_unavailable",error_description:e})}function eH(e,t){if(!Number.isInteger(e)||e<1)throw new m.p(`cimd metadataFetchPolicy.${t} must be a positive integer`);return e}function eW(e,t){let r=t-6e4,i=0;for(;i<e.length&&e[i]<=r;)i+=1;i>0&&e.splice(0,i)}function eY(e){if("string"!=typeof e||!/^\d+$/.test(e))return null;let t=Number(e);return Number.isSafeInteger(t)?t:null}e.s(["f",0,e=>{let t,r=(t=function(e){let t,r=e.metadataRevalidationInterval??"60m",i=e.maxCacheEntries??1e3;if(!Number.isInteger(i)||i<1)throw new m.p("cimd maxCacheEntries must be a positive integer");let a=(t=e.metadataFetchPolicy,{minimumFetchIntervalMs:function(e,t){if("number"==typeof e){if(!Number.isFinite(e)||e<0)throw new m.p(`cimd metadataFetchPolicy.${t} must be a non-negative number of seconds or duration string`);return 1e3*e}try{let t=Math.floor(Date.now()/1e3),r=((0,eN.x)(e,t)-t)*1e3;if(!Number.isFinite(r)||r<0)throw Error("negative duration");return r}catch{throw new m.p(`cimd metadataFetchPolicy.${t} must be a non-negative number of seconds or duration string`)}}(t?.minimumFetchInterval??1,"minimumFetchInterval"),maximumConcurrentFetches:eH(t?.maximumConcurrentFetches??16,"maximumConcurrentFetches"),maximumConcurrentFetchesPerOrigin:eH(t?.maximumConcurrentFetchesPerOrigin??4,"maximumConcurrentFetchesPerOrigin"),maximumFetchesPerMinute:eH(t?.maximumFetchesPerMinute??120,"maximumFetchesPerMinute"),maximumFetchesPerOriginPerMinute:eH(t?.maximumFetchesPerOriginPerMinute??30,"maximumFetchesPerOriginPerMinute")}),o=new Map,n=new Map,s=new Map,l=new Map,c=[],d=0;return async(t,u,p)=>{if(!eC(u))return null;let f=t.context.getPlugin("oauth-provider");if(!f)throw new m.p("cimd discovery invoked without the oauth-provider plugin installed");let h=f.options,g=(e=>{let t=o.get(e);if(t)return o.delete(e),o.set(e,t),t})(u),w=Date.now();if(g&&g.expiresAt>w)return p||eK(t,u,g.metadata,e,h);let y=n.get(u);if(void 0!==y)return y;let b=(e=>{let t=Date.now(),r=s.get(e);if(a.minimumFetchIntervalMs>0&&void 0!==r&&t-r<a.minimumFetchIntervalMs)throw ez("metadata document fetch is within the per-client minimum interval");if(!s.has(e))for(;s.size>=i;){let e=!1;for(let[r,i]of s)if(!n.has(r)&&(!(a.minimumFetchIntervalMs>0)||!(t-i<a.minimumFetchIntervalMs))){s.delete(r),e=!0;break}if(!e)throw ez("metadata fetch client state is at capacity")}let o=((e,t)=>{let r=l.get(e);if(r)return eW(r.fetchStartTimesMs,t),l.delete(e),l.set(e,r),r;for(;l.size>=i;){let e=!1;for(let[r,i]of l)if(eW(i.fetchStartTimesMs,t),!(i.activeFetchCount>0)&&!(i.fetchStartTimesMs.length>0)){l.delete(r),e=!0;break}if(!e)throw ez("metadata fetch origin state is at capacity")}let a={activeFetchCount:0,fetchStartTimesMs:[]};return l.set(e,a),a})(new URL(e).origin,t);if(eW(c,t),d>=a.maximumConcurrentFetches)throw ez("global metadata fetch concurrency limit exceeded");if(o.activeFetchCount>=a.maximumConcurrentFetchesPerOrigin)throw ez("metadata fetch concurrency limit exceeded for client origin");if(c.length>=a.maximumFetchesPerMinute)throw ez("global metadata fetch rate limit exceeded");if(o.fetchStartTimesMs.length>=a.maximumFetchesPerOriginPerMinute)throw ez("metadata fetch rate limit exceeded for client origin");s.delete(e),s.set(e,t),c.push(t),o.fetchStartTimesMs.push(t),d+=1,o.activeFetchCount+=1;let u=!1;return()=>{u||(u=!0,d-=1,o.activeFetchCount-=1)}})(u),E=(async()=>{let a,n=await eF(t,u,e,g?{etag:g.etag,lastModified:g.lastModified}:void 0);if("not-modified"===n.status&&!g)throw f="Metadata document returned 304 without a validated cached document",new ex.E("BAD_REQUEST",{error:"invalid_client",error_description:f});let l="modified"===n.status?n.metadata:g.metadata,c=await eK(t,u,l,e,h,p??void 0),d=(a=function(e,t,r){let{directives:i,duplicates:a}=function(e){let t=new Map,r=new Set;for(let i of e?.split(",")??[]){let[e,...a]=i.trim().split("="),o=e?.toLowerCase();if(!o)continue;t.has(o)&&r.add(o);let n=a.join("=").trim();t.set(o,!n||n.replace(/^"|"$/g,""))}return{directives:t,duplicates:r}}(e.cacheControl),o=e.vary?.split(",").some(e=>"*"===e.trim());if(i.has("no-store")||i.has("private")||o)return{cacheable:!1,expiresAt:r};let n=function(e,t){if("number"==typeof e)return Math.max(0,1e3*e);let r=Math.floor(t/1e3);return Math.max(0,((0,eN.x)(e,r)-r)*1e3)}(t,r);if(i.has("no-cache"))return{cacheable:!0,expiresAt:r};let s=eY(e.age)??0,l=e.date?Date.parse(e.date):r,c=Math.max(Number.isFinite(l)?Math.max(0,r-l):0,1e3*s),d=null,u=i.has("s-maxage"),p=eY(i.get("s-maxage")),f=i.has("max-age"),m=eY(i.get("max-age")),h=u?null===p||a.has("s-maxage"):f&&(null===m||a.has("max-age")),g=u?p:m;if(h)d=0;else if(null!==g)d=Math.max(0,1e3*g-c);else if(e.expires){let t=Date.parse(e.expires);Number.isFinite(t)&&(d=Math.max(0,t-(Number.isFinite(l)?l:r)-c))}return{cacheable:!0,expiresAt:r+Math.min(n,d??n)}}(y="modified"===n.status?n.cacheHeaders:(m=g.responseCacheHeaders,{cacheControl:(w=n.cacheHeaders).cacheControl??m.cacheControl,vary:w.vary??m.vary,expires:w.expires??m.expires,date:w.date??m.date,age:w.age??m.age,etag:w.etag??m.etag,lastModified:w.lastModified??m.lastModified}),r,Date.now())).cacheable?{metadata:l,expiresAt:a.expiresAt,etag:y.etag,lastModified:y.lastModified,responseCacheHeaders:y}:null;if(d){var f,m,w,y;for(o.delete(u);o.size>=i;){let e=o.keys().next().value;if("string"!=typeof e)break;o.delete(e)}o.set(u,d)}else o.delete(u);return s.delete(u),c})();n.set(u,E);try{return await E}catch(e){throw s.delete(u),s.set(u,Date.now()),e}finally{n.get(u)===E&&n.delete(u),b()}}}(e),{id:e$,matches:eC,resolve:t,fetchClientMetadataResource:e.fetchClientMetadataResource,discoveryMetadata:{client_id_metadata_document_supported:!0}});return{id:"cimd",version:"1.7.16",init(e){(0,eT.L)(e,{clientDiscovery:r})}}}],100642);var eQ=e.i(300794),eG=e.i(743698),eJ=e.i(761095),eZ=e.i(81111);let eX=new Set([204,205,304]),e0=async(e,t)=>{let r=new Request(e,t),i=new URL(r.url);if("https:"!==i.protocol)throw TypeError("CIMD Node transport requires an HTTPS URL");if("GET"!==r.method&&"HEAD"!==r.method)throw TypeError("CIMD Node transport supports only GET and HEAD");let a=await (0,eQ.lookup)(i.hostname,{all:!0,verbatim:!0});if(0===a.length)throw TypeError("metadata hostname returned no DNS addresses");for(let e of a)if(!(0,eO.$)(e.address))throw TypeError("metadata hostname must resolve only to public-routable addresses");let o=a[0],n=Object.fromEntries(r.headers.entries());n.host=i.host;let s=t?.signal??(e instanceof Request?e.signal:r.signal);return new Promise((e,t)=>{let a=(0,eG.request)(i,{agent:!1,headers:n,method:r.method,servername:0===(0,eJ.isIP)(i.hostname.replace(/^\[|\]$/g,""))?i.hostname:void 0,signal:s,lookup:(e,t,r)=>{t.all?r(null,[o]):r(null,o.address,o.family)}},i=>{let a=i.statusCode??500,o="HEAD"===r.method||eX.has(a)?null:eZ.Readable.toWeb(i);try{e(new Response(o,{headers:function(e){let t=new Headers;for(let[r,i]of Object.entries(e))if(Array.isArray(i))for(let e of i)t.append(r,e);else void 0!==i&&t.append(r,i);return t}(i.headers),status:a,statusText:i.statusMessage}))}catch(e){i.destroy(),t(e)}});a.once("error",t),a.end()})};e.s(["f",0,e0],781615)},303361,e=>{"use strict";let t=new Set(["localhost","127.0.0.1","::1","[::1]"]);function r(e){let r,i=e.trim();if(!i)throw Error("APP_ORIGINS contains an empty entry.");if(/[\s/\\]/.test(i.replace(/^https?:\/\//,"")))throw Error(`APP_ORIGINS entry "${i}" must be a bare host or an origin, with no path.`);if(i.includes("@"))throw Error(`APP_ORIGINS entry "${i}" must not contain credentials.`);let a=/^(https?):\/\/(.+)$/.exec(i),o=a?"https"===a[1]?"https:":"http:":null,n=a?a[2]:i,s=/^(\[[^\]]+\]|[^:]+)(?::(\d+))?$/.exec(n);if(!s)throw Error(`APP_ORIGINS entry "${i}" is not a valid host.`);let l=s[1].toLowerCase(),c=s[2]??null;if(!l||"."===l)throw Error(`APP_ORIGINS entry "${i}" is not a valid host.`);let d=l.includes("*");return d&&function(e,t){let r=e.split(".");if(r.slice(1).some(e=>e.includes("*")))throw Error(`APP_ORIGINS entry "${t}" may only use a wildcard in its leftmost label.`);if("*"!==r[0])throw Error(`APP_ORIGINS entry "${t}" must use "*" as a whole label, for example "*.example.com".`);if(r.length<3)throw Error(`APP_ORIGINS entry "${t}" is too broad; a wildcard needs at least two literal labels after it.`)}(l,i),{hostname:l,host:c?`${l}:${c}`:l,port:c,protocol:o,wildcard:d,loopback:(r=l.toLowerCase().replace(/^\[|\]$/g,""),!!(t.has(r)||"::1"===r||r.endsWith(".localhost"))||/^127\./.test(r))}}function i(e,t){return e.protocol?e.protocol:e.loopback?"http:":t?"https:":"http:"}let a=!1;function o(e){let t=e.trim().toLowerCase();return!(!t||/[\s/\\@]/.test(t))&&/^(\[[^\]]+\]|[^:]+)(?::\d+)?$/.test(t)}function n(e,t){let r=e.trim().toLowerCase();if(!r)return!1;let i=/^(\[[^\]]+\]|[^:]+)(?::(\d+))?$/.exec(r);if(!i)return!1;let a=i[1],o=i[2]??null;return(!t.port||t.port===o)&&function(e,t){let r=e.trim().toLowerCase();if(!r)return!1;if(!t.wildcard)return t.hostname===r;let i=t.hostname.slice(1);return r.endsWith(i)&&r.length>i.length}(a,t)}function s(e,t){let r=t=>{let r=e.headers.get(t)?.split(",")[0]?.trim();return r&&!/[\s/\\@]/.test(r)?r:null},i=t?r("x-forwarded-host"):null,a=t?r("x-forwarded-proto"):null,n=i??r("host");if(n&&o(n)){let t="https"===a||"http"===a?a:new URL(e.url).protocol.replace(":","");return`${t}://${n.toLowerCase()}`}try{return new URL(e.url).origin}catch{return null}}e.s(["J",0,function(e){if("inferred"!==e.mode)return"single"===e.mode?e.canonical:{allowedHosts:e.patterns.flatMap(e=>e.port?[e.host]:[e.host,`${e.host}:*`]),protocol:e.allHttps?"https":"auto",fallback:e.canonical}},"K",0,function(e,t){let r=e.headers.get("sec-fetch-site");if(r)return"same-origin"===r||"none"===r;let i=e.headers.get("origin");if(!i)return!0;let a=s(e,t);return!!a&&i.trim().toLowerCase()===a},"L",0,function(e,t){let r=t.trim();if(!r)return!1;let i=r;if(/^https?:\/\//i.test(r))try{i=new URL(r).host}catch{return!1}return"inferred"===e.mode?o(i):e.patterns.some(e=>n(i,e))},"v",0,s,"Y",0,r,"U",0,function(e=process.env){let t,o="phase-production-build"===e.NEXT_PHASE,s="production"===e.NODE_ENV&&!o,l=e.APP_ORIGINS?.trim(),c=function(e){let t,r=e.PUBLIC_BASE_URL?.trim();if(!r)return null;try{t=new URL(r)}catch{throw Error("PUBLIC_BASE_URL must be an absolute http or https URL.")}if("http:"!==t.protocol&&"https:"!==t.protocol)throw Error("PUBLIC_BASE_URL must use http or https.");return t}(e),d=l?l.split(",").map(e=>e.trim()).filter(Boolean).map(r):[];if(s&&0===d.length&&!c)return a||(a=!0,console.warn("[origins] Neither APP_ORIGINS nor PUBLIC_BASE_URL is set. Each request's own Host header will be trusted, so absolute URLs this server generates — OAuth callbacks, iOS enrollment and install links, the GitHub webhook URL — follow whatever host the caller asked for. Set APP_ORIGINS to the hostname(s) this server is reached at to pin them.")),{patterns:[],canonical:null,mode:"inferred",allHttps:!1};let u=s?d:function(e){let t=new Map;for(let r of e){let e=t.get(r.host);e?"http:"===r.protocol&&t.set(r.host,{...e,protocol:"http:"}):t.set(r.host,r)}return[...t.values()]}([...(t=e.PORT?.trim()||"3000",["localhost","127.0.0.1","[::1]"].map(e=>r(`http://${e}:${t}`))),...d]);if(0===u.length&&c&&(u=[r(c.origin)]),s){let e=u.filter(e=>e.wildcard);if(e.length>0)throw Error(`APP_ORIGINS may not use wildcards in production (${e.map(e=>e.hostname).join(", ")}). A wildcard trusts every host under it for CSRF and for post-login redirects; list exact hosts instead.`)}c&&!u.some(e=>n(c.host,e))&&(u=[...u,r(c.origin)]);let p=u.find(e=>!e.wildcard);if(!p&&!c)throw Error("APP_ORIGINS must include at least one exact origin; a wildcard alone gives this server no address to put in the links it generates.");return{patterns:u,canonical:c?.origin??`${i(p,s)}//${p.host}`,mode:1!==u.length||u[0].wildcard?"multi":"single",allHttps:u.every(e=>e.loopback||"https:"===i(e,s))}}])},435387,e=>{"use strict";let t=["mcp:read","mcp:write","mcp:destructive"],r={read:["mcp:read"],write:["mcp:read","mcp:write"],destructive:[...t]};e.s(["v",0,r,"n",0,t])},576257,434402,e=>{"use strict";var t=e.i(363004),r=e.i(931129),i=e.i(204721),a=e.i(890659),o=e.i(370728),n=e.i(749599),s=e.i(483052),l=e.i(13681),c=e.i(483319),d=e.i(58260),u=e.i(292243),p=e.i(303361),f=e.i(243783),m=e.i(169040),h=e.i(789714),g=e.i(782393),w=e.i(464661),y=e.i(320170),b=e.i(666680),E=e.i(100642),A=e.i(781615),I=e.i(413417),_=e.i(71616),k=e.i(756023),T=e.i(112996),v=e.i(272003),U=e.i(287292),R=e.i(947448),S=e.i(762542),x=e.i(21568),O=e.i(827957),D=e.i(741242),N=e.i(397554),L=e.i(709939);function P(e){let t=e.context.options.baseURL;return"string"==typeof t?t||"better-auth:session-cache":e.context.baseURL||"better-auth:session-cache"}async function C(e,t,r){let i=(0,D.f)(t).kid;if(!i)return e.context.logger.debug("Cookie-cache JWT missing kid in header"),null;let a=await (0,U.i)(e.context.adapter,r).getAllKeys(e);if(!a?.length)return e.context.logger.debug("No JWKS keys available for cookie-cache JWT"),null;let o=a.find(e=>e.id===i);if(!o)return e.context.logger.debug(`No JWKS key found for cookie-cache JWT kid: ${i}`),null;let n=o.alg??(0,U.V)(r);return{alg:n,publicKey:await (0,N.g)(JSON.parse(o.publicKey),n)}}async function q(e,t,r,i){let a=await (0,S.L)(e,i);if(!a)throw new _.p("`jwt({ sessionCookieCache: true })` requires locally managed JWT plugin keys and does not support `jwt.sign`.");return await new O.f({...t,sid:t.session.token}).setProtectedHeader({alg:a.alg,kid:a.kid,typ:x.Y}).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+r).setIssuer(P(e)).setAudience(x.H).setSubject(t.user.id).sign(a.privateKey)}async function j(e,t,r){try{if("better-auth.session-cache+jwt"!==(0,D.f)(t).typ)return null;let i=await C(e,t,r);if(!i)return null;let{payload:a}=await (0,L.f)(t,i.publicKey,{...(0,x.V)({issuer:P(e)}),algorithms:[i.alg]}),o=(0,x.R)(a);if(!o)return null;return{payload:o,expiresAt:o.exp?1e3*o.exp:Date.now()}}catch(t){return e.context.logger.debug("Cookie-cache JWT verification failed",t),null}}let $={jwks:{fields:{publicKey:{type:"string",required:!0},privateKey:{type:"string",required:!0},createdAt:{type:"date",required:!0},expiresAt:{type:"date",required:!1},alg:{type:"string",required:!1},crv:{type:"string",required:!1}}}};var B=e.i(497515),V=e.i(530501);async function M(e,t){let r=(0,B.g)();try{let i=e.split(".");if(3!==i.length)return null;let a=new TextDecoder().decode(V.t.decode(i[0])),o=JSON.parse(a).kid;if(!o)return r.context.logger.debug("JWT missing kid in header"),null;let n=await (0,U.i)(r.context.adapter,t).getAllKeys(r);if(!n||0===n.length)return r.context.logger.debug("No JWKS keys available"),null;let s=n.find(e=>e.id===o);if(!s)return r.context.logger.debug(`No JWKS key found for kid: ${o}`),null;let l=JSON.parse(s.publicKey),c=s.alg??(0,U.V)(t),d=await (0,N.g)(l,c),u="string"==typeof r.context.options.baseURL?r.context.options.baseURL:void 0,p=t?.jwt?.issuer??u,f=t?.jwt?.audience??u;p&&f||r.context.logger.warn("[better-auth] The JWT plugin is verifying a JWT without checking its issuer or audience because no base URL was resolved for this call. Set `baseURL`, or `jwt.issuer` and `jwt.audience` in the JWT plugin options.");let{payload:m}=await (0,L.f)(e,d,{issuer:p,audience:f,algorithms:[c]});if(!m.sub||!m.aud)return null;return m}catch(e){return r.context.logger.debug("JWT verification failed",e),null}}var F=e.i(907855);let K=F.object({payload:F.record(F.string(),F.any()),overrideOptions:F.record(F.string(),F.any()).optional()}),z=F.object({token:F.string(),issuer:F.string().optional()});var H=e.i(435387);let W="aide_mcp_authorization_id";function Y(){throw new _.E("BAD_REQUEST",{error:"invalid_grant",error_description:"The MCP authorization is inactive. Authorize this application again."})}function Q(e,t){return async r=>{let i;try{i=JSON.parse(r.value)}catch{return}if(i?.type!=="authorization_code")return;let a=i.resource??i.query?.resource;(Array.isArray(a)?a.includes(t.resource):a===t.resource)||Y(),("string"!=typeof i.userId||"string"!=typeof i.query?.client_id)&&Y();let o=await e.oauthClient.findUnique({where:{clientId:i.query.client_id}}),n=await e.mcpAuthorization.create({data:{id:(0,b.randomUUID)(),authorizationCodeId:r.identifier,userId:i.userId,clientId:i.query.client_id,clientName:o?.name??i.query.client_id,scopes:i.query.scope??""}});return{data:{...r,value:JSON.stringify({...i,referenceId:n.id})}}}}function G(e,t){let r=[...H.n,"offline_access"];return[(e=>{if(e?.jwt?.sign&&!e.jwks?.remoteUrl)throw new _.p("options.jwks.remoteUrl must be set when using options.jwt.sign");if(e?.jwks?.remoteUrl&&!e.jwks?.keyPairConfig?.alg)throw new _.p("options.jwks.keyPairConfig.alg must be specified when options.jwks.remoteUrl is used for OpenID metadata");let t=e?.jwks?.jwksPath??"/jwks";if("string"!=typeof t||0===t.length||!t.startsWith("/")||t.includes(".."))throw new _.p("options.jwks.jwksPath must be a non-empty string starting with '/' and not contain '..'");return{id:"jwt",version:v.f,options:e,init(t){if(!e?.sessionCookieCache)return;if(t.options.session?.cookieCache?.strategy!=="jwt")throw new _.p('`jwt({ sessionCookieCache: true })` requires `session.cookieCache.strategy = "jwt"`.');if(e.jwt?.sign)throw new _.p("`jwt({ sessionCookieCache: true })` requires locally managed JWT plugin keys and does not support `jwt.sign`.");let r=e.jwks?.gracePeriod,i=t.options.session.cookieCache.maxAge||300;return void 0!==r&&i>r&&t.logger.warn(`[better-auth] \`session.cookieCache.maxAge\` (${i}s) exceeds the JWT plugin JWKS grace period (${r}s). Rotated keys may stop verifying cookie-cache JWTs before the cookie expires.`),{context:{sessionConfig:{...t.sessionConfig,cookieCacheSigner:{sign:(t,r,i)=>q(t,r,i,e),verify:(t,r)=>j(t,r,e)}}}}},endpoints:{getJwks:(0,a.g)(t,{method:"GET",metadata:{openapi:{operationId:"getJSONWebKeySet",description:"Get the JSON Web Key Set",responses:{200:{description:"JSON Web Key Set retrieved successfully",content:{"application/json":{schema:{type:"object",properties:{keys:{type:"array",description:"Array of public JSON Web Keys",items:{type:"object",properties:{kid:{type:"string",description:"Key ID uniquely identifying the key, corresponds to the 'id' from the stored Jwk"},kty:{type:"string",description:"Key type (e.g., 'RSA', 'EC', 'OKP')"},alg:{type:"string",description:"Algorithm intended for use with the key (e.g., 'EdDSA', 'RS256')"},use:{type:"string",description:"Intended use of the public key (e.g., 'sig' for signature)",enum:["sig"],nullable:!0},n:{type:"string",description:"Modulus for RSA keys (base64url-encoded)",nullable:!0},e:{type:"string",description:"Exponent for RSA keys (base64url-encoded)",nullable:!0},crv:{type:"string",description:"Curve name for elliptic curve keys (e.g., 'Ed25519', 'P-256')",nullable:!0},x:{type:"string",description:"X coordinate for elliptic curve keys (base64url-encoded)",nullable:!0},y:{type:"string",description:"Y coordinate for elliptic curve keys (base64url-encoded)",nullable:!0}},required:["kid","kty","alg"]}}},required:["keys"]}}}}}}}},async t=>{if(e?.jwks?.remoteUrl)throw new _.E("NOT_FOUND");let r=(0,U.i)(t.context.adapter,e),i=await r.getAllKeys(t);if(i&&i?.length!==0||(await (0,R.K)(t,e),i=await r.getAllKeys(t)),!i?.length)throw new _.p("No key sets found. Make sure you have a key in your database.");let a=Date.now(),o=(e?.jwks?.gracePeriod??2592e3)*1e3,n=i.filter(e=>!e.expiresAt||e.expiresAt.getTime()+o>a),s=e?.jwks?.keyPairConfig,l=s&&"crv"in s?s.crv:void 0;return t.json({keys:n.map(t=>({alg:t.alg??(0,U.V)(e),crv:t.crv??l,...JSON.parse(t.publicKey),kid:t.id}))})}),getToken:(0,a.g)("/token",{method:"GET",requireHeaders:!0,use:[T.Z],metadata:{openapi:{operationId:"getJSONWebToken",description:"Get a JWT token",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}}}}}}}}}},async t=>{let r=await (0,S.d)(t,e);return t.json({token:r})}),signJWT:a.g.serverOnly({method:"POST",metadata:{$Infer:{body:{}}},body:K},async t=>{let r=await (0,S.X)(t,{options:{...e,...t.body.overrideOptions},payload:t.body.payload});return t.json({token:r})}),verifyJWT:a.g.serverOnly({method:"POST",metadata:{$Infer:{body:{},response:{}}},body:z},async t=>{let r=t.body.issuer?{...e,jwt:{...e?.jwt,issuer:t.body.issuer}}:e,i=await M(t.body.token,r);return t.json({payload:i})})},hooks:{after:[{matcher:e=>"/get-session"===e.path,handler:(0,a.a)(async t=>{if(e?.disableSettingJwtHeader)return;let r=t.context.session||t.context.newSession;if(r&&r.session){let r=await (0,S.d)(t,e),i=new Set((t.context.responseHeaders?.get("access-control-expose-headers")||"").split(",").map(e=>e.trim()).filter(Boolean));i.add("set-auth-jwt"),t.setHeader("set-auth-jwt",r),t.setHeader("Access-Control-Expose-Headers",Array.from(i).join(", "))}})}]},schema:(0,k.C)($,e?.schema)}})({jwt:{issuer:t.issuer,audience:t.resource}}),(0,I.B)({loginPage:"/mcp/sign-in",consentPage:"/mcp/consent",resource:t.resource,scopes:r,resources:[{identifier:t.resource,allowedScopes:r,accessTokenTtl:300,refreshTokenTtl:2592e3}],grantTypes:["authorization_code","refresh_token"],accessTokenExpiresIn:300,refreshTokenExpiresIn:2592e3,refreshTokenReuseInterval:0,clientRegistrationDefaultScopes:["mcp:read"],clientRegistrationAllowedScopes:r,allowDynamicClientRegistration:t.dcrEnabled,allowUnauthenticatedClientRegistration:t.dcrEnabled,clientRegistrationDefaultApplicationType:"infer",extensions:[{claims:{accessToken:async({user:r,client:i,referenceId:a,resources:o,scopes:n})=>{r&&a&&o?.includes(t.resource)||Y();let s=await e.mcpAuthorization.findFirst({where:{id:a,userId:r.id,clientId:i.clientId,revokedAt:null,user:{is:{id:r.id}}}});return(!s||n.some(e=>!s.scopes.split(" ").includes(e)))&&Y(),{[W]:s.id}}}}]}),(0,E.f)({fetchClientMetadataResource:A.f,metadataProfile:"mcp-2026-07-28"})]}e.s(["P",0,W,"y",0,G,"K",0,Q],434402);let J={disableClientRequest:!0,expiresIn:1,storeToken:"hashed"},Z=(0,u.f)({...J,disableSetSessionCookie:!0}).endpoints.verifyOneTimeToken,X={user:["create","list","set-password","set-email","get","update"],session:["list","revoke","delete"]},ee=(0,c.y)(X),et=ee.newRole(X);async function er(e,t,r){let i=await e.$context,{user:a}=await Z({body:{token:t},context:i}),o=await i.internalAdapter.createSession(a.id,!1,{userAgent:r});return{user:a,session:o}}let ei=null;e.s(["W",0,function(){return ei||(ei=(0,f.U)().then(e=>(function(e,c=(0,m.L)(),f=(0,y.f)()){let b=c.provider,E=(0,p.J)(c.origins),A=b?.providerId.toLowerCase()==="github"?b.userInfoUrl:void 0,I=(0,m._)(c.mode)&&b?(0,d.f)({config:[{providerId:b.providerId,clientId:b.clientId,clientSecret:b.clientSecret,scopes:b.scopes,discoveryUrl:b.discoveryUrl,authorizationUrl:b.authorizationUrl,tokenUrl:b.tokenUrl,userInfoUrl:b.userInfoUrl,getUserInfo:A?async e=>e.accessToken?(0,g.f)(A,e.accessToken):null:void 0,pkce:!0,requireIdTokenVerification:b.requireIssuerValidation,disableImplicitSignUp:!1}]}):null;return(0,i.f)({appName:"AI Development Environment",baseURL:"object"==typeof E?{...E,protocol:"auto"}:E,disabledPaths:f?["/token"]:[],trustedOrigins:e=>{if(!e)return[];let t=(0,p.v)(e,c.trustProxyHeaders);return t&&(0,p.L)(c.origins,t)?[t]:[]},secret:c.secret,logger:{log:h.f},hooks:{before:(0,a.a)(async e=>{let t=e.request?(0,p.v)(e.request,c.trustProxyHeaders):null,r=e.headers?.get("cookie")??"",i=t?"https:"===new URL(t).protocol:!!/(?:^|;\s*)__Secure-better-auth\.session_token=/.test(r)||!/(?:^|;\s*)better-auth\.session_token=/.test(r)&&void 0,a={...e.context.options,advanced:{...e.context.options.advanced,useSecureCookies:i}};e.context.authCookies=(0,o.e)(a),e.context.createAuthCookie=(0,o.g)(a)})},advanced:{trustedProxyHeaders:c.trustProxyHeaders},database:(0,r.f)(e,{provider:"sqlite"}),emailAndPassword:{enabled:(0,m.Z)(c.mode),requireEmailVerification:!1},account:{accountLinking:{enabled:!0,disableImplicitLinking:!0,allowDifferentEmails:!1}},databaseHooks:{...w.x,...f?{verification:{create:{before:Q(e,f)}}}:{}},plugins:[function(){let e=(0,s.f)({ac:ee,roles:{user:et},defaultRole:"user",adminRoles:["user"]}),{setRole:t,banUser:r,unbanUser:i,impersonateUser:a,stopImpersonating:o,removeUser:n,...l}=e.endpoints;return{...e,endpoints:l}}(),(0,t.f)({schema:{apikey:{modelName:"apiKey"}},defaultPrefix:"aide_",requireName:!0,startingCharactersConfig:{shouldStore:!0,charactersLength:12},keyExpiration:{defaultExpiresIn:null,disableCustomExpiresTime:!1,minExpiresIn:1,maxExpiresIn:3650},rateLimit:{enabled:!1},enableSessionForAPIKeys:!1}),(0,l.f)(),(0,u.f)(J),...I?[I]:[],...f?G(e,f):[],(0,n.A)()]})})(e))),ei},"y",0,er],576257)}];
|
|
455
455
|
|
|
456
456
|
//# sourceMappingURL=_1ftldg0qwxhfp._.js.map
|