diff --git a/.gitignore b/.gitignore index a547bf36d..6ec08e091 100644 --- a/.gitignore +++ b/.gitignore @@ -1,24 +1,5 @@ -# Logs -logs -*.log -npm-debug.log* -yarn-debug.log* -yarn-error.log* -pnpm-debug.log* -lerna-debug.log* +# Environment variables +.env -node_modules -dist -dist-ssr -*.local -# Editor directories and files -.vscode/* -!.vscode/extensions.json -.idea -.DS_Store -*.suo -*.ntvs* -*.njsproj -*.sln -*.sw? +node_modules diff --git a/backend/.gitignore b/backend/.gitignore new file mode 100644 index 000000000..6ed48a986 --- /dev/null +++ b/backend/.gitignore @@ -0,0 +1,2 @@ +.env +node_modules diff --git a/backend/controllers/comment.controller.js b/backend/controllers/comment.controller.js new file mode 100644 index 000000000..137537880 --- /dev/null +++ b/backend/controllers/comment.controller.js @@ -0,0 +1,63 @@ + +import Comment from "../models/comment.model.js"; +import User from "../models/user.model.js"; + +export const getPostComments = async (req, res) => { + const comments = await Comment.find({ postId: req.params.postId }) + .populate("user", "username img") + .sort({ createdAt: -1 }); + + res.json(comments); +}; + +export const addComment = async (req, res) => { + const clerkUserId = req.auth().userId; + const postId = req.params.postId; + + if (!clerkUserId) { + return res.status(401).json("Not authenticated!"); + } + + const user = await User.findOne({ clerkUserId }); + + const newComment = new Comment({ + ...req.body, + user: user._id, // The user who made the comment + postId: postId, // The post the comment belongs to + }); + + const savedComment = await newComment.save(); + setTimeout(() => {}, 1000); + // Populate the user field before sending the response + const populatedComment = await Comment.findById(savedComment._id).populate("user", "username img"); + res.status(201).json(populatedComment); +}; + +export const deleteComment = async (req, res) => { + const clerkUserId = req.auth().userId; + const id = req.params.id; + + if (!clerkUserId) { + return res.status(401).json("Not authenticated!"); + } + + const role = req.auth().sessionClaims?.metadata?.role || "user"; + + if (role === "admin") { + await Comment.findByIdAndDelete(req.params.id); + return res.status(200).json("Comment has been deleted"); + } + + const user = await User.findOne({ clerkUserId }); + + const deletedComment = await Comment.findOneAndDelete({ + _id: id, + user: user._id, + }); + + if (!deletedComment) { + return res.status(403).json("You can delete only your comment!"); + } + + res.status(200).json("Comment deleted"); +}; diff --git a/backend/controllers/post.controller.js b/backend/controllers/post.controller.js new file mode 100644 index 000000000..19276454d --- /dev/null +++ b/backend/controllers/post.controller.js @@ -0,0 +1,111 @@ +import ImageKit from "imagekit"; +import User from "../models/user.model.js"; +import Post from "../models/post.model.js" + +import dotenv from "dotenv"; +dotenv.config(); + +export const getPosts = async (req, res) => { +const page = parseInt(req.query.page) || 1; +const limit = parseInt(req.query.limit) || 5; +const skip = (page - 1) * limit; +//const sort = { createdAt: -1 }; + + const posts = await Post + .find() + .populate("user","username") + .limit(limit) + .skip(skip); + const totalPosts = await Post.countDocuments(); + const hasMore = page * limit < totalPosts; + + + res.status(200).json({ posts, hasMore }); + +}; +export const getPost = async (req, res) => { + const post = await Post.findOne({slug:req.params.slug}) + .populate("user","username img"); + res.status(200).json(post); + +}; +export const createPost = async (req, res) => { + try { + const { title, desc, category, content, img } = req.body; + const clerkUserId = req.auth().userId; + if (!clerkUserId) { + return res.status(401).json({ message: "Unauthorized" }); + } + if (!title || !category || !content) { + return res.status(400).json({ message: "Title, category, and content are required." }); + } + const user = await User.findOne({ clerkUserId }); + if (!user) { + return res.status(404).json({ message: "User not found" }); + } + let slug = title.replace(/ /g, "-").toLowerCase(); + let existingPost = await Post.findOne({ slug }); + let counter = 2; + while (existingPost) { + slug = `${slug}-${counter}`; + existingPost = await Post.findOne({ slug }); + counter++; + } + const newPost = new Post({ + user: user._id, + slug, + title, + desc, + category, + content, + img, + }); + const post = await newPost.save(); + res.status(201).json(post); + } catch (error) { + console.error("Error creating post:", error); + // Handle Mongoose validation errors + if (error.name === 'ValidationError') { + const errors = Object.values(error.errors).map(err => err.message); + return res.status(400).json({ + message: "Validation failed", + errors: errors + }); + } + + res.status(500).json({ message: "Failed to create post", error: error.message }); + } +}; +export const deletePost = async (req, res) => { + const clerkUserId = req.auth().userId; + if(!clerkUserId){ + return res.status(401).json({message: "Unauthorized"}); + } + const user = await User.findOne({clerkUserId}); + const post = await Post.findOneAndDelete({_id: req.params.id,user: user._id,}); + res.status(200).json("post has been deleted"); +}; + + +//console.log("ImageKit ENV:", { +// publicKey: process.env.IMAGEKIT_PUBLIC_KEY, +// privateKey: process.env.IMAGEKIT_PRIVATE_KEY ? "loaded" : "missing", +// urlEndpoint: process.env.IMAGEKIT_URL_ENDPOINT, +//}); +// + const imagekit = new ImageKit({ + + publicKey: process.env.IMAGEKIT_PUBLIC_KEY, + privateKey: process.env.IMAGEKIT_PRIVATE_KEY, + urlEndpoint: process.env.IMAGEKIT_URL_ENDPOINT, + }); + +export const uploadAuth = async(req, res) => { + try { + const result = imagekit.getAuthenticationParameters(); + res.status(200).json(result); + } catch (error) { + console.error("ImageKit Auth Generation Error:", error); + res.status(500).json({ message: "Failed to generate authentication parameters." }); + } +}; \ No newline at end of file diff --git a/backend/controllers/user.controller.js b/backend/controllers/user.controller.js new file mode 100644 index 000000000..44565eb93 --- /dev/null +++ b/backend/controllers/user.controller.js @@ -0,0 +1,46 @@ +import User from "../models/user.model.js"; + +export const getUserSavedPosts = async (req, res) => { + const clerkUserId = req.auth().userId; + + if (!clerkUserId) { + return res.status(401).json("Not authenticated!"); + } + + const user = await User.findOne({ clerkUserId }); + + if (!user) { + return res.status(404).json("User not found!"); + } + + res.status(200).json(user.savedPosts); +}; + +export const savePost = async (req, res) => { + const clerkUserId = req.auth().userId; + const postId = req.body.postId; + + if (!clerkUserId) { + return res.status(401).json("Not authenticated!"); + } + + const user = await User.findOne({ clerkUserId }); + + if (!user) { + return res.status(404).json("User not found!"); + } + + const isSaved = user.savedPosts.some((p) => p === postId); + + if (!isSaved) { + await User.findByIdAndUpdate(user._id, { + $push: { savedPosts: postId }, + }); + } else { + await User.findByIdAndUpdate(user._id, { + $pull: { savedPosts: postId }, + }); + } + + res.status(200).json(isSaved ? "Post unsaved" : "Post saved"); +}; \ No newline at end of file diff --git a/backend/controllers/webhook.controller.js b/backend/controllers/webhook.controller.js new file mode 100644 index 000000000..829bfc961 --- /dev/null +++ b/backend/controllers/webhook.controller.js @@ -0,0 +1,40 @@ +import User from "../models/user.model.js"; +import { Webhook } from "svix"; + + +export const clerkWebHook = async (req, res) => { + const WEBHOOK_SECRET = process.env.CLERK_WEBHOOK_SECRET; + if(!WEBHOOK_SECRET){ + throw new Error("CLERK_WEBHOOK_SECRET is not defined") + } + const payload = req.body; + const headers = req.headers; + + const wh = new Webhook(WEBHOOK_SECRET); + let evt; + try { + evt = wh.verify(payload, headers); + } catch (err) { + console.error("Webhook verification failed:", err.message); + return res.status(400).json({message: "Webhook verification failed"}); + } + + if (evt.type === "user.created") { + try { + const newUser = new User({ + clerkUserId: evt.data.id, + username: evt.data.username || evt.data.email_addresses[0].email_address, + email: evt.data.email_addresses[0].email_address, + img: evt.data.image_url, + }); + + await newUser.save(); + return res.status(201).json({message: "User created successfully."}); + } catch (err) { + console.error("Error creating user:", err); + return res.status(500).json({ message: "Internal server error while creating user." }); + } + } + // Acknowledge other webhook events with a success response + return res.status(200).json({ message: "Webhook received, but no action taken." }); +} \ No newline at end of file diff --git a/backend/index.js b/backend/index.js new file mode 100644 index 000000000..35b2abc4c --- /dev/null +++ b/backend/index.js @@ -0,0 +1,53 @@ +import dotenv from "dotenv"; +dotenv.config(); + +import express from "express"; +import cors from "cors"; +import { clerkMiddleware } from "@clerk/express"; + +import connectDB from "./lib/connectDB.js"; +import userRouter from "./routes/user.route.js"; +import postRouter from "./routes/post.route.js"; +import commentsRouter from "./routes/comment.route.js"; +import webhookRouter from "./routes/webhook.route.js"; + +const app = express(); + +// ✅ Configure CORS properly +const allowedOrigins = ["http://localhost:5173"]; // change if needed +const corsOptions = { + origin: (origin, callback) => { + if (!origin || allowedOrigins.includes(origin)) { + callback(null, true); + } else { + callback(new Error("Not allowed by CORS")); + } + }, + optionsSuccessStatus: 200, +}; +app.use(cors(corsOptions)); + +app.use(clerkMiddleware()); +app.use(express.json()); + +// ✅ Routes +app.use("/webhooks", webhookRouter); +app.use("/api/users", userRouter); +app.use("/api/posts", postRouter); +app.use("/api/comments", commentsRouter); + +// ✅ Error handler +//app.use((err, req, res, next) => { +// res.status(err.status || 500).json({ +// message: err.message || "Something went wrong", +// status: err.status, +// stack: process.env.NODE_ENV === "development" ? err.stack : undefined, +// }); +//}); + +const port = process.env.PORT || 3000; +app.listen(port, () => { + connectDB(); + + console.log(`✅ Server is running on port ${port}`); +}); diff --git a/backend/lib/connectDB.js b/backend/lib/connectDB.js new file mode 100644 index 000000000..95c971e53 --- /dev/null +++ b/backend/lib/connectDB.js @@ -0,0 +1,13 @@ +import mongoose from "mongoose"; + +const connectDB = async () => { + try{ + await mongoose.connect(process.env.MONGO); + console.log("DB is successfully connected"); + } + catch(err) + { + console.log(err) + } +} +export default connectDB; \ No newline at end of file diff --git a/backend/models/comment.model.js b/backend/models/comment.model.js new file mode 100644 index 000000000..0819a62f5 --- /dev/null +++ b/backend/models/comment.model.js @@ -0,0 +1,31 @@ +import { Schema } from "mongoose"; +import mongoose from "mongoose"; + + + +const commentSchema = new Schema({ + user: { + type: Schema.Types.ObjectId, + ref: "User", + required: true, + + }, + postId: { + type: Schema.Types.ObjectId, + ref: "Post", + required: true, + + }, + desc: { + type: String, + required: true, + + }, + + +}, + { + timestamps: true + }); + export default mongoose.model("Comment", commentSchema); + diff --git a/backend/models/post.model.js b/backend/models/post.model.js new file mode 100644 index 000000000..1c8d8d66e --- /dev/null +++ b/backend/models/post.model.js @@ -0,0 +1,61 @@ +import mongoose from "mongoose"; +import { Schema } from "mongoose"; + + + + +const postSchema = new Schema({ + user: { + + type: Schema.Types.ObjectId, + ref: "User", + required: true, + + }, + + + img: { + type: String, + + }, + title: { + type: String, + required: true, + + }, + slug: { + type: String, + required: true, + unique: true + }, + desc: { + type: String, + + }, + category: { + type: String, + required: true, + enum: ["general", "web-design", "development", "database", "seo", "marketing"] + }, + content: { + type: String, + required: true + }, + isFeatured: { + type: Boolean, + default: false + }, + visit: { + type: Number, + default: 0 + }, + + + + +}, + { + timestamps: true + }); + export default mongoose.model("Post", postSchema); + diff --git a/backend/models/user.model.js b/backend/models/user.model.js new file mode 100644 index 000000000..d257ab22d --- /dev/null +++ b/backend/models/user.model.js @@ -0,0 +1,43 @@ +import { Schema } from "mongoose"; +import mongoose from "mongoose"; + + + +const userSchema = new Schema({ + clerkUserId: { + type: String, + required: true, + unique: true + }, + username: { + type: String, + required: true, + unique: true + }, + email: { + type: String, + required: true, + unique: true + }, + img: { + type: String, + + }, + savedPosts: { + type: [String], + default: [] + }, + role: { + type: String, + enum: ["user", "admin"], + default: "user" +}, + + + +}, + { + timestamps: true + }); + export default mongoose.model("User", userSchema); + diff --git a/backend/netlify/functions/my-api-function.js b/backend/netlify/functions/my-api-function.js new file mode 100644 index 000000000..b52d7f0ce --- /dev/null +++ b/backend/netlify/functions/my-api-function.js @@ -0,0 +1,68 @@ +// backend/netlify/functions/my-api-function.js +// This function will be accessible at /.netlify/functions/my-api-function + +// Example: If your backend uses Mongoose, ensure it's initialized here or in a shared utility. +// You might need to move your Mongoose connection logic into a utility file +// that each function can import and call. +// const mongoose = require('mongoose'); +// let cachedDb = null; + +// async function connectToDatabase() { +// if (cachedDb) { +// return cachedDb; +// } +// const connectionString = process.env.MONGODB_URI; // Set this in Netlify Environment Variables +// cachedDb = await mongoose.connect(connectionString, { +// useNewUrlParser: true, +// useUnifiedTopology: true, +// }); +// return cachedDb; +// } + +exports.handler = async (event, context) => { + try { + // await connectToDatabase(); // Connect to your database + + // Access environment variables (e.g., Clerk Secret Key) + const clerkSecretKey = process.env.CLERK_SECRET_KEY; + + // Your existing backend logic for this specific API endpoint + // For example, if this was a GET request to /api/items: + // const items = await Item.find({}); + + // The 'event' object contains request details (method, path, headers, body, queryStringParameters) + // The 'context' object contains information about the invocation, function, and user. + + // Example: Handle different HTTP methods + if (event.httpMethod === 'GET') { + return { + statusCode: 200, + body: JSON.stringify({ + message: "Hello from Netlify Function!", + secretKeyStatus: clerkSecretKey ? "Clerk Secret Key is set" : "Clerk Secret Key NOT found", + // data: items, + }), + }; + } else if (event.httpMethod === 'POST') { + const requestBody = JSON.parse(event.body); + // Process POST request + return { + statusCode: 201, + body: JSON.stringify({ received: requestBody, status: "processed" }), + }; + } + + return { + statusCode: 405, + body: JSON.stringify({ message: "Method Not Allowed" }), + }; + + } catch (error) { + console.error("Function error:", error); + return { + statusCode: 500, + body: JSON.stringify({ error: error.message || "Internal Server Error" }), + }; + } +}; +// backend/netlify/functions/my-api-function.js \ No newline at end of file diff --git a/backend/node_modules/.bin/uuid b/backend/node_modules/.bin/uuid new file mode 100644 index 000000000..0c2d46962 --- /dev/null +++ b/backend/node_modules/.bin/uuid @@ -0,0 +1,16 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) + if command -v cygpath > /dev/null 2>&1; then + basedir=`cygpath -w "$basedir"` + fi + ;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../uuid/dist/bin/uuid" "$@" +else + exec node "$basedir/../uuid/dist/bin/uuid" "$@" +fi diff --git a/backend/node_modules/.bin/uuid.cmd b/backend/node_modules/.bin/uuid.cmd new file mode 100644 index 000000000..0f2376eaf --- /dev/null +++ b/backend/node_modules/.bin/uuid.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\uuid\dist\bin\uuid" %* diff --git a/backend/node_modules/.bin/uuid.ps1 b/backend/node_modules/.bin/uuid.ps1 new file mode 100644 index 000000000..78046284b --- /dev/null +++ b/backend/node_modules/.bin/uuid.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../uuid/dist/bin/uuid" $args + } else { + & "$basedir/node$exe" "$basedir/../uuid/dist/bin/uuid" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../uuid/dist/bin/uuid" $args + } else { + & "node$exe" "$basedir/../uuid/dist/bin/uuid" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/backend/node_modules/.package-lock.json b/backend/node_modules/.package-lock.json new file mode 100644 index 000000000..6e4de99f4 --- /dev/null +++ b/backend/node_modules/.package-lock.json @@ -0,0 +1,1528 @@ +{ + "name": "backend", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "node_modules/@clerk/backend": { + "version": "2.15.0", + "resolved": "https://registry.npmjs.org/@clerk/backend/-/backend-2.15.0.tgz", + "integrity": "sha512-JQXLbCiZbxU+wvPGuLowD19ZivkTmhfZUB8eQMPQe8ByNict6/L6kCm2pAxg6MQuhl1B981K/LJF9J1eAkydgg==", + "license": "MIT", + "dependencies": { + "@clerk/shared": "^3.26.1", + "@clerk/types": "^4.88.0", + "cookie": "1.0.2", + "standardwebhooks": "^1.0.0", + "tslib": "2.8.1" + }, + "engines": { + "node": ">=18.17.0" + } + }, + "node_modules/@clerk/backend/node_modules/cookie": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-1.0.2.tgz", + "integrity": "sha512-9Kr/j4O16ISv8zBBhJoi4bXOYNTkFLOqSL3UDB0njXxCXNezjeyVrJyGOWtgfs/q2km1gwBcfH8q1yEGoMYunA==", + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@clerk/express": { + "version": "1.7.33", + "resolved": "https://registry.npmjs.org/@clerk/express/-/express-1.7.33.tgz", + "integrity": "sha512-/AE9QIDH4+2pEuYGdmITDFebsFXuYGtBJlZ84WUWfmFAQ53XUOHJvPWxaj+YcXLzDFXz4Fx0jAbl34qetCM1zA==", + "license": "MIT", + "dependencies": { + "@clerk/backend": "^2.15.0", + "@clerk/shared": "^3.26.1", + "@clerk/types": "^4.88.0", + "tslib": "2.8.1" + }, + "engines": { + "node": ">=18.17.0" + }, + "peerDependencies": { + "express": "^4.17.0 || ^5.0.0" + } + }, + "node_modules/@clerk/shared": { + "version": "3.26.1", + "resolved": "https://registry.npmjs.org/@clerk/shared/-/shared-3.26.1.tgz", + "integrity": "sha512-84dAJutr7JAwKwRI0fRj6mFy3D521okNIiCkJ+ffMp0lniQr5IXQSFqkCEd+cQ3bImr1YHKCGVMLkahZI6s9Ng==", + "hasInstallScript": true, + "license": "MIT", + "dependencies": { + "@clerk/types": "^4.88.0", + "dequal": "2.0.3", + "glob-to-regexp": "0.4.1", + "js-cookie": "3.0.5", + "std-env": "^3.9.0", + "swr": "2.3.4" + }, + "engines": { + "node": ">=18.17.0" + }, + "peerDependencies": { + "react": "^18.0.0 || ^19.0.0 || ^19.0.0-0", + "react-dom": "^18.0.0 || ^19.0.0 || ^19.0.0-0" + }, + "peerDependenciesMeta": { + "react": { + "optional": true + }, + "react-dom": { + "optional": true + } + } + }, + "node_modules/@clerk/types": { + "version": "4.88.0", + "resolved": "https://registry.npmjs.org/@clerk/types/-/types-4.88.0.tgz", + "integrity": "sha512-OAepuiszOrheIThdCtBRiRSq0A3grlD2yhUUO8kvMFv4Uys95gSzkzuvQjUWXZZ23yOdTl6eRUXjtjCGto116w==", + "license": "MIT", + "dependencies": { + "csstype": "3.1.3" + }, + "engines": { + "node": ">=18.17.0" + } + }, + "node_modules/@imagekit/nodejs": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/@imagekit/nodejs/-/nodejs-7.0.1.tgz", + "integrity": "sha512-9BQiB9hUhzid3fEPUO2WFi6ejf+3WmAVF7nJhr3bznulDeStZ+XA+671LuhHyi/SkOcv9G9q7BJlwWHnMU586Q==", + "license": "Apache-2.0", + "dependencies": { + "standardwebhooks": "^1.0.0" + } + }, + "node_modules/@mongodb-js/saslprep": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@mongodb-js/saslprep/-/saslprep-1.3.0.tgz", + "integrity": "sha512-zlayKCsIjYb7/IdfqxorK5+xUMyi4vOKcFy10wKJYc63NSdKI8mNME+uJqfatkPmOSMMUiojrL58IePKBm3gvQ==", + "license": "MIT", + "dependencies": { + "sparse-bitfield": "^3.0.3" + } + }, + "node_modules/@stablelib/base64": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@stablelib/base64/-/base64-1.0.1.tgz", + "integrity": "sha512-1bnPQqSxSuc3Ii6MhBysoWCg58j97aUjuCSZrGSmDxNqtytIi0k8utUenAwTZN4V5mXXYGsVUI9zeBqy+jBOSQ==", + "license": "MIT" + }, + "node_modules/@tanstack/query-core": { + "version": "5.90.2", + "resolved": "https://registry.npmjs.org/@tanstack/query-core/-/query-core-5.90.2.tgz", + "integrity": "sha512-k/TcR3YalnzibscALLwxeiLUub6jN5EDLwKDiO7q5f4ICEoptJ+n9+7vcEFy5/x/i6Q+Lb/tXrsKCggf5uQJXQ==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + } + }, + "node_modules/@tanstack/react-query": { + "version": "5.90.2", + "resolved": "https://registry.npmjs.org/@tanstack/react-query/-/react-query-5.90.2.tgz", + "integrity": "sha512-CLABiR+h5PYfOWr/z+vWFt5VsOA2ekQeRQBFSKlcoW6Ndx/f8rfyVmq4LbgOM4GG2qtxAxjLYLOpCNTYm4uKzw==", + "license": "MIT", + "dependencies": { + "@tanstack/query-core": "5.90.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + }, + "peerDependencies": { + "react": "^18 || ^19" + } + }, + "node_modules/@types/node": { + "version": "22.18.6", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.18.6.tgz", + "integrity": "sha512-r8uszLPpeIWbNKtvWRt/DbVi5zbqZyj1PTmhRMqBMvDnaz1QpmSKujUtJLrqGZeoM8v72MfYggDceY4K1itzWQ==", + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/@types/webidl-conversions": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/@types/webidl-conversions/-/webidl-conversions-7.0.3.tgz", + "integrity": "sha512-CiJJvcRtIgzadHCYXw7dqEnMNRjhGZlYK05Mj9OyktqV8uVT8fD2BFOB7S1uwBE3Kj2Z+4UyPmFw/Ixgw/LAlA==", + "license": "MIT" + }, + "node_modules/@types/whatwg-url": { + "version": "11.0.5", + "resolved": "https://registry.npmjs.org/@types/whatwg-url/-/whatwg-url-11.0.5.tgz", + "integrity": "sha512-coYR071JRaHa+xoEvvYqvnIHaVqaYrLPbsufM9BF63HkwI5Lgmy2QR8Q5K/lYDYo5AK82wOvSOS0UsLTpTG7uQ==", + "license": "MIT", + "dependencies": { + "@types/webidl-conversions": "*" + } + }, + "node_modules/accepts": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz", + "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==", + "license": "MIT", + "dependencies": { + "mime-types": "^3.0.0", + "negotiator": "^1.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", + "license": "MIT" + }, + "node_modules/axios": { + "version": "1.12.2", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.12.2.tgz", + "integrity": "sha512-vMJzPewAlRyOgxV2dU0Cuz2O8zzzx9VYtbJOaBgXFeLc4IV/Eg50n4LowmehOOR61S8ZMpc2K5Sa7g6A4jfkUw==", + "license": "MIT", + "dependencies": { + "follow-redirects": "^1.15.6", + "form-data": "^4.0.4", + "proxy-from-env": "^1.1.0" + } + }, + "node_modules/body-parser": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.2.0.tgz", + "integrity": "sha512-02qvAaxv8tp7fBa/mw1ga98OGm+eCbqzJOKoRt70sLmfEEi+jyBYVTDGfCL/k06/4EMk/z01gCe7HoCH/f2LTg==", + "license": "MIT", + "dependencies": { + "bytes": "^3.1.2", + "content-type": "^1.0.5", + "debug": "^4.4.0", + "http-errors": "^2.0.0", + "iconv-lite": "^0.6.3", + "on-finished": "^2.4.1", + "qs": "^6.14.0", + "raw-body": "^3.0.0", + "type-is": "^2.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/bson": { + "version": "6.10.4", + "resolved": "https://registry.npmjs.org/bson/-/bson-6.10.4.tgz", + "integrity": "sha512-WIsKqkSC0ABoBJuT1LEX+2HEvNmNKKgnTAyd0fL8qzK4SH2i9NXg+t08YtdZp/V9IZ33cxe3iV4yM0qg8lMQng==", + "license": "Apache-2.0", + "engines": { + "node": ">=16.20.1" + } + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "license": "MIT", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/content-disposition": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.0.0.tgz", + "integrity": "sha512-Au9nRL8VNUut/XSzbQA38+M78dzP4D+eqg3gfJHMIHHYa3bg067xj1KxMUWj+VULbiZMowKngFFbKczUrNJ1mg==", + "license": "MIT", + "dependencies": { + "safe-buffer": "5.2.1" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz", + "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==", + "license": "MIT", + "engines": { + "node": ">=6.6.0" + } + }, + "node_modules/cors": { + "version": "2.8.5", + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz", + "integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==", + "license": "MIT", + "dependencies": { + "object-assign": "^4", + "vary": "^1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/csstype": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.1.3.tgz", + "integrity": "sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw==", + "license": "MIT" + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "license": "MIT", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/dequal": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz", + "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/dotenv": { + "version": "16.6.1", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.6.1.tgz", + "integrity": "sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "license": "MIT" + }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", + "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-set-tostringtag": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", + "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es6-promise": { + "version": "4.2.8", + "resolved": "https://registry.npmjs.org/es6-promise/-/es6-promise-4.2.8.tgz", + "integrity": "sha512-HJDGx5daxeIvxdBxvG2cb9g4tEvwIk3i8+nhX0yGrYmZUzbkdg8QbDevheDB8gd0//uPj4c1EQua8Q+MViT0/w==", + "license": "MIT" + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "license": "MIT" + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/express": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/express/-/express-5.1.0.tgz", + "integrity": "sha512-DT9ck5YIRU+8GYzzU5kT3eHGA5iL+1Zd0EutOmTE9Dtk+Tvuzd23VBU+ec7HPNSTxXYO55gPV/hq4pSBJDjFpA==", + "license": "MIT", + "dependencies": { + "accepts": "^2.0.0", + "body-parser": "^2.2.0", + "content-disposition": "^1.0.0", + "content-type": "^1.0.5", + "cookie": "^0.7.1", + "cookie-signature": "^1.2.1", + "debug": "^4.4.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "finalhandler": "^2.1.0", + "fresh": "^2.0.0", + "http-errors": "^2.0.0", + "merge-descriptors": "^2.0.0", + "mime-types": "^3.0.0", + "on-finished": "^2.4.1", + "once": "^1.4.0", + "parseurl": "^1.3.3", + "proxy-addr": "^2.0.7", + "qs": "^6.14.0", + "range-parser": "^1.2.1", + "router": "^2.2.0", + "send": "^1.1.0", + "serve-static": "^2.2.0", + "statuses": "^2.0.1", + "type-is": "^2.0.1", + "vary": "^1.1.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/fast-sha256": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/fast-sha256/-/fast-sha256-1.3.0.tgz", + "integrity": "sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ==", + "license": "Unlicense" + }, + "node_modules/finalhandler": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.0.tgz", + "integrity": "sha512-/t88Ty3d5JWQbWYgaOGCCYfXRwV1+be02WqYYlL6h0lEiUAMPM8o8qKGO01YIkOHzka2up08wvgYD0mDiI+q3Q==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "on-finished": "^2.4.1", + "parseurl": "^1.3.3", + "statuses": "^2.0.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/follow-redirects": { + "version": "1.15.11", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.11.tgz", + "integrity": "sha512-deG2P0JfjrTxl50XGCDyfI97ZGVCxIpfKYmfyrQ54n5FO/0gfIES8C/Psl6kWVDolizcaaxZJnTS0QSMxvnsBQ==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "license": "MIT", + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true + } + } + }, + "node_modules/form-data": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.4.tgz", + "integrity": "sha512-KrGhL9Q4zjj0kiUt5OO4Mr/A/jlI2jDYs5eHBpYHPcBEVSiipAvn2Ko2HnPe20rmcuuvMHNdZFp+4IlGTMF0Ow==", + "license": "MIT", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "es-set-tostringtag": "^2.1.0", + "hasown": "^2.0.2", + "mime-types": "^2.1.12" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/form-data/node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/form-data/node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz", + "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/glob-to-regexp": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/glob-to-regexp/-/glob-to-regexp-0.4.1.tgz", + "integrity": "sha512-lkX1HJXwyMcprw/5YUZc2s7DrpAiHB21/V+E1rHUrVNokkvB6bqMzT0VfV6/86ZNabt1k14YOIaT7nDvOX3Iiw==", + "license": "BSD-2-Clause" + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hamming-distance": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/hamming-distance/-/hamming-distance-1.0.0.tgz", + "integrity": "sha512-hYz2IIKtyuZGfOqCs7skNiFEATf+v9IUNSOaQSr6Ll4JOxxWhOvXvc3mIdCW82Z3xW+zUoto7N/ssD4bDxAWoA==", + "license": "MIT" + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-tostringtag": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", + "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", + "license": "MIT", + "dependencies": { + "has-symbols": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/http-errors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz", + "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", + "license": "MIT", + "dependencies": { + "depd": "2.0.0", + "inherits": "2.0.4", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "toidentifier": "1.0.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/http-errors/node_modules/statuses": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", + "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/iconv-lite": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", + "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/imagekit": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/imagekit/-/imagekit-6.0.0.tgz", + "integrity": "sha512-0MsxThZM2PYH6ngwN3zi9PDa8pCB5mEZG2FSySYiZk3Hfri8IMwUqVNzRlLQewBHQ3YtTN9M59O0Xe9HRewtOA==", + "license": "MIT", + "dependencies": { + "axios": "^1.6.5", + "form-data": "^4.0.0", + "hamming-distance": "^1.0.0", + "lodash": "^4.17.15", + "tslib": "^2.4.0", + "uuid": "^8.3.2" + }, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/imagekit/node_modules/uuid": { + "version": "8.3.2", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", + "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==", + "license": "MIT", + "bin": { + "uuid": "dist/bin/uuid" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/is-promise": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz", + "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==", + "license": "MIT" + }, + "node_modules/js-cookie": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/js-cookie/-/js-cookie-3.0.5.tgz", + "integrity": "sha512-cEiJEAEoIbWfCZYKWhVwFuvPX1gETRYPw6LlaTKoxD3s2AkXzkCjnp6h0V77ozyqj0jakteJ4YqDJT830+lVGw==", + "license": "MIT", + "engines": { + "node": ">=14" + } + }, + "node_modules/kareem": { + "version": "2.6.3", + "resolved": "https://registry.npmjs.org/kareem/-/kareem-2.6.3.tgz", + "integrity": "sha512-C3iHfuGUXK2u8/ipq9LfjFfXFxAZMQJJq7vLS45r3D9Y2xQ/m4S8zaR4zMLFWh9AsNPXmcFfUDhTEO8UIC/V6Q==", + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/lodash": { + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", + "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", + "license": "MIT" + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/media-typer": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz", + "integrity": "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/memory-pager": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/memory-pager/-/memory-pager-1.5.0.tgz", + "integrity": "sha512-ZS4Bp4r/Zoeq6+NLJpP+0Zzm0pR8whtGPf1XExKLJBAczGMnSi3It14OiNCStjQjM6NU1okjQGSxgEZN8eBYKg==", + "license": "MIT" + }, + "node_modules/merge-descriptors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz", + "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/mime-db": { + "version": "1.54.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", + "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.1.tgz", + "integrity": "sha512-xRc4oEhT6eaBpU1XF7AjpOFD+xQmXNB5OVKwp4tqCuBpHLS/ZbBDrc07mYTDqVMg6PfxUjjNp85O6Cd2Z/5HWA==", + "license": "MIT", + "dependencies": { + "mime-db": "^1.54.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mongodb": { + "version": "6.18.0", + "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-6.18.0.tgz", + "integrity": "sha512-fO5ttN9VC8P0F5fqtQmclAkgXZxbIkYRTUi1j8JO6IYwvamkhtYDilJr35jOPELR49zqCJgXZWwCtW7B+TM8vQ==", + "license": "Apache-2.0", + "dependencies": { + "@mongodb-js/saslprep": "^1.1.9", + "bson": "^6.10.4", + "mongodb-connection-string-url": "^3.0.0" + }, + "engines": { + "node": ">=16.20.1" + }, + "peerDependencies": { + "@aws-sdk/credential-providers": "^3.188.0", + "@mongodb-js/zstd": "^1.1.0 || ^2.0.0", + "gcp-metadata": "^5.2.0", + "kerberos": "^2.0.1", + "mongodb-client-encryption": ">=6.0.0 <7", + "snappy": "^7.2.2", + "socks": "^2.7.1" + }, + "peerDependenciesMeta": { + "@aws-sdk/credential-providers": { + "optional": true + }, + "@mongodb-js/zstd": { + "optional": true + }, + "gcp-metadata": { + "optional": true + }, + "kerberos": { + "optional": true + }, + "mongodb-client-encryption": { + "optional": true + }, + "snappy": { + "optional": true + }, + "socks": { + "optional": true + } + } + }, + "node_modules/mongodb-connection-string-url": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/mongodb-connection-string-url/-/mongodb-connection-string-url-3.0.2.tgz", + "integrity": "sha512-rMO7CGo/9BFwyZABcKAWL8UJwH/Kc2x0g72uhDWzG48URRax5TCIcJ7Rc3RZqffZzO/Gwff/jyKwCU9TN8gehA==", + "license": "Apache-2.0", + "dependencies": { + "@types/whatwg-url": "^11.0.2", + "whatwg-url": "^14.1.0 || ^13.0.0" + } + }, + "node_modules/mongoose": { + "version": "8.18.2", + "resolved": "https://registry.npmjs.org/mongoose/-/mongoose-8.18.2.tgz", + "integrity": "sha512-gA6GFlshOHUdNyw9OQTmMLSGzVOPbcbjaSZ1dvR5iMp668N2UUznTuzgTY6V6Q41VtBc4kmL/qqML1RNgXB5Fg==", + "license": "MIT", + "dependencies": { + "bson": "^6.10.4", + "kareem": "2.6.3", + "mongodb": "~6.18.0", + "mpath": "0.9.0", + "mquery": "5.0.0", + "ms": "2.1.3", + "sift": "17.1.3" + }, + "engines": { + "node": ">=16.20.1" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/mongoose" + } + }, + "node_modules/mpath": { + "version": "0.9.0", + "resolved": "https://registry.npmjs.org/mpath/-/mpath-0.9.0.tgz", + "integrity": "sha512-ikJRQTk8hw5DEoFVxHG1Gn9T/xcjtdnOKIU1JTmGjZZlg9LST2mBLmcX3/ICIbgJydT2GOc15RnNy5mHmzfSew==", + "license": "MIT", + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/mquery": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/mquery/-/mquery-5.0.0.tgz", + "integrity": "sha512-iQMncpmEK8R8ncT8HJGsGc9Dsp8xcgYMVSbs5jgnm1lFHTZqMJTUWTDx1LBO8+mK3tPNZWFLBghQEIOULSTHZg==", + "license": "MIT", + "dependencies": { + "debug": "4.x" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/negotiator": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz", + "integrity": "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-to-regexp": { + "version": "8.3.0", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.3.0.tgz", + "integrity": "sha512-7jdwVIRtsP8MYpdXSwOS0YdD0Du+qOoF/AEPIt88PcCFrZCzx41oxku1jD88hZBwbNUIEfpqvuhjFaMAqMTWnA==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "license": "MIT", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/proxy-from-env": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz", + "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==", + "license": "MIT" + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/qs": { + "version": "6.14.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.14.0.tgz", + "integrity": "sha512-YWWTjgABSKcvs/nWBi9PycY/JiPJqOD4JA6o9Sej2AtvSGarXxKC3OQSk4pAarbdQlKAh5D4FCQkJNkW+GAn3w==", + "license": "BSD-3-Clause", + "dependencies": { + "side-channel": "^1.1.0" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/querystringify": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/querystringify/-/querystringify-2.2.0.tgz", + "integrity": "sha512-FIqgj2EUvTa7R50u0rGsyTftzjYmv/a3hO345bZNrqabNqjtgiDMgmo4mkUjd+nzU5oF3dClKqFIPUKybUyqoQ==", + "license": "MIT" + }, + "node_modules/range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.1.tgz", + "integrity": "sha512-9G8cA+tuMS75+6G/TzW8OtLzmBDMo8p1JRxN5AZ+LAp8uxGA8V8GZm4GQ4/N5QNQEnLmg6SS7wyuSmbKepiKqA==", + "license": "MIT", + "dependencies": { + "bytes": "3.1.2", + "http-errors": "2.0.0", + "iconv-lite": "0.7.0", + "unpipe": "1.0.0" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/raw-body/node_modules/iconv-lite": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.0.tgz", + "integrity": "sha512-cf6L2Ds3h57VVmkZe+Pn+5APsT7FpqJtEhhieDCvrE2MK5Qk9MyffgQyuxQTm6BChfeZNtcOLHp9IcWRVcIcBQ==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/react": { + "version": "19.1.1", + "resolved": "https://registry.npmjs.org/react/-/react-19.1.1.tgz", + "integrity": "sha512-w8nqGImo45dmMIfljjMwOGtbmC/mk4CMYhWIicdSflH91J9TyCyczcPFXJzrZ/ZXcgGRFeP6BU0BEJTw6tZdfQ==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/requires-port": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz", + "integrity": "sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==", + "license": "MIT" + }, + "node_modules/router": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz", + "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "depd": "^2.0.0", + "is-promise": "^4.0.0", + "parseurl": "^1.3.3", + "path-to-regexp": "^8.0.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, + "node_modules/send": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/send/-/send-1.2.0.tgz", + "integrity": "sha512-uaW0WwXKpL9blXE2o0bRhoL2EGXIrZxQ2ZQ4mgcfoBxdFmQold+qWsD2jLrfZ0trjKL6vOw0j//eAwcALFjKSw==", + "license": "MIT", + "dependencies": { + "debug": "^4.3.5", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "fresh": "^2.0.0", + "http-errors": "^2.0.0", + "mime-types": "^3.0.1", + "ms": "^2.1.3", + "on-finished": "^2.4.1", + "range-parser": "^1.2.1", + "statuses": "^2.0.1" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/serve-static": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.0.tgz", + "integrity": "sha512-61g9pCh0Vnh7IutZjtLGGpTA355+OPn2TyDv/6ivP2h/AdAVX9azsoxmg2/M6nZeQZNYBEwIcsne1mJd9oQItQ==", + "license": "MIT", + "dependencies": { + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "parseurl": "^1.3.3", + "send": "^1.2.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "license": "ISC" + }, + "node_modules/side-channel": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", + "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3", + "side-channel-list": "^1.0.0", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz", + "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/sift": { + "version": "17.1.3", + "resolved": "https://registry.npmjs.org/sift/-/sift-17.1.3.tgz", + "integrity": "sha512-Rtlj66/b0ICeFzYTuNvX/EF1igRbbnGSvEyT79McoZa/DeGhMyC5pWKOEsZKnpkqtSeovd5FL/bjHWC3CIIvCQ==", + "license": "MIT" + }, + "node_modules/sparse-bitfield": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/sparse-bitfield/-/sparse-bitfield-3.0.3.tgz", + "integrity": "sha512-kvzhi7vqKTfkh0PZU+2D2PIllw2ymqJKujUcyPMd9Y75Nv4nPbGJZXNhxsgdQab2BmlDct1YnfQCguEvHr7VsQ==", + "license": "MIT", + "dependencies": { + "memory-pager": "^1.0.2" + } + }, + "node_modules/standardwebhooks": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/standardwebhooks/-/standardwebhooks-1.0.0.tgz", + "integrity": "sha512-BbHGOQK9olHPMvQNHWul6MYlrRTAOKn03rOe4A8O3CLWhNf4YHBqq2HJKKC+sfqpxiBY52pNeesD6jIiLDz8jg==", + "license": "MIT", + "dependencies": { + "@stablelib/base64": "^1.0.0", + "fast-sha256": "^1.3.0" + } + }, + "node_modules/statuses": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/std-env": { + "version": "3.9.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-3.9.0.tgz", + "integrity": "sha512-UGvjygr6F6tpH7o2qyqR6QYpwraIjKSdtzyBdyytFOHmPZY917kwdwLG0RbOjWOnKmnm3PeHjaoLLMie7kPLQw==", + "license": "MIT" + }, + "node_modules/svix": { + "version": "1.76.1", + "resolved": "https://registry.npmjs.org/svix/-/svix-1.76.1.tgz", + "integrity": "sha512-CRuDWBTgYfDnBLRaZdKp9VuoPcNUq9An14c/k+4YJ15Qc5Grvf66vp0jvTltd4t7OIRj+8lM1DAgvSgvf7hdLw==", + "license": "MIT", + "dependencies": { + "@stablelib/base64": "^1.0.0", + "@types/node": "^22.7.5", + "es6-promise": "^4.2.8", + "fast-sha256": "^1.3.0", + "url-parse": "^1.5.10", + "uuid": "^10.0.0" + } + }, + "node_modules/swr": { + "version": "2.3.4", + "resolved": "https://registry.npmjs.org/swr/-/swr-2.3.4.tgz", + "integrity": "sha512-bYd2lrhc+VarcpkgWclcUi92wYCpOgMws9Sd1hG1ntAu0NEy+14CbotuFjshBU2kt9rYj9TSmDcybpxpeTU1fg==", + "license": "MIT", + "dependencies": { + "dequal": "^2.0.3", + "use-sync-external-store": "^1.4.0" + }, + "peerDependencies": { + "react": "^16.11.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/tr46": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-5.1.1.tgz", + "integrity": "sha512-hdF5ZgjTqgAntKkklYw0R03MG2x/bSzTtkxmIRw/sTNV8YXsCJ1tfLAX23lhxhHJlEf3CRCOCGGWw3vI3GaSPw==", + "license": "MIT", + "dependencies": { + "punycode": "^2.3.1" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "license": "0BSD" + }, + "node_modules/type-is": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.0.1.tgz", + "integrity": "sha512-OZs6gsjF4vMp32qrCbiVSkrFmXtG/AZhY3t0iAMrMBiAZyV9oALtXO8hsrHbMXF9x6L3grlFuwW2oAz7cav+Gw==", + "license": "MIT", + "dependencies": { + "content-type": "^1.0.5", + "media-typer": "^1.1.0", + "mime-types": "^3.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "license": "MIT" + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/url-parse": { + "version": "1.5.10", + "resolved": "https://registry.npmjs.org/url-parse/-/url-parse-1.5.10.tgz", + "integrity": "sha512-WypcfiRhfeUP9vvF0j6rw0J3hrWrw6iZv3+22h6iRMJ/8z1Tj6XfLP4DsUix5MhMPnXpiHDoKyoZ/bdCkwBCiQ==", + "license": "MIT", + "dependencies": { + "querystringify": "^2.1.1", + "requires-port": "^1.0.0" + } + }, + "node_modules/use-sync-external-store": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.5.0.tgz", + "integrity": "sha512-Rb46I4cGGVBmjamjphe8L/UnvJD+uPPtTkNvX5mZgqdbavhI4EbgIWJiIHXJ8bc/i9EQGPRh4DwEURJ552Do0A==", + "license": "MIT", + "peerDependencies": { + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" + } + }, + "node_modules/uuid": { + "version": "10.0.0", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-10.0.0.tgz", + "integrity": "sha512-8XkAphELsDnEGrDxUOHB3RGvXz6TeuYSGEZBOjtTtPm2lwhGBjLgOzLHB63IUWfBpNucQjND6d3AOudO+H3RWQ==", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "license": "MIT", + "bin": { + "uuid": "dist/bin/uuid" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/webidl-conversions": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz", + "integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + } + }, + "node_modules/whatwg-url": { + "version": "14.2.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-14.2.0.tgz", + "integrity": "sha512-De72GdQZzNTUBBChsXueQUnPKDkg/5A5zp7pFDuQAj5UFoENpiACU0wlCvzpAGnTkj++ihpKwKyYewn/XNUbKw==", + "license": "MIT", + "dependencies": { + "tr46": "^5.1.0", + "webidl-conversions": "^7.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "license": "ISC" + } + } +} diff --git a/backend/node_modules/@clerk/backend/LICENSE b/backend/node_modules/@clerk/backend/LICENSE new file mode 100644 index 000000000..66914b6af --- /dev/null +++ b/backend/node_modules/@clerk/backend/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 Clerk, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/backend/node_modules/@clerk/backend/README.md b/backend/node_modules/@clerk/backend/README.md new file mode 100644 index 000000000..7aa545ac0 --- /dev/null +++ b/backend/node_modules/@clerk/backend/README.md @@ -0,0 +1,76 @@ +

+ + + + + + +
+

@clerk/backend

+

+ +
+ +[![Chat on Discord](https://img.shields.io/discord/856971667393609759.svg?logo=discord)](https://clerk.com/discord) +[![Clerk documentation](https://img.shields.io/badge/documentation-clerk-green.svg)](https://clerk.com/docs?utm_source=github&utm_medium=clerk_backend) +[![Follow on Twitter](https://img.shields.io/twitter/follow/ClerkDev?style=social)](https://twitter.com/intent/follow?screen_name=ClerkDev) + +[Changelog](https://github.com/clerk/javascript/blob/main/packages/backend/CHANGELOG.md) +· +[Report a Bug](https://github.com/clerk/javascript/issues/new?assignees=&labels=needs-triage&projects=&template=BUG_REPORT.yml) +· +[Request a Feature](https://feedback.clerk.com/roadmap) +· +[Get help](https://clerk.com/contact/support?utm_source=github&utm_medium=clerk_backend) + +
+ +## Getting Started + +[Clerk's](https://clerk.com/?utm_source=github&utm_medium=clerk_backend) JavaScript Backend SDK exposes [Clerk's Backend API](https://clerk.com/docs/reference/backend-api) resources and low-level authentication utilities **for JavaScript environments**. + +### Prerequisites + +- Node.js `>=18.17.0` (or later) or any V8 isolates runtime +- An existing Clerk application. [Create your account for free](https://dashboard.clerk.com/sign-up?utm_source=github&utm_medium=clerk_backend). + +### Installation + +The fastest way to get started with `@clerk/backend` is by following the [JavaScript Backend SDK reference documentation](https://clerk.com/docs/references/backend/overview?utm_source=github&utm_medium=clerk_backend). + +You'll learn how to install `@clerk/backend` and how to use `createClerkClient()`. + +## Usage + +For further information, guides, and examples visit the [JavaScript Backend SDK reference documentation](https://clerk.com/docs/references/backend/overview?utm_source=github&utm_medium=clerk_backend). It lists all the available APIs and methods. + +## Testing + +This project uses [vitest](https://vitest.dev/) as the unit test runner and [msw](https://mswjs.io/) for mocking network requests. + +If you need to see which requests are being intercepted by `msw`, you can run the test suite with the following env: `DEBUG_MOCK_REQUESTS=true` + +## Support + +You can get in touch with us in any of the following ways: + +- Join our official community [Discord server](https://clerk.com/discord) +- On [our support page](https://clerk.com/contact/support?utm_source=github&utm_medium=clerk_backend) + +## Contributing + +We're open to all community contributions! If you'd like to contribute in any way, please read [our contribution guidelines](https://github.com/clerk/javascript/blob/main/docs/CONTRIBUTING.md) and [code of conduct](https://github.com/clerk/javascript/blob/main/docs/CODE_OF_CONDUCT.md). + +## Security + +`@clerk/backend` follows good practices of security, but 100% security cannot be assured. + +`@clerk/backend` is provided **"as is"** without any **warranty**. Use at your own risk. + +_For more information and to report security issues, please refer to our [security documentation](https://github.com/clerk/javascript/blob/main/docs/SECURITY.md)._ + +## License + +This project is licensed under the **MIT license**. + +See [LICENSE](https://github.com/clerk/javascript/blob/main/packages/backend/LICENSE) for more information. diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/APIKeysApi.d.ts b/backend/node_modules/@clerk/backend/dist/api/endpoints/APIKeysApi.d.ts new file mode 100644 index 000000000..0f126e002 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/APIKeysApi.d.ts @@ -0,0 +1,41 @@ +import type { APIKey } from '../resources/APIKey'; +import { AbstractAPI } from './AbstractApi'; +type CreateAPIKeyParams = { + type?: 'api_key'; + /** + * API key name + */ + name: string; + /** + * user or organization ID the API key is associated with + */ + subject: string; + /** + * API key description + */ + description?: string | null; + claims?: Record | null; + scopes?: string[]; + createdBy?: string | null; + secondsUntilExpiration?: number | null; +}; +type RevokeAPIKeyParams = { + /** + * API key ID + */ + apiKeyId: string; + /** + * Reason for revocation + */ + revocationReason?: string | null; +}; +export declare class APIKeysAPI extends AbstractAPI { + create(params: CreateAPIKeyParams): Promise; + revoke(params: RevokeAPIKeyParams): Promise; + getSecret(apiKeyId: string): Promise<{ + secret: string; + }>; + verifySecret(secret: string): Promise; +} +export {}; +//# sourceMappingURL=APIKeysApi.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/APIKeysApi.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/endpoints/APIKeysApi.d.ts.map new file mode 100644 index 000000000..6d67c1184 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/APIKeysApi.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"APIKeysApi.d.ts","sourceRoot":"","sources":["../../../src/api/endpoints/APIKeysApi.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAClD,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAI5C,KAAK,kBAAkB,GAAG;IACxB,IAAI,CAAC,EAAE,SAAS,CAAC;IACjB;;OAEG;IACH,IAAI,EAAE,MAAM,CAAC;IACb;;OAEG;IACH,OAAO,EAAE,MAAM,CAAC;IAChB;;OAEG;IACH,WAAW,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC5B,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,IAAI,CAAC;IACpC,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;IAClB,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,sBAAsB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CACxC,CAAC;AAEF,KAAK,kBAAkB,GAAG;IACxB;;OAEG;IACH,QAAQ,EAAE,MAAM,CAAC;IACjB;;OAEG;IACH,gBAAgB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAClC,CAAC;AAEF,qBAAa,UAAW,SAAQ,WAAW;IACnC,MAAM,CAAC,MAAM,EAAE,kBAAkB;IAQjC,MAAM,CAAC,MAAM,EAAE,kBAAkB;IAYjC,SAAS,CAAC,QAAQ,EAAE,MAAM;gBAGA,MAAM;;IAMhC,YAAY,CAAC,MAAM,EAAE,MAAM;CAOlC"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/AbstractApi.d.ts b/backend/node_modules/@clerk/backend/dist/api/endpoints/AbstractApi.d.ts new file mode 100644 index 000000000..861fa1196 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/AbstractApi.d.ts @@ -0,0 +1,7 @@ +import type { RequestFunction } from '../request'; +export declare abstract class AbstractAPI { + protected request: RequestFunction; + constructor(request: RequestFunction); + protected requireId(id: string): void; +} +//# sourceMappingURL=AbstractApi.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/AbstractApi.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/endpoints/AbstractApi.d.ts.map new file mode 100644 index 000000000..e8e0e0ce7 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/AbstractApi.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"AbstractApi.d.ts","sourceRoot":"","sources":["../../../src/api/endpoints/AbstractApi.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAElD,8BAAsB,WAAW;IACnB,SAAS,CAAC,OAAO,EAAE,eAAe;gBAAxB,OAAO,EAAE,eAAe;IAE9C,SAAS,CAAC,SAAS,CAAC,EAAE,EAAE,MAAM;CAK/B"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/AccountlessApplicationsAPI.d.ts b/backend/node_modules/@clerk/backend/dist/api/endpoints/AccountlessApplicationsAPI.d.ts new file mode 100644 index 000000000..4ee9fea04 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/AccountlessApplicationsAPI.d.ts @@ -0,0 +1,11 @@ +import type { AccountlessApplication } from '../resources/AccountlessApplication'; +import { AbstractAPI } from './AbstractApi'; +export declare class AccountlessApplicationAPI extends AbstractAPI { + createAccountlessApplication(params?: { + requestHeaders?: Headers; + }): Promise; + completeAccountlessApplicationOnboarding(params?: { + requestHeaders?: Headers; + }): Promise; +} +//# sourceMappingURL=AccountlessApplicationsAPI.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/AccountlessApplicationsAPI.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/endpoints/AccountlessApplicationsAPI.d.ts.map new file mode 100644 index 000000000..7ee54101a --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/AccountlessApplicationsAPI.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"AccountlessApplicationsAPI.d.ts","sourceRoot":"","sources":["../../../src/api/endpoints/AccountlessApplicationsAPI.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,qCAAqC,CAAC;AAClF,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAI5C,qBAAa,yBAA0B,SAAQ,WAAW;IAC3C,4BAA4B,CAAC,MAAM,CAAC,EAAE;QAAE,cAAc,CAAC,EAAE,OAAO,CAAA;KAAE;IASlE,wCAAwC,CAAC,MAAM,CAAC,EAAE;QAAE,cAAc,CAAC,EAAE,OAAO,CAAA;KAAE;CAQ5F"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/ActorTokenApi.d.ts b/backend/node_modules/@clerk/backend/dist/api/endpoints/ActorTokenApi.d.ts new file mode 100644 index 000000000..a74d85abb --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/ActorTokenApi.d.ts @@ -0,0 +1,47 @@ +import type { ActorToken } from '../resources/ActorToken'; +import { AbstractAPI } from './AbstractApi'; +type ActorTokenActorCreateParams = { + /** + * The ID of the actor. + */ + sub: string; + /** + * Additional properties of the actor. + */ + additionalProperties?: { + [k: string]: any; + }; +}; +type ActorTokenCreateParams = { + /** + * The ID of the user being impersonated. + */ + userId: string; + /** + * The actor payload. It needs to include a sub property which should contain the ID of the actor. + * + * @remarks + * This whole payload will be also included in the JWT session token. + */ + actor: ActorTokenActorCreateParams; + /** + * Optional parameter to specify the life duration of the actor token in seconds. + * + * @remarks + * By default, the duration is 1 hour. + */ + expiresInSeconds?: number | undefined; + /** + * The maximum duration that the session which will be created by the generated actor token should last. + * + * @remarks + * By default, the duration of a session created via an actor token, lasts 30 minutes. + */ + sessionMaxDurationInSeconds?: number | undefined; +}; +export declare class ActorTokenAPI extends AbstractAPI { + create(params: ActorTokenCreateParams): Promise; + revoke(actorTokenId: string): Promise; +} +export {}; +//# sourceMappingURL=ActorTokenApi.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/ActorTokenApi.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/endpoints/ActorTokenApi.d.ts.map new file mode 100644 index 000000000..010ed71c3 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/ActorTokenApi.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ActorTokenApi.d.ts","sourceRoot":"","sources":["../../../src/api/endpoints/ActorTokenApi.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAC;AAC1D,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAI5C,KAAK,2BAA2B,GAAG;IACjC;;OAEG;IACH,GAAG,EAAE,MAAM,CAAC;IACZ;;OAEG;IACH,oBAAoB,CAAC,EAAE;QAAE,CAAC,CAAC,EAAE,MAAM,GAAG,GAAG,CAAA;KAAE,CAAC;CAC7C,CAAC;AAEF,KAAK,sBAAsB,GAAG;IAC5B;;OAEG;IACH,MAAM,EAAE,MAAM,CAAC;IACf;;;;;OAKG;IACH,KAAK,EAAE,2BAA2B,CAAC;IACnC;;;;;OAKG;IACH,gBAAgB,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IACtC;;;;;OAKG;IACH,2BAA2B,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CAClD,CAAC;AAEF,qBAAa,aAAc,SAAQ,WAAW;IAC/B,MAAM,CAAC,MAAM,EAAE,sBAAsB;IAQrC,MAAM,CAAC,YAAY,EAAE,MAAM;CAOzC"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/AllowlistIdentifierApi.d.ts b/backend/node_modules/@clerk/backend/dist/api/endpoints/AllowlistIdentifierApi.d.ts new file mode 100644 index 000000000..567642af6 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/AllowlistIdentifierApi.d.ts @@ -0,0 +1,16 @@ +import type { ClerkPaginationRequest } from '@clerk/types'; +import type { AllowlistIdentifier } from '../resources/AllowlistIdentifier'; +import type { DeletedObject } from '../resources/DeletedObject'; +import type { PaginatedResourceResponse } from '../resources/Deserializer'; +import { AbstractAPI } from './AbstractApi'; +type AllowlistIdentifierCreateParams = { + identifier: string; + notify: boolean; +}; +export declare class AllowlistIdentifierAPI extends AbstractAPI { + getAllowlistIdentifierList(params?: ClerkPaginationRequest): Promise>; + createAllowlistIdentifier(params: AllowlistIdentifierCreateParams): Promise; + deleteAllowlistIdentifier(allowlistIdentifierId: string): Promise; +} +export {}; +//# sourceMappingURL=AllowlistIdentifierApi.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/AllowlistIdentifierApi.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/endpoints/AllowlistIdentifierApi.d.ts.map new file mode 100644 index 000000000..0327038a0 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/AllowlistIdentifierApi.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"AllowlistIdentifierApi.d.ts","sourceRoot":"","sources":["../../../src/api/endpoints/AllowlistIdentifierApi.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAC;AAG3D,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,kCAAkC,CAAC;AAC5E,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAChE,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,2BAA2B,CAAC;AAC3E,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAI5C,KAAK,+BAA+B,GAAG;IACrC,UAAU,EAAE,MAAM,CAAC;IACnB,MAAM,EAAE,OAAO,CAAC;CACjB,CAAC;AAEF,qBAAa,sBAAuB,SAAQ,WAAW;IACxC,0BAA0B,CAAC,MAAM,GAAE,sBAA2B;IAQ9D,yBAAyB,CAAC,MAAM,EAAE,+BAA+B;IAQjE,yBAAyB,CAAC,qBAAqB,EAAE,MAAM;CAOrE"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/BetaFeaturesApi.d.ts b/backend/node_modules/@clerk/backend/dist/api/endpoints/BetaFeaturesApi.d.ts new file mode 100644 index 000000000..6bf73c890 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/BetaFeaturesApi.d.ts @@ -0,0 +1,29 @@ +import { AbstractAPI } from './AbstractApi'; +type ChangeDomainParams = { + /** + * The new home URL of the production instance e.g. https://www.example.com + */ + homeUrl?: string; + /** + * Whether this is a domain for a secondary app, meaning that any subdomain + * provided is significant and will be stored as part of the domain. This is + * useful for supporting multiple apps (one primary and multiple secondaries) + * on the same root domain (eTLD+1). + */ + isSecondary?: boolean; +}; +export declare class BetaFeaturesAPI extends AbstractAPI { + /** + * Change the domain of a production instance. + * + * Changing the domain requires updating the DNS records accordingly, deploying new SSL certificates, + * updating your Social Connection's redirect URLs and setting the new keys in your code. + * + * @remarks + * WARNING: Changing your domain will invalidate all current user sessions (i.e. users will be logged out). + * Also, while your application is being deployed, a small downtime is expected to occur. + */ + changeDomain(params: ChangeDomainParams): Promise; +} +export {}; +//# sourceMappingURL=BetaFeaturesApi.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/BetaFeaturesApi.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/endpoints/BetaFeaturesApi.d.ts.map new file mode 100644 index 000000000..87c4aaa19 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/BetaFeaturesApi.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"BetaFeaturesApi.d.ts","sourceRoot":"","sources":["../../../src/api/endpoints/BetaFeaturesApi.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAI5C,KAAK,kBAAkB,GAAG;IACxB;;OAEG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB;;;;;OAKG;IACH,WAAW,CAAC,EAAE,OAAO,CAAC;CACvB,CAAC;AAEF,qBAAa,eAAgB,SAAQ,WAAW;IAC9C;;;;;;;;;OASG;IACU,YAAY,CAAC,MAAM,EAAE,kBAAkB;CAOrD"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/BillingApi.d.ts b/backend/node_modules/@clerk/backend/dist/api/endpoints/BillingApi.d.ts new file mode 100644 index 000000000..09eb1d3f4 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/BillingApi.d.ts @@ -0,0 +1,47 @@ +import type { ClerkPaginationRequest } from '@clerk/types'; +import type { BillingPlan } from '../resources/CommercePlan'; +import type { BillingSubscription } from '../resources/CommerceSubscription'; +import type { BillingSubscriptionItem } from '../resources/CommerceSubscriptionItem'; +import type { PaginatedResourceResponse } from '../resources/Deserializer'; +import { AbstractAPI } from './AbstractApi'; +type GetOrganizationListParams = ClerkPaginationRequest<{ + payerType: 'org' | 'user'; +}>; +type CancelSubscriptionItemParams = { + /** + * If true, the subscription item will be canceled immediately. If false or undefined, the subscription item will be canceled at the end of the current billing period. + * @default undefined + */ + endNow?: boolean; +}; +type ExtendSubscriptionItemFreeTrialParams = { + /** + * RFC3339 timestamp to extend the free trial to. + * Must be in the future and not more than 365 days from the current trial end. + */ + extendTo: Date; +}; +export declare class BillingAPI extends AbstractAPI { + /** + * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. + */ + getPlanList(params?: GetOrganizationListParams): Promise>; + /** + * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. + */ + cancelSubscriptionItem(subscriptionItemId: string, params?: CancelSubscriptionItemParams): Promise; + /** + * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. + */ + extendSubscriptionItemFreeTrial(subscriptionItemId: string, params: ExtendSubscriptionItemFreeTrialParams): Promise; + /** + * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. + */ + getOrganizationBillingSubscription(organizationId: string): Promise; + /** + * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. + */ + getUserBillingSubscription(userId: string): Promise; +} +export {}; +//# sourceMappingURL=BillingApi.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/BillingApi.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/endpoints/BillingApi.d.ts.map new file mode 100644 index 000000000..1208e5873 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/BillingApi.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"BillingApi.d.ts","sourceRoot":"","sources":["../../../src/api/endpoints/BillingApi.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAC;AAG3D,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,2BAA2B,CAAC;AAC7D,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,mCAAmC,CAAC;AAC7E,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,uCAAuC,CAAC;AACrF,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,2BAA2B,CAAC;AAC3E,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAM5C,KAAK,yBAAyB,GAAG,sBAAsB,CAAC;IACtD,SAAS,EAAE,KAAK,GAAG,MAAM,CAAC;CAC3B,CAAC,CAAC;AAEH,KAAK,4BAA4B,GAAG;IAClC;;;OAGG;IACH,MAAM,CAAC,EAAE,OAAO,CAAC;CAClB,CAAC;AAEF,KAAK,qCAAqC,GAAG;IAC3C;;;OAGG;IACH,QAAQ,EAAE,IAAI,CAAC;CAChB,CAAC;AAEF,qBAAa,UAAW,SAAQ,WAAW;IACzC;;OAEG;IACU,WAAW,CAAC,MAAM,CAAC,EAAE,yBAAyB;IAQ3D;;OAEG;IACU,sBAAsB,CAAC,kBAAkB,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,4BAA4B;IASrG;;OAEG;IACU,+BAA+B,CAC1C,kBAAkB,EAAE,MAAM,EAC1B,MAAM,EAAE,qCAAqC;IAU/C;;OAEG;IACU,kCAAkC,CAAC,cAAc,EAAE,MAAM;IAQtE;;OAEG;IACU,0BAA0B,CAAC,MAAM,EAAE,MAAM;CAOvD"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/BlocklistIdentifierApi.d.ts b/backend/node_modules/@clerk/backend/dist/api/endpoints/BlocklistIdentifierApi.d.ts new file mode 100644 index 000000000..95e416f66 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/BlocklistIdentifierApi.d.ts @@ -0,0 +1,15 @@ +import type { ClerkPaginationRequest } from '@clerk/types'; +import type { BlocklistIdentifier } from '../resources/BlocklistIdentifier'; +import type { DeletedObject } from '../resources/DeletedObject'; +import type { PaginatedResourceResponse } from '../resources/Deserializer'; +import { AbstractAPI } from './AbstractApi'; +type BlocklistIdentifierCreateParams = { + identifier: string; +}; +export declare class BlocklistIdentifierAPI extends AbstractAPI { + getBlocklistIdentifierList(params?: ClerkPaginationRequest): Promise>; + createBlocklistIdentifier(params: BlocklistIdentifierCreateParams): Promise; + deleteBlocklistIdentifier(blocklistIdentifierId: string): Promise; +} +export {}; +//# sourceMappingURL=BlocklistIdentifierApi.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/BlocklistIdentifierApi.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/endpoints/BlocklistIdentifierApi.d.ts.map new file mode 100644 index 000000000..3f0cdca14 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/BlocklistIdentifierApi.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"BlocklistIdentifierApi.d.ts","sourceRoot":"","sources":["../../../src/api/endpoints/BlocklistIdentifierApi.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAC;AAG3D,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,kCAAkC,CAAC;AAC5E,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAChE,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,2BAA2B,CAAC;AAC3E,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAI5C,KAAK,+BAA+B,GAAG;IACrC,UAAU,EAAE,MAAM,CAAC;CACpB,CAAC;AAEF,qBAAa,sBAAuB,SAAQ,WAAW;IACxC,0BAA0B,CAAC,MAAM,GAAE,sBAA2B;IAQ9D,yBAAyB,CAAC,MAAM,EAAE,+BAA+B;IAQjE,yBAAyB,CAAC,qBAAqB,EAAE,MAAM;CAOrE"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/ClientApi.d.ts b/backend/node_modules/@clerk/backend/dist/api/endpoints/ClientApi.d.ts new file mode 100644 index 000000000..7223adf69 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/ClientApi.d.ts @@ -0,0 +1,16 @@ +import type { ClerkPaginationRequest } from '@clerk/types'; +import type { Client } from '../resources/Client'; +import type { PaginatedResourceResponse } from '../resources/Deserializer'; +import type { HandshakePayload } from '../resources/HandshakePayload'; +import { AbstractAPI } from './AbstractApi'; +type GetHandshakePayloadParams = { + nonce: string; +}; +export declare class ClientAPI extends AbstractAPI { + getClientList(params?: ClerkPaginationRequest): Promise>; + getClient(clientId: string): Promise; + verifyClient(token: string): Promise; + getHandshakePayload(queryParams: GetHandshakePayloadParams): Promise; +} +export {}; +//# sourceMappingURL=ClientApi.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/ClientApi.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/endpoints/ClientApi.d.ts.map new file mode 100644 index 000000000..08f253310 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/ClientApi.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ClientApi.d.ts","sourceRoot":"","sources":["../../../src/api/endpoints/ClientApi.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAC;AAG3D,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAClD,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,2BAA2B,CAAC;AAC3E,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,+BAA+B,CAAC;AACtE,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAI5C,KAAK,yBAAyB,GAAG;IAC/B,KAAK,EAAE,MAAM,CAAC;CACf,CAAC;AAEF,qBAAa,SAAU,SAAQ,WAAW;IAC3B,aAAa,CAAC,MAAM,GAAE,sBAA2B;IAQjD,SAAS,CAAC,QAAQ,EAAE,MAAM;IAQhC,YAAY,CAAC,KAAK,EAAE,MAAM;IAQpB,mBAAmB,CAAC,WAAW,EAAE,yBAAyB;CAOxE"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/DomainApi.d.ts b/backend/node_modules/@clerk/backend/dist/api/endpoints/DomainApi.d.ts new file mode 100644 index 000000000..ea79c6577 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/DomainApi.d.ts @@ -0,0 +1,46 @@ +import type { DeletedObject } from '../resources/DeletedObject'; +import type { PaginatedResourceResponse } from '../resources/Deserializer'; +import type { Domain } from '../resources/Domain'; +import { AbstractAPI } from './AbstractApi'; +type AddDomainParams = { + /** + * The new domain name. For development instances, can contain the port, i.e myhostname:3000. For production instances, must be a valid FQDN, i.e mysite.com. Cannot contain protocol scheme. + */ + name: string; + /** + * Marks the new domain as satellite. Only true is accepted at the moment. + */ + is_satellite: boolean; + /** + * The full URL of the proxy which will forward requests to the Clerk Frontend API for this domain. Applicable only to production instances. + */ + proxy_url?: string | null; +}; +type UpdateDomainParams = Partial> & { + /** + * The ID of the domain that will be updated. + */ + domainId: string; + /** + * Whether this is a domain for a secondary app, meaning that any subdomain provided is significant + * and will be stored as part of the domain. This is useful for supporting multiple apps + * (one primary and multiple secondaries) on the same root domain (eTLD+1). + */ + is_secondary?: boolean | null; +}; +export declare class DomainAPI extends AbstractAPI { + list(): Promise>; + add(params: AddDomainParams): Promise; + update(params: UpdateDomainParams): Promise; + /** + * Deletes a satellite domain for the instance. + * It is currently not possible to delete the instance's primary domain. + */ + delete(satelliteDomainId: string): Promise; + /** + * @deprecated Use `delete` instead + */ + deleteDomain(satelliteDomainId: string): Promise; +} +export {}; +//# sourceMappingURL=DomainApi.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/DomainApi.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/endpoints/DomainApi.d.ts.map new file mode 100644 index 000000000..17cedefc9 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/DomainApi.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"DomainApi.d.ts","sourceRoot":"","sources":["../../../src/api/endpoints/DomainApi.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAChE,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,2BAA2B,CAAC;AAC3E,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAClD,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAI5C,KAAK,eAAe,GAAG;IACrB;;OAEG;IACH,IAAI,EAAE,MAAM,CAAC;IACb;;OAEG;IACH,YAAY,EAAE,OAAO,CAAC;IACtB;;OAEG;IACH,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAC3B,CAAC;AAEF,KAAK,kBAAkB,GAAG,OAAO,CAAC,IAAI,CAAC,eAAe,EAAE,MAAM,GAAG,WAAW,CAAC,CAAC,GAAG;IAC/E;;OAEG;IACH,QAAQ,EAAE,MAAM,CAAC;IACjB;;;;OAIG;IACH,YAAY,CAAC,EAAE,OAAO,GAAG,IAAI,CAAC;CAC/B,CAAC;AAEF,qBAAa,SAAU,SAAQ,WAAW;IAC3B,IAAI;IAOJ,GAAG,CAAC,MAAM,EAAE,eAAe;IAQ3B,MAAM,CAAC,MAAM,EAAE,kBAAkB;IAY9C;;;OAGG;IACU,MAAM,CAAC,iBAAiB,EAAE,MAAM;IAI7C;;OAEG;IACU,YAAY,CAAC,iBAAiB,EAAE,MAAM;CAOpD"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/EmailAddressApi.d.ts b/backend/node_modules/@clerk/backend/dist/api/endpoints/EmailAddressApi.d.ts new file mode 100644 index 000000000..f9bab3aa3 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/EmailAddressApi.d.ts @@ -0,0 +1,20 @@ +import type { DeletedObject, EmailAddress } from '../resources'; +import { AbstractAPI } from './AbstractApi'; +type CreateEmailAddressParams = { + userId: string; + emailAddress: string; + verified?: boolean; + primary?: boolean; +}; +type UpdateEmailAddressParams = { + verified?: boolean; + primary?: boolean; +}; +export declare class EmailAddressAPI extends AbstractAPI { + getEmailAddress(emailAddressId: string): Promise; + createEmailAddress(params: CreateEmailAddressParams): Promise; + updateEmailAddress(emailAddressId: string, params?: UpdateEmailAddressParams): Promise; + deleteEmailAddress(emailAddressId: string): Promise; +} +export {}; +//# sourceMappingURL=EmailAddressApi.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/EmailAddressApi.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/endpoints/EmailAddressApi.d.ts.map new file mode 100644 index 000000000..00f51a3b2 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/EmailAddressApi.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"EmailAddressApi.d.ts","sourceRoot":"","sources":["../../../src/api/endpoints/EmailAddressApi.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAChE,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAI5C,KAAK,wBAAwB,GAAG;IAC9B,MAAM,EAAE,MAAM,CAAC;IACf,YAAY,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB,CAAC;AAEF,KAAK,wBAAwB,GAAG;IAC9B,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB,CAAC;AAEF,qBAAa,eAAgB,SAAQ,WAAW;IACjC,eAAe,CAAC,cAAc,EAAE,MAAM;IAStC,kBAAkB,CAAC,MAAM,EAAE,wBAAwB;IAQnD,kBAAkB,CAAC,cAAc,EAAE,MAAM,EAAE,MAAM,GAAE,wBAA6B;IAUhF,kBAAkB,CAAC,cAAc,EAAE,MAAM;CAQvD"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/IdPOAuthAccessTokenApi.d.ts b/backend/node_modules/@clerk/backend/dist/api/endpoints/IdPOAuthAccessTokenApi.d.ts new file mode 100644 index 000000000..ebf6fae80 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/IdPOAuthAccessTokenApi.d.ts @@ -0,0 +1,6 @@ +import type { IdPOAuthAccessToken } from '../resources'; +import { AbstractAPI } from './AbstractApi'; +export declare class IdPOAuthAccessTokenApi extends AbstractAPI { + verifyAccessToken(accessToken: string): Promise; +} +//# sourceMappingURL=IdPOAuthAccessTokenApi.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/IdPOAuthAccessTokenApi.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/endpoints/IdPOAuthAccessTokenApi.d.ts.map new file mode 100644 index 000000000..c87bccd3d --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/IdPOAuthAccessTokenApi.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"IdPOAuthAccessTokenApi.d.ts","sourceRoot":"","sources":["../../../src/api/endpoints/IdPOAuthAccessTokenApi.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AACxD,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAI5C,qBAAa,sBAAuB,SAAQ,WAAW;IAC/C,iBAAiB,CAAC,WAAW,EAAE,MAAM;CAO5C"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/InstanceApi.d.ts b/backend/node_modules/@clerk/backend/dist/api/endpoints/InstanceApi.d.ts new file mode 100644 index 000000000..d7e9e5562 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/InstanceApi.d.ts @@ -0,0 +1,70 @@ +import type { Instance } from '../resources/Instance'; +import type { InstanceRestrictions } from '../resources/InstanceRestrictions'; +import type { OrganizationSettings } from '../resources/OrganizationSettings'; +import { AbstractAPI } from './AbstractApi'; +type UpdateParams = { + /** + * Toggles test mode for this instance, allowing the use of test email addresses and phone numbers. + * + * @remarks Defaults to true for development instances. + */ + testMode?: boolean | null | undefined; + /** + * Whether the instance should be using the HIBP service to check passwords for breaches + */ + hibp?: boolean | null | undefined; + /** + * The "enhanced_email_deliverability" feature will send emails from "verifications@clerk.dev" instead of your domain. + * + * @remarks This can be helpful if you do not have a high domain reputation. + */ + enhancedEmailDeliverability?: boolean | null | undefined; + supportEmail?: string | null | undefined; + clerkJsVersion?: string | null | undefined; + developmentOrigin?: string | null | undefined; + /** + * For browser-like stacks such as browser extensions, Electron, or Capacitor.js the instance allowed origins need to be updated with the request origin value. + * + * @remarks For Chrome extensions popup, background, or service worker pages the origin is chrome-extension://extension_uiid. For Electron apps the default origin is http://localhost:3000. For Capacitor, the origin is capacitor://localhost. + */ + allowedOrigins?: Array | undefined; + /** + * Whether the instance should use URL-based session syncing in development mode (i.e. without third-party cookies). + */ + urlBasedSessionSyncing?: boolean | null | undefined; +}; +type UpdateRestrictionsParams = { + allowlist?: boolean | null | undefined; + blocklist?: boolean | null | undefined; + blockEmailSubaddresses?: boolean | null | undefined; + blockDisposableEmailDomains?: boolean | null | undefined; + ignoreDotsForGmailAddresses?: boolean | null | undefined; +}; +type UpdateOrganizationSettingsParams = { + enabled?: boolean | null | undefined; + maxAllowedMemberships?: number | null | undefined; + adminDeleteEnabled?: boolean | null | undefined; + domainsEnabled?: boolean | null | undefined; + /** + * Specifies which [enrollment modes](https://clerk.com/docs/organizations/verified-domains#enrollment-mode) to enable for your Organization Domains. + * + * @remarks Supported modes are 'automatic_invitation' & 'automatic_suggestion'. + */ + domainsEnrollmentModes?: Array | undefined; + /** + * Specifies what the default organization role is for an organization creator. + */ + creatorRoleId?: string | null | undefined; + /** + * Specifies what the default organization role is for the organization domains. + */ + domainsDefaultRoleId?: string | null | undefined; +}; +export declare class InstanceAPI extends AbstractAPI { + get(): Promise; + update(params: UpdateParams): Promise; + updateRestrictions(params: UpdateRestrictionsParams): Promise; + updateOrganizationSettings(params: UpdateOrganizationSettingsParams): Promise; +} +export {}; +//# sourceMappingURL=InstanceApi.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/InstanceApi.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/endpoints/InstanceApi.d.ts.map new file mode 100644 index 000000000..f2e421004 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/InstanceApi.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"InstanceApi.d.ts","sourceRoot":"","sources":["../../../src/api/endpoints/InstanceApi.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,uBAAuB,CAAC;AACtD,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,mCAAmC,CAAC;AAC9E,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,mCAAmC,CAAC;AAC9E,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAI5C,KAAK,YAAY,GAAG;IAClB;;;;OAIG;IACH,QAAQ,CAAC,EAAE,OAAO,GAAG,IAAI,GAAG,SAAS,CAAC;IACtC;;OAEG;IACH,IAAI,CAAC,EAAE,OAAO,GAAG,IAAI,GAAG,SAAS,CAAC;IAClC;;;;OAIG;IACH,2BAA2B,CAAC,EAAE,OAAO,GAAG,IAAI,GAAG,SAAS,CAAC;IACzD,YAAY,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC;IACzC,cAAc,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC;IAC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0B,CAAC,MAAM,EAAE,gCAAgC;CAOjF"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/InvitationApi.d.ts b/backend/node_modules/@clerk/backend/dist/api/endpoints/InvitationApi.d.ts new file mode 100644 index 000000000..891ded5e0 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/InvitationApi.d.ts @@ -0,0 +1,50 @@ +import type { ClerkPaginationRequest } from '@clerk/types'; +import type { PaginatedResourceResponse } from '../resources/Deserializer'; +import type { InvitationStatus } from '../resources/Enums'; +import type { Invitation } from '../resources/Invitation'; +import { AbstractAPI } from './AbstractApi'; +type TemplateSlug = 'invitation' | 'waitlist_invitation'; +type CreateParams = { + emailAddress: string; + expiresInDays?: number; + ignoreExisting?: boolean; + notify?: boolean; + publicMetadata?: UserPublicMetadata; + redirectUrl?: string; + templateSlug?: TemplateSlug; +}; +type CreateBulkParams = Array; +type GetInvitationListParams = ClerkPaginationRequest<{ + /** + * Filters invitations based on their status. + * + * @example + * Get all revoked invitations + * ```ts + * import { createClerkClient } from '@clerk/backend'; + * const clerkClient = createClerkClient(...) + * await clerkClient.invitations.getInvitationList({ status: 'revoked' }) + * ``` + */ + status?: InvitationStatus; + /** + * Filters invitations based on `email_address` or `id`. + * + * @example + * Get all invitations for a specific email address + * ```ts + * import { createClerkClient } from '@clerk/backend'; + * const clerkClient = createClerkClient(...) + * await clerkClient.invitations.getInvitationList({ query: 'user@example.com' }) + * ``` + */ + query?: string; +}>; +export declare class InvitationAPI extends AbstractAPI { + getInvitationList(params?: GetInvitationListParams): Promise>; + createInvitation(params: CreateParams): Promise; + createInvitationBulk(params: CreateBulkParams): Promise; + revokeInvitation(invitationId: string): Promise; +} +export {}; +//# sourceMappingURL=InvitationApi.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/InvitationApi.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/endpoints/InvitationApi.d.ts.map new file mode 100644 index 000000000..e5e435ee2 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/InvitationApi.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"InvitationApi.d.ts","sourceRoot":"","sources":["../../../src/api/endpoints/InvitationApi.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAC;AAG3D,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,2BAA2B,CAAC;AAC3E,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAC3D,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAC;AAC1D,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAI5C,KAAK,YAAY,GAAG,YAAY,GAAG,qBAAqB,CAAC;AAEzD,KAAK,YAAY,GAAG;IAClB,YAAY,EAAE,MAAM,CAAC;IACrB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,cAAc,CAAC,EAAE,kBAAkB,CAAC;IACpC,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,YAAY,CAAC,EAAE,YAAY,CAAC;CAC7B,CAAC;AAEF,KAAK,gBAAgB,GAAG,KAAK,CAAC,YAAY,CAAC,CAAC;AAE5C,KAAK,uBAAuB,GAAG,sBAAsB,CAAC;IACpD;;;;;;;;;;OAUG;IACH,MAAM,CAAC,EAAE,gBAAgB,CAAC;IAC1B;;;;;;;;;;OAUG;IACH,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB,CAAC,CAAC;AAEH,qBAAa,aAAc,SAAQ,WAAW;IAC/B,iBAAiB,CAAC,MAAM,GAAE,uBAA4B;IAQtD,gBAAgB,CAAC,MAAM,EAAE,YAAY;IAQrC,oBAAoB,CAAC,MAAM,EAAE,gBAAgB;IAQ7C,gBAAgB,CAAC,YAAY,EAAE,MAAM;CAOnD"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/JwksApi.d.ts b/backend/node_modules/@clerk/backend/dist/api/endpoints/JwksApi.d.ts new file mode 100644 index 000000000..ce372866f --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/JwksApi.d.ts @@ -0,0 +1,6 @@ +import type { JwksJSON } from '../resources/JSON'; +import { AbstractAPI } from './AbstractApi'; +export declare class JwksAPI extends AbstractAPI { + getJwks(): Promise; +} +//# sourceMappingURL=JwksApi.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/JwksApi.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/endpoints/JwksApi.d.ts.map new file mode 100644 index 000000000..c15907712 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/JwksApi.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"JwksApi.d.ts","sourceRoot":"","sources":["../../../src/api/endpoints/JwksApi.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAClD,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAI5C,qBAAa,OAAQ,SAAQ,WAAW;IACzB,OAAO;CAMrB"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/JwtTemplatesApi.d.ts b/backend/node_modules/@clerk/backend/dist/api/endpoints/JwtTemplatesApi.d.ts new file mode 100644 index 000000000..ec43471fb --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/JwtTemplatesApi.d.ts @@ -0,0 +1,49 @@ +import type { ClerkPaginationRequest } from '@clerk/types'; +import type { DeletedObject, JwtTemplate } from '../resources'; +import { AbstractAPI } from './AbstractApi'; +type Claims = object; +type CreateJWTTemplateParams = { + /** + * JWT template name + */ + name: string; + /** + * JWT template claims in JSON format + */ + claims: Claims; + /** + * JWT token lifetime + */ + lifetime?: number | null | undefined; + /** + * JWT token allowed clock skew + */ + allowedClockSkew?: number | null | undefined; + /** + * Whether a custom signing key/algorithm is also provided for this template + */ + customSigningKey?: boolean | undefined; + /** + * The custom signing algorithm to use when minting JWTs. Required if `custom_signing_key` is `true`. + */ + signingAlgorithm?: string | null | undefined; + /** + * The custom signing private key to use when minting JWTs. Required if `custom_signing_key` is `true`. + */ + signingKey?: string | null | undefined; +}; +type UpdateJWTTemplateParams = CreateJWTTemplateParams & { + /** + * JWT template ID + */ + templateId: string; +}; +export declare class JwtTemplatesApi extends AbstractAPI { + list(params?: ClerkPaginationRequest): Promise; + get(templateId: string): Promise; + create(params: CreateJWTTemplateParams): Promise; + update(params: UpdateJWTTemplateParams): Promise; + delete(templateId: string): Promise; +} +export {}; +//# sourceMappingURL=JwtTemplatesApi.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/JwtTemplatesApi.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/endpoints/JwtTemplatesApi.d.ts.map new file mode 100644 index 000000000..d01fa4e90 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/JwtTemplatesApi.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"JwtTemplatesApi.d.ts","sourceRoot":"","sources":["../../../src/api/endpoints/JwtTemplatesApi.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAC;AAG3D,OAAO,KAAK,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC/D,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAI5C,KAAK,MAAM,GAAG,MAAM,CAAC;AAErB,KAAK,uBAAuB,GAAG;IAC7B;;OAEG;IACH,IAAI,EAAE,MAAM,CAAC;IACb;;OAEG;IACH,MAAM,EAAE,MAAM,CAAC;IACf;;OAEG;IACH,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC;IACrC;;OAEG;IACH,gBAAgB,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC;IAC7C;;OAEG;IACH,gBAAgB,CAAC,EAAE,OAAO,GAAG,SAAS,CAAC;IACvC;;OAEG;IACH,gBAAgB,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC;IAC7C;;OAEG;IACH,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC;CACxC,CAAC;AAEF,KAAK,uBAAuB,GAAG,uBAAuB,GAAG;IACvD;;OAEG;IACH,UAAU,EAAE,MAAM,CAAC;CACpB,CAAC;AAEF,qBAAa,eAAgB,SAAQ,WAAW;IACjC,IAAI,CAAC,MAAM,GAAE,sBAA2B;IAQxC,GAAG,CAAC,UAAU,EAAE,MAAM;IAStB,MAAM,CAAC,MAAM,EAAE,uBAAuB;IAQtC,MAAM,CAAC,MAAM,EAAE,uBAAuB;IAWtC,MAAM,CAAC,UAAU,EAAE,MAAM;CAQvC"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/M2MTokenApi.d.ts b/backend/node_modules/@clerk/backend/dist/api/endpoints/M2MTokenApi.d.ts new file mode 100644 index 000000000..0ba323740 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/M2MTokenApi.d.ts @@ -0,0 +1,44 @@ +import type { M2MToken } from '../resources/M2MToken'; +import { AbstractAPI } from './AbstractApi'; +type CreateM2MTokenParams = { + /** + * Custom machine secret key for authentication. + */ + machineSecretKey?: string; + /** + * Number of seconds until the token expires. + * + * @default null - Token does not expire + */ + secondsUntilExpiration?: number | null; + claims?: Record | null; +}; +type RevokeM2MTokenParams = { + /** + * Custom machine secret key for authentication. + */ + machineSecretKey?: string; + /** + * Machine-to-machine token ID to revoke. + */ + m2mTokenId: string; + revocationReason?: string | null; +}; +type VerifyM2MTokenParams = { + /** + * Custom machine secret key for authentication. + */ + machineSecretKey?: string; + /** + * Machine-to-machine token to verify. + */ + token: string; +}; +export declare class M2MTokenApi extends AbstractAPI { + #private; + createToken(params?: CreateM2MTokenParams): Promise; + revokeToken(params: RevokeM2MTokenParams): Promise; + verifyToken(params: VerifyM2MTokenParams): Promise; +} +export {}; +//# sourceMappingURL=M2MTokenApi.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/M2MTokenApi.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/endpoints/M2MTokenApi.d.ts.map new file mode 100644 index 000000000..bff6b38b1 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/M2MTokenApi.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"M2MTokenApi.d.ts","sourceRoot":"","sources":["../../../src/api/endpoints/M2MTokenApi.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,uBAAuB,CAAC;AACtD,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAI5C,KAAK,oBAAoB,GAAG;IAC1B;;OAEG;IACH,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B;;;;OAIG;IACH,sBAAsB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACvC,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAAC;CACzC,CAAC;AAEF,KAAK,oBAAoB,GAAG;IAC1B;;OAEG;IACH,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B;;OAEG;IACH,UAAU,EAAE,MAAM,CAAC;IACnB,gBAAgB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAClC,CAAC;AAEF,KAAK,oBAAoB,GAAG;IAC1B;;OAEG;IACH,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B;;OAEG;IACH,KAAK,EAAE,MAAM,CAAC;CACf,CAAC;AAEF,qBAAa,WAAY,SAAQ,WAAW;;IAepC,WAAW,CAAC,MAAM,CAAC,EAAE,oBAAoB;IAkBzC,WAAW,CAAC,MAAM,EAAE,oBAAoB;IAmBxC,WAAW,CAAC,MAAM,EAAE,oBAAoB;CAc/C"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/MachineApi.d.ts b/backend/node_modules/@clerk/backend/dist/api/endpoints/MachineApi.d.ts new file mode 100644 index 000000000..e63cd4259 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/MachineApi.d.ts @@ -0,0 +1,81 @@ +import type { ClerkPaginationRequest } from '@clerk/types'; +import type { PaginatedResourceResponse } from '../resources/Deserializer'; +import type { Machine } from '../resources/Machine'; +import type { MachineScope } from '../resources/MachineScope'; +import type { MachineSecretKey } from '../resources/MachineSecretKey'; +import { AbstractAPI } from './AbstractApi'; +import type { WithSign } from './util-types'; +type CreateMachineParams = { + /** + * The name of the machine. + */ + name: string; + /** + * Array of machine IDs that this machine will have access to. + */ + scopedMachines?: string[]; + /** + * The default time-to-live (TTL) in seconds for tokens created by this machine. + */ + defaultTokenTtl?: number; +}; +type UpdateMachineParams = { + /** + * The ID of the machine to update. + */ + machineId: string; + /** + * The name of the machine. + */ + name?: string; + /** + * The default time-to-live (TTL) in seconds for tokens created by this machine. + */ + defaultTokenTtl?: number; +}; +type GetMachineListParams = ClerkPaginationRequest<{ + /** + * Sorts machines by name or created_at. + * By prepending one of those values with + or -, we can choose to sort in ascending (ASC) or descending (DESC) order. + */ + orderBy?: WithSign<'name' | 'created_at'>; + /** + * Returns machines that have a ID or name that matches the given query. + */ + query?: string; +}>; +type RotateMachineSecretKeyParams = { + /** + * The ID of the machine to rotate the secret key for. + */ + machineId: string; + /** + * The time in seconds that the previous secret key will remain valid after rotation. + */ + previousTokenTtl: number; +}; +export declare class MachineApi extends AbstractAPI { + get(machineId: string): Promise; + list(queryParams?: GetMachineListParams): Promise>; + create(bodyParams: CreateMachineParams): Promise; + update(params: UpdateMachineParams): Promise; + delete(machineId: string): Promise; + getSecretKey(machineId: string): Promise; + rotateSecretKey(params: RotateMachineSecretKeyParams): Promise; + /** + * Creates a new machine scope, allowing the specified machine to access another machine. + * + * @param machineId - The ID of the machine that will have access to another machine. + * @param toMachineId - The ID of the machine that will be scoped to the current machine. + */ + createScope(machineId: string, toMachineId: string): Promise; + /** + * Deletes a machine scope, removing access from one machine to another. + * + * @param machineId - The ID of the machine that has access to another machine. + * @param otherMachineId - The ID of the machine that is being accessed. + */ + deleteScope(machineId: string, otherMachineId: string): Promise; +} +export {}; +//# sourceMappingURL=MachineApi.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/MachineApi.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/endpoints/MachineApi.d.ts.map new file mode 100644 index 000000000..1ccd218a2 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/MachineApi.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"MachineApi.d.ts","sourceRoot":"","sources":["../../../src/api/endpoints/MachineApi.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAC;AAG3D,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,2BAA2B,CAAC;AAC3E,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,sBAAsB,CAAC;AACpD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AAC9D,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,+BAA+B,CAAC;AACtE,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAI7C,KAAK,mBAAmB,GAAG;IACzB;;OAEG;IACH,IAAI,EAAE,MAAM,CAAC;IACb;;OAEG;IACH,cAAc,CAAC,EAAE,MAAM,EAAE,CAAC;IAC1B;;OAEG;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;CAC1B,CAAC;AAEF,KAAK,mBAAmB,GAAG;IACzB;;OAEG;IACH,SAAS,EAAE,MAAM,CAAC;IAClB;;OAEG;IACH,IAAI,CAAC,EAAE,MAAM,CAAC;IACd;;OAEG;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;CAC1B,CAAC;AAEF,KAAK,oBAAoB,GAAG,sBAAsB,CAAC;IACjD;;;OAGG;IACH,OAAO,CAAC,EAAE,QAAQ,CAAC,MAAM,GAAG,YAAY,CAAC,CAAC;IAC1C;;OAEG;IACH,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB,CAAC,CAAC;AAEH,KAAK,4BAA4B,GAAG;IAClC;;OAEG;IACH,SAAS,EAAE,MAAM,CAAC;IAClB;;OAEG;IACH,gBAAgB,EAAE,MAAM,CAAC;CAC1B,CAAC;AAEF,qBAAa,UAAW,SAAQ,WAAW;IACnC,GAAG,CAAC,SAAS,EAAE,MAAM;IAQrB,IAAI,CAAC,WAAW,GAAE,oBAAyB;IAQ3C,MAAM,CAAC,UAAU,EAAE,mBAAmB;IAQtC,MAAM,CAAC,MAAM,EAAE,mBAAmB;IAUlC,MAAM,CAAC,SAAS,EAAE,MAAM;IAQxB,YAAY,CAAC,SAAS,EAAE,MAAM;IAQ9B,eAAe,CAAC,MAAM,EAAE,4BAA4B;IAY1D;;;;;OAKG;IACG,WAAW,CAAC,SAAS,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM;IAWxD;;;;;OAKG;IACG,WAAW,CAAC,SAAS,EAAE,MAAM,EAAE,cAAc,EAAE,MAAM;CAO5D"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/OAuthApplicationsApi.d.ts b/backend/node_modules/@clerk/backend/dist/api/endpoints/OAuthApplicationsApi.d.ts new file mode 100644 index 000000000..9f7be3d23 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/OAuthApplicationsApi.d.ts @@ -0,0 +1,49 @@ +import type { ClerkPaginationRequest } from '@clerk/types'; +import type { DeletedObject } from '../resources'; +import type { PaginatedResourceResponse } from '../resources/Deserializer'; +import type { OAuthApplication } from '../resources/OAuthApplication'; +import { AbstractAPI } from './AbstractApi'; +import type { WithSign } from './util-types'; +type CreateOAuthApplicationParams = { + /** + * The name of the new OAuth application. + * + * @remarks Max length: 256 + */ + name: string; + /** + * An array of redirect URIs of the new OAuth application + */ + redirectUris?: Array | null | undefined; + /** + * Define the allowed scopes for the new OAuth applications that dictate the user payload of the OAuth user info endpoint. Available scopes are `profile`, `email`, `public_metadata`, `private_metadata`. Provide the requested scopes as a string, separated by spaces. + */ + scopes?: string | null | undefined; + /** + * If true, this client is public and you can use the Proof Key of Code Exchange (PKCE) flow. + */ + public?: boolean | null | undefined; +}; +type UpdateOAuthApplicationParams = CreateOAuthApplicationParams & { + /** + * The ID of the OAuth application to update + */ + oauthApplicationId: string; +}; +type GetOAuthApplicationListParams = ClerkPaginationRequest<{ + /** + * Sorts OAuth applications by name or created_at. + * By prepending one of those values with + or -, we can choose to sort in ascending (ASC) or descending (DESC) order. + */ + orderBy?: WithSign<'name' | 'created_at'>; +}>; +export declare class OAuthApplicationsApi extends AbstractAPI { + list(params?: GetOAuthApplicationListParams): Promise>; + get(oauthApplicationId: string): Promise; + create(params: CreateOAuthApplicationParams): Promise; + update(params: UpdateOAuthApplicationParams): Promise; + delete(oauthApplicationId: string): Promise; + rotateSecret(oauthApplicationId: string): Promise; +} +export {}; +//# sourceMappingURL=OAuthApplicationsApi.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/OAuthApplicationsApi.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/endpoints/OAuthApplicationsApi.d.ts.map new file mode 100644 index 000000000..3ad2c284c --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/OAuthApplicationsApi.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"OAuthApplicationsApi.d.ts","sourceRoot":"","sources":["../../../src/api/endpoints/OAuthApplicationsApi.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAC;AAG3D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAClD,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,2BAA2B,CAAC;AAC3E,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,+BAA+B,CAAC;AACtE,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAI7C,KAAK,4BAA4B,GAAG;IAClC;;;;OAIG;IACH,IAAI,EAAE,MAAM,CAAC;IACb;;OAEG;IACH,YAAY,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,GAAG,IAAI,GAAG,SAAS,CAAC;IAChD;;OAEG;IACH,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC;IACnC;;OAEG;IACH,MAAM,CAAC,EAAE,OAAO,GAAG,IAAI,GAAG,SAAS,CAAC;CACrC,CAAC;AAEF,KAAK,4BAA4B,GAAG,4BAA4B,GAAG;IACjE;;OAEG;IACH,kBAAkB,EAAE,MAAM,CAAC;CAC5B,CAAC;AAEF,KAAK,6BAA6B,GAAG,sBAAsB,CAAC;IAC1D;;;OAGG;IACH,OAAO,CAAC,EAAE,QAAQ,CAAC,MAAM,GAAG,YAAY,CAAC,CAAC;CAC3C,CAAC,CAAC;AAEH,qBAAa,oBAAqB,SAAQ,WAAW;IACtC,IAAI,CAAC,MAAM,GAAE,6BAAkC;IAQ/C,GAAG,CAAC,kBAAkB,EAAE,MAAM;IAS9B,MAAM,CAAC,MAAM,EAAE,4BAA4B;IAQ3C,MAAM,CAAC,MAAM,EAAE,4BAA4B;IAY3C,MAAM,CAAC,kBAAkB,EAAE,MAAM;IASjC,YAAY,CAAC,kBAAkB,EAAE,MAAM;CAQrD"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/OrganizationApi.d.ts b/backend/node_modules/@clerk/backend/dist/api/endpoints/OrganizationApi.d.ts new file mode 100644 index 000000000..e636fdfc6 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/OrganizationApi.d.ts @@ -0,0 +1,199 @@ +import type { ClerkPaginationRequest, OrganizationEnrollmentMode } from '@clerk/types'; +import type { Organization, OrganizationDomain, OrganizationInvitation, OrganizationInvitationStatus, OrganizationMembership } from '../resources'; +import type { PaginatedResourceResponse } from '../resources/Deserializer'; +import type { OrganizationMembershipRole } from '../resources/Enums'; +import { AbstractAPI } from './AbstractApi'; +import type { WithSign } from './util-types'; +type MetadataParams = { + publicMetadata?: TPublic; + privateMetadata?: TPrivate; +}; +type GetOrganizationListParams = ClerkPaginationRequest<{ + includeMembersCount?: boolean; + query?: string; + orderBy?: WithSign<'name' | 'created_at' | 'members_count'>; + organizationId?: string[]; +}>; +type CreateParams = { + name: string; + slug?: string; + createdBy?: string; + maxAllowedMemberships?: number; +} & MetadataParams; +type GetOrganizationParams = ({ + organizationId: string; +} | { + slug: string; +}) & { + includeMembersCount?: boolean; +}; +type UpdateParams = { + name?: string; + slug?: string; + maxAllowedMemberships?: number; +} & MetadataParams; +type UpdateLogoParams = { + file: Blob | File; + uploaderUserId?: string; +}; +type UpdateMetadataParams = MetadataParams; +type GetOrganizationMembershipListParams = ClerkPaginationRequest<{ + organizationId: string; + /** + * Sorts organizations memberships by phone_number, email_address, created_at, first_name, last_name or username. + * By prepending one of those values with + or -, we can choose to sort in ascending (ASC) or descending (DESC) order. + */ + orderBy?: WithSign<'phone_number' | 'email_address' | 'created_at' | 'first_name' | 'last_name' | 'username'>; + /** + * Returns users with the user ids specified. For each user id, the `+` and `-` can be + * prepended to the id, which denote whether the respective user id should be included or + * excluded from the result set. Accepts up to 100 user ids. Any user ids not found are ignored. + */ + userId?: string[]; + emailAddress?: string[]; + phoneNumber?: string[]; + username?: string[]; + web3Wallet?: string[]; + role?: OrganizationMembershipRole[]; + /** + * Returns users that match the given query. + * For possible matches, we check the email addresses, phone numbers, usernames, web3 wallets, user ids, first and last names. + * The query value doesn't need to match the exact value you are looking for, it is capable of partial matches as well. + */ + query?: string; + /** + * Returns users with emails that match the given query, via case-insensitive partial match. + * For example, `email_address_query=ello` will match a user with the email `HELLO@example.com`. + */ + emailAddressQuery?: string; + /** + * Returns users with phone numbers that match the given query, via case-insensitive partial match. + * For example, `phone_number_query=555` will match a user with the phone number `+1555xxxxxxx`. + */ + phoneNumberQuery?: string; + /** + * Returns users with usernames that match the given query, via case-insensitive partial match. + * For example, `username_query=CoolUser` will match a user with the username `SomeCoolUser`. + */ + usernameQuery?: string; + nameQuery?: string; + /** + * Returns users whose last session activity was before the given date (with millisecond precision). + * Example: use 1700690400000 to retrieve users whose last session activity was before 2023-11-23. + */ + lastActiveAtBefore?: number; + /** + * Returns users whose last session activity was after the given date (with millisecond precision). + * Example: use 1700690400000 to retrieve users whose last session activity was after 2023-11-23. + */ + lastActiveAtAfter?: number; + /** + * Returns users who have been created before the given date (with millisecond precision). + * Example: use 1730160000000 to retrieve users who have been created before 2024-10-29. + */ + createdAtBefore?: number; + /** + * Returns users who have been created after the given date (with millisecond precision). + * Example: use 1730160000000 to retrieve users who have been created after 2024-10-29. + */ + createdAtAfter?: number; +}>; +type GetInstanceOrganizationMembershipListParams = ClerkPaginationRequest<{ + /** + * Sorts organizations memberships by phone_number, email_address, created_at, first_name, last_name or username. + * By prepending one of those values with + or -, we can choose to sort in ascending (ASC) or descending (DESC) order. + */ + orderBy?: WithSign<'phone_number' | 'email_address' | 'created_at' | 'first_name' | 'last_name' | 'username'>; +}>; +type CreateOrganizationMembershipParams = { + organizationId: string; + userId: string; + role: OrganizationMembershipRole; +}; +type UpdateOrganizationMembershipParams = CreateOrganizationMembershipParams; +type UpdateOrganizationMembershipMetadataParams = { + organizationId: string; + userId: string; +} & MetadataParams; +type DeleteOrganizationMembershipParams = { + organizationId: string; + userId: string; +}; +type CreateOrganizationInvitationParams = { + organizationId: string; + emailAddress: string; + role: OrganizationMembershipRole; + expiresInDays?: number; + inviterUserId?: string; + privateMetadata?: OrganizationInvitationPrivateMetadata; + publicMetadata?: OrganizationInvitationPublicMetadata; + redirectUrl?: string; +}; +type CreateBulkOrganizationInvitationParams = Array<{ + emailAddress: string; + role: OrganizationMembershipRole; + expiresInDays?: number; + inviterUserId?: string; + privateMetadata?: OrganizationInvitationPrivateMetadata; + publicMetadata?: OrganizationInvitationPublicMetadata; + redirectUrl?: string; +}>; +type GetOrganizationInvitationListParams = ClerkPaginationRequest<{ + organizationId: string; + status?: OrganizationInvitationStatus[]; +}>; +type GetOrganizationInvitationParams = { + organizationId: string; + invitationId: string; +}; +type RevokeOrganizationInvitationParams = { + organizationId: string; + invitationId: string; + requestingUserId?: string; +}; +type GetOrganizationDomainListParams = { + organizationId: string; + limit?: number; + offset?: number; +}; +type CreateOrganizationDomainParams = { + organizationId: string; + name: string; + enrollmentMode: OrganizationEnrollmentMode; + verified?: boolean; +}; +type UpdateOrganizationDomainParams = { + organizationId: string; + domainId: string; +} & Partial; +type DeleteOrganizationDomainParams = { + organizationId: string; + domainId: string; +}; +export declare class OrganizationAPI extends AbstractAPI { + getOrganizationList(params?: GetOrganizationListParams): Promise>; + createOrganization(params: CreateParams): Promise; + getOrganization(params: GetOrganizationParams): Promise; + updateOrganization(organizationId: string, params: UpdateParams): Promise; + updateOrganizationLogo(organizationId: string, params: UpdateLogoParams): Promise; + deleteOrganizationLogo(organizationId: string): Promise; + updateOrganizationMetadata(organizationId: string, params: UpdateMetadataParams): Promise; + deleteOrganization(organizationId: string): Promise; + getOrganizationMembershipList(params: GetOrganizationMembershipListParams): Promise>; + getInstanceOrganizationMembershipList(params: GetInstanceOrganizationMembershipListParams): Promise>; + createOrganizationMembership(params: CreateOrganizationMembershipParams): Promise; + updateOrganizationMembership(params: UpdateOrganizationMembershipParams): Promise; + updateOrganizationMembershipMetadata(params: UpdateOrganizationMembershipMetadataParams): Promise; + deleteOrganizationMembership(params: DeleteOrganizationMembershipParams): Promise; + getOrganizationInvitationList(params: GetOrganizationInvitationListParams): Promise>; + createOrganizationInvitation(params: CreateOrganizationInvitationParams): Promise; + createOrganizationInvitationBulk(organizationId: string, params: CreateBulkOrganizationInvitationParams): Promise; + getOrganizationInvitation(params: GetOrganizationInvitationParams): Promise; + revokeOrganizationInvitation(params: RevokeOrganizationInvitationParams): Promise; + getOrganizationDomainList(params: GetOrganizationDomainListParams): Promise>; + createOrganizationDomain(params: CreateOrganizationDomainParams): Promise; + updateOrganizationDomain(params: UpdateOrganizationDomainParams): Promise; + deleteOrganizationDomain(params: DeleteOrganizationDomainParams): Promise; +} +export {}; +//# sourceMappingURL=OrganizationApi.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/OrganizationApi.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/endpoints/OrganizationApi.d.ts.map new file mode 100644 index 000000000..72cd16284 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/OrganizationApi.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"OrganizationApi.d.ts","sourceRoot":"","sources":["../../../src/api/endpoints/OrganizationApi.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,sBAAsB,EAAE,0BAA0B,EAAE,MAAM,cAAc,CAAC;AAIvF,OAAO,KAAK,EACV,YAAY,EACZ,kBAAkB,EAClB,sBAAsB,EACtB,4BAA4B,EAC5B,sBAAsB,EACvB,MAAM,cAAc,CAAC;AACtB,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,2BAA2B,CAAC;AAC3E,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,oBAAoB,CAAC;AACrE,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAI7C,KAAK,cAAc,CAAC,OAAO,GAAG,0BAA0B,EAAE,QAAQ,GAAG,2BAA2B,IAAI;IAClG,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,eAAe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+B;IAWjE,4BAA4B,CAAC,MAAM,EAAE,kCAAkC;IAWvE,yBAAyB,CAAC,MAAM,EAAE,+BAA+B;IAWjE,wBAAwB,CAAC,MAAM,EAAE,8BAA8B;IAc/D,wBAAwB,CAAC,MAAM,EAAE,8BAA8B;IAY/D,wBAAwB,CAAC,MAAM,EAAE,8BAA8B;CAU7E"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/PhoneNumberApi.d.ts b/backend/node_modules/@clerk/backend/dist/api/endpoints/PhoneNumberApi.d.ts new file mode 100644 index 000000000..3a77e8f33 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/PhoneNumberApi.d.ts @@ -0,0 +1,22 @@ +import type { DeletedObject, PhoneNumber } from '../resources'; +import { AbstractAPI } from './AbstractApi'; +type CreatePhoneNumberParams = { + userId: string; + phoneNumber: string; + verified?: boolean; + primary?: boolean; + reservedForSecondFactor?: boolean; +}; +type UpdatePhoneNumberParams = { + verified?: boolean; + primary?: boolean; + reservedForSecondFactor?: boolean; +}; +export declare class PhoneNumberAPI extends AbstractAPI { + getPhoneNumber(phoneNumberId: string): Promise; + createPhoneNumber(params: CreatePhoneNumberParams): Promise; + updatePhoneNumber(phoneNumberId: string, params?: UpdatePhoneNumberParams): Promise; + deletePhoneNumber(phoneNumberId: string): Promise; +} +export {}; +//# sourceMappingURL=PhoneNumberApi.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/PhoneNumberApi.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/endpoints/PhoneNumberApi.d.ts.map new file mode 100644 index 000000000..27ebefa0b --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/PhoneNumberApi.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"PhoneNumberApi.d.ts","sourceRoot":"","sources":["../../../src/api/endpoints/PhoneNumberApi.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC/D,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAI5C,KAAK,uBAAuB,GAAG;IAC7B,MAAM,EAAE,MAAM,CAAC;IACf,WAAW,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,uBAAuB,CAAC,EAAE,OAAO,CAAC;CACnC,CAAC;AAEF,KAAK,uBAAuB,GAAG;IAC7B,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,uBAAuB,CAAC,EAAE,OAAO,CAAC;CACnC,CAAC;AAEF,qBAAa,cAAe,SAAQ,WAAW;IAChC,cAAc,CAAC,aAAa,EAAE,MAAM;IASpC,iBAAiB,CAAC,MAAM,EAAE,uBAAuB;IAQjD,iBAAiB,CAAC,aAAa,EAAE,MAAM,EAAE,MAAM,GAAE,uBAA4B;IAU7E,iBAAiB,CAAC,aAAa,EAAE,MAAM;CAQrD"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/ProxyCheckApi.d.ts b/backend/node_modules/@clerk/backend/dist/api/endpoints/ProxyCheckApi.d.ts new file mode 100644 index 000000000..fb9b15382 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/ProxyCheckApi.d.ts @@ -0,0 +1,11 @@ +import type { ProxyCheck } from '../resources'; +import { AbstractAPI } from './AbstractApi'; +type VerifyParams = { + domainId: string; + proxyUrl: string; +}; +export declare class ProxyCheckAPI extends AbstractAPI { + verify(params: VerifyParams): Promise; +} +export {}; +//# sourceMappingURL=ProxyCheckApi.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/ProxyCheckApi.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/endpoints/ProxyCheckApi.d.ts.map new file mode 100644 index 000000000..e40e1cc81 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/ProxyCheckApi.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ProxyCheckApi.d.ts","sourceRoot":"","sources":["../../../src/api/endpoints/ProxyCheckApi.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC/C,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAI5C,KAAK,YAAY,GAAG;IAClB,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,MAAM,CAAC;CAClB,CAAC;AAEF,qBAAa,aAAc,SAAQ,WAAW;IAC/B,MAAM,CAAC,MAAM,EAAE,YAAY;CAOzC"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/RedirectUrlApi.d.ts b/backend/node_modules/@clerk/backend/dist/api/endpoints/RedirectUrlApi.d.ts new file mode 100644 index 000000000..5fa401bba --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/RedirectUrlApi.d.ts @@ -0,0 +1,14 @@ +import type { PaginatedResourceResponse } from '../resources/Deserializer'; +import type { RedirectUrl } from '../resources/RedirectUrl'; +import { AbstractAPI } from './AbstractApi'; +type CreateRedirectUrlParams = { + url: string; +}; +export declare class RedirectUrlAPI extends AbstractAPI { + getRedirectUrlList(): Promise>; + getRedirectUrl(redirectUrlId: string): Promise; + createRedirectUrl(params: CreateRedirectUrlParams): Promise; + deleteRedirectUrl(redirectUrlId: string): Promise; +} +export {}; +//# sourceMappingURL=RedirectUrlApi.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/RedirectUrlApi.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/endpoints/RedirectUrlApi.d.ts.map new file mode 100644 index 000000000..cb6b9b16d --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/RedirectUrlApi.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"RedirectUrlApi.d.ts","sourceRoot":"","sources":["../../../src/api/endpoints/RedirectUrlApi.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,2BAA2B,CAAC;AAC3E,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AAC5D,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAI5C,KAAK,uBAAuB,GAAG;IAC7B,GAAG,EAAE,MAAM,CAAC;CACb,CAAC;AAEF,qBAAa,cAAe,SAAQ,WAAW;IAChC,kBAAkB;IAQlB,cAAc,CAAC,aAAa,EAAE,MAAM;IAQpC,iBAAiB,CAAC,MAAM,EAAE,uBAAuB;IAQjD,iBAAiB,CAAC,aAAa,EAAE,MAAM;CAOrD"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/SamlConnectionApi.d.ts b/backend/node_modules/@clerk/backend/dist/api/endpoints/SamlConnectionApi.d.ts new file mode 100644 index 000000000..12b289fbd --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/SamlConnectionApi.d.ts @@ -0,0 +1,69 @@ +import type { ClerkPaginationRequest, SamlIdpSlug } from '@clerk/types'; +import type { SamlConnection } from '../resources'; +import type { PaginatedResourceResponse } from '../resources/Deserializer'; +import { AbstractAPI } from './AbstractApi'; +import type { WithSign } from './util-types'; +type SamlConnectionListParams = ClerkPaginationRequest<{ + /** + * Returns SAML connections that have a name that matches the given query, via case-insensitive partial match. + */ + query?: string; + /** + * Sorts SAML connections by phone_number, email_address, created_at, first_name, last_name or username. + * By prepending one of those values with + or -, we can choose to sort in ascending (ASC) or descending (DESC) order. + */ + orderBy?: WithSign<'phone_number' | 'email_address' | 'created_at' | 'first_name' | 'last_name' | 'username'>; + /** + * Returns SAML connections that have an associated organization ID to the given organizations. + * For each organization id, the + and - can be prepended to the id, which denote whether the + * respective organization should be included or excluded from the result set. Accepts up to 100 organization ids. + */ + organizationId?: WithSign[]; +}>; +type CreateSamlConnectionParams = { + name: string; + provider: SamlIdpSlug; + domain: string; + organizationId?: string; + idpEntityId?: string; + idpSsoUrl?: string; + idpCertificate?: string; + idpMetadataUrl?: string; + idpMetadata?: string; + attributeMapping?: { + emailAddress?: string; + firstName?: string; + lastName?: string; + userId?: string; + }; +}; +type UpdateSamlConnectionParams = { + name?: string; + provider?: SamlIdpSlug; + domain?: string; + organizationId?: string; + idpEntityId?: string; + idpSsoUrl?: string; + idpCertificate?: string; + idpMetadataUrl?: string; + idpMetadata?: string; + attributeMapping?: { + emailAddress?: string; + firstName?: string; + lastName?: string; + userId?: string; + }; + active?: boolean; + syncUserAttributes?: boolean; + allowSubdomains?: boolean; + allowIdpInitiated?: boolean; +}; +export declare class SamlConnectionAPI extends AbstractAPI { + getSamlConnectionList(params?: SamlConnectionListParams): Promise>; + createSamlConnection(params: CreateSamlConnectionParams): Promise; + getSamlConnection(samlConnectionId: string): Promise; + updateSamlConnection(samlConnectionId: string, params?: UpdateSamlConnectionParams): Promise; + deleteSamlConnection(samlConnectionId: string): Promise; +} +export {}; +//# sourceMappingURL=SamlConnectionApi.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/SamlConnectionApi.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/endpoints/SamlConnectionApi.d.ts.map new file mode 100644 index 000000000..e13d220af --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/SamlConnectionApi.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"SamlConnectionApi.d.ts","sourceRoot":"","sources":["../../../src/api/endpoints/SamlConnectionApi.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,sBAAsB,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAGxE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AACnD,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,2BAA2B,CAAC;AAC3E,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C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AAM,CAAC;IACrB,gBAAgB,CAAC,EAAE;QACjB,YAAY,CAAC,EAAE,MAAM,CAAC;QACtB,SAAS,CAAC,EAAE,MAAM,CAAC;QACnB,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB,MAAM,CAAC,EAAE,MAAM,CAAC;KACjB,CAAC;IACF,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,kBAAkB,CAAC,EAAE,OAAO,CAAC;IAC7B,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,iBAAiB,CAAC,EAAE,OAAO,CAAC;CAC7B,CAAC;AAEF,qBAAa,iBAAkB,SAAQ,WAAW;IACnC,qBAAqB,CAAC,MAAM,GAAE,wBAA6B;IAQ3D,oBAAoB,CAAC,MAAM,EAAE,0BAA0B;IAWvD,iBAAiB,CAAC,gBAAgB,EAAE,MAAM;IAQ1C,oBAAoB,CAAC,gBAAgB,EAAE,MAAM,EAAE,MAAM,GAAE,0BAA+B;IAYtF,oBAAoB,CAAC,gBAAgB,EAAE,MAAM;CAO3D"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/SessionApi.d.ts b/backend/node_modules/@clerk/backend/dist/api/endpoints/SessionApi.d.ts new file mode 100644 index 000000000..74466f68e --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/SessionApi.d.ts @@ -0,0 +1,52 @@ +import type { ClerkPaginationRequest, SessionStatus } from '@clerk/types'; +import type { Cookies } from '../resources/Cookies'; +import type { PaginatedResourceResponse } from '../resources/Deserializer'; +import type { Session } from '../resources/Session'; +import type { Token } from '../resources/Token'; +import { AbstractAPI } from './AbstractApi'; +type SessionListParams = ClerkPaginationRequest<{ + clientId?: string; + userId?: string; + status?: SessionStatus; +}>; +type RefreshTokenParams = { + expired_token: string; + refresh_token: string; + request_origin: string; + request_originating_ip?: string; + request_headers?: Record; + suffixed_cookies?: boolean; + format?: 'token' | 'cookie'; +}; +type CreateSessionParams = { + userId: string; +}; +export declare class SessionAPI extends AbstractAPI { + getSessionList(params?: SessionListParams): Promise>; + getSession(sessionId: string): Promise; + createSession(params: CreateSessionParams): Promise; + revokeSession(sessionId: string): Promise; + verifySession(sessionId: string, token: string): Promise; + /** + * Retrieves a session token or generates a JWT using a specified template. + * + * @param sessionId - The ID of the session for which to generate the token + * @param template - Optional name of the JWT template configured in the Clerk Dashboard. + * @param expiresInSeconds - Optional expiration time for the token in seconds. + * If not provided, uses the default expiration. + * + * @returns A promise that resolves to the generated token + * + * @throws {Error} When sessionId is invalid or empty + */ + getToken(sessionId: string, template?: string, expiresInSeconds?: number): Promise; + refreshSession(sessionId: string, params: RefreshTokenParams & { + format: 'token'; + }): Promise; + refreshSession(sessionId: string, params: RefreshTokenParams & { + format: 'cookie'; + }): Promise; + refreshSession(sessionId: string, params: RefreshTokenParams): Promise; +} +export {}; +//# sourceMappingURL=SessionApi.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/SessionApi.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/endpoints/SessionApi.d.ts.map new file mode 100644 index 000000000..0e609ce83 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/SessionApi.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"SessionApi.d.ts","sourceRoot":"","sources":["../../../src/api/endpoints/SessionApi.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,sBAAsB,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAG1E,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,sBAAsB,CAAC;AACpD,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,2BAA2B,CAAC;AAC3E,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,sBAAsB,CAAC;AACpD,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAI5C,KAAK,iBAAiB,GAAG,sBAAsB,CAAC;IA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AAkB,GAAG,OAAO,CAAC,KAAK,CAAC;CAW3F"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/SignInTokenApi.d.ts b/backend/node_modules/@clerk/backend/dist/api/endpoints/SignInTokenApi.d.ts new file mode 100644 index 000000000..5d2c57e8b --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/SignInTokenApi.d.ts @@ -0,0 +1,12 @@ +import type { SignInToken } from '../resources/SignInTokens'; +import { AbstractAPI } from './AbstractApi'; +type CreateSignInTokensParams = { + userId: string; + expiresInSeconds: number; +}; +export declare class SignInTokenAPI extends AbstractAPI { + createSignInToken(params: CreateSignInTokensParams): Promise; + revokeSignInToken(signInTokenId: string): Promise; +} +export {}; +//# sourceMappingURL=SignInTokenApi.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/SignInTokenApi.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/endpoints/SignInTokenApi.d.ts.map new file mode 100644 index 000000000..5568edbf1 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/SignInTokenApi.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"SignInTokenApi.d.ts","sourceRoot":"","sources":["../../../src/api/endpoints/SignInTokenApi.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,2BAA2B,CAAC;AAC7D,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAE5C,KAAK,wBAAwB,GAAG;IAC9B,MAAM,EAAE,MAAM,CAAC;IACf,gBAAgB,EAAE,MAAM,CAAC;CAC1B,CAAC;AAIF,qBAAa,cAAe,SAAQ,WAAW;IAChC,iBAAiB,CAAC,MAAM,EAAE,wBAAwB;IAQlD,iBAAiB,CAAC,aAAa,EAAE,MAAM;CAOrD"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/SignUpApi.d.ts b/backend/node_modules/@clerk/backend/dist/api/endpoints/SignUpApi.d.ts new file mode 100644 index 000000000..1c5061ab3 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/SignUpApi.d.ts @@ -0,0 +1,13 @@ +import type { SignUpAttempt } from '../resources/SignUpAttempt'; +import { AbstractAPI } from './AbstractApi'; +type UpdateSignUpParams = { + signUpAttemptId: string; + externalId?: string | null; + customAction?: boolean | null; +}; +export declare class SignUpAPI extends AbstractAPI { + get(signUpAttemptId: string): Promise; + update(params: UpdateSignUpParams): Promise; +} +export {}; +//# sourceMappingURL=SignUpApi.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/SignUpApi.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/endpoints/SignUpApi.d.ts.map new file mode 100644 index 000000000..bffc4924c --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/SignUpApi.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"SignUpApi.d.ts","sourceRoot":"","sources":["../../../src/api/endpoints/SignUpApi.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAChE,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAE5C,KAAK,kBAAkB,GAAG;IACxB,eAAe,EAAE,MAAM,CAAC;IACxB,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,YAAY,CAAC,EAAE,OAAO,GAAG,IAAI,CAAC;CAC/B,CAAC;AAIF,qBAAa,SAAU,SAAQ,WAAW;IAC3B,GAAG,CAAC,eAAe,EAAE,MAAM;IAS3B,MAAM,CAAC,MAAM,EAAE,kBAAkB;CAS/C"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/TestingTokenApi.d.ts b/backend/node_modules/@clerk/backend/dist/api/endpoints/TestingTokenApi.d.ts new file mode 100644 index 000000000..6b16501e1 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/TestingTokenApi.d.ts @@ -0,0 +1,6 @@ +import type { TestingToken } from '../resources/TestingToken'; +import { AbstractAPI } from './AbstractApi'; +export declare class TestingTokenAPI extends AbstractAPI { + createTestingToken(): Promise; +} +//# sourceMappingURL=TestingTokenApi.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/TestingTokenApi.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/endpoints/TestingTokenApi.d.ts.map new file mode 100644 index 000000000..25105069e --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/TestingTokenApi.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"TestingTokenApi.d.ts","sourceRoot":"","sources":["../../../src/api/endpoints/TestingTokenApi.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AAC9D,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAI5C,qBAAa,eAAgB,SAAQ,WAAW;IACjC,kBAAkB;CAMhC"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/UserApi.d.ts b/backend/node_modules/@clerk/backend/dist/api/endpoints/UserApi.d.ts new file mode 100644 index 000000000..f9d8d8fdc --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/UserApi.d.ts @@ -0,0 +1,160 @@ +import type { ClerkPaginationRequest, OAuthProvider, OrganizationInvitationStatus } from '@clerk/types'; +import type { DeletedObject, OauthAccessToken, OrganizationInvitation, OrganizationMembership, User } from '../resources'; +import type { PaginatedResourceResponse } from '../resources/Deserializer'; +import { AbstractAPI } from './AbstractApi'; +import type { WithSign } from './util-types'; +type UserCountParams = { + emailAddress?: string[]; + phoneNumber?: string[]; + username?: string[]; + web3Wallet?: string[]; + query?: string; + userId?: string[]; + externalId?: string[]; +}; +type UserListParams = ClerkPaginationRequest; + last_active_at_since?: number; + organizationId?: string[]; +}>; +type UserMetadataParams = { + publicMetadata?: UserPublicMetadata; + privateMetadata?: UserPrivateMetadata; + unsafeMetadata?: UserUnsafeMetadata; +}; +type PasswordHasher = 'argon2i' | 'argon2id' | 'awscognito' | 'bcrypt' | 'bcrypt_sha256_django' | 'md5' | 'pbkdf2_sha256' | 'pbkdf2_sha256_django' | 'pbkdf2_sha1' | 'phpass' | 'scrypt_firebase' | 'scrypt_werkzeug' | 'sha256' | 'md5_phpass' | 'ldap_ssha'; +type UserPasswordHashingParams = { + passwordDigest: string; + passwordHasher: PasswordHasher; +}; +type CreateUserParams = { + externalId?: string; + emailAddress?: string[]; + phoneNumber?: string[]; + username?: string; + password?: string; + firstName?: string; + lastName?: string; + skipPasswordChecks?: boolean; + skipPasswordRequirement?: boolean; + skipLegalChecks?: boolean; + legalAcceptedAt?: Date; + totpSecret?: string; + backupCodes?: string[]; + createdAt?: Date; +} & UserMetadataParams & (UserPasswordHashingParams | object); +type UpdateUserParams = { + /** The first name to assign to the user. */ + firstName?: string; + /** The last name of the user. */ + lastName?: string; + /** The username to give to the user. It must be unique across your instance. */ + username?: string; + /** The plaintext password to give the user. Must be at least 8 characters long, and can not be in any list of hacked passwords. */ + password?: string; + /** Set it to true if you're updating the user's password and want to skip any password policy settings check. This parameter can only be used when providing a password. */ + skipPasswordChecks?: boolean; + /** Set to true to sign out the user from all their active sessions once their password is updated. This parameter can only be used when providing a password. */ + signOutOfOtherSessions?: boolean; + /** The ID of the email address to set as primary. It must be verified, and present on the current user. */ + primaryEmailAddressID?: string; + /** If set to true, the user will be notified that their primary email address has changed. By default, no notification is sent. */ + notifyPrimaryEmailAddressChanged?: boolean; + /** The ID of the phone number to set as primary. It must be verified, and present on the current user. */ + primaryPhoneNumberID?: string; + /** The ID of the web3 wallets to set as primary. It must be verified, and present on the current user. */ + primaryWeb3WalletID?: string; + /** The ID of the image to set as the user's profile image */ + profileImageID?: string; + /** + * In case TOTP is configured on the instance, you can provide the secret to enable it on the specific user without the need to reset it. + * Please note that currently the supported options are: + * - Period: 30 seconds + * - Code length: 6 digits + * - Algorithm: SHA1 + */ + totpSecret?: string; + /** If Backup Codes are configured on the instance, you can provide them to enable it on the specific user without the need to reset them. You must provide the backup codes in plain format or the corresponding bcrypt digest. */ + backupCodes?: string[]; + /** The ID of the user as used in your external systems or your previous authentication solution. Must be unique across your instance. */ + externalId?: string; + /** A custom timestamp denoting when the user signed up to the application, specified in RFC3339 format (e.g. 2012-10-20T07:15:20.902Z). */ + createdAt?: Date; + /** When set to true all legal checks are skipped. It is not recommended to skip legal checks unless you are migrating a user to Clerk. */ + skipLegalChecks?: boolean; + /** A custom timestamp denoting when the user accepted legal requirements, specified in RFC3339 format (e.g. 2012-10-20T07:15:20.902Z). */ + legalAcceptedAt?: Date; + /** If true, the user can delete themselves with the Frontend API. */ + deleteSelfEnabled?: boolean; + /** If true, the user can create organizations with the Frontend API. */ + createOrganizationEnabled?: boolean; + /** The maximum number of organizations the user can create. 0 means unlimited. */ + createOrganizationsLimit?: number; +} & UserMetadataParams & (UserPasswordHashingParams | object); +type GetOrganizationMembershipListParams = ClerkPaginationRequest<{ + userId: string; +}>; +type GetOrganizationInvitationListParams = ClerkPaginationRequest<{ + userId: string; + status?: OrganizationInvitationStatus; +}>; +type VerifyPasswordParams = { + userId: string; + password: string; +}; +type VerifyTOTPParams = { + userId: string; + code: string; +}; +type DeleteUserPasskeyParams = { + userId: string; + passkeyIdentificationId: string; +}; +type DeleteWeb3WalletParams = { + userId: string; + web3WalletIdentificationId: string; +}; +type DeleteUserExternalAccountParams = { + userId: string; + externalAccountId: string; +}; +type UserID = { + userId: string; +}; +export declare class UserAPI extends AbstractAPI { + getUserList(params?: UserListParams): Promise>; + getUser(userId: string): Promise; + createUser(params: CreateUserParams): Promise; + updateUser(userId: string, params?: UpdateUserParams): Promise; + updateUserProfileImage(userId: string, params: { + file: Blob | File; + }): Promise; + updateUserMetadata(userId: string, params: UserMetadataParams): Promise; + deleteUser(userId: string): Promise; + getCount(params?: UserCountParams): Promise; + /** @deprecated Use `getUserOauthAccessToken` without the `oauth_` provider prefix . */ + getUserOauthAccessToken(userId: string, provider: `oauth_${OAuthProvider}`): Promise>; + getUserOauthAccessToken(userId: string, provider: OAuthProvider): Promise>; + disableUserMFA(userId: string): Promise; + getOrganizationMembershipList(params: GetOrganizationMembershipListParams): Promise>; + getOrganizationInvitationList(params: GetOrganizationInvitationListParams): Promise>; + verifyPassword(params: VerifyPasswordParams): Promise<{ + verified: true; + }>; + verifyTOTP(params: VerifyTOTPParams): Promise<{ + verified: true; + code_type: "totp"; + }>; + banUser(userId: string): Promise; + unbanUser(userId: string): Promise; + lockUser(userId: string): Promise; + unlockUser(userId: string): Promise; + deleteUserProfileImage(userId: string): Promise; + deleteUserPasskey(params: DeleteUserPasskeyParams): Promise; + deleteUserWeb3Wallet(params: DeleteWeb3WalletParams): Promise; + deleteUserExternalAccount(params: DeleteUserExternalAccountParams): Promise; + deleteUserBackupCodes(userId: string): Promise; + deleteUserTOTP(userId: string): Promise; +} +export {}; +//# sourceMappingURL=UserApi.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/UserApi.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/endpoints/UserApi.d.ts.map new file mode 100644 index 000000000..332889173 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/UserApi.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"UserApi.d.ts","sourceRoot":"","sources":["../../../src/api/endpoints/UserApi.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,sBAAsB,EAAE,aAAa,EAAE,4BAA4B,EAAE,MAAM,cAAc,CAAC;AAKxG,OAAO,KAAK,EACV,aAAa,EACb,gBAAgB,EAChB,sBAAsB,EACtB,sBAAsB,EACtB,IAAI,EACL,MAAM,cAAc,CAAC;AACtB,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,2BAA2B,CAAC;AAC3E,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,KAAK,EAAE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oB,CAAC,MAAM,EAAE,sBAAsB;IASnD,yBAAyB,CAAC,MAAM,EAAE,+BAA+B;IASjE,qBAAqB,CAAC,MAAM,EAAE,MAAM;IAQpC,cAAc,CAAC,MAAM,EAAE,MAAM;CAO3C"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/WaitlistEntryApi.d.ts b/backend/node_modules/@clerk/backend/dist/api/endpoints/WaitlistEntryApi.d.ts new file mode 100644 index 000000000..6c7f45252 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/WaitlistEntryApi.d.ts @@ -0,0 +1,55 @@ +import type { ClerkPaginationRequest } from '@clerk/types'; +import type { DeletedObject } from '../resources/DeletedObject'; +import type { PaginatedResourceResponse } from '../resources/Deserializer'; +import type { WaitlistEntryStatus } from '../resources/Enums'; +import type { WaitlistEntry } from '../resources/WaitlistEntry'; +import { AbstractAPI } from './AbstractApi'; +import type { WithSign } from './util-types'; +type WaitlistEntryListParams = ClerkPaginationRequest<{ + /** + * Filter waitlist entries by `email_address` or `id` + */ + query?: string; + status?: WaitlistEntryStatus; + orderBy?: WithSign<'created_at' | 'invited_at' | 'email_address'>; +}>; +type WaitlistEntryCreateParams = { + emailAddress: string; + notify?: boolean; +}; +type WaitlistEntryInviteParams = { + /** + * When true, do not error if an invitation already exists. Default: false. + */ + ignoreExisting?: boolean; +}; +export declare class WaitlistEntryAPI extends AbstractAPI { + /** + * List waitlist entries. + * @param params Optional parameters (e.g., `query`, `status`, `orderBy`). + */ + list(params?: WaitlistEntryListParams): Promise>; + /** + * Create a waitlist entry. + * @param params The parameters for creating a waitlist entry. + */ + create(params: WaitlistEntryCreateParams): Promise; + /** + * Invite a waitlist entry. + * @param id The waitlist entry ID. + * @param params Optional parameters (e.g., `ignoreExisting`). + */ + invite(id: string, params?: WaitlistEntryInviteParams): Promise; + /** + * Reject a waitlist entry. + * @param id The waitlist entry ID. + */ + reject(id: string): Promise; + /** + * Delete a waitlist entry. + * @param id The waitlist entry ID. + */ + delete(id: string): Promise; +} +export {}; +//# sourceMappingURL=WaitlistEntryApi.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/WaitlistEntryApi.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/endpoints/WaitlistEntryApi.d.ts.map new file mode 100644 index 000000000..e1db1688b --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/WaitlistEntryApi.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"WaitlistEntryApi.d.ts","sourceRoot":"","sources":["../../../src/api/endpoints/WaitlistEntryApi.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAC;AAG3D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAChE,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,2BAA2B,CAAC;AAC3E,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AAC9D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAChE,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAI7C,KAAK,uBAAuB,GAAG,sBAAsB,CAAC;IACpD;;OAEG;IACH,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,mBAAmB,CAAC;IAC7B,OAAO,CAAC,EAAE,QAAQ,CAAC,YAAY,GAAG,YAAY,GAAG,eAAe,CAAC,CAAC;CACnE,CAAC,CAAC;AAEH,KAAK,yBAAyB,GAAG;IAC/B,YAAY,EAAE,MAAM,CAAC;IACrB,MAAM,CAAC,EAAE,OAAO,CAAC;CAClB,CAAC;AAEF,KAAK,yBAAyB,GAAG;IAC/B;;OAEG;IACH,cAAc,CAAC,EAAE,OAAO,CAAC;CAC1B,CAAC;AAEF,qBAAa,gBAAiB,SAAQ,WAAW;IAC/C;;;OAGG;IACU,IAAI,CAAC,MAAM,GAAE,uBAA4B;IAQtD;;;OAGG;IACU,MAAM,CAAC,MAAM,EAAE,yBAAyB;IAQrD;;;;OAIG;IACU,MAAM,CAAC,EAAE,EAAE,MAAM,EAAE,MAAM,GAAE,yBAA8B;IAUtE;;;OAGG;IACU,MAAM,CAAC,EAAE,EAAE,MAAM;IAS9B;;;OAGG;IACU,MAAM,CAAC,EAAE,EAAE,MAAM;CAQ/B"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/WebhookApi.d.ts b/backend/node_modules/@clerk/backend/dist/api/endpoints/WebhookApi.d.ts new file mode 100644 index 000000000..f1765e637 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/WebhookApi.d.ts @@ -0,0 +1,8 @@ +import type { WebhooksSvixJSON } from '../resources/JSON'; +import { AbstractAPI } from './AbstractApi'; +export declare class WebhookAPI extends AbstractAPI { + createSvixApp(): Promise; + generateSvixAuthURL(): Promise; + deleteSvixApp(): Promise; +} +//# sourceMappingURL=WebhookApi.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/WebhookApi.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/endpoints/WebhookApi.d.ts.map new file mode 100644 index 000000000..ff10470f9 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/WebhookApi.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"WebhookApi.d.ts","sourceRoot":"","sources":["../../../src/api/endpoints/WebhookApi.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAC1D,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAI5C,qBAAa,UAAW,SAAQ,WAAW;IAC5B,aAAa;IAOb,mBAAmB;IAOnB,aAAa;CAM3B"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/index.d.ts b/backend/node_modules/@clerk/backend/dist/api/endpoints/index.d.ts new file mode 100644 index 000000000..e6b4da180 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/index.d.ts @@ -0,0 +1,31 @@ +export * from './ActorTokenApi'; +export * from './AccountlessApplicationsAPI'; +export * from './AbstractApi'; +export * from './AllowlistIdentifierApi'; +export * from './APIKeysApi'; +export * from './BetaFeaturesApi'; +export * from './BlocklistIdentifierApi'; +export * from './ClientApi'; +export * from './DomainApi'; +export * from './EmailAddressApi'; +export * from './IdPOAuthAccessTokenApi'; +export * from './InstanceApi'; +export * from './InvitationApi'; +export * from './MachineApi'; +export * from './M2MTokenApi'; +export * from './JwksApi'; +export * from './JwtTemplatesApi'; +export * from './OrganizationApi'; +export * from './OAuthApplicationsApi'; +export * from './PhoneNumberApi'; +export * from './ProxyCheckApi'; +export * from './RedirectUrlApi'; +export * from './SamlConnectionApi'; +export * from './SessionApi'; +export * from './SignInTokenApi'; +export * from './SignUpApi'; +export * from './TestingTokenApi'; +export * from './UserApi'; +export * from './WaitlistEntryApi'; +export * from './WebhookApi'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/index.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/endpoints/index.d.ts.map new file mode 100644 index 000000000..985c4aab1 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/api/endpoints/index.ts"],"names":[],"mappings":"AAAA,cAAc,iBAAiB,CAAC;AAChC,cAAc,8BAA8B,CAAC;AAC7C,cAAc,eAAe,CAAC;AAC9B,cAAc,0BAA0B,CAAC;AACzC,cAAc,cAAc,CAAC;AAC7B,cAAc,mBAAmB,CAAC;AAClC,cAAc,0BAA0B,CAAC;AACzC,cAAc,aAAa,CAAC;AAC5B,cAAc,aAAa,CAAC;AAC5B,cAAc,mBAAmB,CAAC;AAClC,cAAc,0BAA0B,CAAC;AACzC,cAAc,eAAe,CAAC;AAC9B,cAAc,iBAAiB,CAAC;AAChC,cAAc,cAAc,CAAC;AAC7B,cAAc,eAAe,CAAC;AAC9B,cAAc,WAAW,CAAC;AAC1B,cAAc,mBAAmB,CAAC;AAClC,cAAc,mBAAmB,CAAC;AAClC,cAAc,wBAAwB,CAAC;AACvC,cAAc,kBAAkB,CAAC;AACjC,cAAc,iBAAiB,CAAC;AAChC,cAAc,kBAAkB,CAAC;AACjC,cAAc,qBAAqB,CAAC;AACpC,cAAc,cAAc,CAAC;AAC7B,cAAc,kBAAkB,CAAC;AACjC,cAAc,aAAa,CAAC;AAC5B,cAAc,mBAAmB,CAAC;AAClC,cAAc,WAAW,CAAC;AAC1B,cAAc,oBAAoB,CAAC;AACnC,cAAc,cAAc,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/util-types.d.ts b/backend/node_modules/@clerk/backend/dist/api/endpoints/util-types.d.ts new file mode 100644 index 000000000..e1826a005 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/util-types.d.ts @@ -0,0 +1,2 @@ +export type WithSign = `+${T}` | `-${T}` | T; +//# sourceMappingURL=util-types.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/endpoints/util-types.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/endpoints/util-types.d.ts.map new file mode 100644 index 000000000..82ad2ffe1 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/endpoints/util-types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"util-types.d.ts","sourceRoot":"","sources":["../../../src/api/endpoints/util-types.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,QAAQ,CAAC,CAAC,SAAS,MAAM,IAAI,IAAI,CAAC,EAAE,GAAG,IAAI,CAAC,EAAE,GAAG,CAAC,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/factory.d.ts b/backend/node_modules/@clerk/backend/dist/api/factory.d.ts new file mode 100644 index 000000000..915862409 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/factory.d.ts @@ -0,0 +1,41 @@ +import { AccountlessApplicationAPI, ActorTokenAPI, AllowlistIdentifierAPI, APIKeysAPI, BetaFeaturesAPI, BlocklistIdentifierAPI, ClientAPI, DomainAPI, EmailAddressAPI, IdPOAuthAccessTokenApi, InstanceAPI, InvitationAPI, JwksAPI, JwtTemplatesApi, M2MTokenApi, MachineApi, OAuthApplicationsApi, OrganizationAPI, PhoneNumberAPI, ProxyCheckAPI, RedirectUrlAPI, SamlConnectionAPI, SessionAPI, SignInTokenAPI, SignUpAPI, TestingTokenAPI, UserAPI, WaitlistEntryAPI, WebhookAPI } from './endpoints'; +import { BillingAPI } from './endpoints/BillingApi'; +import { buildRequest } from './request'; +export type CreateBackendApiOptions = Parameters[0]; +export type ApiClient = ReturnType; +export declare function createBackendApiClient(options: CreateBackendApiOptions): { + __experimental_accountlessApplications: AccountlessApplicationAPI; + actorTokens: ActorTokenAPI; + allowlistIdentifiers: AllowlistIdentifierAPI; + apiKeys: APIKeysAPI; + betaFeatures: BetaFeaturesAPI; + blocklistIdentifiers: BlocklistIdentifierAPI; + /** + * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. + */ + billing: BillingAPI; + clients: ClientAPI; + domains: DomainAPI; + emailAddresses: EmailAddressAPI; + idPOAuthAccessToken: IdPOAuthAccessTokenApi; + instance: InstanceAPI; + invitations: InvitationAPI; + jwks: JwksAPI; + jwtTemplates: JwtTemplatesApi; + machines: MachineApi; + m2m: M2MTokenApi; + oauthApplications: OAuthApplicationsApi; + organizations: OrganizationAPI; + phoneNumbers: PhoneNumberAPI; + proxyChecks: ProxyCheckAPI; + redirectUrls: RedirectUrlAPI; + samlConnections: SamlConnectionAPI; + sessions: SessionAPI; + signInTokens: SignInTokenAPI; + signUps: SignUpAPI; + testingTokens: TestingTokenAPI; + users: UserAPI; + waitlistEntries: WaitlistEntryAPI; + webhooks: WebhookAPI; +}; +//# sourceMappingURL=factory.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/factory.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/factory.d.ts.map new file mode 100644 index 000000000..c4cfe00f3 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/factory.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"factory.d.ts","sourceRoot":"","sources":["../../src/api/factory.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,yBAAyB,EACzB,aAAa,EACb,sBAAsB,EACtB,UAAU,EACV,eAAe,EACf,sBAAsB,EACtB,SAAS,EACT,SAAS,EACT,eAAe,EACf,sBAAsB,EACtB,WAAW,EACX,aAAa,EACb,OAAO,EACP,eAAe,EACf,WAAW,EACX,UAAU,EACV,oBAAoB,EACpB,eAAe,EACf,cAAc,EACd,aAAa,EACb,cAAc,EACd,iBAAiB,EACjB,UAAU,EACV,cAAc,EACd,SAAS,EACT,eAAe,EACf,OAAO,EACP,gBAAgB,EAChB,UAAU,EACX,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AACpD,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAEzC,MAAM,MAAM,uBAAuB,GAAG,UAAU,CAAC,OAAO,YAAY,CAAC,CAAC,CAAC,CAAC,CAAC;AAEzE,MAAM,MAAM,SAAS,GAAG,UAAU,CAAC,OAAO,sBAAsB,CAAC,CAAC;AAElE,wBAAgB,sBAAsB,CAAC,OAAO,EAAE,uBAAuB;;;;;;;IAiBnE;;OAEG;;;;;;;;;;;;;;;;;;;;;;;;;EAsCN"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/index.d.ts b/backend/node_modules/@clerk/backend/dist/api/index.d.ts new file mode 100644 index 000000000..8abb1250d --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/index.d.ts @@ -0,0 +1,3 @@ +export * from './factory'; +export * from './resources'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/index.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/index.d.ts.map new file mode 100644 index 000000000..c950cae66 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/api/index.ts"],"names":[],"mappings":"AAAA,cAAc,WAAW,CAAC;AAC1B,cAAc,aAAa,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/request.d.ts b/backend/node_modules/@clerk/backend/dist/api/request.d.ts new file mode 100644 index 000000000..ae0bd67fd --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/request.d.ts @@ -0,0 +1,76 @@ +import type { ClerkAPIError } from '@clerk/types'; +type ClerkBackendApiRequestOptionsUrlOrPath = { + url: string; + path?: string; +} | { + url?: string; + path: string; +}; +type ClerkBackendApiRequestOptionsBodyParams = { + bodyParams: Record | Array>; + options?: { + /** + * If true, snakecases the keys of the bodyParams object recursively. + * @default false + */ + deepSnakecaseBodyParamKeys?: boolean; + }; +} | { + bodyParams?: never; + options?: { + deepSnakecaseBodyParamKeys?: never; + }; +}; +export type ClerkBackendApiRequestOptions = { + method: 'GET' | 'POST' | 'PATCH' | 'DELETE' | 'PUT'; + queryParams?: Record; + headerParams?: Record; + formData?: FormData; +} & ClerkBackendApiRequestOptionsUrlOrPath & ClerkBackendApiRequestOptionsBodyParams; +export type ClerkBackendApiResponse = { + data: T; + errors: null; + totalCount?: number; +} | { + data: null; + errors: ClerkAPIError[]; + totalCount?: never; + clerkTraceId?: string; + status?: number; + statusText?: string; + retryAfter?: number; +}; +export type RequestFunction = ReturnType; +type BuildRequestOptions = { + secretKey?: string; + apiUrl?: string; + apiVersion?: string; + userAgent?: string; + /** + * Allow requests without specifying a secret key. In most cases this should be set to `false`. + * @default true + */ + requireSecretKey?: boolean; + /** + * If true, omits the API version from the request URL path. + * This is required for bapi-proxy endpoints, which do not use versioning in the URL. + * + * Note: API versioning for these endpoints is instead handled via the `Clerk-API-Version` HTTP header. + * + * @default false + */ + skipApiVersionInUrl?: boolean; + machineSecretKey?: string; + /** + * If true, uses machineSecretKey for authorization instead of secretKey. + * + * Note: This is only used for machine-to-machine tokens. + * + * @default false + */ + useMachineSecretKey?: boolean; +}; +export declare function buildRequest(options: BuildRequestOptions): LegacyRequestFunction; +type LegacyRequestFunction = (requestOptions: ClerkBackendApiRequestOptions) => Promise; +export {}; +//# sourceMappingURL=request.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/request.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/request.d.ts.map new file mode 100644 index 000000000..e9ae48a4a --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/request.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"request.d.ts","sourceRoot":"","sources":["../../src/api/request.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAqB,MAAM,cAAc,CAAC;AASrE,KAAK,sCAAsC,GACvC;IACE,GAAG,EAAE,MAAM,CAAC;IACZ,IAAI,CAAC,EAAE,MAAM,CAAC;CACf,GACD;IACE,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;CACd,CAAC;AAEN,KAAK,uCAAuC,GACxC;IACE,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,KAAK,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;IACrE,OAAO,CAAC,EAAE;QACR;;;WAGG;QACH,0BAA0B,CAAC,EAAE,OAAO,CAAC;KACtC,CAAC;CACH,GACD;IACE,UAAU,CAAC,EAAE,KAAK,CAAC;IACnB,OAAO,CAAC,EAA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AO,CAAC;CAC/B,CAAC;AAEF,wBAAgB,YAAY,CAAC,OAAO,EAAE,mBAAmB,yBAqIxD;AAmCD,KAAK,qBAAqB,GAAG,CAAC,CAAC,EAAE,cAAc,EAAE,6BAA6B,KAAK,OAAO,CAAC,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/APIKey.d.ts b/backend/node_modules/@clerk/backend/dist/api/resources/APIKey.d.ts new file mode 100644 index 000000000..65bd24450 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/APIKey.d.ts @@ -0,0 +1,22 @@ +import type { APIKeyJSON } from './JSON'; +export declare class APIKey { + readonly id: string; + readonly type: string; + readonly name: string; + readonly subject: string; + readonly scopes: string[]; + readonly claims: Record | null; + readonly revoked: boolean; + readonly revocationReason: string | null; + readonly expired: boolean; + readonly expiration: number | null; + readonly createdBy: string | null; + readonly description: string | null; + readonly lastUsedAt: number | null; + readonly createdAt: number; + readonly updatedAt: number; + readonly secret?: string | undefined; + constructor(id: string, type: string, name: string, subject: string, scopes: string[], claims: Record | null, revoked: boolean, revocationReason: string | null, expired: boolean, expiration: number | null, createdBy: string | null, description: string | null, lastUsedAt: number | null, createdAt: number, updatedAt: number, secret?: string | undefined); + static fromJSON(data: APIKeyJSON): APIKey; +} +//# sourceMappingURL=APIKey.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/APIKey.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/resources/APIKey.d.ts.map new file mode 100644 index 000000000..fbc1a6f7d --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/APIKey.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"APIKey.d.ts","sourceRoot":"","sources":["../../../src/api/resources/APIKey.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAC;AAEzC,qBAAa,MAAM;IAEf,QAAQ,CAAC,EAAE,EAAE,M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AAE,UAAU;CAoBjC"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/AccountlessApplication.d.ts b/backend/node_modules/@clerk/backend/dist/api/resources/AccountlessApplication.d.ts new file mode 100644 index 000000000..af0b7c2bd --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/AccountlessApplication.d.ts @@ -0,0 +1,10 @@ +import type { AccountlessApplicationJSON } from './JSON'; +export declare class AccountlessApplication { + readonly publishableKey: string; + readonly secretKey: string; + readonly claimUrl: string; + readonly apiKeysUrl: string; + constructor(publishableKey: string, secretKey: string, claimUrl: string, apiKeysUrl: string); + static fromJSON(data: AccountlessApplicationJSON): AccountlessApplication; +} +//# sourceMappingURL=AccountlessApplication.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/AccountlessApplication.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/resources/AccountlessApplication.d.ts.map new file mode 100644 index 000000000..2bad649b1 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/AccountlessApplication.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"AccountlessApplication.d.ts","sourceRoot":"","sources":["../../../src/api/resources/AccountlessApplication.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,QAAQ,CAAC;AAEzD,qBAAa,sBAAsB;IAE/B,QAAQ,CAAC,cAAc,EAAE,MAAM;IAC/B,QAAQ,CAAC,SAAS,EAAE,MAAM;IAC1B,QAAQ,CAAC,QAAQ,EAAE,MAAM;IACzB,QAAQ,CAAC,UAAU,EAAE,MAAM;gBAHlB,cAAc,EAAE,MAAM,EACtB,SAAS,EAAE,MAAM,EACjB,QAAQ,EAAE,MAAM,EAChB,UAAU,EAAE,MAAM;IAG7B,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,0BAA0B,GAAG,sBAAsB;CAG1E"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/ActorToken.d.ts b/backend/node_modules/@clerk/backend/dist/api/resources/ActorToken.d.ts new file mode 100644 index 000000000..3106af5c6 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/ActorToken.d.ts @@ -0,0 +1,15 @@ +import type { ActorTokenStatus } from './Enums'; +import type { ActorTokenJSON } from './JSON'; +export declare class ActorToken { + readonly id: string; + readonly status: ActorTokenStatus; + readonly userId: string; + readonly actor: Record | null; + readonly token: string | null | undefined; + readonly url: string | null | undefined; + readonly createdAt: number; + readonly updatedAt: number; + constructor(id: string, status: ActorTokenStatus, userId: string, actor: Record | null, token: string | null | undefined, url: string | null | undefined, createdAt: number, updatedAt: number); + static fromJSON(data: ActorTokenJSON): ActorToken; +} +//# sourceMappingURL=ActorToken.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/ActorToken.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/resources/ActorToken.d.ts.map new file mode 100644 index 000000000..16fa70364 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/ActorToken.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ActorToken.d.ts","sourceRoot":"","sources":["../../../src/api/resources/ActorToken.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC;AAChD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,QAAQ,CAAC;AAE7C,qBAAa,UAAU;IAEnB,QAAQ,CAAC,EAAE,EAAE,MAAM;IACnB,QAAQ,CAAC,MAAM,EAAE,gBAAgB;IACjC,QAAQ,CAAC,MAAM,EAAE,MAAM;IACvB,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI;IAC9C,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS;IACzC,QAAQ,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS;IACvC,QAAQ,CAAC,SAAS,EAAE,MAAM;IAC1B,QAAQ,CAAC,SAAS,EAAE,MAAM;gBAPjB,EAAE,EAAE,MAAM,EACV,MAAM,EAAE,gBAAgB,EACxB,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,EACrC,KAAK,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,EAChC,GAAG,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,EAC9B,SAAS,EAAE,MAAM,EACjB,SAAS,EAAE,MAAM;IAG5B,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,cAAc,GAAG,UAAU;CAYlD"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/AllowlistIdentifier.d.ts b/backend/node_modules/@clerk/backend/dist/api/resources/AllowlistIdentifier.d.ts new file mode 100644 index 000000000..4c80710f6 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/AllowlistIdentifier.d.ts @@ -0,0 +1,66 @@ +import type { AllowlistIdentifierType } from './Enums'; +import type { AllowlistIdentifierJSON } from './JSON'; +/** + * The Backend `AllowlistIdentifier` object represents an identifier that has been added to the allowlist of your application. The Backend `AllowlistIdentifier` object is used in the [Backend API](https://clerk.com/docs/reference/backend-api/tag/Allow-list-Block-list#operation/ListAllowlistIdentifiers) and is not directly accessible from the Frontend API. + */ +export declare class AllowlistIdentifier { + /** + * A unique ID for the allowlist identifier. + */ + readonly id: string; + /** + * The [identifier](https://clerk.com/docs/authentication/configuration/sign-up-sign-in-options#identifiers) that was added to the allowlist. + */ + readonly identifier: string; + /** + * The type of the allowlist identifier. + */ + readonly identifierType: AllowlistIdentifierType; + /** + * The date when the allowlist identifier was first created. + */ + readonly createdAt: number; + /** + * The date when the allowlist identifier was last updated. + */ + readonly updatedAt: number; + /** + * The ID of the instance that this allowlist identifier belongs to. + */ + readonly instanceId?: string | undefined; + /** + * The ID of the invitation sent to the identifier. + */ + readonly invitationId?: string | undefined; + constructor( + /** + * A unique ID for the allowlist identifier. + */ + id: string, + /** + * The [identifier](https://clerk.com/docs/authentication/configuration/sign-up-sign-in-options#identifiers) that was added to the allowlist. + */ + identifier: string, + /** + * The type of the allowlist identifier. + */ + identifierType: AllowlistIdentifierType, + /** + * The date when the allowlist identifier was first created. + */ + createdAt: number, + /** + * The date when the allowlist identifier was last updated. + */ + updatedAt: number, + /** + * The ID of the instance that this allowlist identifier belongs to. + */ + instanceId?: string | undefined, + /** + * The ID of the invitation sent to the identifier. + */ + invitationId?: string | undefined); + static fromJSON(data: AllowlistIdentifierJSON): AllowlistIdentifier; +} +//# sourceMappingURL=AllowlistIdentifier.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/AllowlistIdentifier.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/resources/AllowlistIdentifier.d.ts.map new file mode 100644 index 000000000..b0046cbba --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/AllowlistIdentifier.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"AllowlistIdentifier.d.ts","sourceRoot":"","sources":["../../../src/api/resources/AllowlistIdentifier.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,SAAS,CAAC;AACvD,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,QAAQ,CAAC;AAEtD;;GAEG;AACH,qBAAa,mBAAmB;IAE5B;;OAEG;IACH,QAAQ,CAAC,EAAE,EAAE,MAAM;IACnB;;OAEG;IACH,QAAQ,CAAC,UAAU,EAAE,MAAM;IAC3B;;OAEG;IACH,QAAQ,CAAC,cAAc,EAAE,uBAAuB;IAChD;;OAEG;IACH,QAAQ,CAAC,SAAS,EAAE,MAAM;IAC1B;;OAEG;IACH,QAAQ,CAAC,SAAS,EAAE,MAAM;IAC1B;;OAEG;IACH,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM;IAC5B;;OAEG;IACH,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM;;IA3B9B;;OAEG;IACM,EAAE,EAAE,MAAM;IACnB;;OAEG;IACM,UAAU,EAAE,MAAM;IAC3B;;OAEG;IACM,cAAc,EAAE,uBAAuB;IAChD;;OAEG;IACM,SAAS,EAAE,MAAM;IAC1B;;OAEG;IACM,SAAS,EAAE,MAAM;IAC1B;;OAEG;IACM,UAAU,CAAC,EAAE,MAAM,YAAA;IAC5B;;OAEG;IACM,YAAY,CAAC,EAAE,MAAM,YAAA;IAGhC,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,uBAAuB,GAAG,mBAAmB;CAWpE"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/BlocklistIdentifier.d.ts b/backend/node_modules/@clerk/backend/dist/api/resources/BlocklistIdentifier.d.ts new file mode 100644 index 000000000..5fb56a312 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/BlocklistIdentifier.d.ts @@ -0,0 +1,13 @@ +import type { BlocklistIdentifierType } from './Enums'; +import type { BlocklistIdentifierJSON } from './JSON'; +export declare class BlocklistIdentifier { + readonly id: string; + readonly identifier: string; + readonly identifierType: BlocklistIdentifierType; + readonly createdAt: number; + readonly updatedAt: number; + readonly instanceId?: string | undefined; + constructor(id: string, identifier: string, identifierType: BlocklistIdentifierType, createdAt: number, updatedAt: number, instanceId?: string | undefined); + static fromJSON(data: BlocklistIdentifierJSON): BlocklistIdentifier; +} +//# sourceMappingURL=BlocklistIdentifier.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/BlocklistIdentifier.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/resources/BlocklistIdentifier.d.ts.map new file mode 100644 index 000000000..d8834083d --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/BlocklistIdentifier.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"BlocklistIdentifier.d.ts","sourceRoot":"","sources":["../../../src/api/resources/BlocklistIdentifier.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,SAAS,CAAC;AACvD,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,QAAQ,CAAC;AAEtD,qBAAa,mBAAmB;IAE5B,QAAQ,CAAC,EAAE,EAAE,MAAM;IACnB,QAAQ,CAAC,UAAU,EAAE,MAAM;IAC3B,QAAQ,CAAC,cAAc,EAAE,uBAAuB;IAChD,QAAQ,CAAC,SAAS,EAAE,MAAM;IAC1B,QAAQ,CAAC,SAAS,EAAE,MAAM;IAC1B,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM;gBALnB,EAAE,EAAE,MAAM,EACV,UAAU,EAAE,MAAM,EAClB,cAAc,EAAE,uBAAuB,EACvC,SAAS,EAAE,MAAM,EACjB,SAAS,EAAE,MAAM,EACjB,UAAU,CAAC,EAAE,MAAM,YAAA;IAG9B,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,uBAAuB,GAAG,mBAAmB;CAUpE"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/Client.d.ts b/backend/node_modules/@clerk/backend/dist/api/resources/Client.d.ts new file mode 100644 index 000000000..0c67ef993 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/Client.d.ts @@ -0,0 +1,83 @@ +import type { LastAuthenticationStrategy } from '@clerk/types'; +import type { ClientJSON } from './JSON'; +import { Session } from './Session'; +/** + * The Backend `Client` object is similar to the [`Client`](https://clerk.com/docs/references/javascript/client) object as it holds information about the authenticated sessions in the current device. However, the Backend `Client` object is different from the `Client` object in that it is used in the [Backend API](https://clerk.com/docs/reference/backend-api/tag/Clients#operation/GetClient) and is not directly accessible from the Frontend API. + */ +export declare class Client { + /** + * The unique identifier for the `Client`. + */ + readonly id: string; + /** + * An array of [Session](https://clerk.com/docs/references/backend/types/backend-session){{ target: '_blank' }} IDs associated with the `Client`. + */ + readonly sessionIds: string[]; + /** + * An array of [Session](https://clerk.com/docs/references/backend/types/backend-session){{ target: '_blank' }} objects associated with the `Client`. + */ + readonly sessions: Session[]; + /** + * The ID of the [`SignIn`](https://clerk.com/docs/references/javascript/sign-in){{ target: '_blank' }}. + */ + readonly signInId: string | null; + /** + * The ID of the [`SignUp`](https://clerk.com/docs/references/javascript/sign-up){{ target: '_blank' }}. + */ + readonly signUpId: string | null; + /** + * The ID of the last active [Session](https://clerk.com/docs/references/backend/types/backend-session). + */ + readonly lastActiveSessionId: string | null; + /** + * The last authentication strategy used by the `Client`. + */ + readonly lastAuthenticationStrategy: LastAuthenticationStrategy | null; + /** + * The date when the `Client` was first created. + */ + readonly createdAt: number; + /** + * The date when the `Client` was last updated. + */ + readonly updatedAt: number; + constructor( + /** + * The unique identifier for the `Client`. + */ + id: string, + /** + * An array of [Session](https://clerk.com/docs/references/backend/types/backend-session){{ target: '_blank' }} IDs associated with the `Client`. + */ + sessionIds: string[], + /** + * An array of [Session](https://clerk.com/docs/references/backend/types/backend-session){{ target: '_blank' }} objects associated with the `Client`. + */ + sessions: Session[], + /** + * The ID of the [`SignIn`](https://clerk.com/docs/references/javascript/sign-in){{ target: '_blank' }}. + */ + signInId: string | null, + /** + * The ID of the [`SignUp`](https://clerk.com/docs/references/javascript/sign-up){{ target: '_blank' }}. + */ + signUpId: string | null, + /** + * The ID of the last active [Session](https://clerk.com/docs/references/backend/types/backend-session). + */ + lastActiveSessionId: string | null, + /** + * The last authentication strategy used by the `Client`. + */ + lastAuthenticationStrategy: LastAuthenticationStrategy | null, + /** + * The date when the `Client` was first created. + */ + createdAt: number, + /** + * The date when the `Client` was last updated. + */ + updatedAt: number); + static fromJSON(data: ClientJSON): Client; +} +//# sourceMappingURL=Client.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/Client.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/resources/Client.d.ts.map new file mode 100644 index 000000000..f68b9484b --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/Client.d.ts.map @@ -0,0 +1 @@ +{"version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AU,GAAG,MAAM;CAa1C"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/CnameTarget.d.ts b/backend/node_modules/@clerk/backend/dist/api/resources/CnameTarget.d.ts new file mode 100644 index 000000000..80c07cd7f --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/CnameTarget.d.ts @@ -0,0 +1,9 @@ +import type { CnameTargetJSON } from './JSON'; +export declare class CnameTarget { + readonly host: string; + readonly value: string; + readonly required: boolean; + constructor(host: string, value: string, required: boolean); + static fromJSON(data: CnameTargetJSON): CnameTarget; +} +//# sourceMappingURL=CnameTarget.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/CnameTarget.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/resources/CnameTarget.d.ts.map new file mode 100644 index 000000000..d2f1c7dad --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/CnameTarget.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"CnameTarget.d.ts","sourceRoot":"","sources":["../../../src/api/resources/CnameTarget.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,QAAQ,CAAC;AAE9C,qBAAa,WAAW;IAEpB,QAAQ,CAAC,IAAI,EAAE,MAAM;IACrB,QAAQ,CAAC,KAAK,EAAE,MAAM;IACtB,QAAQ,CAAC,QAAQ,EAAE,OAAO;gBAFjB,IAAI,EAAE,MAAM,EACZ,KAAK,EAAE,MAAM,EACb,QAAQ,EAAE,OAAO;IAG5B,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,eAAe,GAAG,WAAW;CAGpD"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/CommercePlan.d.ts b/backend/node_modules/@clerk/backend/dist/api/resources/CommercePlan.d.ts new file mode 100644 index 000000000..83146fc38 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/CommercePlan.d.ts @@ -0,0 +1,125 @@ +import type { BillingMoneyAmount } from '@clerk/types'; +import { Feature } from './Feature'; +import type { BillingPlanJSON } from './JSON'; +/** + * The `BillingPlan` object is similar to the [`BillingPlanResource`](/docs/references/javascript/types/billing-plan-resource) object as it holds information about a plan, as well as methods for managing it. However, the `BillingPlan` object is different in that it is used in the [Backend API](https://clerk.com/docs/reference/backend-api/tag/commerce/get/commerce/plans) and is not directly accessible from the Frontend API. + * + * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. + */ +export declare class BillingPlan { + /** + * The unique identifier for the plan. + */ + readonly id: string; + /** + * The ID of the product the plan belongs to. + */ + readonly productId: string; + /** + * The name of the plan. + */ + readonly name: string; + /** + * The URL-friendly identifier of the plan. + */ + readonly slug: string; + /** + * The description of the plan. + */ + readonly description: string | undefined; + /** + * Whether the plan is the default plan. + */ + readonly isDefault: boolean; + /** + * Whether the plan is recurring. + */ + readonly isRecurring: boolean; + /** + * Whether the plan has a base fee. + */ + readonly hasBaseFee: boolean; + /** + * Whether the plan is displayed in the `` component. + */ + readonly publiclyVisible: boolean; + /** + * The monthly fee of the plan. + */ + readonly fee: BillingMoneyAmount; + /** + * The annual fee of the plan. + */ + readonly annualFee: BillingMoneyAmount; + /** + * The annual fee of the plan on a monthly basis. + */ + readonly annualMonthlyFee: BillingMoneyAmount; + /** + * The type of payer for the plan. + */ + readonly forPayerType: 'org' | 'user'; + /** + * The features the plan offers. + */ + readonly features: Feature[]; + constructor( + /** + * The unique identifier for the plan. + */ + id: string, + /** + * The ID of the product the plan belongs to. + */ + productId: string, + /** + * The name of the plan. + */ + name: string, + /** + * The URL-friendly identifier of the plan. + */ + slug: string, + /** + * The description of the plan. + */ + description: string | undefined, + /** + * Whether the plan is the default plan. + */ + isDefault: boolean, + /** + * Whether the plan is recurring. + */ + isRecurring: boolean, + /** + * Whether the plan has a base fee. + */ + hasBaseFee: boolean, + /** + * Whether the plan is displayed in the `` component. + */ + publiclyVisible: boolean, + /** + * The monthly fee of the plan. + */ + fee: BillingMoneyAmount, + /** + * The annual fee of the plan. + */ + annualFee: BillingMoneyAmount, + /** + * The annual fee of the plan on a monthly basis. + */ + annualMonthlyFee: BillingMoneyAmount, + /** + * The type of payer for the plan. + */ + forPayerType: 'org' | 'user', + /** + * The features the plan offers. + */ + features: Feature[]); + static fromJSON(data: BillingPlanJSON): BillingPlan; +} +//# sourceMappingURL=CommercePlan.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/CommercePlan.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/resources/CommercePlan.d.ts.map new file mode 100644 index 000000000..a03e548ff --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/CommercePlan.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"CommercePlan.d.ts","sourceRoot":"","sources":["../../../src/api/resources/CommercePlan.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAEvD,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,QAAQ,CAAC;AAE9C;;;;GAIG;AACH,qBAAa,WAAW;IAEpB;;OAEG;IACH,QAAQ,CAAC,EAAE,EAAE,MAAM;IACnB;;OAEG;IACH,QAAQ,CAAC,SAAS,EAAE,MAAM;IAC1B;;OAEG;IACH,QAAQ,CAAC,IAAI,EAAE,MAAM;IACrB;;OAEG;IACH,QAAQ,CAAC,IAAI,EAAE,MAAM;IACrB;;OAEG;IACH,QAAQ,CAAC,WAAW,EAAE,MAAM,GAAG,SAAS;IACxC;;OAEG;IACH,QAAQ,CAAC,SAAS,EAAE,OAAO;IAC3B;;OAEG;IACH,QAAQ,CAAC,WAAW,EAAE,OAAO;IAC7B;;OAEG;IACH,QAAQ,CAAC,UAAU,EAAE,OAAO;IAC5B;;OAEG;IACH,QAAQ,CAAC,eAAe,EAAE,OAAO;IACjC;;OAEG;IACH,QAAQ,CAAC,GAAG,EAAE,kBAAkB;IAChC;;OAEG;IACH,QAAQ,CAAC,SAAS,EAAE,kBAAkB;IACtC;;OAEG;IACH,QAAQ,CAAC,gBAAgB,EAAE,kBAAkB;IAC7C;;OAEG;IACH,QAAQ,CAAC,YAAY,EAAE,KAAK,GAAG,MAAM;IACrC;;OAEG;IACH,QAAQ,CAAC,QAAQ,EAAE,OAAO,EAAE;;IAvD5B;;OAEG;IACM,EAAE,EAAE,MAAM;IACnB;;OAEG;IACM,SAAS,EAAE,MAAM;IAC1B;;OAEG;IACM,IAAI,EAAE,MAAM;IACrB;;OAEG;IACM,IAAI,EAAE,MAAM;IACrB;;OAEG;IACM,WAAW,EAAE,MAAM,GAAG,SAAS;IACxC;;OAEG;IACM,SAAS,EAAE,OAAO;IAC3B;;OAEG;IACM,WAAW,EAAE,OAAO;IAC7B;;OAEG;IACM,UAAU,EAAE,OAAO;IAC5B;;OAEG;IACM,eAAe,EAAE,OAAO;IACjC;;OAEG;IACM,GAAG,EAAE,kBAAkB;IAChC;;OAEG;IACM,SAAS,EAAE,kBAAkB;IACtC;;OAEG;IACM,gBAAgB,EAAE,kBAAkB;IAC7C;;OAEG;IACM,YAAY,EAAE,KAAK,GAAG,MAAM;IACrC;;OAEG;IACM,QAAQ,EAAE,OAAO,EAAE;IAG9B,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,eAAe,GAAG,WAAW;CA0BpD"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/CommerceSubscription.d.ts b/backend/node_modules/@clerk/backend/dist/api/resources/CommerceSubscription.d.ts new file mode 100644 index 000000000..34b8c3eeb --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/CommerceSubscription.d.ts @@ -0,0 +1,99 @@ +import type { BillingMoneyAmount } from '@clerk/types'; +import { BillingSubscriptionItem } from './CommerceSubscriptionItem'; +import type { BillingSubscriptionJSON } from './JSON'; +/** + * The `BillingSubscription` object is similar to the [`BillingSubscriptionResource`](/docs/references/javascript/types/commerce-subscription-resource) object as it holds information about a subscription, as well as methods for managing it. However, the `BillingSubscription` object is different in that it is used in the [Backend API](https://clerk.com/docs/reference/backend-api/tag/billing/get/organizations/%7Borganization_id%7D/billing/subscription) and is not directly accessible from the Frontend API. + * + * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. + */ +export declare class BillingSubscription { + /** + * The unique identifier for the billing subscription. + */ + readonly id: string; + /** + * The current status of the subscription. + */ + readonly status: BillingSubscriptionJSON['status']; + /** + * The ID of the payer for this subscription. + */ + readonly payerId: string; + /** + * Unix timestamp (milliseconds) of when the subscription was created. + */ + readonly createdAt: number; + /** + * Unix timestamp (milliseconds) of when the subscription was last updated. + */ + readonly updatedAt: number; + /** + * Unix timestamp (milliseconds) of when the subscription became active. + */ + readonly activeAt: number | null; + /** + * Unix timestamp (milliseconds) of when the subscription became past due. + */ + readonly pastDueAt: number | null; + /** + * Array of subscription items in this subscription. + */ + readonly subscriptionItems: BillingSubscriptionItem[]; + /** + * Information about the next scheduled payment. + */ + readonly nextPayment: { + date: number; + amount: BillingMoneyAmount; + } | null; + /** + * Whether the payer is eligible for a free trial. + */ + readonly eligibleForFreeTrial: boolean; + constructor( + /** + * The unique identifier for the billing subscription. + */ + id: string, + /** + * The current status of the subscription. + */ + status: BillingSubscriptionJSON['status'], + /** + * The ID of the payer for this subscription. + */ + payerId: string, + /** + * Unix timestamp (milliseconds) of when the subscription was created. + */ + createdAt: number, + /** + * Unix timestamp (milliseconds) of when the subscription was last updated. + */ + updatedAt: number, + /** + * Unix timestamp (milliseconds) of when the subscription became active. + */ + activeAt: number | null, + /** + * Unix timestamp (milliseconds) of when the subscription became past due. + */ + pastDueAt: number | null, + /** + * Array of subscription items in this subscription. + */ + subscriptionItems: BillingSubscriptionItem[], + /** + * Information about the next scheduled payment. + */ + nextPayment: { + date: number; + amount: BillingMoneyAmount; + } | null, + /** + * Whether the payer is eligible for a free trial. + */ + eligibleForFreeTrial: boolean); + static fromJSON(data: BillingSubscriptionJSON): BillingSubscription; +} +//# sourceMappingURL=CommerceSubscription.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/CommerceSubscription.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/resources/CommerceSubscription.d.ts.map new file mode 100644 index 000000000..af96a5be0 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/CommerceSubscription.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"CommerceSubscription.d.ts","sourceRoot":"","sources":["../../../src/api/resources/CommerceSubscription.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAEvD,OAAO,EAAE,uBAAuB,EAAE,MAAM,4BAA4B,CAAC;AACrE,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,QAAQ,CAAC;AAEtD;;;;GAIG;AACH,qBAAa,mBAAmB;IAE5B;;OAEG;IACH,QAAQ,CAAC,EAAE,EAAE,MAAM;IACnB;;OAEG;IACH,QAAQ,CAAC,MAAM,EAAE,uBAAuB,CAAC,QAAQ,CAAC;IAClD;;OAEG;IACH,QAAQ,CAAC,OAAO,EAAE,MAAM;IACxB;;OAEG;IACH,QAAQ,CAAC,SAAS,EAAE,MAAM;IAC1B;;OAEG;IACH,QAAQ,CAAC,SAAS,EAAE,MAAM;IAC1B;;OAEG;IACH,QAAQ,CAAC,QAAQ,EAAE,MAAM,GAAG,IAAI;IAChC;;OAEG;IACH,QAAQ,CAAC,SAAS,EAAE,MAAM,GAAG,IAAI;IACjC;;OAEG;IACH,QAAQ,CAAC,iBAAiB,EAAE,uBAAuB,EAAE;IACrD;;OAEG;IACH,QAAQ,CAAC,WAAW,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,kBAAkB,CAAA;KAAE,GAAG,IAAI;IACzE;;OAEG;IACH,QAAQ,CAAC,oBAAoB,EAAE,OAAO;;IAvCtC;;OAEG;IACM,EAAE,EAAE,MAAM;IACnB;;OAEG;IACM,MAAM,EAAE,uBAAuB,CAAC,QAAQ,CAAC;IAClD;;OAEG;IACM,OAAO,EAAE,MAAM;IACxB;;OAEG;IACM,SAAS,EAAE,MAAM;IAC1B;;OAEG;IACM,SAAS,EAAE,MAAM;IAC1B;;OAEG;IACM,QAAQ,EAAE,MAAM,GAAG,IAAI;IAChC;;OAEG;IACM,SAAS,EAAE,MAAM,GAAG,IAAI;IACjC;;OAEG;IACM,iBAAiB,EAAE,uBAAuB,EAAE;IACrD;;OAEG;IACM,WAAW,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,kBAAkB,CAAA;KAAE,GAAG,IAAI;IACzE;;OAEG;IACM,oBAAoB,EAAE,OAAO;IAGxC,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,uBAAuB,GAAG,mBAAmB;CA0BpE"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/CommerceSubscriptionItem.d.ts b/backend/node_modules/@clerk/backend/dist/api/resources/CommerceSubscriptionItem.d.ts new file mode 100644 index 000000000..fb04b7efe --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/CommerceSubscriptionItem.d.ts @@ -0,0 +1,167 @@ +import type { BillingMoneyAmount } from '@clerk/types'; +import { BillingPlan } from './CommercePlan'; +import type { BillingSubscriptionItemJSON } from './JSON'; +/** + * The `BillingSubscriptionItem` object is similar to the [`BillingSubscriptionItemResource`](/docs/references/javascript/types/commerce-subscription-item-resource) object as it holds information about a subscription item, as well as methods for managing it. However, the `BillingSubscriptionItem` object is different in that it is used in the [Backend API](https://clerk.com/docs/reference/backend-api/tag/commerce/get/commerce/subscription_items) and is not directly accessible from the Frontend API. + * + * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. + */ +export declare class BillingSubscriptionItem { + /** + * The unique identifier for the subscription item. + */ + readonly id: string; + /** + * The status of the subscription item. + */ + readonly status: BillingSubscriptionItemJSON['status']; + /** + * The plan period for the subscription item. + */ + readonly planPeriod: 'month' | 'annual'; + /** + * Unix timestamp (milliseconds) of when the current period starts. + */ + readonly periodStart: number; + /** + * The next payment information. + */ + readonly nextPayment: { + /** + * The amount of the next payment. + */ + amount: number; + /** + * Unix timestamp (milliseconds) of when the next payment is scheduled. + */ + date: number; + } | null; + /** + * The current amount for the subscription item. + */ + readonly amount: BillingMoneyAmount | null | undefined; + /** + * The plan associated with this subscription item. + */ + readonly plan: BillingPlan; + /** + * The plan ID. + */ + readonly planId: string; + /** + * Unix timestamp (milliseconds) of when the subscription item was created. + */ + readonly createdAt: number; + /** + * Unix timestamp (milliseconds) of when the subscription item was last updated. + */ + readonly updatedAt: number; + /** + * Unix timestamp (milliseconds) of when the current period ends. + */ + readonly periodEnd: number | null; + /** + * Unix timestamp (milliseconds) of when the subscription item was canceled. + */ + readonly canceledAt: number | null; + /** + * Unix timestamp (milliseconds) of when the subscription item became past due. + */ + readonly pastDueAt: number | null; + /** + * Unix timestamp (milliseconds) of when the subscription item ended. + */ + readonly endedAt: number | null; + /** + * The payer ID. + */ + readonly payerId: string; + /** + * Whether this subscription item is currently in a free trial period. + */ + readonly isFreeTrial?: boolean | undefined; + /** + * The lifetime amount paid for this subscription item. + */ + readonly lifetimePaid?: (BillingMoneyAmount | null) | undefined; + constructor( + /** + * The unique identifier for the subscription item. + */ + id: string, + /** + * The status of the subscription item. + */ + status: BillingSubscriptionItemJSON['status'], + /** + * The plan period for the subscription item. + */ + planPeriod: 'month' | 'annual', + /** + * Unix timestamp (milliseconds) of when the current period starts. + */ + periodStart: number, + /** + * The next payment information. + */ + nextPayment: { + /** + * The amount of the next payment. + */ + amount: number; + /** + * Unix timestamp (milliseconds) of when the next payment is scheduled. + */ + date: number; + } | null, + /** + * The current amount for the subscription item. + */ + amount: BillingMoneyAmount | null | undefined, + /** + * The plan associated with this subscription item. + */ + plan: BillingPlan, + /** + * The plan ID. + */ + planId: string, + /** + * Unix timestamp (milliseconds) of when the subscription item was created. + */ + createdAt: number, + /** + * Unix timestamp (milliseconds) of when the subscription item was last updated. + */ + updatedAt: number, + /** + * Unix timestamp (milliseconds) of when the current period ends. + */ + periodEnd: number | null, + /** + * Unix timestamp (milliseconds) of when the subscription item was canceled. + */ + canceledAt: number | null, + /** + * Unix timestamp (milliseconds) of when the subscription item became past due. + */ + pastDueAt: number | null, + /** + * Unix timestamp (milliseconds) of when the subscription item ended. + */ + endedAt: number | null, + /** + * The payer ID. + */ + payerId: string, + /** + * Whether this subscription item is currently in a free trial period. + */ + isFreeTrial?: boolean | undefined, + /** + * The lifetime amount paid for this subscription item. + */ + lifetimePaid?: (BillingMoneyAmount | null) | undefined); + static fromJSON(data: BillingSubscriptionItemJSON): BillingSubscriptionItem; +} +//# sourceMappingURL=CommerceSubscriptionItem.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/CommerceSubscriptionItem.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/resources/CommerceSubscriptionItem.d.ts.map new file mode 100644 index 000000000..f276728c6 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/CommerceSubscriptionItem.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"CommerceSubscriptionItem.d.ts","sourceRoot":"","sources":["../../../src/api/resources/CommerceSubscriptionItem.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAA0B,MAAM,cAAc,CAAC;AAE/E,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC7C,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,QAAQ,CAAC;AAE1D;;;;GAIG;AACH,qBAAa,uBAAuB;IAEhC;;OAEG;IACH,QAAQ,CAAC,EAAE,EAAE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M,WAAW,EAAE;QACpB;;WAEG;QACH,MAAM,EAAE,MAAM,CAAC;QACf;;WAEG;QACH,IAAI,EAAE,MAAM,CAAC;KACd,GAAG,IAAI;IACR;;OAEG;IACM,MAAM,EAAE,kBAAkB,GAAG,IAAI,GAAG,SAAS;IACtD;;OAEG;IACM,IAAI,EAAE,WAAW;IAC1B;;OAEG;IACM,MAAM,EAAE,MAAM;IACvB;;OAEG;IACM,SAAS,EAAE,MAAM;IAC1B;;OAEG;IACM,SAAS,EAAE,MAAM;IAC1B;;OAEG;IACM,SAAS,EAAE,MAAM,GAAG,IAAI;IACjC;;OAEG;IACM,UAAU,EAAE,MAAM,GAAG,IAAI;IAClC;;OAEG;IACM,SAAS,EAAE,MAAM,GAAG,IAAI;IACjC;;OAEG;IACM,OAAO,EAAE,MAAM,GAAG,IAAI;IAC/B;;OAEG;IACM,OAAO,EAAE,MAAM;IACxB;;OAEG;IACM,WAAW,CAAC,EAAE,OAAO,YAAA;IAC9B;;OAEG;IACM,YAAY,CAAC,GAAE,kBAAkB,GAAG,IAAI,aAAA;IAGnD,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,2BAA2B,GAAG,uBAAuB;CAoC5E"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/Cookies.d.ts b/backend/node_modules/@clerk/backend/dist/api/resources/Cookies.d.ts new file mode 100644 index 000000000..6683b946c --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/Cookies.d.ts @@ -0,0 +1,7 @@ +import type { CookiesJSON } from './JSON'; +export declare class Cookies { + readonly cookies: string[]; + constructor(cookies: string[]); + static fromJSON(data: CookiesJSON): Cookies; +} +//# sourceMappingURL=Cookies.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/Cookies.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/resources/Cookies.d.ts.map new file mode 100644 index 000000000..c70c831a5 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/Cookies.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"Cookies.d.ts","sourceRoot":"","sources":["../../../src/api/resources/Cookies.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,QAAQ,CAAC;AAE1C,qBAAa,OAAO;IACN,QAAQ,CAAC,OAAO,EAAE,MAAM,EAAE;gBAAjB,OAAO,EAAE,MAAM,EAAE;IAEtC,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,WAAW,GAAG,OAAO;CAG5C"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/DeletedObject.d.ts b/backend/node_modules/@clerk/backend/dist/api/resources/DeletedObject.d.ts new file mode 100644 index 000000000..8aa45e6a6 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/DeletedObject.d.ts @@ -0,0 +1,10 @@ +import type { DeletedObjectJSON } from './JSON'; +export declare class DeletedObject { + readonly object: string; + readonly id: string | null; + readonly slug: string | null; + readonly deleted: boolean; + constructor(object: string, id: string | null, slug: string | null, deleted: boolean); + static fromJSON(data: DeletedObjectJSON): DeletedObject; +} +//# sourceMappingURL=DeletedObject.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/DeletedObject.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/resources/DeletedObject.d.ts.map new file mode 100644 index 000000000..90508aba0 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/DeletedObject.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"DeletedObject.d.ts","sourceRoot":"","sources":["../../../src/api/resources/DeletedObject.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,QAAQ,CAAC;AAEhD,qBAAa,aAAa;IAEtB,QAAQ,CAAC,MAAM,EAAE,MAAM;IACvB,QAAQ,CAAC,EAAE,EAAE,MAAM,GAAG,IAAI;IAC1B,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI;IAC5B,QAAQ,CAAC,OAAO,EAAE,OAAO;gBAHhB,MAAM,EAAE,MAAM,EACd,EAAE,EAAE,MAAM,GAAG,IAAI,EACjB,IAAI,EAAE,MAAM,GAAG,IAAI,EACnB,OAAO,EAAE,OAAO;IAG3B,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,iBAAiB;CAGxC"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/Deserializer.d.ts b/backend/node_modules/@clerk/backend/dist/api/resources/Deserializer.d.ts new file mode 100644 index 000000000..4824e997c --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/Deserializer.d.ts @@ -0,0 +1,26 @@ +type ResourceResponse = { + /** + * An array that contains the fetched data. + */ + data: T; +}; +/** + * An interface that describes the response of a method that returns a paginated list of resources. + * + * If the promise resolves, you will get back the [properties](#properties) listed below. `data` will be an array of the resource type you requested. You can use the `totalCount` property to determine how many total items exist remotely. + * + * Some methods that return this type allow pagination with the `limit` and `offset` parameters, in which case the first 10 items will be returned by default. For methods such as [`getAllowlistIdentifierList()`](https://clerk.com/docs/references/backend/allowlist/get-allowlist-identifier-list), which do not take a `limit` or `offset`, all items will be returned. + * + * If the promise is rejected, you will receive a `ClerkAPIResponseError` or network error. + * + * @interface + */ +export type PaginatedResourceResponse = ResourceResponse & { + /** + * The total count of data that exist remotely. + */ + totalCount: number; +}; +export declare function deserialize(payload: unknown): PaginatedResourceResponse | ResourceResponse; +export {}; +//# sourceMappingURL=Deserializer.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/Deserializer.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/resources/Deserializer.d.ts.map new file mode 100644 index 000000000..77eb97f28 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/Deserializer.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"Deserializer.d.ts","sourceRoot":"","sources":["../../../src/api/resources/Deserializer.ts"],"names":[],"mappings":"AA+CA,KAAK,gBAAgB,CAAC,CAAC,IAAI;IACzB;;OAEG;IACH,IAAI,EAAE,CAAC,CAAC;CACT,CAAC;AAEF;;;;;;;;;;GAUG;AACH,MAAM,MAAM,yBAAyB,CAAC,CAAC,IAAI,gBAAgB,CAAC,CAAC,CAAC,GAAG;IAC/D;;OAEG;IACH,UAAU,EAAE,MAAM,CAAC;CACpB,CAAC;AAEF,wBAAgB,WAAW,CAAC,CAAC,GAAG,GAAG,EAAE,OAAO,EAAE,OAAO,GAAG,yBAAyB,CAAC,CAAC,CAAC,GAAG,gBAAgB,CAAC,CAAC,CAAC,CAczG"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/Domain.d.ts b/backend/node_modules/@clerk/backend/dist/api/resources/Domain.d.ts new file mode 100644 index 000000000..b6bb3eb35 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/Domain.d.ts @@ -0,0 +1,15 @@ +import { CnameTarget } from './CnameTarget'; +import type { DomainJSON } from './JSON'; +export declare class Domain { + readonly id: string; + readonly name: string; + readonly isSatellite: boolean; + readonly frontendApiUrl: string; + readonly developmentOrigin: string; + readonly cnameTargets: CnameTarget[]; + readonly accountsPortalUrl?: string | null | undefined; + readonly proxyUrl?: string | null | undefined; + constructor(id: string, name: string, isSatellite: boolean, frontendApiUrl: string, developmentOrigin: string, cnameTargets: CnameTarget[], accountsPortalUrl?: string | null | undefined, proxyUrl?: string | null | undefined); + static fromJSON(data: DomainJSON): Domain; +} +//# sourceMappingURL=Domain.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/Domain.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/resources/Domain.d.ts.map new file mode 100644 index 000000000..ce06a1fb8 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/Domain.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"Domain.d.ts","sourceRoot":"","sources":["../../../src/api/resources/Domain.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAC;AAEzC,qBAAa,MAAM;IAEf,QAAQ,CAAC,EAAE,EAAE,MAAM;IACnB,QAAQ,CAAC,IAAI,EAAE,MAAM;IACrB,QAAQ,CAAC,WAAW,EAAE,OAAO;IAC7B,QAAQ,CAAC,cAAc,EAAE,MAAM;IAC/B,QAAQ,CAAC,iBAAiB,EAAE,MAAM;IAClC,QAAQ,CAAC,YAAY,EAAE,WAAW,EAAE;IACpC,QAAQ,CAAC,iBAAiB,CAAC,EAAE,MAAM,GAAG,IAAI;IAC1C,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI;gBAPxB,EAAE,EAAE,MAAM,EACV,IAAI,EAAE,MAAM,EACZ,WAAW,EAAE,OAAO,EACpB,cAAc,EAAE,MAAM,EACtB,iBAAiB,EAAE,MAAM,EACzB,YAAY,EAAE,WAAW,EAAE,EAC3B,iBAAiB,CAAC,EAAE,MAAM,GAAG,IAAI,YAAA,EACjC,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,YAAA;IAGnC,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,UAAU,GAAG,MAAM;CAY1C"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/Email.d.ts b/backend/node_modules/@clerk/backend/dist/api/resources/Email.d.ts new file mode 100644 index 000000000..ceb83937d --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/Email.d.ts @@ -0,0 +1,17 @@ +import type { EmailJSON } from './JSON'; +export declare class Email { + readonly id: string; + readonly fromEmailName: string; + readonly emailAddressId: string | null; + readonly toEmailAddress?: string | undefined; + readonly subject?: string | undefined; + readonly body?: string | undefined; + readonly bodyPlain?: string | null | undefined; + readonly status?: string | undefined; + readonly slug?: string | null | undefined; + readonly data?: (Record | null) | undefined; + readonly deliveredByClerk?: boolean | undefined; + constructor(id: string, fromEmailName: string, emailAddressId: string | null, toEmailAddress?: string | undefined, subject?: string | undefined, body?: string | undefined, bodyPlain?: string | null | undefined, status?: string | undefined, slug?: string | null | undefined, data?: (Record | null) | undefined, deliveredByClerk?: boolean | undefined); + static fromJSON(data: EmailJSON): Email; +} +//# sourceMappingURL=Email.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/Email.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/resources/Email.d.ts.map new file mode 100644 index 000000000..8756d9794 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/Email.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"Email.d.ts","sourceRoot":"","sources":["../../../src/api/resources/Email.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,QAAQ,CAAC;AAExC,qBAAa,KAAK;IAEd,QAAQ,CAAC,EAAE,EAAE,MAAM;IACnB,QAAQ,CAAC,aAAa,EAAE,MAAM;IAC9B,QAAQ,CAAC,cAAc,EAAE,MAAM,GAAG,IAAI;IACtC,QAAQ,CAAC,cAAc,CAAC,EAAE,MAAM;IAChC,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM;IACzB,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM;IACtB,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI;IAClC,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM;IACxB,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI;IAC7B,QAAQ,CAAC,IAAI,CAAC,GAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,IAAI;IAC1C,QAAQ,CAAC,gBAAgB,CAAC,EAAE,OAAO;gBAV1B,EAAE,EAAE,MAAM,EACV,aAAa,EAAE,MAAM,EACrB,cAAc,EAAE,MAAM,GAAG,IAAI,EAC7B,cAAc,CAAC,EAAE,MAAM,YAAA,EACvB,OAAO,CAAC,EAAE,MAAM,YAAA,EAChB,IAAI,CAAC,EAAE,MAAM,YAAA,EACb,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,YAAA,EACzB,MAAM,CAAC,EAAE,MAAM,YAAA,EACf,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,YAAA,EACpB,IAAI,CAAC,GAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,IAAI,aAAA,EACjC,gBAAgB,CAAC,EAAE,OAAO,YAAA;IAGrC,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,SAAS,GAAG,KAAK;CAexC"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/EmailAddress.d.ts b/backend/node_modules/@clerk/backend/dist/api/resources/EmailAddress.d.ts new file mode 100644 index 000000000..ab78c2ef0 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/EmailAddress.d.ts @@ -0,0 +1,47 @@ +import { IdentificationLink } from './IdentificationLink'; +import type { EmailAddressJSON } from './JSON'; +import { Verification } from './Verification'; +/** + * The Backend `EmailAddress` object is a model around an email address. Email addresses are one of the [identifiers](https://clerk.com/docs/authentication/configuration/sign-up-sign-in-options#identifiers) used to provide identification for users. + * + * Email addresses must be **verified** to ensure that they are assigned to their rightful owners. The `EmailAddress` object holds all necessary state around the verification process. + * + * For implementation examples for adding and verifying email addresses, see the [email link custom flow](https://clerk.com/docs/custom-flows/email-links) and [email code custom flow](https://clerk.com/docs/custom-flows/add-email) guides. + */ +export declare class EmailAddress { + /** + * The unique identifier for the email address. + */ + readonly id: string; + /** + * The value of the email address. + */ + readonly emailAddress: string; + /** + * An object holding information on the verification of the email address. + */ + readonly verification: Verification | null; + /** + * An array of objects containing information about any identifications that might be linked to the email address. + */ + readonly linkedTo: IdentificationLink[]; + constructor( + /** + * The unique identifier for the email address. + */ + id: string, + /** + * The value of the email address. + */ + emailAddress: string, + /** + * An object holding information on the verification of the email address. + */ + verification: Verification | null, + /** + * An array of objects containing information about any identifications that might be linked to the email address. + */ + linkedTo: IdentificationLink[]); + static fromJSON(data: EmailAddressJSON): EmailAddress; +} +//# sourceMappingURL=EmailAddress.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/EmailAddress.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/resources/EmailAddress.d.ts.map new file mode 100644 index 000000000..3bb8cff55 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/EmailAddress.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"EmailAddress.d.ts","sourceRoot":"","sources":["../../../src/api/resources/EmailAddress.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAC1D,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,QAAQ,CAAC;AAC/C,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAE9C;;;;;;GAMG;AACH,qBAAa,YAAY;IAErB;;OAEG;IACH,QAAQ,CAAC,EAAE,EAAE,MAAM;IACnB;;OAEG;IACH,QAAQ,CAAC,YAAY,EAAE,MAAM;IAC7B;;OAEG;IACH,QAAQ,CAAC,YAAY,EAAE,YAAY,GAAG,IAAI;IAC1C;;OAEG;IACH,QAAQ,CAAC,QAAQ,EAAE,kBAAkB,EAAE;;IAfvC;;OAEG;IACM,EAAE,EAAE,MAAM;IACnB;;OAEG;IACM,YAAY,EAAE,MAAM;IAC7B;;OAEG;IACM,YAAY,EAAE,YAAY,GAAG,IAAI;IAC1C;;OAEG;IACM,QAAQ,EAAE,kBAAkB,EAAE;IAGzC,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,gBAAgB,GAAG,YAAY;CAQtD"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/Enums.d.ts b/backend/node_modules/@clerk/backend/dist/api/resources/Enums.d.ts new file mode 100644 index 000000000..b3499c3c2 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/Enums.d.ts @@ -0,0 +1,42 @@ +import type { OrganizationCustomRoleKey } from '@clerk/types'; +export type OAuthProvider = 'facebook' | 'google' | 'hubspot' | 'github' | 'tiktok' | 'gitlab' | 'discord' | 'twitter' | 'twitch' | 'linkedin' | 'linkedin_oidc' | 'dropbox' | 'bitbucket' | 'microsoft' | 'notion' | 'apple' | 'x'; +export type OAuthStrategy = `oauth_${OAuthProvider}`; +/** + * @inline + */ +export type OrganizationInvitationStatus = 'pending' | 'accepted' | 'revoked'; +export type OrganizationDomainVerificationStatus = 'unverified' | 'verified'; +export type OrganizationDomainVerificationStrategy = 'email_code'; +export type OrganizationEnrollmentMode = 'manual_invitation' | 'automatic_invitation' | 'automatic_suggestion'; +export type OrganizationMembershipRole = OrganizationCustomRoleKey; +export type SignInStatus = 'needs_identifier' | 'needs_factor_one' | 'needs_factor_two' | 'complete'; +export type SignUpVerificationNextAction = 'needs_prepare' | 'needs_attempt' | ''; +/** + * @inline + */ +export type InvitationStatus = 'pending' | 'accepted' | 'revoked' | 'expired'; +export declare const DomainsEnrollmentModes: { + readonly ManualInvitation: "manual_invitation"; + readonly AutomaticInvitation: "automatic_invitation"; + readonly AutomaticSuggestion: "automatic_suggestion"; +}; +export type DomainsEnrollmentModes = (typeof DomainsEnrollmentModes)[keyof typeof DomainsEnrollmentModes]; +export declare const ActorTokenStatus: { + readonly Pending: "pending"; + readonly Accepted: "accepted"; + readonly Revoked: "revoked"; +}; +export type ActorTokenStatus = (typeof ActorTokenStatus)[keyof typeof ActorTokenStatus]; +/** + * @inline + */ +export type AllowlistIdentifierType = 'email_address' | 'phone_number' | 'web3_wallet'; +/** + * @inline + */ +export type BlocklistIdentifierType = AllowlistIdentifierType; +/** + * @inline + */ +export type WaitlistEntryStatus = 'pending' | 'invited' | 'completed' | 'rejected'; +//# sourceMappingURL=Enums.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/Enums.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/resources/Enums.d.ts.map new file mode 100644 index 000000000..ab1a70c50 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/Enums.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"Enums.d.ts","sourceRoot":"","sources":["../../../src/api/resources/Enums.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,cAAc,CAAC;AAE9D,MAAM,MAAM,aAAa,GACrB,UAAU,GACV,QAAQ,GACR,SAAS,GACT,QAAQ,GACR,QAAQ,GACR,QAAQ,GACR,SAAS,GACT,SAAS,GACT,QAAQ,GACR,UAAU,GACV,eAAe,GACf,SAAS,GACT,WAAW,GACX,WAAW,GACX,QAAQ,GACR,OAAO,GACP,GAAG,CAAC;AAER,MAAM,MAAM,aAAa,GAAG,SAAS,aAAa,EAAE,CAAC;AAErD;;GAEG;AACH,MAAM,MAAM,4BAA4B,GAAG,SAAS,GAAG,UAAU,GAAG,SAAS,CAAC;AAE9E,MAAM,MAAM,oCAAoC,GAAG,YAAY,GAAG,UAAU,CAAC;AAE7E,MAAM,MAAM,sCAAsC,GAAG,YAAY,CAAC;AAElE,MAAM,MAAM,0BAA0B,GAAG,mBAAmB,GAAG,sBAAsB,GAAG,sBAAsB,CAAC;AAE/G,MAAM,MAAM,0BAA0B,GAAG,yBAAyB,CAAC;AAEnE,MAAM,MAAM,YAAY,GAAG,kBAAkB,GAAG,kBAAkB,GAAG,kBAAkB,GAAG,UAAU,CAAC;AAErG,MAAM,MAAM,4BAA4B,GAAG,eAAe,GAAG,eAAe,GAAG,EAAE,CAAC;AAElF;;GAEG;AACH,MAAM,MAAM,gBAAgB,GAAG,SAAS,GAAG,UAAU,GAAG,SAAS,GAAG,SAAS,CAAC;AAE9E,eAAO,MAAM,sBAAsB;;;;CAIzB,CAAC;AACX,MAAM,MAAM,sBAAsB,GAAG,CAAC,OAAO,sBAAsB,CAAC,CAAC,MAAM,OAAO,sBAAsB,CAAC,CAAC;AAE1G,eAAO,MAAM,gBAAgB;;;;CAInB,CAAC;AACX,MAAM,MAAM,gBAAgB,GAAG,CAAC,OAAO,gBAAgB,CAAC,CAAC,MAAM,OAAO,gBAAgB,CAAC,CAAC;AAExF;;GAEG;AACH,MAAM,MAAM,uBAAuB,GAAG,eAAe,GAAG,cAAc,GAAG,aAAa,CAAC;AAEvF;;GAEG;AACH,MAAM,MAAM,uBAAuB,GAAG,uBAAuB,CAAC;AAE9D;;GAEG;AACH,MAAM,MAAM,mBAAmB,GAAG,SAAS,GAAG,SAAS,GAAG,WAAW,GAAG,UAAU,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/ExternalAccount.d.ts b/backend/node_modules/@clerk/backend/dist/api/resources/ExternalAccount.d.ts new file mode 100644 index 000000000..ce0289460 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/ExternalAccount.d.ts @@ -0,0 +1,124 @@ +import type { ExternalAccountJSON } from './JSON'; +import { Verification } from './Verification'; +/** + * The Backend `ExternalAccount` object is a model around an identification obtained by an external provider (e.g. a social provider such as Google). + * + * External account must be verified, so that you can make sure they can be assigned to their rightful owners. The `ExternalAccount` object holds all necessary state around the verification process. + */ +export declare class ExternalAccount { + /** + * The unique identifier for this external account. + */ + readonly id: string; + /** + * The provider name (e.g., `google`). + */ + readonly provider: string; + /** + * The identification with which this external account is associated. + */ + readonly identificationId: string; + /** + * The unique ID of the user in the provider. + */ + readonly externalId: string; + /** + * The scopes that the user has granted access to. + */ + readonly approvedScopes: string; + /** + * The user's email address. + */ + readonly emailAddress: string; + /** + * The user's first name. + */ + readonly firstName: string; + /** + * The user's last name. + */ + readonly lastName: string; + /** + * The user's image URL. + */ + readonly imageUrl: string; + /** + * The user's username. + */ + readonly username: string | null; + /** + * The phone number related to this specific external account. + */ + readonly phoneNumber: string | null; + /** + * Metadata that can be read from the Frontend API and Backend API and can be set only from the Backend API. + */ + readonly publicMetadata: Record | null; + /** + * A descriptive label to differentiate multiple external accounts of the same user for the same provider. + */ + readonly label: string | null; + /** + * An object holding information on the verification of this external account. + */ + readonly verification: Verification | null; + constructor( + /** + * The unique identifier for this external account. + */ + id: string, + /** + * The provider name (e.g., `google`). + */ + provider: string, + /** + * The identification with which this external account is associated. + */ + identificationId: string, + /** + * The unique ID of the user in the provider. + */ + externalId: string, + /** + * The scopes that the user has granted access to. + */ + approvedScopes: string, + /** + * The user's email address. + */ + emailAddress: string, + /** + * The user's first name. + */ + firstName: string, + /** + * The user's last name. + */ + lastName: string, + /** + * The user's image URL. + */ + imageUrl: string, + /** + * The user's username. + */ + username: string | null, + /** + * The phone number related to this specific external account. + */ + phoneNumber: string | null, + /** + * Metadata that can be read from the Frontend API and Backend API and can be set only from the Backend API. + */ + publicMetadata: (Record | null) | undefined, + /** + * A descriptive label to differentiate multiple external accounts of the same user for the same provider. + */ + label: string | null, + /** + * An object holding information on the verification of this external account. + */ + verification: Verification | null); + static fromJSON(data: ExternalAccountJSON): ExternalAccount; +} +//# sourceMappingURL=ExternalAccount.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/ExternalAccount.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/resources/ExternalAccount.d.ts.map new file mode 100644 index 000000000..7a7f894f0 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/ExternalAccount.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ExternalAccount.d.ts","sourceRoot":"","sources":["../../../src/api/resources/ExternalAccount.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,QAAQ,CAAC;AAClD,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAE9C;;;;GAIG;AACH,qBAAa,eAAe;IAExB;;OAEG;IACH,QAAQ,CAAC,EAAE,EAAE,MAAM;IACnB;;OAEG;IACH,QAAQ,CAAC,QAAQ,EAAE,MAAM;IACzB;;OAEG;IACH,QAAQ,CAAC,gBAAgB,EAAE,MAAM;IACjC;;OA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E,YAAY,GAAG,IAAI;IAG5C,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,mBAAmB,GAAG,eAAe;CAkB5D"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/Feature.d.ts b/backend/node_modules/@clerk/backend/dist/api/resources/Feature.d.ts new file mode 100644 index 000000000..1264b7b1c --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/Feature.d.ts @@ -0,0 +1,51 @@ +import type { FeatureJSON } from './JSON'; +/** + * The `Feature` object represents a feature of a subscription plan. + * + * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. + */ +export declare class Feature { + /** + * The unique identifier for the feature. + */ + readonly id: string; + /** + * The name of the feature. + */ + readonly name: string; + /** + * The description of the feature. + */ + readonly description: string; + /** + * The URL-friendly identifier of the feature. + */ + readonly slug: string; + /** + * The URL of the feature's avatar image. + */ + readonly avatarUrl: string; + constructor( + /** + * The unique identifier for the feature. + */ + id: string, + /** + * The name of the feature. + */ + name: string, + /** + * The description of the feature. + */ + description: string, + /** + * The URL-friendly identifier of the feature. + */ + slug: string, + /** + * The URL of the feature's avatar image. + */ + avatarUrl: string); + static fromJSON(data: FeatureJSON): Feature; +} +//# sourceMappingURL=Feature.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/Feature.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/resources/Feature.d.ts.map new file mode 100644 index 000000000..b55248b65 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/Feature.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"Feature.d.ts","sourceRoot":"","sources":["../../../src/api/resources/Feature.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,QAAQ,CAAC;AAE1C;;;;GAIG;AACH,qBAAa,OAAO;IAEhB;;OAEG;IACH,QAAQ,CAAC,EAAE,EAAE,MAAM;IACnB;;OAEG;IACH,QAAQ,CAAC,IAAI,EAAE,MAAM;IACrB;;OAEG;IACH,QAAQ,CAAC,WAAW,EAAE,MAAM;IAC5B;;OAEG;IACH,QAAQ,CAAC,IAAI,EAAE,MAAM;IACrB;;OAEG;IACH,QAAQ,CAAC,SAAS,EAAE,MAAM;;IAnB1B;;OAEG;IACM,EAAE,EAAE,MAAM;IACnB;;OAEG;IACM,IAAI,EAAE,MAAM;IACrB;;OAEG;IACM,WAAW,EAAE,MAAM;IAC5B;;OAEG;IACM,IAAI,EAAE,MAAM;IACrB;;OAEG;IACM,SAAS,EAAE,MAAM;IAG5B,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,WAAW,GAAG,OAAO;CAG5C"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/HandshakePayload.d.ts b/backend/node_modules/@clerk/backend/dist/api/resources/HandshakePayload.d.ts new file mode 100644 index 000000000..240b6d6c2 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/HandshakePayload.d.ts @@ -0,0 +1,9 @@ +export type HandshakePayloadJSON = { + directives: string[]; +}; +export declare class HandshakePayload { + readonly directives: string[]; + constructor(directives: string[]); + static fromJSON(data: HandshakePayloadJSON): HandshakePayload; +} +//# sourceMappingURL=HandshakePayload.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/HandshakePayload.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/resources/HandshakePayload.d.ts.map new file mode 100644 index 000000000..cf5f8eb67 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/HandshakePayload.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"HandshakePayload.d.ts","sourceRoot":"","sources":["../../../src/api/resources/HandshakePayload.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,oBAAoB,GAAG;IACjC,UAAU,EAAE,MAAM,EAAE,CAAC;CACtB,CAAC;AAEF,qBAAa,gBAAgB;IACf,QAAQ,CAAC,UAAU,EAAE,MAAM,EAAE;gBAApB,UAAU,EAAE,MAAM,EAAE;IAEzC,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,oBAAoB,GAAG,gBAAgB;CAG9D"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/IdPOAuthAccessToken.d.ts b/backend/node_modules/@clerk/backend/dist/api/resources/IdPOAuthAccessToken.d.ts new file mode 100644 index 000000000..3f460f60e --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/IdPOAuthAccessToken.d.ts @@ -0,0 +1,17 @@ +import type { IdPOAuthAccessTokenJSON } from './JSON'; +export declare class IdPOAuthAccessToken { + readonly id: string; + readonly clientId: string; + readonly type: string; + readonly subject: string; + readonly scopes: string[]; + readonly revoked: boolean; + readonly revocationReason: string | null; + readonly expired: boolean; + readonly expiration: number | null; + readonly createdAt: number; + readonly updatedAt: number; + constructor(id: string, clientId: string, type: string, subject: string, scopes: string[], revoked: boolean, revocationReason: string | null, expired: boolean, expiration: number | null, createdAt: number, updatedAt: number); + static fromJSON(data: IdPOAuthAccessTokenJSON): IdPOAuthAccessToken; +} +//# sourceMappingURL=IdPOAuthAccessToken.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/IdPOAuthAccessToken.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/resources/IdPOAuthAccessToken.d.ts.map new file mode 100644 index 000000000..78be45488 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/IdPOAuthAccessToken.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"IdPOAuthAccessToken.d.ts","sourceRoot":"","sources":["../../../src/api/resources/IdPOAuthAccessToken.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,QAAQ,CAAC;AAEtD,qBAAa,mBAAmB;IAE5B,QAAQ,CAAC,EAAE,EAAE,MAAM;IACnB,QAAQ,CAAC,QAAQ,EAAE,MAAM;IACzB,QAAQ,CAAC,IAAI,EAAE,MAAM;IACrB,QAAQ,CAAC,OAAO,EAAE,MAAM;IACxB,QAAQ,CAAC,MAAM,EAAE,MAAM,EAAE;IACzB,QAAQ,CAAC,OAAO,EAAE,OAAO;IACzB,QAAQ,CAAC,gBAAgB,EAAE,MAAM,GAAG,IAAI;IACxC,QAAQ,CAAC,OAAO,EAAE,OAAO;IACzB,QAAQ,CAAC,UAAU,EAAE,MAAM,GAAG,IAAI;IAClC,QAAQ,CAAC,SAAS,EAAE,MAAM;IAC1B,QAAQ,CAAC,SAAS,EAAE,MAAM;gBAVjB,EAAE,EAAE,MAAM,EACV,QAAQ,EAAE,MAAM,EAChB,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,MAAM,EACf,MAAM,EAAE,MAAM,EAAE,EAChB,OAAO,EAAE,OAAO,EAChB,gBAAgB,EAAE,MAAM,GAAG,IAAI,EAC/B,OAAO,EAAE,OAAO,EAChB,UAAU,EAAE,MAAM,GAAG,IAAI,EACzB,SAAS,EAAE,MAAM,EACjB,SAAS,EAAE,MAAM;IAG5B,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,uBAAuB;CAe9C"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/IdentificationLink.d.ts b/backend/node_modules/@clerk/backend/dist/api/resources/IdentificationLink.d.ts new file mode 100644 index 000000000..8d976e769 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/IdentificationLink.d.ts @@ -0,0 +1,25 @@ +import type { IdentificationLinkJSON } from './JSON'; +/** + * Contains information about any identifications that might be linked to the email address. + */ +export declare class IdentificationLink { + /** + * The unique identifier for the identification link. + */ + readonly id: string; + /** + * The type of the identification link, e.g., `"email_address"`, `"phone_number"`, etc. + */ + readonly type: string; + constructor( + /** + * The unique identifier for the identification link. + */ + id: string, + /** + * The type of the identification link, e.g., `"email_address"`, `"phone_number"`, etc. + */ + type: string); + static fromJSON(data: IdentificationLinkJSON): IdentificationLink; +} +//# sourceMappingURL=IdentificationLink.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/IdentificationLink.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/resources/IdentificationLink.d.ts.map new file mode 100644 index 000000000..ba91f8319 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/IdentificationLink.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"IdentificationLink.d.ts","sourceRoot":"","sources":["../../../src/api/resources/IdentificationLink.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,QAAQ,CAAC;AAErD;;GAEG;AACH,qBAAa,kBAAkB;IAE3B;;OAEG;IACH,QAAQ,CAAC,EAAE,EAAE,MAAM;IACnB;;OAEG;IACH,QAAQ,CAAC,IAAI,EAAE,MAAM;;IAPrB;;OAEG;IACM,EAAE,EAAE,MAAM;IACnB;;OAEG;IACM,IAAI,EAAE,MAAM;IAGvB,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,sBAAsB,GAAG,kBAAkB;CAGlE"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/Instance.d.ts b/backend/node_modules/@clerk/backend/dist/api/resources/Instance.d.ts new file mode 100644 index 000000000..ee6691b71 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/Instance.d.ts @@ -0,0 +1,9 @@ +import type { InstanceJSON } from './JSON'; +export declare class Instance { + readonly id: string; + readonly environmentType: string; + readonly allowedOrigins: Array | null; + constructor(id: string, environmentType: string, allowedOrigins: Array | null); + static fromJSON(data: InstanceJSON): Instance; +} +//# sourceMappingURL=Instance.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/Instance.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/resources/Instance.d.ts.map new file mode 100644 index 000000000..61afd5af2 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/Instance.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"Instance.d.ts","sourceRoot":"","sources":["../../../src/api/resources/Instance.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AAE3C,qBAAa,QAAQ;IAEjB,QAAQ,CAAC,EAAE,EAAE,MAAM;IACnB,QAAQ,CAAC,eAAe,EAAE,MAAM;IAChC,QAAQ,CAAC,cAAc,EAAE,KAAK,CAAC,MAAM,CAAC,GAAG,IAAI;gBAFpC,EAAE,EAAE,MAAM,EACV,eAAe,EAAE,MAAM,EACvB,cAAc,EAAE,KAAK,CAAC,MAAM,CAAC,GAAG,IAAI;IAG/C,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,YAAY,GAAG,QAAQ;CAG9C"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/InstanceRestrictions.d.ts b/backend/node_modules/@clerk/backend/dist/api/resources/InstanceRestrictions.d.ts new file mode 100644 index 000000000..efc40e7b3 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/InstanceRestrictions.d.ts @@ -0,0 +1,11 @@ +import type { InstanceRestrictionsJSON } from './JSON'; +export declare class InstanceRestrictions { + readonly allowlist: boolean; + readonly blocklist: boolean; + readonly blockEmailSubaddresses: boolean; + readonly blockDisposableEmailDomains: boolean; + readonly ignoreDotsForGmailAddresses: boolean; + constructor(allowlist: boolean, blocklist: boolean, blockEmailSubaddresses: boolean, blockDisposableEmailDomains: boolean, ignoreDotsForGmailAddresses: boolean); + static fromJSON(data: InstanceRestrictionsJSON): InstanceRestrictions; +} +//# sourceMappingURL=InstanceRestrictions.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/InstanceRestrictions.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/resources/InstanceRestrictions.d.ts.map new file mode 100644 index 000000000..33d8a1ff2 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/InstanceRestrictions.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"InstanceRestrictions.d.ts","sourceRoot":"","sources":["../../../src/api/resources/InstanceRestrictions.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,QAAQ,CAAC;AAEvD,qBAAa,oBAAoB;IAE7B,QAAQ,CAAC,SAAS,EAAE,OAAO;IAC3B,QAAQ,CAAC,SAAS,EAAE,OAAO;IAC3B,QAAQ,CAAC,sBAAsB,EAAE,OAAO;IACxC,QAAQ,CAAC,2BAA2B,EAAE,OAAO;IAC7C,QAAQ,CAAC,2BAA2B,EAAE,OAAO;gBAJpC,SAAS,EAAE,OAAO,EAClB,SAAS,EAAE,OAAO,EAClB,sBAAsB,EAAE,OAAO,EAC/B,2BAA2B,EAAE,OAAO,EACpC,2BAA2B,EAAE,OAAO;IAG/C,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,wBAAwB,GAAG,oBAAoB;CAStE"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/InstanceSettings.d.ts b/backend/node_modules/@clerk/backend/dist/api/resources/InstanceSettings.d.ts new file mode 100644 index 000000000..0f01361f1 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/InstanceSettings.d.ts @@ -0,0 +1,11 @@ +import type { InstanceSettingsJSON } from './JSON'; +export declare class InstanceSettings { + readonly id?: string | undefined; + readonly restrictedToAllowlist?: boolean | undefined; + readonly fromEmailAddress?: string | undefined; + readonly progressiveSignUp?: boolean | undefined; + readonly enhancedEmailDeliverability?: boolean | undefined; + constructor(id?: string | undefined, restrictedToAllowlist?: boolean | undefined, fromEmailAddress?: string | undefined, progressiveSignUp?: boolean | undefined, enhancedEmailDeliverability?: boolean | undefined); + static fromJSON(data: InstanceSettingsJSON): InstanceSettings; +} +//# sourceMappingURL=InstanceSettings.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/InstanceSettings.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/resources/InstanceSettings.d.ts.map new file mode 100644 index 000000000..379db793e --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/InstanceSettings.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"InstanceSettings.d.ts","sourceRoot":"","sources":["../../../src/api/resources/InstanceSettings.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,QAAQ,CAAC;AAEnD,qBAAa,gBAAgB;IAEzB,QAAQ,CAAC,EAAE,CAAC,EAAE,MAAM,GAAG,SAAS;IAChC,QAAQ,CAAC,qBAAqB,CAAC,EAAE,OAAO,GAAG,SAAS;IACpD,QAAQ,CAAC,gBAAgB,CAAC,EAAE,MAAM,GAAG,SAAS;IAC9C,QAAQ,CAAC,iBAAiB,CAAC,EAAE,OAAO,GAAG,SAAS;IAChD,QAAQ,CAAC,2BAA2B,CAAC,EAAE,OAAO,GAAG,SAAS;gBAJjD,EAAE,CAAC,EAAE,MAAM,GAAG,SAAS,EACvB,qBAAqB,CAAC,EAAE,OAAO,GAAG,SAAS,EAC3C,gBAAgB,CAAC,EAAE,MAAM,GAAG,SAAS,EACrC,iBAAiB,CAAC,EAAE,OAAO,GAAG,SAAS,EACvC,2BAA2B,CAAC,EAAE,OAAO,GAAG,SAAS;IAG5D,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,oBAAoB,GAAG,gBAAgB;CAS9D"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/Invitation.d.ts b/backend/node_modules/@clerk/backend/dist/api/resources/Invitation.d.ts new file mode 100644 index 000000000..389f9e5d4 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/Invitation.d.ts @@ -0,0 +1,76 @@ +import type { InvitationStatus } from './Enums'; +import type { InvitationJSON } from './JSON'; +/** + * The Backend `Invitation` object represents an invitation to join your application. + */ +export declare class Invitation { + /** + * The unique identifier for the `Invitation`. + */ + readonly id: string; + /** + * The email address that the invitation was sent to. + */ + readonly emailAddress: string; + /** + * [Metadata](https://clerk.com/docs/references/javascript/types/metadata#user-public-metadata){{ target: '_blank' }} that can be read from the Frontend API and [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }} and can be set only from the Backend API. Once the user accepts the invitation and signs up, these metadata will end up in the user's public metadata. + */ + readonly publicMetadata: Record | null; + /** + * The date when the `Invitation` was first created. + */ + readonly createdAt: number; + /** + * The date when the `Invitation` was last updated. + */ + readonly updatedAt: number; + /** + * The status of the `Invitation`. + */ + readonly status: InvitationStatus; + /** + * The URL that the user can use to accept the invitation. + */ + readonly url?: string | undefined; + /** + * Whether the `Invitation` has been revoked. + */ + readonly revoked?: boolean | undefined; + private _raw; + get raw(): InvitationJSON | null; + constructor( + /** + * The unique identifier for the `Invitation`. + */ + id: string, + /** + * The email address that the invitation was sent to. + */ + emailAddress: string, + /** + * [Metadata](https://clerk.com/docs/references/javascript/types/metadata#user-public-metadata){{ target: '_blank' }} that can be read from the Frontend API and [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }} and can be set only from the Backend API. Once the user accepts the invitation and signs up, these metadata will end up in the user's public metadata. + */ + publicMetadata: Record | null, + /** + * The date when the `Invitation` was first created. + */ + createdAt: number, + /** + * The date when the `Invitation` was last updated. + */ + updatedAt: number, + /** + * The status of the `Invitation`. + */ + status: InvitationStatus, + /** + * The URL that the user can use to accept the invitation. + */ + url?: string | undefined, + /** + * Whether the `Invitation` has been revoked. + */ + revoked?: boolean | undefined); + static fromJSON(data: InvitationJSON): Invitation; +} +//# sourceMappingURL=Invitation.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/Invitation.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/resources/Invitation.d.ts.map new file mode 100644 index 000000000..58b38a520 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/Invitation.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"Invitation.d.ts","sourceRoot":"","sources":["../../../src/api/resources/Invitation.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC;AAChD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,QAAQ,CAAC;AAE7C;;GAEG;AACH,qBAAa,UAAU;IAQnB;;OAEG;IACH,QAAQ,CAAC,EAAE,EAAE,MAAM;IACnB;;OAEG;IACH,QAAQ,CAAC,YAAY,EAAE,MAAM;IAC7B;;OAEG;IACH,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI;IACvD;;OAEG;IACH,QAAQ,CAAC,SAAS,EAAE,MAAM;IAC1B;;OAEG;IACH,QAAQ,CAAC,SAAS,EAAE,MAAM;IAC1B;;OAEG;IACH,QAAQ,CAAC,MAAM,EAAE,gBAAgB;IACjC;;OAEG;IACH,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM;IACrB;;OAEG;IACH,QAAQ,CAAC,OAAO,CAAC,EAAE,OAAO;IAtC5B,OAAO,CAAC,IAAI,CAA+B;IAE3C,IAAW,GAAG,IAAI,cAAc,GAAG,IAAI,CAEtC;;IAGC;;OAEG;IACM,EAAE,EAAE,MAAM;IACnB;;OAEG;IACM,YAAY,EAAE,MAAM;IAC7B;;OAEG;IACM,cAAc,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI;IACvD;;OAEG;IACM,SAAS,EAAE,MAAM;IAC1B;;OAEG;IACM,SAAS,EAAE,MAAM;IAC1B;;OAEG;IACM,MAAM,EAAE,gBAAgB;IACjC;;OAEG;IACM,GAAG,CAAC,EAAE,MAAM,YAAA;IACrB;;OAEG;IACM,OAAO,CAAC,EAAE,OAAO,YAAA;IAG5B,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,cAAc,GAAG,UAAU;CAclD"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/JSON.d.ts b/backend/node_modules/@clerk/backend/dist/api/resources/JSON.d.ts new file mode 100644 index 000000000..aef45043d --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/JSON.d.ts @@ -0,0 +1,902 @@ +import type { LastAuthenticationStrategy, SignUpStatus, VerificationStatus } from '@clerk/types'; +import type { ActorTokenStatus, AllowlistIdentifierType, BlocklistIdentifierType, DomainsEnrollmentModes, InvitationStatus, OrganizationDomainVerificationStatus, OrganizationDomainVerificationStrategy, OrganizationEnrollmentMode, OrganizationInvitationStatus, OrganizationMembershipRole, SignInStatus, SignUpVerificationNextAction, WaitlistEntryStatus } from './Enums'; +export declare const ObjectType: { + readonly AccountlessApplication: "accountless_application"; + readonly ActorToken: "actor_token"; + readonly AllowlistIdentifier: "allowlist_identifier"; + readonly ApiKey: "api_key"; + readonly BlocklistIdentifier: "blocklist_identifier"; + readonly Client: "client"; + readonly Cookies: "cookies"; + readonly Domain: "domain"; + readonly Email: "email"; + readonly EmailAddress: "email_address"; + readonly ExternalAccount: "external_account"; + readonly FacebookAccount: "facebook_account"; + readonly GoogleAccount: "google_account"; + readonly Instance: "instance"; + readonly InstanceRestrictions: "instance_restrictions"; + readonly InstanceSettings: "instance_settings"; + readonly Invitation: "invitation"; + readonly Machine: "machine"; + readonly MachineScope: "machine_scope"; + readonly MachineSecretKey: "machine_secret_key"; + readonly M2MToken: "machine_to_machine_token"; + readonly JwtTemplate: "jwt_template"; + readonly OauthAccessToken: "oauth_access_token"; + readonly IdpOAuthAccessToken: "clerk_idp_oauth_access_token"; + readonly OAuthApplication: "oauth_application"; + readonly Organization: "organization"; + readonly OrganizationDomain: "organization_domain"; + readonly OrganizationInvitation: "organization_invitation"; + readonly OrganizationMembership: "organization_membership"; + readonly OrganizationSettings: "organization_settings"; + readonly PhoneNumber: "phone_number"; + readonly ProxyCheck: "proxy_check"; + readonly RedirectUrl: "redirect_url"; + readonly SamlAccount: "saml_account"; + readonly SamlConnection: "saml_connection"; + readonly Session: "session"; + readonly SignInAttempt: "sign_in_attempt"; + readonly SignInToken: "sign_in_token"; + readonly SignUpAttempt: "sign_up_attempt"; + readonly SmsMessage: "sms_message"; + readonly User: "user"; + readonly WaitlistEntry: "waitlist_entry"; + readonly Web3Wallet: "web3_wallet"; + readonly Token: "token"; + readonly TotalCount: "total_count"; + readonly TestingToken: "testing_token"; + readonly Role: "role"; + readonly Permission: "permission"; + readonly BillingPayer: "commerce_payer"; + readonly BillingPaymentAttempt: "commerce_payment_attempt"; + readonly BillingSubscription: "commerce_subscription"; + readonly BillingSubscriptionItem: "commerce_subscription_item"; + readonly BillingPlan: "commerce_plan"; + readonly Feature: "feature"; +}; +export type ObjectType = (typeof ObjectType)[keyof typeof ObjectType]; +export interface ClerkResourceJSON { + /** + * The type of the resource. + */ + object: ObjectType; + /** + * The unique identifier for the resource. + */ + id: string; +} +export interface CookiesJSON { + object: typeof ObjectType.Cookies; + cookies: string[]; +} +export interface TokenJSON { + object: typeof ObjectType.Token; + jwt: string; +} +export interface AccountlessApplicationJSON extends ClerkResourceJSON { + object: typeof ObjectType.AccountlessApplication; + publishable_key: string; + secret_key: string; + claim_url: string; + api_keys_url: string; +} +export interface ActorTokenJSON extends ClerkResourceJSON { + object: typeof ObjectType.ActorToken; + id: string; + status: ActorTokenStatus; + user_id: string; + actor: Record | null; + token?: string | null; + url?: string | null; + created_at: number; + updated_at: number; +} +export interface AllowlistIdentifierJSON extends ClerkResourceJSON { + object: typeof ObjectType.AllowlistIdentifier; + identifier: string; + identifier_type: AllowlistIdentifierType; + instance_id?: string; + invitation_id?: string; + created_at: number; + updated_at: number; +} +export interface BlocklistIdentifierJSON extends ClerkResourceJSON { + object: typeof ObjectType.BlocklistIdentifier; + identifier: string; + identifier_type: BlocklistIdentifierType; + instance_id?: string; + created_at: number; + updated_at: number; +} +export interface ClientJSON extends ClerkResourceJSON { + object: typeof ObjectType.Client; + session_ids: string[]; + sessions: SessionJSON[]; + sign_in_id: string | null; + sign_up_id: string | null; + last_active_session_id: string | null; + last_authentication_strategy: LastAuthenticationStrategy | null; + created_at: number; + updated_at: number; +} +export interface CnameTargetJSON { + host: string; + value: string; + /** + * Denotes whether this CNAME target is required to be set in order for the domain to be considered deployed. + */ + required: boolean; +} +export interface DomainJSON extends ClerkResourceJSON { + object: typeof ObjectType.Domain; + id: string; + name: string; + is_satellite: boolean; + frontend_api_url: string; + /** + * null for satellite domains + */ + accounts_portal_url?: string | null; + proxy_url?: string; + development_origin: string; + cname_targets: CnameTargetJSON[]; +} +export interface EmailJSON extends ClerkResourceJSON { + object: typeof ObjectType.Email; + slug?: string | null; + from_email_name: string; + to_email_address?: string; + email_address_id: string | null; + user_id?: string | null; + subject?: string; + body?: string; + body_plain?: string | null; + status?: string; + data?: Record | null; + delivered_by_clerk: boolean; +} +export interface EmailAddressJSON extends ClerkResourceJSON { + object: typeof ObjectType.EmailAddress; + email_address: string; + verification: VerificationJSON | null; + linked_to: IdentificationLinkJSON[]; +} +export interface ExternalAccountJSON extends ClerkResourceJSON { + object: typeof ObjectType.ExternalAccount; + provider: string; + identification_id: string; + provider_user_id: string; + approved_scopes: string; + email_address: string; + first_name: string; + last_name: string; + image_url?: string; + username: string | null; + phone_number: string | null; + public_metadata?: Record | null; + label: string | null; + verification: VerificationJSON | null; +} +export interface JwksJSON { + keys?: JwksKeyJSON[]; +} +export interface JwksKeyJSON { + use: string; + kty: string; + kid: string; + alg: string; + n: string; + e: string; +} +export interface JwtTemplateJSON extends ClerkResourceJSON { + object: typeof ObjectType.JwtTemplate; + id: string; + name: string; + claims: object; + lifetime: number; + allowed_clock_skew: number; + custom_signing_key: boolean; + signing_algorithm: string; + created_at: number; + updated_at: number; +} +export interface SamlAccountJSON extends ClerkResourceJSON { + object: typeof ObjectType.SamlAccount; + provider: string; + provider_user_id: string | null; + active: boolean; + email_address: string; + first_name: string; + last_name: string; + verification: VerificationJSON | null; + saml_connection: SamlAccountConnectionJSON | null; +} +export interface IdentificationLinkJSON extends ClerkResourceJSON { + type: string; +} +export interface OrganizationSettingsJSON extends ClerkResourceJSON { + object: typeof ObjectType.OrganizationSettings; + enabled: boolean; + max_allowed_memberships: number; + max_allowed_roles: number; + max_allowed_permissions: number; + creator_role: string; + admin_delete_enabled: boolean; + domains_enabled: boolean; + domains_enrollment_modes: Array; + domains_default_role: string; +} +export interface InstanceJSON extends ClerkResourceJSON { + object: typeof ObjectType.Instance; + id: string; + environment_type: string; + allowed_origins: Array | null; +} +export interface InstanceRestrictionsJSON extends ClerkResourceJSON { + object: typeof ObjectType.InstanceRestrictions; + allowlist: boolean; + blocklist: boolean; + block_email_subaddresses: boolean; + block_disposable_email_domains: boolean; + ignore_dots_for_gmail_addresses: boolean; +} +export interface InstanceSettingsJSON extends ClerkResourceJSON { + object: typeof ObjectType.InstanceSettings; + id: string; + restricted_to_allowlist: boolean; + from_email_address: string; + progressive_sign_up: boolean; + enhanced_email_deliverability: boolean; +} +export interface InvitationJSON extends ClerkResourceJSON { + object: typeof ObjectType.Invitation; + email_address: string; + public_metadata: Record | null; + revoked?: boolean; + status: InvitationStatus; + url?: string; + created_at: number; + updated_at: number; +} +export interface OauthAccessTokenJSON { + external_account_id: string; + object: typeof ObjectType.OauthAccessToken; + token: string; + provider: string; + public_metadata: Record; + label: string | null; + scopes?: string[]; + token_secret?: string; + expires_at?: number; +} +export interface OAuthApplicationJSON extends ClerkResourceJSON { + object: typeof ObjectType.OAuthApplication; + id: string; + instance_id: string; + name: string; + client_id: string; + client_uri: string | null; + client_image_url: string | null; + dynamically_registered: boolean; + consent_screen_enabled: boolean; + pkce_required: boolean; + public: boolean; + scopes: string; + redirect_uris: Array; + authorize_url: string; + token_fetch_url: string; + user_info_url: string; + discovery_url: string; + token_introspection_url: string; + created_at: number; + updated_at: number; + client_secret?: string; +} +export interface OrganizationJSON extends ClerkResourceJSON { + object: typeof ObjectType.Organization; + name: string; + slug: string; + image_url?: string; + has_image: boolean; + members_count?: number; + pending_invitations_count?: number; + max_allowed_memberships: number; + admin_delete_enabled: boolean; + public_metadata: OrganizationPublicMetadata | null; + private_metadata?: OrganizationPrivateMetadata; + created_by?: string; + created_at: number; + updated_at: number; +} +export interface OrganizationDomainJSON extends ClerkResourceJSON { + object: typeof ObjectType.OrganizationDomain; + id: string; + name: string; + organization_id: string; + enrollment_mode: OrganizationEnrollmentMode; + verification: OrganizationDomainVerificationJSON | null; + affiliation_email_address: string | null; + created_at: number; + updated_at: number; + total_pending_invitations: number; + total_pending_suggestions: number; +} +export interface OrganizationDomainVerificationJSON { + status: OrganizationDomainVerificationStatus; + strategy: OrganizationDomainVerificationStrategy; + attempts: number; + expires_at: number; +} +export interface OrganizationInvitationJSON extends ClerkResourceJSON { + email_address: string; + role: OrganizationMembershipRole; + role_name: string; + organization_id: string; + public_organization_data?: PublicOrganizationDataJSON | null; + status?: OrganizationInvitationStatus; + public_metadata: OrganizationInvitationPublicMetadata; + private_metadata: OrganizationInvitationPrivateMetadata; + url: string | null; + created_at: number; + updated_at: number; + expires_at: number; +} +/** + * @interface + */ +export interface PublicOrganizationDataJSON extends ClerkResourceJSON { + /** + * The name of the organization. + */ + name: string; + /** + * The slug of the organization. + */ + slug: string; + /** + * Holds the default organization profile image. Compatible with Clerk's [Image Optimization](https://clerk.com/docs/guides/image-optimization). + */ + image_url?: string; + /** + * Whether the organization has a profile image. + */ + has_image: boolean; +} +export interface OrganizationMembershipJSON extends ClerkResourceJSON { + object: typeof ObjectType.OrganizationMembership; + public_metadata: OrganizationMembershipPublicMetadata; + private_metadata?: OrganizationMembershipPrivateMetadata; + role: OrganizationMembershipRole; + permissions: string[]; + created_at: number; + updated_at: number; + organization: OrganizationJSON; + public_user_data: OrganizationMembershipPublicUserDataJSON; +} +export interface OrganizationMembershipPublicUserDataJSON { + identifier: string; + first_name: string | null; + last_name: string | null; + image_url: string; + has_image: boolean; + user_id: string; +} +export interface PhoneNumberJSON extends ClerkResourceJSON { + object: typeof ObjectType.PhoneNumber; + phone_number: string; + reserved_for_second_factor: boolean; + default_second_factor: boolean; + reserved: boolean; + verification: VerificationJSON | null; + linked_to: IdentificationLinkJSON[]; + backup_codes: string[]; +} +export type ProxyCheckJSON = { + object: typeof ObjectType.ProxyCheck; + id: string; + domain_id: string; + last_run_at: number | null; + proxy_url: string; + successful: boolean; + created_at: number; + updated_at: number; +}; +export interface RedirectUrlJSON extends ClerkResourceJSON { + object: typeof ObjectType.RedirectUrl; + url: string; + created_at: number; + updated_at: number; +} +export interface SessionActivityJSON extends ClerkResourceJSON { + id: string; + device_type?: string; + is_mobile: boolean; + browser_name?: string; + browser_version?: string; + ip_address?: string; + city?: string; + country?: string; +} +export interface SessionJSON extends ClerkResourceJSON { + object: typeof ObjectType.Session; + client_id: string; + user_id: string; + status: string; + last_active_organization_id?: string; + actor: Record | null; + latest_activity?: SessionActivityJSON; + last_active_at: number; + expire_at: number; + abandon_at: number; + created_at: number; + updated_at: number; +} +export interface SignInJSON extends ClerkResourceJSON { + object: typeof ObjectType.SignInToken; + status: SignInStatus; + identifier: string; + created_session_id: string | null; +} +export interface SignInTokenJSON extends ClerkResourceJSON { + object: typeof ObjectType.SignInToken; + user_id: string; + token: string; + status: 'pending' | 'accepted' | 'revoked'; + url: string; + created_at: number; + updated_at: number; +} +export interface SignUpJSON extends ClerkResourceJSON { + object: typeof ObjectType.SignUpAttempt; + id: string; + status: SignUpStatus; + required_fields: string[]; + optional_fields: string[]; + missing_fields: string[]; + unverified_fields: string[]; + verifications: SignUpVerificationsJSON; + username: string | null; + email_address: string | null; + phone_number: string | null; + web3_wallet: string | null; + password_enabled: boolean; + first_name: string | null; + last_name: string | null; + public_metadata?: Record | null; + unsafe_metadata?: Record | null; + custom_action: boolean; + external_id: string | null; + created_session_id: string | null; + created_user_id: string | null; + abandon_at: number | null; + legal_accepted_at: number | null; + /** + * @deprecated Please use `verifications.external_account` instead + */ + external_account: object | null; +} +export interface SignUpVerificationsJSON { + email_address: SignUpVerificationJSON; + phone_number: SignUpVerificationJSON; + web3_wallet: SignUpVerificationJSON; + external_account: VerificationJSON; +} +export interface SignUpVerificationJSON { + next_action: SignUpVerificationNextAction; + supported_strategies: string[]; +} +export interface SMSMessageJSON extends ClerkResourceJSON { + object: typeof ObjectType.SmsMessage; + from_phone_number: string; + to_phone_number: string; + phone_number_id: string | null; + user_id?: string; + message: string; + status: string; + slug?: string | null; + data?: Record | null; + delivered_by_clerk: boolean; +} +export interface UserJSON extends ClerkResourceJSON { + object: typeof ObjectType.User; + username: string | null; + first_name: string | null; + last_name: string | null; + image_url: string; + has_image: boolean; + primary_email_address_id: string | null; + primary_phone_number_id: string | null; + primary_web3_wallet_id: string | null; + password_enabled: boolean; + two_factor_enabled: boolean; + totp_enabled: boolean; + backup_code_enabled: boolean; + email_addresses: EmailAddressJSON[]; + phone_numbers: PhoneNumberJSON[]; + web3_wallets: Web3WalletJSON[]; + organization_memberships: OrganizationMembershipJSON[] | null; + external_accounts: ExternalAccountJSON[]; + saml_accounts: SamlAccountJSON[]; + password_last_updated_at: number | null; + public_metadata: UserPublicMetadata; + private_metadata: UserPrivateMetadata; + unsafe_metadata: UserUnsafeMetadata; + external_id: string | null; + last_sign_in_at: number | null; + banned: boolean; + locked: boolean; + lockout_expires_in_seconds: number | null; + verification_attempts_remaining: number | null; + created_at: number; + updated_at: number; + last_active_at: number | null; + create_organization_enabled: boolean; + create_organizations_limit: number | null; + delete_self_enabled: boolean; + legal_accepted_at: number | null; +} +export interface VerificationJSON extends ClerkResourceJSON { + status: VerificationStatus; + strategy: string; + attempts: number | null; + expire_at: number | null; + verified_at_client?: string; + external_verification_redirect_url?: string | null; + nonce?: string | null; + message?: string | null; +} +export interface WaitlistEntryJSON extends ClerkResourceJSON { + object: typeof ObjectType.WaitlistEntry; + id: string; + status: WaitlistEntryStatus; + email_address: string; + invitation: InvitationJSON | null; + is_locked: boolean; + created_at: number; + updated_at: number; +} +export interface Web3WalletJSON extends ClerkResourceJSON { + object: typeof ObjectType.Web3Wallet; + web3_wallet: string; + verification: VerificationJSON | null; +} +export interface DeletedObjectJSON { + object: string; + id?: string; + slug?: string; + deleted: boolean; +} +export interface PaginatedResponseJSON { + data: object[]; + total_count?: number; +} +export interface SamlConnectionJSON extends ClerkResourceJSON { + object: typeof ObjectType.SamlConnection; + name: string; + domain: string; + organization_id: string | null; + idp_entity_id: string; + idp_sso_url: string; + idp_certificate: string; + idp_metadata_url: string; + idp_metadata: string; + acs_url: string; + sp_entity_id: string; + sp_metadata_url: string; + active: boolean; + provider: string; + user_count: number; + sync_user_attributes: boolean; + allow_subdomains: boolean; + allow_idp_initiated: boolean; + created_at: number; + updated_at: number; + attribute_mapping: AttributeMappingJSON; +} +export interface AttributeMappingJSON { + user_id: string; + email_address: string; + first_name: string; + last_name: string; +} +export interface TestingTokenJSON { + object: typeof ObjectType.TestingToken; + token: string; + expires_at: number; +} +export interface RoleJSON extends ClerkResourceJSON { + object: typeof ObjectType.Role; + key: string; + name: string; + description: string; + permissions: PermissionJSON[]; + is_creator_eligible: boolean; + created_at: number; + updated_at: number; +} +export interface PermissionJSON extends ClerkResourceJSON { + object: typeof ObjectType.Permission; + key: string; + name: string; + description: string; + created_at: number; + updated_at: number; +} +export interface SamlAccountConnectionJSON extends ClerkResourceJSON { + id: string; + name: string; + domain: string; + active: boolean; + provider: string; + sync_user_attributes: boolean; + allow_subdomains: boolean; + allow_idp_initiated: boolean; + disable_additional_identifications: boolean; + created_at: number; + updated_at: number; +} +export interface MachineJSON extends ClerkResourceJSON { + object: typeof ObjectType.Machine; + id: string; + name: string; + instance_id: string; + created_at: number; + updated_at: number; + default_token_ttl: number; + scoped_machines: MachineJSON[]; + secret_key?: string; +} +export interface MachineScopeJSON { + object: typeof ObjectType.MachineScope; + from_machine_id: string; + to_machine_id: string; + created_at?: number; + deleted?: boolean; +} +export interface MachineSecretKeyJSON { + object: typeof ObjectType.MachineSecretKey; + secret: string; +} +export interface M2MTokenJSON extends ClerkResourceJSON { + object: typeof ObjectType.M2MToken; + token?: string; + subject: string; + scopes: string[]; + claims: Record | null; + revoked: boolean; + revocation_reason: string | null; + expired: boolean; + expiration: number | null; + created_at: number; + updated_at: number; +} +export interface APIKeyJSON extends ClerkResourceJSON { + object: typeof ObjectType.ApiKey; + type: string; + name: string; + secret?: string; + subject: string; + scopes: string[]; + claims: Record | null; + revoked: boolean; + revocation_reason: string | null; + expired: boolean; + expiration: number | null; + created_by: string | null; + description: string | null; + last_used_at: number | null; + created_at: number; + updated_at: number; +} +export interface IdPOAuthAccessTokenJSON extends ClerkResourceJSON { + object: typeof ObjectType.IdpOAuthAccessToken; + client_id: string; + type: string; + subject: string; + scopes: string[]; + revoked: boolean; + revocation_reason: string | null; + expired: boolean; + expiration: number | null; + created_at: number; + updated_at: number; +} +export interface BillingPayerJSON extends ClerkResourceJSON { + object: typeof ObjectType.BillingPayer; + instance_id: string; + user_id?: string; + first_name?: string; + last_name?: string; + email: string; + organization_id?: string; + organization_name?: string; + image_url: string; + created_at: number; + updated_at: number; +} +interface BillingPayeeJSON { + id: string; + gateway_type: string; + gateway_external_id: string; + gateway_status: 'active' | 'pending' | 'restricted' | 'disconnected'; +} +interface BillingMoneyAmountJSON { + amount: number; + amount_formatted: string; + currency: string; + currency_symbol: string; +} +interface BillingTotalsJSON { + subtotal: BillingMoneyAmountJSON; + tax_total: BillingMoneyAmountJSON; + grand_total: BillingMoneyAmountJSON; +} +export interface FeatureJSON extends ClerkResourceJSON { + object: typeof ObjectType.Feature; + name: string; + description: string; + slug: string; + avatar_url: string; +} +/** + * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. + */ +export interface BillingPlanJSON extends ClerkResourceJSON { + object: typeof ObjectType.BillingPlan; + id: string; + product_id: string; + name: string; + slug: string; + description?: string; + is_default: boolean; + is_recurring: boolean; + has_base_fee: boolean; + publicly_visible: boolean; + fee: BillingMoneyAmountJSON; + annual_fee: BillingMoneyAmountJSON; + annual_monthly_fee: BillingMoneyAmountJSON; + for_payer_type: 'org' | 'user'; + features: FeatureJSON[]; +} +type BillingSubscriptionItemStatus = 'abandoned' | 'active' | 'canceled' | 'ended' | 'expired' | 'incomplete' | 'past_due' | 'upcoming'; +/** + * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. + */ +export interface BillingSubscriptionItemJSON extends ClerkResourceJSON { + object: typeof ObjectType.BillingSubscriptionItem; + status: BillingSubscriptionItemStatus; + plan_period: 'month' | 'annual'; + payer_id: string; + period_start: number; + period_end: number | null; + is_free_trial?: boolean; + ended_at: number | null; + created_at: number; + updated_at: number; + canceled_at: number | null; + past_due_at: number | null; + lifetime_paid: BillingMoneyAmountJSON; + next_payment: { + amount: number; + date: number; + } | null; + amount: BillingMoneyAmountJSON | null; + plan: BillingPlanJSON; + plan_id: string; +} +/** + * Webhooks specific interface for BillingSubscriptionItem. + */ +export interface BillingSubscriptionItemWebhookEventJSON extends ClerkResourceJSON { + object: typeof ObjectType.BillingSubscriptionItem; + status: BillingSubscriptionItemStatus; + credit: { + amount: BillingMoneyAmountJSON; + cycle_days_remaining: number; + cycle_days_total: number; + cycle_remaining_percent: number; + }; + proration_date: string; + plan_period: 'month' | 'annual'; + period_start: number; + period_end?: number; + canceled_at?: number; + past_due_at?: number; + lifetime_paid: number; + next_payment_amount: number; + next_payment_date: number; + amount: BillingMoneyAmountJSON; + plan: { + id: string; + instance_id: string; + product_id: string; + name: string; + slug: string; + description?: string; + is_default: boolean; + is_recurring: boolean; + amount: number; + period: 'month' | 'annual'; + interval: number; + has_base_fee: boolean; + currency: string; + annual_monthly_amount: number; + publicly_visible: boolean; + }; + plan_id: string; +} +/** + * Webhooks specific interface for BillingPaymentAttempt. + */ +export interface BillingPaymentAttemptWebhookEventJSON extends ClerkResourceJSON { + object: typeof ObjectType.BillingPaymentAttempt; + instance_id: string; + payment_id: string; + statement_id: string; + gateway_external_id: string; + status: 'pending' | 'paid' | 'failed'; + created_at: number; + updated_at: number; + paid_at?: number; + failed_at?: number; + failed_reason?: { + code: string; + decline_code: string; + }; + billing_date: number; + charge_type: 'checkout' | 'recurring'; + payee: BillingPayeeJSON; + payer: BillingPayerJSON; + totals: BillingTotalsJSON; + payment_source: { + id: string; + gateway: string; + gateway_external_id: string; + gateway_external_account_id?: string; + payment_method: string; + status: 'active' | 'disconnected'; + card_type?: string; + last4?: string; + }; + subscription_items: BillingSubscriptionItemWebhookEventJSON[]; +} +/** + * Webhooks specific interface for BillingSubscription. + */ +export interface BillingSubscriptionWebhookEventJSON extends ClerkResourceJSON { + object: typeof ObjectType.BillingSubscription; + status: 'abandoned' | 'active' | 'canceled' | 'ended' | 'expired' | 'incomplete' | 'past_due' | 'upcoming'; + active_at?: number; + canceled_at?: number; + created_at: number; + ended_at?: number; + past_due_at?: number; + updated_at: number; + latest_payment_id: string; + payer_id: string; + payer: BillingPayerJSON; + payment_source_id: string; + items: BillingSubscriptionItemWebhookEventJSON[]; +} +export interface BillingSubscriptionJSON extends ClerkResourceJSON { + object: typeof ObjectType.BillingSubscription; + status: 'active' | 'past_due' | 'canceled' | 'ended' | 'abandoned' | 'incomplete'; + payer_id: string; + created_at: number; + updated_at: number; + active_at: number | null; + past_due_at: number | null; + subscription_items: BillingSubscriptionItemJSON[]; + next_payment?: { + date: number; + amount: BillingMoneyAmountJSON; + }; + eligible_for_free_trial?: boolean; +} +export interface WebhooksSvixJSON { + svix_url: string; +} +export {}; +//# sourceMappingURL=JSON.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/JSON.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/resources/JSON.d.ts.map new file mode 100644 index 000000000..aedf6030e --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/JSON.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"JSON.d.ts","sourceRoot":"","sources":["../../../src/api/resources/JSON.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,0BAA0B,EAAE,YAAY,EAAE,kBAA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,gBAAgB;IAC/B,QAAQ,EAAE,MAAM,CAAC;CAClB"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/JwtTemplate.d.ts b/backend/node_modules/@clerk/backend/dist/api/resources/JwtTemplate.d.ts new file mode 100644 index 000000000..a09577f79 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/JwtTemplate.d.ts @@ -0,0 +1,15 @@ +import type { JwtTemplateJSON } from './JSON'; +export declare class JwtTemplate { + readonly id: string; + readonly name: string; + readonly claims: object; + readonly lifetime: number; + readonly allowedClockSkew: number; + readonly customSigningKey: boolean; + readonly signingAlgorithm: string; + readonly createdAt: number; + readonly updatedAt: number; + constructor(id: string, name: string, claims: object, lifetime: number, allowedClockSkew: number, customSigningKey: boolean, signingAlgorithm: string, createdAt: number, updatedAt: number); + static fromJSON(data: JwtTemplateJSON): JwtTemplate; +} +//# sourceMappingURL=JwtTemplate.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/JwtTemplate.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/resources/JwtTemplate.d.ts.map new file mode 100644 index 000000000..1be733a59 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/JwtTemplate.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"JwtTemplate.d.ts","sourceRoot":"","sources":["../../../src/api/resources/JwtTemplate.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,QAAQ,CAAC;AAE9C,qBAAa,WAAW;IAEpB,QAAQ,CAAC,EAAE,EAAE,MAAM;IACnB,QAAQ,CAAC,IAAI,EAAE,MAAM;IACrB,QAAQ,CAAC,MAAM,EAAE,MAAM;IACvB,QAAQ,CAAC,QAAQ,EAAE,MAAM;IACzB,QAAQ,CAAC,gBAAgB,EAAE,MAAM;IACjC,QAAQ,CAAC,gBAAgB,EAAE,OAAO;IAClC,QAAQ,CAAC,gBAAgB,EAAE,MAAM;IACjC,QAAQ,CAAC,SAAS,EAAE,MAAM;IAC1B,QAAQ,CAAC,SAAS,EAAE,MAAM;gBARjB,EAAE,EAAE,MAAM,EACV,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,MAAM,EAChB,gBAAgB,EAAE,MAAM,EACxB,gBAAgB,EAAE,OAAO,EACzB,gBAAgB,EAAE,MAAM,EACxB,SAAS,EAAE,MAAM,EACjB,SAAS,EAAE,MAAM;IAG5B,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,eAAe,GAAG,WAAW;CAapD"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/M2MToken.d.ts b/backend/node_modules/@clerk/backend/dist/api/resources/M2MToken.d.ts new file mode 100644 index 000000000..63ccfd892 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/M2MToken.d.ts @@ -0,0 +1,20 @@ +import type { M2MTokenJSON } from './JSON'; +/** + * The Backend `M2MToken` object holds information about a machine-to-machine token. + */ +export declare class M2MToken { + readonly id: string; + readonly subject: string; + readonly scopes: string[]; + readonly claims: Record | null; + readonly revoked: boolean; + readonly revocationReason: string | null; + readonly expired: boolean; + readonly expiration: number | null; + readonly createdAt: number; + readonly updatedAt: number; + readonly token?: string | undefined; + constructor(id: string, subject: string, scopes: string[], claims: Record | null, revoked: boolean, revocationReason: string | null, expired: boolean, expiration: number | null, createdAt: number, updatedAt: number, token?: string | undefined); + static fromJSON(data: M2MTokenJSON): M2MToken; +} +//# sourceMappingURL=M2MToken.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/M2MToken.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/resources/M2MToken.d.ts.map new file mode 100644 index 000000000..afe217783 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/M2MToken.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"M2MToken.d.ts","sourceRoot":"","sources":["../../../src/api/resources/M2MToken.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AAE3C;;GAEG;AACH,qBAAa,QAAQ;IAEjB,QAAQ,CAAC,EAAE,EAAE,MAAM;IACnB,QAAQ,CAAC,OAAO,EAAE,MAAM;IACxB,QAAQ,CAAC,MAAM,EAAE,MAAM,EAAE;IACzB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,IAAI;IAC3C,QAAQ,CAAC,OAAO,EAAE,OAAO;IACzB,QAAQ,CAAC,gBAAgB,EAAE,MAAM,GAAG,IAAI;IACxC,QAAQ,CAAC,OAAO,EAAE,OAAO;IACzB,QAAQ,CAAC,UAAU,EAAE,MAAM,GAAG,IAAI;IAClC,QAAQ,CAAC,SAAS,EAAE,MAAM;IAC1B,QAAQ,CAAC,SAAS,EAAE,MAAM;IAC1B,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM;gBAVd,EAAE,EAAE,MAAM,EACV,OAAO,EAAE,MAAM,EACf,MAAM,EAAE,MAAM,EAAE,EAChB,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,IAAI,EAClC,OAAO,EAAE,OAAO,EAChB,gBAAgB,EAAE,MAAM,GAAG,IAAI,EAC/B,OAAO,EAAE,OAAO,EAChB,UAAU,EAAE,MAAM,GAAG,IAAI,EACzB,SAAS,EAAE,MAAM,EACjB,SAAS,EAAE,MAAM,EACjB,KAAK,CAAC,EAAE,MAAM,YAAA;IAGzB,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,YAAY,GAAG,QAAQ;CAe9C"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/Machine.d.ts b/backend/node_modules/@clerk/backend/dist/api/resources/Machine.d.ts new file mode 100644 index 000000000..aa49bb1a1 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/Machine.d.ts @@ -0,0 +1,17 @@ +import type { MachineJSON } from './JSON'; +/** + * The Backend `Machine` object holds information about a machine. + */ +export declare class Machine { + readonly id: string; + readonly name: string; + readonly instanceId: string; + readonly createdAt: number; + readonly updatedAt: number; + readonly scopedMachines: Machine[]; + readonly defaultTokenTtl: number; + readonly secretKey?: string | undefined; + constructor(id: string, name: string, instanceId: string, createdAt: number, updatedAt: number, scopedMachines: Machine[], defaultTokenTtl: number, secretKey?: string | undefined); + static fromJSON(data: MachineJSON): Machine; +} +//# sourceMappingURL=Machine.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/Machine.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/resources/Machine.d.ts.map new file mode 100644 index 000000000..4f7f886a4 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/Machine.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"Machine.d.ts","sourceRoot":"","sources":["../../../src/api/resources/Machine.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,QAAQ,CAAC;AAE1C;;GAEG;AACH,qBAAa,OAAO;IAEhB,QAAQ,CAAC,EAAE,EAAE,MAAM;IACnB,QAAQ,CAAC,IAAI,EAAE,MAAM;IACrB,QAAQ,CAAC,UAAU,EAAE,MAAM;IAC3B,QAAQ,CAAC,SAAS,EAAE,MAAM;IAC1B,QAAQ,CAAC,SAAS,EAAE,MAAM;IAC1B,QAAQ,CAAC,cAAc,EAAE,OAAO,EAAE;IAClC,QAAQ,CAAC,eAAe,EAAE,MAAM;IAChC,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM;gBAPlB,EAAE,EAAE,MAAM,EACV,IAAI,EAAE,MAAM,EACZ,UAAU,EAAE,MAAM,EAClB,SAAS,EAAE,MAAM,EACjB,SAAS,EAAE,MAAM,EACjB,cAAc,EAAE,OAAO,EAAE,EACzB,eAAe,EAAE,MAAM,EACvB,SAAS,CAAC,EAAE,MAAM,YAAA;IAG7B,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,WAAW,GAAG,OAAO;CAuB5C"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/MachineScope.d.ts b/backend/node_modules/@clerk/backend/dist/api/resources/MachineScope.d.ts new file mode 100644 index 000000000..212fc31d1 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/MachineScope.d.ts @@ -0,0 +1,13 @@ +import type { MachineScopeJSON } from './JSON'; +/** + * The Backend `MachineScope` object holds information about a machine scope. + */ +export declare class MachineScope { + readonly fromMachineId: string; + readonly toMachineId: string; + readonly createdAt?: number | undefined; + readonly deleted?: boolean | undefined; + constructor(fromMachineId: string, toMachineId: string, createdAt?: number | undefined, deleted?: boolean | undefined); + static fromJSON(data: MachineScopeJSON): MachineScope; +} +//# sourceMappingURL=MachineScope.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/MachineScope.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/resources/MachineScope.d.ts.map new file mode 100644 index 000000000..faa1eee2c --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/MachineScope.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"MachineScope.d.ts","sourceRoot":"","sources":["../../../src/api/resources/MachineScope.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,QAAQ,CAAC;AAE/C;;GAEG;AACH,qBAAa,YAAY;IAErB,QAAQ,CAAC,aAAa,EAAE,MAAM;IAC9B,QAAQ,CAAC,WAAW,EAAE,MAAM;IAC5B,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM;IAC3B,QAAQ,CAAC,OAAO,CAAC,EAAE,OAAO;gBAHjB,aAAa,EAAE,MAAM,EACrB,WAAW,EAAE,MAAM,EACnB,SAAS,CAAC,EAAE,MAAM,YAAA,EAClB,OAAO,CAAC,EAAE,OAAO,YAAA;IAG5B,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,gBAAgB,GAAG,YAAY;CAGtD"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/MachineSecretKey.d.ts b/backend/node_modules/@clerk/backend/dist/api/resources/MachineSecretKey.d.ts new file mode 100644 index 000000000..8c9d9fe86 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/MachineSecretKey.d.ts @@ -0,0 +1,10 @@ +import type { MachineSecretKeyJSON } from './JSON'; +/** + * The Backend `MachineSecretKey` object holds information about a machine secret key. + */ +export declare class MachineSecretKey { + readonly secret: string; + constructor(secret: string); + static fromJSON(data: MachineSecretKeyJSON): MachineSecretKey; +} +//# sourceMappingURL=MachineSecretKey.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/MachineSecretKey.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/resources/MachineSecretKey.d.ts.map new file mode 100644 index 000000000..c8b116879 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/MachineSecretKey.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"MachineSecretKey.d.ts","sourceRoot":"","sources":["../../../src/api/resources/MachineSecretKey.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,QAAQ,CAAC;AAEnD;;GAEG;AACH,qBAAa,gBAAgB;IACf,QAAQ,CAAC,MAAM,EAAE,MAAM;gBAAd,MAAM,EAAE,MAAM;IAEnC,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,oBAAoB,GAAG,gBAAgB;CAG9D"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/OAuthApplication.d.ts b/backend/node_modules/@clerk/backend/dist/api/resources/OAuthApplication.d.ts new file mode 100644 index 000000000..76f4ebf81 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/OAuthApplication.d.ts @@ -0,0 +1,169 @@ +import type { OAuthApplicationJSON } from './JSON'; +/** + * The Backend `OAuthApplication` object holds information about an OAuth application. + */ +export declare class OAuthApplication { + /** + * The unique identifier for the OAuth application. + */ + readonly id: string; + /** + * The ID of the instance that this OAuth application belongs to. + */ + readonly instanceId: string; + /** + * The name of the new OAuth application. + */ + readonly name: string; + /** + * The ID of the client associated with the OAuth application. + */ + readonly clientId: string; + /** + * The public-facing URL of the OAuth application, often shown on consent screens. + */ + readonly clientUri: string | null; + /** + * The URL of the image or logo representing the OAuth application. + */ + readonly clientImageUrl: string | null; + /** + * Specifies whether the OAuth application is dynamically registered. + */ + readonly dynamicallyRegistered: boolean; + /** + * Specifies whether the consent screen should be displayed in the authentication flow. Cannot be disabled for dynamically registered OAuth applications. + */ + readonly consentScreenEnabled: boolean; + /** + * Specifies whether the Proof Key of Code Exchange (PKCE) flow should be required in the authentication flow. + */ + readonly pkceRequired: boolean; + /** + * Indicates whether the client is public. If true, the Proof Key of Code Exchange (PKCE) flow can be used. + */ + readonly isPublic: boolean; + /** + * Scopes for the new OAuth application. + */ + readonly scopes: string; + /** + * An array of redirect URIs of the new OAuth application. + */ + readonly redirectUris: Array; + /** + * The URL used to authorize the user and obtain an authorization code. + */ + readonly authorizeUrl: string; + /** + * The URL used by the client to exchange an authorization code for an access token. + */ + readonly tokenFetchUrl: string; + /** + * The URL where the client can retrieve user information using an access token. + */ + readonly userInfoUrl: string; + /** + * The OpenID Connect discovery endpoint URL for this OAuth application. + */ + readonly discoveryUrl: string; + /** + * The URL used to introspect and validate issued access tokens. + */ + readonly tokenIntrospectionUrl: string; + /** + * The date when the OAuth application was first created. + */ + readonly createdAt: number; + /** + * The date when the OAuth application was last updated. + */ + readonly updatedAt: number; + /** + * The client secret associated with the OAuth application. Empty if public client. + */ + readonly clientSecret?: string | undefined; + constructor( + /** + * The unique identifier for the OAuth application. + */ + id: string, + /** + * The ID of the instance that this OAuth application belongs to. + */ + instanceId: string, + /** + * The name of the new OAuth application. + */ + name: string, + /** + * The ID of the client associated with the OAuth application. + */ + clientId: string, + /** + * The public-facing URL of the OAuth application, often shown on consent screens. + */ + clientUri: string | null, + /** + * The URL of the image or logo representing the OAuth application. + */ + clientImageUrl: string | null, + /** + * Specifies whether the OAuth application is dynamically registered. + */ + dynamicallyRegistered: boolean, + /** + * Specifies whether the consent screen should be displayed in the authentication flow. Cannot be disabled for dynamically registered OAuth applications. + */ + consentScreenEnabled: boolean, + /** + * Specifies whether the Proof Key of Code Exchange (PKCE) flow should be required in the authentication flow. + */ + pkceRequired: boolean, + /** + * Indicates whether the client is public. If true, the Proof Key of Code Exchange (PKCE) flow can be used. + */ + isPublic: boolean, // NOTE: `public` is reserved + /** + * Scopes for the new OAuth application. + */ + scopes: string, + /** + * An array of redirect URIs of the new OAuth application. + */ + redirectUris: Array, + /** + * The URL used to authorize the user and obtain an authorization code. + */ + authorizeUrl: string, + /** + * The URL used by the client to exchange an authorization code for an access token. + */ + tokenFetchUrl: string, + /** + * The URL where the client can retrieve user information using an access token. + */ + userInfoUrl: string, + /** + * The OpenID Connect discovery endpoint URL for this OAuth application. + */ + discoveryUrl: string, + /** + * The URL used to introspect and validate issued access tokens. + */ + tokenIntrospectionUrl: string, + /** + * The date when the OAuth application was first created. + */ + createdAt: number, + /** + * The date when the OAuth application was last updated. + */ + updatedAt: number, + /** + * The client secret associated with the OAuth application. Empty if public client. + */ + clientSecret?: string | undefined); + static fromJSON(data: OAuthApplicationJSON): OAuthApplication; +} +//# sourceMappingURL=OAuthApplication.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/OAuthApplication.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/resources/OAuthApplication.d.ts.map new file mode 100644 index 000000000..9f53a3fa5 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/OAuthApplication.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"OAuthApplication.d.ts","sourceRoot":"","sources":["../../../src/api/resources/OAuthApplication.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,QAAQ,CAAC;AAEnD;;GAEG;AACH,q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G;IACM,SAAS,EAAE,MAAM,GAAG,IAAI;IACjC;;OAEG;IACM,cAAc,EAAE,MAAM,GAAG,IAAI;IACtC;;OAEG;IACM,qBAAqB,EAAE,OAAO;IACvC;;OAEG;IACM,oBAAoB,EAAE,OAAO;IACtC;;OAEG;IACM,YAAY,EAAE,OAAO;IAC9B;;OAEG;IACM,QAAQ,EAAE,OAAO,EAAE,6BAA6B;IACzD;;OAEG;IACM,MAAM,EAAE,MAAM;IACvB;;OAEG;IACM,YAAY,EAAE,KAAK,CAAC,MAAM,CAAC;IACpC;;OAEG;IACM,YAAY,EAAE,MAAM;IAC7B;;OAEG;IACM,aAAa,EAAE,MAAM;IAC9B;;OAEG;IACM,WAAW,EAAE,MAAM;IAC5B;;OAEG;IACM,YAAY,EAAE,MAAM;IAC7B;;OAEG;IACM,qBAAqB,EAAE,MAAM;IACtC;;OAEG;IACM,SAAS,EAAE,MAAM;IAC1B;;OAEG;IACM,SAAS,EAAE,MAAM;IAC1B;;OAEG;IACM,YAAY,CAAC,EAAE,MAAM,YAAA;IAGhC,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,oBAAoB;CAwB3C"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/OauthAccessToken.d.ts b/backend/node_modules/@clerk/backend/dist/api/resources/OauthAccessToken.d.ts new file mode 100644 index 000000000..1c0cccb1f --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/OauthAccessToken.d.ts @@ -0,0 +1,14 @@ +import type { OauthAccessTokenJSON } from './JSON'; +export declare class OauthAccessToken { + readonly externalAccountId: string; + readonly provider: string; + readonly token: string; + readonly publicMetadata: Record; + readonly label: string; + readonly scopes?: string[] | undefined; + readonly tokenSecret?: string | undefined; + readonly expiresAt?: number | undefined; + constructor(externalAccountId: string, provider: string, token: string, publicMetadata: Record | undefined, label: string, scopes?: string[] | undefined, tokenSecret?: string | undefined, expiresAt?: number | undefined); + static fromJSON(data: OauthAccessTokenJSON): OauthAccessToken; +} +//# sourceMappingURL=OauthAccessToken.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/OauthAccessToken.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/resources/OauthAccessToken.d.ts.map new file mode 100644 index 000000000..265c9b00d --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/OauthAccessToken.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"OauthAccessToken.d.ts","sourceRoot":"","sources":["../../../src/api/resources/OauthAccessToken.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,QAAQ,CAAC;AAEnD,qBAAa,gBAAgB;IAEzB,QAAQ,CAAC,iBAAiB,EAAE,MAAM;IAClC,QAAQ,CAAC,QAAQ,EAAE,MAAM;IACzB,QAAQ,CAAC,KAAK,EAAE,MAAM;IACtB,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;IAChD,QAAQ,CAAC,KAAK,EAAE,MAAM;IACtB,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE;IAC1B,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM;IAC7B,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM;gBAPlB,iBAAiB,EAAE,MAAM,EACzB,QAAQ,EAAE,MAAM,EAChB,KAAK,EAAE,MAAM,EACb,cAAc,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,YAAK,EAC5C,KAAK,EAAE,MAAM,EACb,MAAM,CAAC,EAAE,MAAM,EAAE,YAAA,EACjB,WAAW,CAAC,EAAE,MAAM,YAAA,EACpB,SAAS,CAAC,EAAE,MAAM,YAAA;IAG7B,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,oBAAoB;CAY3C"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/Organization.d.ts b/backend/node_modules/@clerk/backend/dist/api/resources/Organization.d.ts new file mode 100644 index 000000000..29756776e --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/Organization.d.ts @@ -0,0 +1,115 @@ +import type { OrganizationJSON } from './JSON'; +/** + * The Backend `Organization` object is similar to the [`Organization`](https://clerk.com/docs/references/javascript/organization) object as it holds information about an organization, as well as methods for managing it. However, the Backend `Organization` object is different in that it is used in the [Backend API](https://clerk.com/docs/reference/backend-api/tag/Organizations#operation/ListOrganizations){{ target: '_blank' }} and is not directly accessible from the Frontend API. + */ +export declare class Organization { + /** + * The unique identifier for the organization. + */ + readonly id: string; + /** + * The name of the organization. + */ + readonly name: string; + /** + * The URL-friendly identifier of the user's active organization. If supplied, it must be unique for the instance. + */ + readonly slug: string; + /** + * Holds the organization's logo. Compatible with Clerk's [Image Optimization](https://clerk.com/docs/guides/image-optimization). + */ + readonly imageUrl: string; + /** + * Whether the organization has an image. + */ + readonly hasImage: boolean; + /** + * The date when the organization was first created. + */ + readonly createdAt: number; + /** + * The date when the organization was last updated. + */ + readonly updatedAt: number; + /** + * Metadata that can be read from the Frontend API and [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }} and can be set only from the Backend API. + */ + readonly publicMetadata: OrganizationPublicMetadata | null; + /** + * Metadata that can be read and set only from the [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }}. + */ + readonly privateMetadata: OrganizationPrivateMetadata; + /** + * The maximum number of memberships allowed in the organization. + */ + readonly maxAllowedMemberships: number; + /** + * Whether the organization allows admins to delete users. + */ + readonly adminDeleteEnabled: boolean; + /** + * The number of members in the organization. + */ + readonly membersCount?: number | undefined; + /** + * The ID of the user who created the organization. + */ + readonly createdBy?: string | undefined; + private _raw; + get raw(): OrganizationJSON | null; + constructor( + /** + * The unique identifier for the organization. + */ + id: string, + /** + * The name of the organization. + */ + name: string, + /** + * The URL-friendly identifier of the user's active organization. If supplied, it must be unique for the instance. + */ + slug: string, + /** + * Holds the organization's logo. Compatible with Clerk's [Image Optimization](https://clerk.com/docs/guides/image-optimization). + */ + imageUrl: string, + /** + * Whether the organization has an image. + */ + hasImage: boolean, + /** + * The date when the organization was first created. + */ + createdAt: number, + /** + * The date when the organization was last updated. + */ + updatedAt: number, + /** + * Metadata that can be read from the Frontend API and [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }} and can be set only from the Backend API. + */ + publicMetadata: (OrganizationPublicMetadata | null) | undefined, + /** + * Metadata that can be read and set only from the [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }}. + */ + privateMetadata: OrganizationPrivateMetadata | undefined, + /** + * The maximum number of memberships allowed in the organization. + */ + maxAllowedMemberships: number, + /** + * Whether the organization allows admins to delete users. + */ + adminDeleteEnabled: boolean, + /** + * The number of members in the organization. + */ + membersCount?: number | undefined, + /** + * The ID of the user who created the organization. + */ + createdBy?: string | undefined); + static fromJSON(data: OrganizationJSON): Organization; +} +//# sourceMappingURL=Organization.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/Organization.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/resources/Organization.d.ts.map new file mode 100644 index 000000000..6de935fb7 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/Organization.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"Organization.d.ts","sourceRoot":"","sources":["../../../src/api/resources/Organization.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,QAAQ,CAAC;AAE/C;;GAEG;AACH,qBAAa,YAAY;IAQrB;;OAEG;IACH,QAAQ,CAAC,EAAE,EAAE,MAAM;IACnB;;OAEG;IACH,QAAQ,CAAC,IAAI,EAAE,MAAM;IACrB;;OAEG;IACH,QAAQ,CAAC,IAAI,EAAE,MAAM;IACrB;;OAEG;IACH,QAAQ,CAAC,QAAQ,EAAE,MAAM;IACzB;;OAEG;IACH,QAAQ,CAAC,QAAQ,EAAE,OAAO;IAC1B;;OAEG;IACH,QAAQ,CAAC,SAAS,EAAE,MAAM;IAC1B;;OAEG;IACH,QAAQ,CAAC,SAAS,EAAE,MAAM;IAC1B;;OAEG;IACH,QAAQ,CAAC,cAAc,EAAE,0BAA0B,GAAG,IAAI;IAC1D;;OAEG;IACH,QAAQ,CAAC,eAAe,EAAE,2BAA2B;IACrD;;OAEG;IACH,QAAQ,CAAC,qBAAqB,EAAE,MAAM;IACtC;;OAEG;IACH,QAAQ,CAAC,kBAAkB,EAAE,OAAO;IACpC;;OAEG;IACH,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM;IAC9B;;OAEG;IACH,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM;IA1D7B,OAAO,CAAC,IAAI,CAAiC;IAE7C,IAAW,GAAG,IAAI,gBAAgB,GAAG,IAAI,CAExC;;IAGC;;OAEG;IACM,EAAE,EAAE,MAAM;IACnB;;OAEG;IACM,IAAI,EAAE,MAAM;IACrB;;OAEG;IACM,IAAI,EAAE,MAAM;IACrB;;OAEG;IACM,QAAQ,EAAE,MAAM;IACzB;;OAEG;IACM,QAAQ,EAAE,OAAO;IAC1B;;OAEG;IACM,SAAS,EAAE,MAAM;IAC1B;;OAEG;IACM,SAAS,EAAE,MAAM;IAC1B;;OAEG;IACM,cAAc,GAAE,0BAA0B,GAAG,IAAI,aAAK;IAC/D;;OAEG;IACM,eAAe,EAAE,2BAA2B,YAAK;IAC1D;;OAEG;IACM,qBAAqB,EAAE,MAAM;IACtC;;OAEG;IACM,kBAAkB,EAAE,OAAO;IACpC;;OAEG;IACM,YAAY,CAAC,EAAE,MAAM,YAAA;IAC9B;;OAEG;IACM,SAAS,CAAC,EAAE,MAAM,YAAA;IAG7B,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,gBAAgB,GAAG,YAAY;CAmBtD"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/OrganizationDomain.d.ts b/backend/node_modules/@clerk/backend/dist/api/resources/OrganizationDomain.d.ts new file mode 100644 index 000000000..813a653da --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/OrganizationDomain.d.ts @@ -0,0 +1,18 @@ +import type { OrganizationEnrollmentMode } from './Enums'; +import type { OrganizationDomainJSON } from './JSON'; +import { OrganizationDomainVerification } from './Verification'; +export declare class OrganizationDomain { + readonly id: string; + readonly organizationId: string; + readonly name: string; + readonly enrollmentMode: OrganizationEnrollmentMode; + readonly verification: OrganizationDomainVerification | null; + readonly totalPendingInvitations: number; + readonly totalPendingSuggestions: number; + readonly createdAt: number; + readonly updatedAt: number; + readonly affiliationEmailAddress: string | null; + constructor(id: string, organizationId: string, name: string, enrollmentMode: OrganizationEnrollmentMode, verification: OrganizationDomainVerification | null, totalPendingInvitations: number, totalPendingSuggestions: number, createdAt: number, updatedAt: number, affiliationEmailAddress: string | null); + static fromJSON(data: OrganizationDomainJSON): OrganizationDomain; +} +//# sourceMappingURL=OrganizationDomain.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/OrganizationDomain.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/resources/OrganizationDomain.d.ts.map new file mode 100644 index 000000000..205d710f5 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/OrganizationDomain.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"OrganizationDomain.d.ts","sourceRoot":"","sources":["../../../src/api/resources/OrganizationDomain.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,SAAS,CAAC;AAC1D,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,QAAQ,CAAC;AACrD,OAAO,EAAE,8BAA8B,EAAE,MAAM,gBAAgB,CAAC;AAEhE,qBAAa,kBAAkB;IAE3B,QAAQ,CAAC,EAAE,EAAE,MAAM;IACnB,QAAQ,CAAC,cAAc,EAAE,MAAM;IAC/B,QAAQ,CAAC,IAAI,EAAE,MAAM;IACrB,QAAQ,CAAC,cAAc,EAAE,0BAA0B;IACnD,QAAQ,CAAC,YAAY,EAAE,8BAA8B,GAAG,IAAI;IAC5D,QAAQ,CAAC,uBAAuB,EAAE,MAAM;IACxC,QAAQ,CAAC,uBAAuB,EAAE,MAAM;IACxC,QAAQ,CAAC,SAAS,EAAE,MAAM;IAC1B,QAAQ,CAAC,SAAS,EAAE,MAAM;IAC1B,QAAQ,CAAC,uBAAuB,EAAE,MAAM,GAAG,IAAI;gBATtC,EAAE,EAAE,MAAM,EACV,cAAc,EAAE,MAAM,EACtB,IAAI,EAAE,MAAM,EACZ,cAAc,EAAE,0BAA0B,EAC1C,YAAY,EAAE,8BAA8B,GAAG,IAAI,EACnD,uBAAuB,EAAE,MAAM,EAC/B,uBAAuB,EAAE,MAAM,EAC/B,SAAS,EAAE,MAAM,EACjB,SAAS,EAAE,MAAM,EACjB,uBAAuB,EAAE,MAAM,GAAG,IAAI;IAGjD,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,sBAAsB;CAc7C"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/OrganizationInvitation.d.ts b/backend/node_modules/@clerk/backend/dist/api/resources/OrganizationInvitation.d.ts new file mode 100644 index 000000000..89f407854 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/OrganizationInvitation.d.ts @@ -0,0 +1,116 @@ +import type { OrganizationInvitationStatus, OrganizationMembershipRole } from './Enums'; +import type { OrganizationInvitationJSON, PublicOrganizationDataJSON } from './JSON'; +/** + * The Backend `OrganizationInvitation` object is similar to the [`OrganizationInvitation`](https://clerk.com/docs/references/javascript/types/organization-invitation) object as it's the model around an organization invitation. However, the Backend `OrganizationInvitation` object is different in that it's used in the [Backend API](https://clerk.com/docs/reference/backend-api/tag/Organization-Invitations#operation/CreateOrganizationInvitation){{ target: '_blank' }} and is not directly accessible from the Frontend API. + */ +export declare class OrganizationInvitation { + /** + * The unique identifier for the `OrganizationInvitation`. + */ + readonly id: string; + /** + * The email address of the user who is invited to the [`Organization`](https://clerk.com/docs/references/backend/types/backend-organization). + */ + readonly emailAddress: string; + /** + * The role of the invited user. + */ + readonly role: OrganizationMembershipRole; + /** + * The name of the role of the invited user. + */ + readonly roleName: string; + /** + * The ID of the [`Organization`](https://clerk.com/docs/references/backend/types/backend-organization) that the user is invited to. + */ + readonly organizationId: string; + /** + * The date when the invitation was first created. + */ + readonly createdAt: number; + /** + * The date when the invitation was last updated. + */ + readonly updatedAt: number; + /** + * The date when the invitation expires. + */ + readonly expiresAt: number; + /** + * The URL that the user can use to accept the invitation. + */ + readonly url: string | null; + /** + * The status of the invitation. + */ + readonly status?: OrganizationInvitationStatus | undefined; + /** + * Metadata that can be read from the Frontend API and [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }} and can be set only from the Backend API. + */ + readonly publicMetadata: OrganizationInvitationPublicMetadata; + /** + * Metadata that can be read and set only from the [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }}. + */ + readonly privateMetadata: OrganizationInvitationPrivateMetadata; + /** + * Public data about the organization that the user is invited to. + */ + readonly publicOrganizationData?: (PublicOrganizationDataJSON | null) | undefined; + private _raw; + get raw(): OrganizationInvitationJSON | null; + constructor( + /** + * The unique identifier for the `OrganizationInvitation`. + */ + id: string, + /** + * The email address of the user who is invited to the [`Organization`](https://clerk.com/docs/references/backend/types/backend-organization). + */ + emailAddress: string, + /** + * The role of the invited user. + */ + role: OrganizationMembershipRole, + /** + * The name of the role of the invited user. + */ + roleName: string, + /** + * The ID of the [`Organization`](https://clerk.com/docs/references/backend/types/backend-organization) that the user is invited to. + */ + organizationId: string, + /** + * The date when the invitation was first created. + */ + createdAt: number, + /** + * The date when the invitation was last updated. + */ + updatedAt: number, + /** + * The date when the invitation expires. + */ + expiresAt: number, + /** + * The URL that the user can use to accept the invitation. + */ + url: string | null, + /** + * The status of the invitation. + */ + status?: OrganizationInvitationStatus | undefined, + /** + * Metadata that can be read from the Frontend API and [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }} and can be set only from the Backend API. + */ + publicMetadata?: OrganizationInvitationPublicMetadata, + /** + * Metadata that can be read and set only from the [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }}. + */ + privateMetadata?: OrganizationInvitationPrivateMetadata, + /** + * Public data about the organization that the user is invited to. + */ + publicOrganizationData?: (PublicOrganizationDataJSON | null) | undefined); + static fromJSON(data: OrganizationInvitationJSON): OrganizationInvitation; +} +//# sourceMappingURL=OrganizationInvitation.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/OrganizationInvitation.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/resources/OrganizationInvitation.d.ts.map new file mode 100644 index 000000000..2a911a5cb --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/OrganizationInvitation.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"OrganizationInvitation.d.ts","sourceRoot":"","sources":["../../../src/api/resources/OrganizationInvitation.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,4BAA4B,EAAE,0BAA0B,EAAE,MAAM,SAAS,CAAC;AACxF,OAAO,KAAK,EAAE,0BAA0B,EAAE,0BAA0B,EAAE,MAAM,QAAQ,CAAC;AAErF;;GAEG;AACH,qBAAa,sBAAsB;IAQ/B;;OAEG;IACH,QAAQ,CAAC,EAAE,EAAE,MAAM;IACnB;;OAEG;IACH,QAAQ,CAAC,YAAY,EAAE,MAAM;IAC7B;;OAEG;IACH,QAAQ,CAAC,IAAI,EAAE,0BAA0B;IACzC;;OAEG;IACH,QAAQ,CAAC,QAAQ,EAAE,MAAM;IACzB;;OAEG;IACH,QAAQ,CAAC,cAAc,EAAE,MAAM;IAC/B;;OAEG;IACH,QAAQ,CAAC,SAAS,EAAE,MAAM;IAC1B;;OAEG;IACH,QAAQ,CAAC,SAAS,EAAE,MAAM;IAC1B;;OAEG;IACH,QAAQ,CAAC,SAAS,EAAE,MAAM;IAC1B;;OAEG;IACH,QAAQ,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI;IAC3B;;OAEG;IACH,QAAQ,CAAC,MAAM,CAAC,EAAE,4BAA4B;IAC9C;;OAEG;IACH,QAAQ,CAAC,cAAc,EAAE,oCAAoC;IAC7D;;OAEG;IACH,QAAQ,CAAC,eAAe,EAAE,qCAAqC;IAC/D;;OAEG;IACH,QAAQ,CAAC,sBAAsB,CAAC,GAAE,0BAA0B,GAAG,IAAI;IA1DrE,OAAO,CAAC,IAAI,CAA2C;IAEvD,IAAW,GAAG,IAAI,0BAA0B,GAAG,IAAI,CAElD;;IAGC;;OAEG;IACM,EAAE,EAAE,MAAM;IACnB;;OAEG;IACM,YAAY,EAAE,MAAM;IAC7B;;OAEG;IACM,IAAI,EAAE,0BAA0B;IACzC;;OAEG;IACM,QAAQ,EAAE,MAAM;IACzB;;OAEG;IACM,cAAc,EAAE,MAAM;IAC/B;;OAEG;IACM,SAAS,EAAE,MAAM;IAC1B;;OAEG;IACM,SAAS,EAAE,MAAM;IAC1B;;OAEG;IACM,SAAS,EAAE,MAAM;IAC1B;;OAEG;IACM,GAAG,EAAE,MAAM,GAAG,IAAI;IAC3B;;OAEG;IACM,MAAM,CAAC,EAAE,4BAA4B,YAAA;IAC9C;;OAEG;IACM,cAAc,GAAE,oCAAyC;IAClE;;OAEG;IACM,eAAe,GAAE,qCAA0C;IACpE;;OAEG;IACM,sBAAsB,CAAC,GAAE,0BAA0B,GAAG,IAAI,aAAA;IAGrE,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,0BAA0B;CAmBjD"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/OrganizationMembership.d.ts b/backend/node_modules/@clerk/backend/dist/api/resources/OrganizationMembership.d.ts new file mode 100644 index 000000000..4337f0bc0 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/OrganizationMembership.d.ts @@ -0,0 +1,140 @@ +import { Organization } from '../resources'; +import type { OrganizationMembershipRole } from './Enums'; +import type { OrganizationMembershipJSON, OrganizationMembershipPublicUserDataJSON } from './JSON'; +/** + * The Backend `OrganizationMembership` object is similar to the [`OrganizationMembership`](https://clerk.com/docs/references/javascript/types/organization-membership) object as it's the model around an organization membership entity and describes the relationship between users and organizations. However, the Backend `OrganizationMembership` object is different in that it's used in the [Backend API](https://clerk.com/docs/reference/backend-api/tag/Organization-Memberships#operation/CreateOrganizationMembership){{ target: '_blank' }} and is not directly accessible from the Frontend API. + */ +export declare class OrganizationMembership { + /** + * The unique identifier for the membership. + */ + readonly id: string; + /** + * The role of the user. + */ + readonly role: OrganizationMembershipRole; + /** + * The permissions granted to the user in the organization. + */ + readonly permissions: string[]; + /** + * Metadata that can be read from the Frontend API and [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }} and can be set only from the Backend API. + */ + readonly publicMetadata: OrganizationMembershipPublicMetadata; + /** + * Metadata that can be read and set only from the [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }}. + */ + readonly privateMetadata: OrganizationMembershipPrivateMetadata; + /** + * The date when the membership was first created. + */ + readonly createdAt: number; + /** + * The date when the membership was last updated. + */ + readonly updatedAt: number; + /** + * The organization that the user is a member of. + */ + readonly organization: Organization; + /** + * Public information about the user that this membership belongs to. + */ + readonly publicUserData?: (OrganizationMembershipPublicUserData | null) | undefined; + private _raw; + get raw(): OrganizationMembershipJSON | null; + constructor( + /** + * The unique identifier for the membership. + */ + id: string, + /** + * The role of the user. + */ + role: OrganizationMembershipRole, + /** + * The permissions granted to the user in the organization. + */ + permissions: string[], + /** + * Metadata that can be read from the Frontend API and [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }} and can be set only from the Backend API. + */ + publicMetadata: OrganizationMembershipPublicMetadata | undefined, + /** + * Metadata that can be read and set only from the [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }}. + */ + privateMetadata: OrganizationMembershipPrivateMetadata | undefined, + /** + * The date when the membership was first created. + */ + createdAt: number, + /** + * The date when the membership was last updated. + */ + updatedAt: number, + /** + * The organization that the user is a member of. + */ + organization: Organization, + /** + * Public information about the user that this membership belongs to. + */ + publicUserData?: (OrganizationMembershipPublicUserData | null) | undefined); + static fromJSON(data: OrganizationMembershipJSON): OrganizationMembership; +} +/** + * @class + */ +export declare class OrganizationMembershipPublicUserData { + /** + * The [identifier](https://clerk.com/docs/authentication/configuration/sign-up-sign-in-options#identifiers) of the user. + */ + readonly identifier: string; + /** + * The first name of the user. + */ + readonly firstName: string | null; + /** + * The last name of the user. + */ + readonly lastName: string | null; + /** + * Holds the default avatar or user's uploaded profile image. Compatible with Clerk's [Image Optimization](https://clerk.com/docs/guides/image-optimization). + */ + readonly imageUrl: string; + /** + * Whether the user has a profile picture. + */ + readonly hasImage: boolean; + /** + * The ID of the user that this public data belongs to. + */ + readonly userId: string; + constructor( + /** + * The [identifier](https://clerk.com/docs/authentication/configuration/sign-up-sign-in-options#identifiers) of the user. + */ + identifier: string, + /** + * The first name of the user. + */ + firstName: string | null, + /** + * The last name of the user. + */ + lastName: string | null, + /** + * Holds the default avatar or user's uploaded profile image. Compatible with Clerk's [Image Optimization](https://clerk.com/docs/guides/image-optimization). + */ + imageUrl: string, + /** + * Whether the user has a profile picture. + */ + hasImage: boolean, + /** + * The ID of the user that this public data belongs to. + */ + userId: string); + static fromJSON(data: OrganizationMembershipPublicUserDataJSON): OrganizationMembershipPublicUserData; +} +//# sourceMappingURL=OrganizationMembership.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/OrganizationMembership.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/resources/OrganizationMembership.d.ts.map new file mode 100644 index 000000000..cf63d8998 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/OrganizationMembership.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"OrganizationMembership.d.ts","sourceRoot":"","sources":["../../../src/api/resources/OrganizationMembership.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,SAAS,CA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,CAAC,SAAS,EAAE,MAAM,GAAG,IAAI;IACjC;;OAEG;IACH,QAAQ,CAAC,QAAQ,EAAE,MAAM,GAAG,IAAI;IAChC;;OAEG;IACH,QAAQ,CAAC,QAAQ,EAAE,MAAM;IACzB;;OAEG;IACH,QAAQ,CAAC,QAAQ,EAAE,OAAO;IAC1B;;OAEG;IACH,QAAQ,CAAC,MAAM,EAAE,MAAM;;IAvBvB;;OAEG;IACM,UAAU,EAAE,MAAM;IAC3B;;OAEG;IACM,SAAS,EAAE,MAAM,GAAG,IAAI;IACjC;;OAEG;IACM,QAAQ,EAAE,MAAM,GAAG,IAAI;IAChC;;OAEG;IACM,QAAQ,EAAE,MAAM;IACzB;;OAEG;IACM,QAAQ,EAAE,OAAO;IAC1B;;OAEG;IACM,MAAM,EAAE,MAAM;IAGzB,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,wCAAwC;CAU/D"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/OrganizationSettings.d.ts b/backend/node_modules/@clerk/backend/dist/api/resources/OrganizationSettings.d.ts new file mode 100644 index 000000000..2febe8230 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/OrganizationSettings.d.ts @@ -0,0 +1,16 @@ +import type { DomainsEnrollmentModes } from './Enums'; +import type { OrganizationSettingsJSON } from './JSON'; +export declare class OrganizationSettings { + readonly enabled: boolean; + readonly maxAllowedMemberships: number; + readonly maxAllowedRoles: number; + readonly maxAllowedPermissions: number; + readonly creatorRole: string; + readonly adminDeleteEnabled: boolean; + readonly domainsEnabled: boolean; + readonly domainsEnrollmentModes: Array; + readonly domainsDefaultRole: string; + constructor(enabled: boolean, maxAllowedMemberships: number, maxAllowedRoles: number, maxAllowedPermissions: number, creatorRole: string, adminDeleteEnabled: boolean, domainsEnabled: boolean, domainsEnrollmentModes: Array, domainsDefaultRole: string); + static fromJSON(data: OrganizationSettingsJSON): OrganizationSettings; +} +//# sourceMappingURL=OrganizationSettings.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/OrganizationSettings.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/resources/OrganizationSettings.d.ts.map new file mode 100644 index 000000000..6b2f516ba --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/OrganizationSettings.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"OrganizationSettings.d.ts","sourceRoot":"","sources":["../../../src/api/resources/OrganizationSettings.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,SAAS,CAAC;AACtD,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,QAAQ,CAAC;AAEvD,qBAAa,oBAAoB;IAE7B,QAAQ,CAAC,OAAO,EAAE,OAAO;IACzB,QAAQ,CAAC,qBAAqB,EAAE,MAAM;IACtC,QAAQ,CAAC,eAAe,EAAE,MAAM;IAChC,QAAQ,CAAC,qBAAqB,EAAE,MAAM;IACtC,QAAQ,CAAC,WAAW,EAAE,MAAM;IAC5B,QAAQ,CAAC,kBAAkB,EAAE,OAAO;IACpC,QAAQ,CAAC,cAAc,EAAE,OAAO;IAChC,QAAQ,CAAC,sBAAsB,EAAE,KAAK,CAAC,sBAAsB,CAAC;IAC9D,QAAQ,CAAC,kBAAkB,EAAE,MAAM;gBAR1B,OAAO,EAAE,OAAO,EAChB,qBAAqB,EAAE,MAAM,EAC7B,eAAe,EAAE,MAAM,EACvB,qBAAqB,EAAE,MAAM,EAC7B,WAAW,EAAE,MAAM,EACnB,kBAAkB,EAAE,OAAO,EAC3B,cAAc,EAAE,OAAO,EACvB,sBAAsB,EAAE,KAAK,CAAC,sBAAsB,CAAC,EACrD,kBAAkB,EAAE,MAAM;IAGrC,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,wBAAwB,GAAG,oBAAoB;CAatE"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/PhoneNumber.d.ts b/backend/node_modules/@clerk/backend/dist/api/resources/PhoneNumber.d.ts new file mode 100644 index 000000000..d4af50bc6 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/PhoneNumber.d.ts @@ -0,0 +1,63 @@ +import { IdentificationLink } from './IdentificationLink'; +import type { PhoneNumberJSON } from './JSON'; +import { Verification } from './Verification'; +/** + * The Backend `PhoneNumber` object describes a phone number. Phone numbers can be used as a proof of identification for users, or simply as a means of contacting users. + * + * Phone numbers must be **verified** to ensure that they can be assigned to their rightful owners. The `PhoneNumber` object holds all the necessary state around the verification process. + * + * Finally, phone numbers can be used as part of [multi-factor authentication](https://clerk.com/docs/authentication/configuration/sign-up-sign-in-options#multi-factor-authentication). During sign in, users can opt in to an extra verification step where they will receive an SMS message with a one-time code. This code must be entered to complete the sign in process. + */ +export declare class PhoneNumber { + /** + * The unique identifier for this phone number. + */ + readonly id: string; + /** + * The value of this phone number, in [E.164 format](https://en.wikipedia.org/wiki/E.164). + */ + readonly phoneNumber: string; + /** + * Set to `true` if this phone number is reserved for multi-factor authentication (2FA). Set to `false` otherwise. + */ + readonly reservedForSecondFactor: boolean; + /** + * Set to `true` if this phone number is the default second factor. Set to `false` otherwise. A user must have exactly one default second factor, if multi-factor authentication (2FA) is enabled. + */ + readonly defaultSecondFactor: boolean; + /** + * An object holding information on the verification of this phone number. + */ + readonly verification: Verification | null; + /** + * An object containing information about any other identification that might be linked to this phone number. + */ + readonly linkedTo: IdentificationLink[]; + constructor( + /** + * The unique identifier for this phone number. + */ + id: string, + /** + * The value of this phone number, in [E.164 format](https://en.wikipedia.org/wiki/E.164). + */ + phoneNumber: string, + /** + * Set to `true` if this phone number is reserved for multi-factor authentication (2FA). Set to `false` otherwise. + */ + reservedForSecondFactor: boolean, + /** + * Set to `true` if this phone number is the default second factor. Set to `false` otherwise. A user must have exactly one default second factor, if multi-factor authentication (2FA) is enabled. + */ + defaultSecondFactor: boolean, + /** + * An object holding information on the verification of this phone number. + */ + verification: Verification | null, + /** + * An object containing information about any other identification that might be linked to this phone number. + */ + linkedTo: IdentificationLink[]); + static fromJSON(data: PhoneNumberJSON): PhoneNumber; +} +//# sourceMappingURL=PhoneNumber.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/PhoneNumber.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/resources/PhoneNumber.d.ts.map new file mode 100644 index 000000000..a1dc5af96 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/PhoneNumber.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"PhoneNumber.d.ts","sourceRoot":"","sources":["../../../src/api/resources/PhoneNumber.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAC1D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,QAAQ,CAAC;AAC9C,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAE9C;;;;;;GAMG;AACH,qBAAa,WAAW;IAEpB;;OAEG;IACH,QAAQ,CAAC,EAAE,EAAE,MAAM;IACnB;;OAEG;IACH,QAAQ,CAAC,WAAW,EAAE,MAAM;IAC5B;;OAEG;IACH,QAAQ,CAAC,uBAAuB,EAAE,OAAO;IACzC;;OAEG;IACH,QAAQ,CAAC,mBAAmB,EAAE,OAAO;IACrC;;OAEG;IACH,QAAQ,CAAC,YAAY,EAAE,YAAY,GAAG,IAAI;IAC1C;;OAEG;IACH,QAAQ,CAAC,QAAQ,EAAE,kBAAkB,EAAE;;IAvBvC;;OAEG;IACM,EAAE,EAAE,MAAM;IACnB;;OAEG;IACM,WAAW,EAAE,MAAM;IAC5B;;OAEG;IACM,uBAAuB,EAAE,OAAO;IACzC;;OAEG;IACM,mBAAmB,EAAE,OAAO;IACrC;;OAEG;IACM,YAAY,EAAE,YAAY,GAAG,IAAI;IAC1C;;OAEG;IACM,QAAQ,EAAE,kBAAkB,EAAE;IAGzC,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,eAAe,GAAG,WAAW;CAUpD"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/ProxyCheck.d.ts b/backend/node_modules/@clerk/backend/dist/api/resources/ProxyCheck.d.ts new file mode 100644 index 000000000..5054d78f8 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/ProxyCheck.d.ts @@ -0,0 +1,13 @@ +import type { ProxyCheckJSON } from './JSON'; +export declare class ProxyCheck { + readonly id: string; + readonly domainId: string; + readonly lastRunAt: number | null; + readonly proxyUrl: string; + readonly successful: boolean; + readonly createdAt: number; + readonly updatedAt: number; + constructor(id: string, domainId: string, lastRunAt: number | null, proxyUrl: string, successful: boolean, createdAt: number, updatedAt: number); + static fromJSON(data: ProxyCheckJSON): ProxyCheck; +} +//# sourceMappingURL=ProxyCheck.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/ProxyCheck.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/resources/ProxyCheck.d.ts.map new file mode 100644 index 000000000..06622c773 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/ProxyCheck.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ProxyCheck.d.ts","sourceRoot":"","sources":["../../../src/api/resources/ProxyCheck.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,QAAQ,CAAC;AAE7C,qBAAa,UAAU;IAEnB,QAAQ,CAAC,EAAE,EAAE,MAAM;IACnB,QAAQ,CAAC,QAAQ,EAAE,MAAM;IACzB,QAAQ,CAAC,SAAS,EAAE,MAAM,GAAG,IAAI;IACjC,QAAQ,CAAC,QAAQ,EAAE,MAAM;IACzB,QAAQ,CAAC,UAAU,EAAE,OAAO;IAC5B,QAAQ,CAAC,SAAS,EAAE,MAAM;IAC1B,QAAQ,CAAC,SAAS,EAAE,MAAM;gBANjB,EAAE,EAAE,MAAM,EACV,QAAQ,EAAE,MAAM,EAChB,SAAS,EAAE,MAAM,GAAG,IAAI,EACxB,QAAQ,EAAE,MAAM,EAChB,UAAU,EAAE,OAAO,EACnB,SAAS,EAAE,MAAM,EACjB,SAAS,EAAE,MAAM;IAG5B,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,cAAc,GAAG,UAAU;CAWlD"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/RedirectUrl.d.ts b/backend/node_modules/@clerk/backend/dist/api/resources/RedirectUrl.d.ts new file mode 100644 index 000000000..05a0e3336 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/RedirectUrl.d.ts @@ -0,0 +1,47 @@ +import type { RedirectUrlJSON } from './JSON'; +/** + * Redirect URLs are whitelisted URLs that facilitate secure authentication flows in native applications (e.g. React Native, Expo). In these contexts, Clerk ensures that security-critical nonces are passed only to the whitelisted URLs. + +The Backend `RedirectUrl` object represents a redirect URL in your application. This object is used in the Backend API. + */ +export declare class RedirectUrl { + /** + * The unique identifier for the redirect URL. + */ + readonly id: string; + /** + * The full URL value prefixed with `https://` or a custom scheme. + * @example https://my-app.com/oauth-callback + * @example my-app://oauth-callback + */ + readonly url: string; + /** + * The date when the redirect URL was first created. + */ + readonly createdAt: number; + /** + * The date when the redirect URL was last updated. + */ + readonly updatedAt: number; + constructor( + /** + * The unique identifier for the redirect URL. + */ + id: string, + /** + * The full URL value prefixed with `https://` or a custom scheme. + * @example https://my-app.com/oauth-callback + * @example my-app://oauth-callback + */ + url: string, + /** + * The date when the redirect URL was first created. + */ + createdAt: number, + /** + * The date when the redirect URL was last updated. + */ + updatedAt: number); + static fromJSON(data: RedirectUrlJSON): RedirectUrl; +} +//# sourceMappingURL=RedirectUrl.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/RedirectUrl.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/resources/RedirectUrl.d.ts.map new file mode 100644 index 000000000..51c41aa79 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/RedirectUrl.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"RedirectUrl.d.ts","sourceRoot":"","sources":["../../../src/api/resources/RedirectUrl.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,QAAQ,CAAC;AAE9C;;;;GAIG;AACH,qBAAa,WAAW;IAEpB;;OAEG;IACH,QAAQ,CAAC,EAAE,EAAE,MAAM;IACnB;;;;OAIG;IACH,QAAQ,CAAC,GAAG,EAAE,MAAM;IACpB;;OAEG;IACH,QAAQ,CAAC,SAAS,EAAE,MAAM;IAC1B;;OAEG;IACH,QAAQ,CAAC,SAAS,EAAE,MAAM;;IAjB1B;;OAEG;IACM,EAAE,EAAE,MAAM;IACnB;;;;OAIG;IACM,GAAG,EAAE,MAAM;IACpB;;OAEG;IACM,SAAS,EAAE,MAAM;IAC1B;;OAEG;IACM,SAAS,EAAE,MAAM;IAG5B,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,eAAe,GAAG,WAAW;CAGpD"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/SMSMessage.d.ts b/backend/node_modules/@clerk/backend/dist/api/resources/SMSMessage.d.ts new file mode 100644 index 000000000..f8be9598b --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/SMSMessage.d.ts @@ -0,0 +1,13 @@ +import type { SMSMessageJSON } from './JSON'; +export declare class SMSMessage { + readonly id: string; + readonly fromPhoneNumber: string; + readonly toPhoneNumber: string; + readonly message: string; + readonly status: string; + readonly phoneNumberId: string | null; + readonly data?: (Record | null) | undefined; + constructor(id: string, fromPhoneNumber: string, toPhoneNumber: string, message: string, status: string, phoneNumberId: string | null, data?: (Record | null) | undefined); + static fromJSON(data: SMSMessageJSON): SMSMessage; +} +//# sourceMappingURL=SMSMessage.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/SMSMessage.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/resources/SMSMessage.d.ts.map new file mode 100644 index 000000000..3177575ec --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/SMSMessage.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"SMSMessage.d.ts","sourceRoot":"","sources":["../../../src/api/resources/SMSMessage.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,QAAQ,CAAC;AAE7C,qBAAa,UAAU;IAEnB,QAAQ,CAAC,EAAE,EAAE,MAAM;IACnB,QAAQ,CAAC,eAAe,EAAE,MAAM;IAChC,QAAQ,CAAC,aAAa,EAAE,MAAM;IAC9B,QAAQ,CAAC,OAAO,EAAE,MAAM;IACxB,QAAQ,CAAC,MAAM,EAAE,MAAM;IACvB,QAAQ,CAAC,aAAa,EAAE,MAAM,GAAG,IAAI;IACrC,QAAQ,CAAC,IAAI,CAAC,GAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,IAAI;gBANjC,EAAE,EAAE,MAAM,EACV,eAAe,EAAE,MAAM,EACvB,aAAa,EAAE,MAAM,EACrB,OAAO,EAAE,MAAM,EACf,MAAM,EAAE,MAAM,EACd,aAAa,EAAE,MAAM,GAAG,IAAI,EAC5B,IAAI,CAAC,GAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,IAAI,aAAA;IAG5C,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,cAAc,GAAG,UAAU;CAWlD"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/SamlAccount.d.ts b/backend/node_modules/@clerk/backend/dist/api/resources/SamlAccount.d.ts new file mode 100644 index 000000000..1b747c53e --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/SamlAccount.d.ts @@ -0,0 +1,83 @@ +import type { SamlAccountJSON } from './JSON'; +import { SamlAccountConnection } from './SamlConnection'; +import { Verification } from './Verification'; +/** + * The Backend `SamlAccount` object describes a SAML account. + */ +export declare class SamlAccount { + /** + * The unique identifier for the SAML account. + */ + readonly id: string; + /** + * The provider of the SAML account. + */ + readonly provider: string; + /** + * The user's ID as used in the provider. + */ + readonly providerUserId: string | null; + /** + * A boolean that indicates whether the SAML account is active. + */ + readonly active: boolean; + /** + * The email address of the SAML account. + */ + readonly emailAddress: string; + /** + * The first name of the SAML account. + */ + readonly firstName: string; + /** + * The last name of the SAML account. + */ + readonly lastName: string; + /** + * The verification of the SAML account. + */ + readonly verification: Verification | null; + /** + * The SAML connection of the SAML account. + */ + readonly samlConnection: SamlAccountConnection | null; + constructor( + /** + * The unique identifier for the SAML account. + */ + id: string, + /** + * The provider of the SAML account. + */ + provider: string, + /** + * The user's ID as used in the provider. + */ + providerUserId: string | null, + /** + * A boolean that indicates whether the SAML account is active. + */ + active: boolean, + /** + * The email address of the SAML account. + */ + emailAddress: string, + /** + * The first name of the SAML account. + */ + firstName: string, + /** + * The last name of the SAML account. + */ + lastName: string, + /** + * The verification of the SAML account. + */ + verification: Verification | null, + /** + * The SAML connection of the SAML account. + */ + samlConnection: SamlAccountConnection | null); + static fromJSON(data: SamlAccountJSON): SamlAccount; +} +//# sourceMappingURL=SamlAccount.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/SamlAccount.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/resources/SamlAccount.d.ts.map new file mode 100644 index 000000000..0f356d646 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/SamlAccount.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"SamlAccount.d.ts","sourceRoot":"","sources":["../../../src/api/resources/SamlAccount.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,QAAQ,CAAC;AAC9C,OAAO,EAAE,qBAAqB,EAAE,MAAM,kBAAkB,CAAC;AACzD,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAE9C;;GAEG;AACH,qBAAa,WAAW;IAEpB;;OAEG;IACH,QAAQ,CAAC,EAAE,EAAE,MAAM;IACnB;;OAEG;IACH,QAAQ,CAAC,QAAQ,EAAE,MAAM;IACzB;;OAEG;IACH,QAAQ,CAAC,cAAc,EAAE,MAAM,GAAG,IAAI;IACtC;;OAEG;IACH,QAAQ,CAAC,MAAM,EAAE,OAAO;IACxB;;OAEG;IACH,QAAQ,CAAC,YAAY,EAAE,MAAM;IAC7B;;OAEG;IACH,QAAQ,CAAC,SAAS,EAAE,MAAM;IAC1B;;OAEG;IACH,QAAQ,CAAC,QAAQ,EAAE,MAAM;IACzB;;OAEG;IACH,QAAQ,CAAC,YAAY,EAAE,YAAY,GAAG,IAAI;IAC1C;;OAEG;IACH,QAAQ,CAAC,cAAc,EAAE,qBAAqB,GAAG,IAAI;;IAnCrD;;OAEG;IACM,EAAE,EAAE,MAAM;IACnB;;OAEG;IACM,QAAQ,EAAE,MAAM;IACzB;;OAEG;IACM,cAAc,EAAE,MAAM,GAAG,IAAI;IACtC;;OAEG;IACM,MAAM,EAAE,OAAO;IACxB;;OAEG;IACM,YAAY,EAAE,MAAM;IAC7B;;OAEG;IACM,SAAS,EAAE,MAAM;IAC1B;;OAEG;IACM,QAAQ,EAAE,MAAM;IACzB;;OAEG;IACM,YAAY,EAAE,YAAY,GAAG,IAAI;IAC1C;;OAEG;IACM,cAAc,EAAE,qBAAqB,GAAG,IAAI;IAGvD,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,eAAe,GAAG,WAAW;CAapD"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/SamlConnection.d.ts b/backend/node_modules/@clerk/backend/dist/api/resources/SamlConnection.d.ts new file mode 100644 index 000000000..b589326e1 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/SamlConnection.d.ts @@ -0,0 +1,228 @@ +import type { AttributeMappingJSON, SamlAccountConnectionJSON, SamlConnectionJSON } from './JSON'; +/** + * The Backend `SamlConnection` object holds information about a SAML connection for an organization. + */ +export declare class SamlConnection { + /** + * The unique identifier for the connection. + */ + readonly id: string; + /** + * The name to use as a label for the connection. + */ + readonly name: string; + /** + * The domain of your organization. Sign in flows using an email with this domain will use the connection. + */ + readonly domain: string; + /** + * The organization ID of the organization. + */ + readonly organizationId: string | null; + /** + * The Entity ID as provided by the Identity Provider (IdP). + */ + readonly idpEntityId: string | null; + /** + * The Single-Sign On URL as provided by the Identity Provider (IdP). + */ + readonly idpSsoUrl: string | null; + /** + * The X.509 certificate as provided by the Identity Provider (IdP). + */ + readonly idpCertificate: string | null; + /** + * The URL which serves the Identity Provider (IdP) metadata. If present, it takes priority over the corresponding individual properties. + */ + readonly idpMetadataUrl: string | null; + /** + * The XML content of the Identity Provider (IdP) metadata file. If present, it takes priority over the corresponding individual properties. + */ + readonly idpMetadata: string | null; + /** + * The Assertion Consumer Service (ACS) URL of the connection. + */ + readonly acsUrl: string; + /** + * The Entity ID as provided by the Service Provider (Clerk). + */ + readonly spEntityId: string; + /** + * The metadata URL as provided by the Service Provider (Clerk). + */ + readonly spMetadataUrl: string; + /** + * Indicates whether the connection is active or not. + */ + readonly active: boolean; + /** + * The Identity Provider (IdP) of the connection. + */ + readonly provider: string; + /** + * The number of users associated with the connection. + */ + readonly userCount: number; + /** + * Indicates whether the connection syncs user attributes between the Service Provider (SP) and Identity Provider (IdP) or not. + */ + readonly syncUserAttributes: boolean; + /** + * Indicates whether users with an email address subdomain are allowed to use this connection in order to authenticate or not. + */ + readonly allowSubdomains: boolean; + /** + * Indicates whether the connection allows Identity Provider (IdP) initiated flows or not. + */ + readonly allowIdpInitiated: boolean; + /** + * The date when the connection was first created. + */ + readonly createdAt: number; + /** + * The date when the SAML connection was last updated. + */ + readonly updatedAt: number; + /** + * Defines the attribute name mapping between the Identity Provider (IdP) and Clerk's [`User`](https://clerk.com/docs/references/javascript/user) properties. + */ + readonly attributeMapping: AttributeMapping; + constructor( + /** + * The unique identifier for the connection. + */ + id: string, + /** + * The name to use as a label for the connection. + */ + name: string, + /** + * The domain of your organization. Sign in flows using an email with this domain will use the connection. + */ + domain: string, + /** + * The organization ID of the organization. + */ + organizationId: string | null, + /** + * The Entity ID as provided by the Identity Provider (IdP). + */ + idpEntityId: string | null, + /** + * The Single-Sign On URL as provided by the Identity Provider (IdP). + */ + idpSsoUrl: string | null, + /** + * The X.509 certificate as provided by the Identity Provider (IdP). + */ + idpCertificate: string | null, + /** + * The URL which serves the Identity Provider (IdP) metadata. If present, it takes priority over the corresponding individual properties. + */ + idpMetadataUrl: string | null, + /** + * The XML content of the Identity Provider (IdP) metadata file. If present, it takes priority over the corresponding individual properties. + */ + idpMetadata: string | null, + /** + * The Assertion Consumer Service (ACS) URL of the connection. + */ + acsUrl: string, + /** + * The Entity ID as provided by the Service Provider (Clerk). + */ + spEntityId: string, + /** + * The metadata URL as provided by the Service Provider (Clerk). + */ + spMetadataUrl: string, + /** + * Indicates whether the connection is active or not. + */ + active: boolean, + /** + * The Identity Provider (IdP) of the connection. + */ + provider: string, + /** + * The number of users associated with the connection. + */ + userCount: number, + /** + * Indicates whether the connection syncs user attributes between the Service Provider (SP) and Identity Provider (IdP) or not. + */ + syncUserAttributes: boolean, + /** + * Indicates whether users with an email address subdomain are allowed to use this connection in order to authenticate or not. + */ + allowSubdomains: boolean, + /** + * Indicates whether the connection allows Identity Provider (IdP) initiated flows or not. + */ + allowIdpInitiated: boolean, + /** + * The date when the connection was first created. + */ + createdAt: number, + /** + * The date when the SAML connection was last updated. + */ + updatedAt: number, + /** + * Defines the attribute name mapping between the Identity Provider (IdP) and Clerk's [`User`](https://clerk.com/docs/references/javascript/user) properties. + */ + attributeMapping: AttributeMapping); + static fromJSON(data: SamlConnectionJSON): SamlConnection; +} +export declare class SamlAccountConnection { + readonly id: string; + readonly name: string; + readonly domain: string; + readonly active: boolean; + readonly provider: string; + readonly syncUserAttributes: boolean; + readonly allowSubdomains: boolean; + readonly allowIdpInitiated: boolean; + readonly createdAt: number; + readonly updatedAt: number; + constructor(id: string, name: string, domain: string, active: boolean, provider: string, syncUserAttributes: boolean, allowSubdomains: boolean, allowIdpInitiated: boolean, createdAt: number, updatedAt: number); + static fromJSON(data: SamlAccountConnectionJSON): SamlAccountConnection; +} +declare class AttributeMapping { + /** + * The user ID attribute name. + */ + readonly userId: string; + /** + * The email address attribute name. + */ + readonly emailAddress: string; + /** + * The first name attribute name. + */ + readonly firstName: string; + /** + * The last name attribute name. + */ + readonly lastName: string; + constructor( + /** + * The user ID attribute name. + */ + userId: string, + /** + * The email address attribute name. + */ + emailAddress: string, + /** + * The first name attribute name. + */ + firstName: string, + /** + * The last name attribute name. + */ + lastName: string); + static fromJSON(data: AttributeMappingJSON): AttributeMapping; +} +export {}; +//# sourceMappingURL=SamlConnection.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/SamlConnection.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/resources/SamlConnection.d.ts.map new file mode 100644 index 000000000..605d1be32 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/SamlConnection.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"SamlConnection.d.ts","sourceRoot":"","sources":["../../../src/api/resources/SamlConnection.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,yBAAyB,EAAE,kBAAkB,EAAE,MAAM,QAAQ,CAAC;AAElG;;GAEG;AACH,qBAAa,cAAc;IAEvB;;OAEG;IACH,QAAQ,CAAC,EAAE,EAAE,MAAM;IACnB;;OAEG;IACH,QAAQ,CAAC,IAAI,EAAE,MAAM;IACrB;;OAEG;IACH,QAAQ,CAAC,MAAM,EAAE,MAAM;IACvB;;OAEG;IACH,QAAQ,CAAC,cAAc,EAAE,MAAM,GAAG,IAAI;IACtC;;OAEG;IACH,QAAQ,CAAC,WAAW,EAAE,MAAM,GAAG,IAAI;IACnC;;OAEG;IACH,QAAQ,CAAC,SAAS,EAAE,MAAM,GAAG,IAAI;IACjC;;OAEG;IACH,QAAQ,CAAC,cAAc,EAAE,MAAM,GAAG,IAAI;IACtC;;OAEG;IACH,QAAQ,CA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AAM;IAC7B;;OAEG;IACH,QAAQ,CAAC,SAAS,EAAE,MAAM;IAC1B;;OAEG;IACH,QAAQ,CAAC,QAAQ,EAAE,MAAM;;IAfzB;;OAEG;IACM,MAAM,EAAE,MAAM;IACvB;;OAEG;IACM,YAAY,EAAE,MAAM;IAC7B;;OAEG;IACM,SAAS,EAAE,MAAM;IAC1B;;OAEG;IACM,QAAQ,EAAE,MAAM;IAG3B,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,oBAAoB,GAAG,gBAAgB;CAG9D"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/Session.d.ts b/backend/node_modules/@clerk/backend/dist/api/resources/Session.d.ts new file mode 100644 index 000000000..5fd2c5d34 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/Session.d.ts @@ -0,0 +1,176 @@ +import type { SessionActivityJSON, SessionJSON } from './JSON'; +/** + * The Backend `SessionActivity` object models the activity of a user session, capturing details such as the device type, browser information, and geographical location. + */ +export declare class SessionActivity { + /** + * The unique identifier for the session activity record. + */ + readonly id: string; + /** + * Will be set to `true` if the session activity came from a mobile device. Set to `false` otherwise. + */ + readonly isMobile: boolean; + /** + * The IP address from which this session activity originated. + */ + readonly ipAddress?: string | undefined; + /** + * The city from which this session activity occurred. Resolved by IP address geo-location. + */ + readonly city?: string | undefined; + /** + * The country from which this session activity occurred. Resolved by IP address geo-location. + */ + readonly country?: string | undefined; + /** + * The version of the browser from which this session activity occurred. + */ + readonly browserVersion?: string | undefined; + /** + * The name of the browser from which this session activity occurred. + */ + readonly browserName?: string | undefined; + /** + * The type of the device which was used in this session activity. + */ + readonly deviceType?: string | undefined; + constructor( + /** + * The unique identifier for the session activity record. + */ + id: string, + /** + * Will be set to `true` if the session activity came from a mobile device. Set to `false` otherwise. + */ + isMobile: boolean, + /** + * The IP address from which this session activity originated. + */ + ipAddress?: string | undefined, + /** + * The city from which this session activity occurred. Resolved by IP address geo-location. + */ + city?: string | undefined, + /** + * The country from which this session activity occurred. Resolved by IP address geo-location. + */ + country?: string | undefined, + /** + * The version of the browser from which this session activity occurred. + */ + browserVersion?: string | undefined, + /** + * The name of the browser from which this session activity occurred. + */ + browserName?: string | undefined, + /** + * The type of the device which was used in this session activity. + */ + deviceType?: string | undefined); + static fromJSON(data: SessionActivityJSON): SessionActivity; +} +/** + * The Backend `Session` object is similar to the [`Session`](https://clerk.com/docs/references/javascript/session) object as it is an abstraction over an HTTP session and models the period of information exchange between a user and the server. However, the Backend `Session` object is different as it is used in the [Backend API](https://clerk.com/docs/reference/backend-api/tag/Sessions#operation/GetSessionList) and is not directly accessible from the Frontend API. + */ +export declare class Session { + /** + * The unique identifier for the `Session`. + */ + readonly id: string; + /** + * The ID of the client associated with the `Session`. + */ + readonly clientId: string; + /** + * The ID of the user associated with the `Session`. + */ + readonly userId: string; + /** + * The current state of the `Session`. + */ + readonly status: string; + /** + * The time the session was last active on the [`Client`](https://clerk.com/docs/references/backend/types/backend-client). + */ + readonly lastActiveAt: number; + /** + * The date when the `Session` will expire. + */ + readonly expireAt: number; + /** + * The date when the `Session` will be abandoned. + */ + readonly abandonAt: number; + /** + * The date when the `Session` was first created. + */ + readonly createdAt: number; + /** + * The date when the `Session` was last updated. + */ + readonly updatedAt: number; + /** + * The ID of the last active organization. + */ + readonly lastActiveOrganizationId?: string | undefined; + /** + * An object that provides additional information about this session, focused around user activity data. + */ + readonly latestActivity?: SessionActivity | undefined; + /** + * The JWT actor for the session. Holds identifier for the user that is impersonating the current user. Read more about [impersonation](https://clerk.com/docs/users/user-impersonation). + */ + readonly actor: Record | null; + constructor( + /** + * The unique identifier for the `Session`. + */ + id: string, + /** + * The ID of the client associated with the `Session`. + */ + clientId: string, + /** + * The ID of the user associated with the `Session`. + */ + userId: string, + /** + * The current state of the `Session`. + */ + status: string, + /** + * The time the session was last active on the [`Client`](https://clerk.com/docs/references/backend/types/backend-client). + */ + lastActiveAt: number, + /** + * The date when the `Session` will expire. + */ + expireAt: number, + /** + * The date when the `Session` will be abandoned. + */ + abandonAt: number, + /** + * The date when the `Session` was first created. + */ + createdAt: number, + /** + * The date when the `Session` was last updated. + */ + updatedAt: number, + /** + * The ID of the last active organization. + */ + lastActiveOrganizationId?: string | undefined, + /** + * An object that provides additional information about this session, focused around user activity data. + */ + latestActivity?: SessionActivity | undefined, + /** + * The JWT actor for the session. Holds identifier for the user that is impersonating the current user. Read more about [impersonation](https://clerk.com/docs/users/user-impersonation). + */ + actor?: Record | null); + static fromJSON(data: SessionJSON): Session; +} +//# sourceMappingURL=Session.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/Session.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/resources/Session.d.ts.map new file mode 100644 index 000000000..7f28eb12e --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/Session.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"Session.d.ts","sourceRoot":"","sources":["../../../src/api/resources/Session.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,WAAW,EAAE,MAAM,QAAQ,CAAC;AAE/D;;GAEG;AACH,qBAAa,eAAe;IAExB;;OAEG;IACH,QAAQ,CAAC,EAAE,EAAE,MAAM;IACnB;;OAEG;IACH,QAAQ,CAAC,QAAQ,EAAE,OAAO;IAC1B;;OAEG;IACH,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM;IAC3B;;OAEG;IACH,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM;IACtB;;OAEG;IACH,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM;IACzB;;OAEG;IACH,QAAQ,CAAC,cAAc,CAAC,EAAE,MAAM;IAChC;;OAEG;IACH,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM;IAC7B;;OAEG;IACH,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM;;IA/B5B;;OAEG;IACM,EAAE,EAAE,MAAM;IACnB;;OAEG;IACM,QAAQ,EAAE,OAAO;IA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AM;IAC7B;;OAEG;IACM,QAAQ,EAAE,MAAM;IACzB;;OAEG;IACM,SAAS,EAAE,MAAM;IAC1B;;OAEG;IACM,SAAS,EAAE,MAAM;IAC1B;;OAEG;IACM,SAAS,EAAE,MAAM;IAC1B;;OAEG;IACM,wBAAwB,CAAC,EAAE,MAAM,YAAA;IAC1C;;OAEG;IACM,cAAc,CAAC,EAAE,eAAe,YAAA;IACzC;;OAEG;IACM,KAAK,GAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAW;IAGvD,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,WAAW,GAAG,OAAO;CAgB5C"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/SignInTokens.d.ts b/backend/node_modules/@clerk/backend/dist/api/resources/SignInTokens.d.ts new file mode 100644 index 000000000..dd7006a1f --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/SignInTokens.d.ts @@ -0,0 +1,13 @@ +import type { SignInTokenJSON } from './JSON'; +export declare class SignInToken { + readonly id: string; + readonly userId: string; + readonly token: string; + readonly status: string; + readonly url: string; + readonly createdAt: number; + readonly updatedAt: number; + constructor(id: string, userId: string, token: string, status: string, url: string, createdAt: number, updatedAt: number); + static fromJSON(data: SignInTokenJSON): SignInToken; +} +//# sourceMappingURL=SignInTokens.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/SignInTokens.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/resources/SignInTokens.d.ts.map new file mode 100644 index 000000000..bfadc4cf3 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/SignInTokens.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"SignInTokens.d.ts","sourceRoot":"","sources":["../../../src/api/resources/SignInTokens.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,QAAQ,CAAC;AAE9C,qBAAa,WAAW;IAEpB,QAAQ,CAAC,EAAE,EAAE,MAAM;IACnB,QAAQ,CAAC,MAAM,EAAE,MAAM;IACvB,QAAQ,CAAC,KAAK,EAAE,MAAM;IACtB,QAAQ,CAAC,MAAM,EAAE,MAAM;IACvB,QAAQ,CAAC,GAAG,EAAE,MAAM;IACpB,QAAQ,CAAC,SAAS,EAAE,MAAM;IAC1B,QAAQ,CAAC,SAAS,EAAE,MAAM;gBANjB,EAAE,EAAE,MAAM,EACV,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,MAAM,EACb,MAAM,EAAE,MAAM,EACd,GAAG,EAAE,MAAM,EACX,SAAS,EAAE,MAAM,EACjB,SAAS,EAAE,MAAM;IAG5B,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,eAAe,GAAG,WAAW;CAGpD"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/SignUpAttempt.d.ts b/backend/node_modules/@clerk/backend/dist/api/resources/SignUpAttempt.d.ts new file mode 100644 index 000000000..b713b780a --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/SignUpAttempt.d.ts @@ -0,0 +1,44 @@ +import type { SignUpStatus } from '@clerk/types'; +import type { SignUpVerificationNextAction } from './Enums'; +import type { SignUpJSON, SignUpVerificationJSON, SignUpVerificationsJSON } from './JSON'; +export declare class SignUpAttemptVerification { + readonly nextAction: SignUpVerificationNextAction; + readonly supportedStrategies: string[]; + constructor(nextAction: SignUpVerificationNextAction, supportedStrategies: string[]); + static fromJSON(data: SignUpVerificationJSON): SignUpAttemptVerification; +} +export declare class SignUpAttemptVerifications { + readonly emailAddress: SignUpAttemptVerification | null; + readonly phoneNumber: SignUpAttemptVerification | null; + readonly web3Wallet: SignUpAttemptVerification | null; + readonly externalAccount: object | null; + constructor(emailAddress: SignUpAttemptVerification | null, phoneNumber: SignUpAttemptVerification | null, web3Wallet: SignUpAttemptVerification | null, externalAccount: object | null); + static fromJSON(data: SignUpVerificationsJSON): SignUpAttemptVerifications; +} +export declare class SignUpAttempt { + readonly id: string; + readonly status: SignUpStatus; + readonly requiredFields: string[]; + readonly optionalFields: string[]; + readonly missingFields: string[]; + readonly unverifiedFields: string[]; + readonly verifications: SignUpAttemptVerifications | null; + readonly username: string | null; + readonly emailAddress: string | null; + readonly phoneNumber: string | null; + readonly web3Wallet: string | null; + readonly passwordEnabled: boolean; + readonly firstName: string | null; + readonly lastName: string | null; + readonly customAction: boolean; + readonly externalId: string | null; + readonly createdSessionId: string | null; + readonly createdUserId: string | null; + readonly abandonAt: number | null; + readonly legalAcceptedAt: number | null; + readonly publicMetadata?: (Record | null) | undefined; + readonly unsafeMetadata?: (Record | null) | undefined; + constructor(id: string, status: SignUpStatus, requiredFields: string[], optionalFields: string[], missingFields: string[], unverifiedFields: string[], verifications: SignUpAttemptVerifications | null, username: string | null, emailAddress: string | null, phoneNumber: string | null, web3Wallet: string | null, passwordEnabled: boolean, firstName: string | null, lastName: string | null, customAction: boolean, externalId: string | null, createdSessionId: string | null, createdUserId: string | null, abandonAt: number | null, legalAcceptedAt: number | null, publicMetadata?: (Record | null) | undefined, unsafeMetadata?: (Record | null) | undefined); + static fromJSON(data: SignUpJSON): SignUpAttempt; +} +//# sourceMappingURL=SignUpAttempt.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/SignUpAttempt.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/resources/SignUpAttempt.d.ts.map new file mode 100644 index 000000000..e1d43f575 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/SignUpAttempt.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"SignUpAttempt.d.ts","sourceRoot":"","sources":["../../../src/api/resources/SignUpAttempt.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAEjD,OAAO,KAAK,EAAE,4BAA4B,EAAE,MAAM,SAAS,CAAC;AAC5D,OAAO,KAAK,EAAE,UAAU,EAAE,sBAAsB,EAAE,uBAAuB,EAAE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,IAAI,EACxB,eAAe,EAAE,MAAM,GAAG,IAAI,EAC9B,cAAc,CAAC,GAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,aAAA,EAC/C,cAAc,CAAC,GAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,aAAA;IAG1D,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,UAAU,GAAG,aAAa;CA0BjD"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/TestingToken.d.ts b/backend/node_modules/@clerk/backend/dist/api/resources/TestingToken.d.ts new file mode 100644 index 000000000..fc28b4d70 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/TestingToken.d.ts @@ -0,0 +1,8 @@ +import type { TestingTokenJSON } from './JSON'; +export declare class TestingToken { + readonly token: string; + readonly expiresAt: number; + constructor(token: string, expiresAt: number); + static fromJSON(data: TestingTokenJSON): TestingToken; +} +//# sourceMappingURL=TestingToken.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/TestingToken.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/resources/TestingToken.d.ts.map new file mode 100644 index 000000000..c6c43ce41 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/TestingToken.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"TestingToken.d.ts","sourceRoot":"","sources":["../../../src/api/resources/TestingToken.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,QAAQ,CAAC;AAE/C,qBAAa,YAAY;IAErB,QAAQ,CAAC,KAAK,EAAE,MAAM;IACtB,QAAQ,CAAC,SAAS,EAAE,MAAM;gBADjB,KAAK,EAAE,MAAM,EACb,SAAS,EAAE,MAAM;IAG5B,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,gBAAgB,GAAG,YAAY;CAGtD"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/Token.d.ts b/backend/node_modules/@clerk/backend/dist/api/resources/Token.d.ts new file mode 100644 index 000000000..dd49b5393 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/Token.d.ts @@ -0,0 +1,7 @@ +import type { TokenJSON } from './JSON'; +export declare class Token { + readonly jwt: string; + constructor(jwt: string); + static fromJSON(data: TokenJSON): Token; +} +//# sourceMappingURL=Token.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/Token.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/resources/Token.d.ts.map new file mode 100644 index 000000000..80e84b3a4 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/Token.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"Token.d.ts","sourceRoot":"","sources":["../../../src/api/resources/Token.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,QAAQ,CAAC;AAExC,qBAAa,KAAK;IACJ,QAAQ,CAAC,GAAG,EAAE,MAAM;gBAAX,GAAG,EAAE,MAAM;IAEhC,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,SAAS,GAAG,KAAK;CAGxC"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/User.d.ts b/backend/node_modules/@clerk/backend/dist/api/resources/User.d.ts new file mode 100644 index 000000000..026cb8cd4 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/User.d.ts @@ -0,0 +1,288 @@ +import { EmailAddress } from './EmailAddress'; +import { ExternalAccount } from './ExternalAccount'; +import type { UserJSON } from './JSON'; +import { PhoneNumber } from './PhoneNumber'; +import { SamlAccount } from './SamlAccount'; +import { Web3Wallet } from './Web3Wallet'; +/** + * The Backend `User` object is similar to the `User` object as it holds information about a user of your application, such as their unique identifier, name, email addresses, phone numbers, and more. However, the Backend `User` object is different from the `User` object in that it is used in the [Backend API](https://clerk.com/docs/reference/backend-api/tag/Users#operation/GetUser){{ target: '_blank' }} and is not directly accessible from the Frontend API. + */ +export declare class User { + /** + * The unique identifier for the user. + */ + readonly id: string; + /** + * A boolean indicating whether the user has a password on their account. + */ + readonly passwordEnabled: boolean; + /** + * A boolean indicating whether the user has enabled TOTP by generating a TOTP secret and verifying it via an authenticator app. + */ + readonly totpEnabled: boolean; + /** + * A boolean indicating whether the user has enabled Backup codes. + */ + readonly backupCodeEnabled: boolean; + /** + * A boolean indicating whether the user has enabled two-factor authentication. + */ + readonly twoFactorEnabled: boolean; + /** + * A boolean indicating whether the user is banned or not. + */ + readonly banned: boolean; + /** + * A boolean indicating whether the user is banned or not. + */ + readonly locked: boolean; + /** + * The date when the user was first created. + */ + readonly createdAt: number; + /** + * The date when the user was last updated. + */ + readonly updatedAt: number; + /** + * The URL of the user's profile image. + */ + readonly imageUrl: string; + /** + * A getter boolean to check if the user has uploaded an image or one was copied from OAuth. Returns `false` if Clerk is displaying an avatar for the user. + */ + readonly hasImage: boolean; + /** + * The ID for the `EmailAddress` that the user has set as primary. + */ + readonly primaryEmailAddressId: string | null; + /** + * The ID for the `PhoneNumber` that the user has set as primary. + */ + readonly primaryPhoneNumberId: string | null; + /** + * The ID for the [`Web3Wallet`](https://clerk.com/docs/references/backend/types/backend-web3-wallet) that the user signed up with. + */ + readonly primaryWeb3WalletId: string | null; + /** + * The date when the user last signed in. May be empty if the user has never signed in. + */ + readonly lastSignInAt: number | null; + /** + * The ID of the user as used in your external systems. Must be unique across your instance. + */ + readonly externalId: string | null; + /** + * The user's username. + */ + readonly username: string | null; + /** + * The user's first name. + */ + readonly firstName: string | null; + /** + * The user's last name. + */ + readonly lastName: string | null; + /** + * Metadata that can be read from the Frontend API and [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }} and can be set only from the Backend API. + */ + readonly publicMetadata: UserPublicMetadata; + /** + * Metadata that can be read and set only from the [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }}. + */ + readonly privateMetadata: UserPrivateMetadata; + /** + * Metadata that can be read and set from the Frontend API. It's considered unsafe because it can be modified from the frontend. + */ + readonly unsafeMetadata: UserUnsafeMetadata; + /** + * An array of all the `EmailAddress` objects associated with the user. Includes the primary. + */ + readonly emailAddresses: EmailAddress[]; + /** + * An array of all the `PhoneNumber` objects associated with the user. Includes the primary. + */ + readonly phoneNumbers: PhoneNumber[]; + /** + * An array of all the `Web3Wallet` objects associated with the user. Includes the primary. + */ + readonly web3Wallets: Web3Wallet[]; + /** + * An array of all the `ExternalAccount` objects associated with the user via OAuth. **Note**: This includes both verified & unverified external accounts. + */ + readonly externalAccounts: ExternalAccount[]; + /** + * An array of all the `SamlAccount` objects associated with the user via SAML. + */ + readonly samlAccounts: SamlAccount[]; + /** + * Date when the user was last active. + */ + readonly lastActiveAt: number | null; + /** + * A boolean indicating whether the organization creation is enabled for the user or not. + */ + readonly createOrganizationEnabled: boolean; + /** + * An integer indicating the number of organizations that can be created by the user. If the value is `0`, then the user can create unlimited organizations. Default is `null`. + */ + readonly createOrganizationsLimit: number | null; + /** + * A boolean indicating whether the user can delete their own account. + */ + readonly deleteSelfEnabled: boolean; + /** + * The unix timestamp of when the user accepted the legal requirements. `null` if [**Require express consent to legal documents**](https://clerk.com/docs/authentication/configuration/legal-compliance) is not enabled. + */ + readonly legalAcceptedAt: number | null; + private _raw; + get raw(): UserJSON | null; + constructor( + /** + * The unique identifier for the user. + */ + id: string, + /** + * A boolean indicating whether the user has a password on their account. + */ + passwordEnabled: boolean, + /** + * A boolean indicating whether the user has enabled TOTP by generating a TOTP secret and verifying it via an authenticator app. + */ + totpEnabled: boolean, + /** + * A boolean indicating whether the user has enabled Backup codes. + */ + backupCodeEnabled: boolean, + /** + * A boolean indicating whether the user has enabled two-factor authentication. + */ + twoFactorEnabled: boolean, + /** + * A boolean indicating whether the user is banned or not. + */ + banned: boolean, + /** + * A boolean indicating whether the user is banned or not. + */ + locked: boolean, + /** + * The date when the user was first created. + */ + createdAt: number, + /** + * The date when the user was last updated. + */ + updatedAt: number, + /** + * The URL of the user's profile image. + */ + imageUrl: string, + /** + * A getter boolean to check if the user has uploaded an image or one was copied from OAuth. Returns `false` if Clerk is displaying an avatar for the user. + */ + hasImage: boolean, + /** + * The ID for the `EmailAddress` that the user has set as primary. + */ + primaryEmailAddressId: string | null, + /** + * The ID for the `PhoneNumber` that the user has set as primary. + */ + primaryPhoneNumberId: string | null, + /** + * The ID for the [`Web3Wallet`](https://clerk.com/docs/references/backend/types/backend-web3-wallet) that the user signed up with. + */ + primaryWeb3WalletId: string | null, + /** + * The date when the user last signed in. May be empty if the user has never signed in. + */ + lastSignInAt: number | null, + /** + * The ID of the user as used in your external systems. Must be unique across your instance. + */ + externalId: string | null, + /** + * The user's username. + */ + username: string | null, + /** + * The user's first name. + */ + firstName: string | null, + /** + * The user's last name. + */ + lastName: string | null, + /** + * Metadata that can be read from the Frontend API and [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }} and can be set only from the Backend API. + */ + publicMetadata: UserPublicMetadata | undefined, + /** + * Metadata that can be read and set only from the [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }}. + */ + privateMetadata: UserPrivateMetadata | undefined, + /** + * Metadata that can be read and set from the Frontend API. It's considered unsafe because it can be modified from the frontend. + */ + unsafeMetadata: UserUnsafeMetadata | undefined, + /** + * An array of all the `EmailAddress` objects associated with the user. Includes the primary. + */ + emailAddresses: EmailAddress[] | undefined, + /** + * An array of all the `PhoneNumber` objects associated with the user. Includes the primary. + */ + phoneNumbers: PhoneNumber[] | undefined, + /** + * An array of all the `Web3Wallet` objects associated with the user. Includes the primary. + */ + web3Wallets: Web3Wallet[] | undefined, + /** + * An array of all the `ExternalAccount` objects associated with the user via OAuth. **Note**: This includes both verified & unverified external accounts. + */ + externalAccounts: ExternalAccount[] | undefined, + /** + * An array of all the `SamlAccount` objects associated with the user via SAML. + */ + samlAccounts: SamlAccount[] | undefined, + /** + * Date when the user was last active. + */ + lastActiveAt: number | null, + /** + * A boolean indicating whether the organization creation is enabled for the user or not. + */ + createOrganizationEnabled: boolean, + /** + * An integer indicating the number of organizations that can be created by the user. If the value is `0`, then the user can create unlimited organizations. Default is `null`. + */ + createOrganizationsLimit: number | null | undefined, + /** + * A boolean indicating whether the user can delete their own account. + */ + deleteSelfEnabled: boolean, + /** + * The unix timestamp of when the user accepted the legal requirements. `null` if [**Require express consent to legal documents**](https://clerk.com/docs/authentication/configuration/legal-compliance) is not enabled. + */ + legalAcceptedAt: number | null); + static fromJSON(data: UserJSON): User; + /** + * The primary email address of the user. + */ + get primaryEmailAddress(): EmailAddress | null; + /** + * The primary phone number of the user. + */ + get primaryPhoneNumber(): PhoneNumber | null; + /** + * The primary web3 wallet of the user. + */ + get primaryWeb3Wallet(): Web3Wallet | null; + /** + * The full name of the user. + */ + get fullName(): string | null; +} +//# sourceMappingURL=User.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/User.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/resources/User.d.ts.map new file mode 100644 index 000000000..dd68dd7bd --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/User.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"User.d.ts","sourceRoot":"","sources":["../../../src/api/resources/User.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AACpD,OAAO,KAAK,EAAwC,QAAQ,EAAE,MAAM,QAAQ,CAAC;AAC7E,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAE1C;;GAEG;AACH,qBAAa,IAAI;IAQb;;OAEG;IACH,QAAQ,CAAC,EAAE,EAAE,MAAM;IACnB;;OAEG;IACH,QAAQ,CAAC,eAAe,EAAE,OAAO;IACjC;;OAEG;IACH,QAAQ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AChC;;OAEG;IACM,SAAS,EAAE,MAAM,GAAG,IAAI;IACjC;;OAEG;IACM,QAAQ,EAAE,MAAM,GAAG,IAAI;IAChC;;OAEG;IACM,cAAc,EAAE,kBAAkB,YAAK;IAChD;;OAEG;IACM,eAAe,EAAE,mBAAmB,YAAK;IAClD;;OAEG;IACM,cAAc,EAAE,kBAAkB,YAAK;IAChD;;OAEG;IACM,cAAc,EAAE,YAAY,EAAE,YAAK;IAC5C;;OAEG;IACM,YAAY,EAAE,WAAW,EAAE,YAAK;IACzC;;OAEG;IACM,WAAW,EAAE,UAAU,EAAE,YAAK;IACvC;;OAEG;IACM,gBAAgB,EAAE,eAAe,EAAE,YAAK;IACjD;;OAEG;IACM,YAAY,EAAE,WAAW,EAAE,YAAK;IACzC;;OAEG;IACM,YAAY,EAAE,MAAM,GAAG,IAAI;IACpC;;OAEG;IACM,yBAAyB,EAAE,OAAO;IAC3C;;OAEG;IACM,wBAAwB,EAAE,MAAM,GAAG,IAAI,YAAO;IACvD;;OAEG;IACM,iBAAiB,EAAE,OAAO;IACnC;;OAEG;IACM,eAAe,EAAE,MAAM,GAAG,IAAI;IAGzC,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,QAAQ,GAAG,IAAI;IAuCrC;;OAEG;IACH,IAAI,mBAAmB,wBAEtB;IAED;;OAEG;IACH,IAAI,kBAAkB,uBAErB;IAED;;OAEG;IACH,IAAI,iBAAiB,sBAEpB;IAED;;OAEG;IACH,IAAI,QAAQ,kBAEX;CACF"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/Verification.d.ts b/backend/node_modules/@clerk/backend/dist/api/resources/Verification.d.ts new file mode 100644 index 000000000..7e58990f2 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/Verification.d.ts @@ -0,0 +1,90 @@ +import type { VerificationStatus } from '@clerk/types'; +import type { OrganizationDomainVerificationJSON, VerificationJSON } from './JSON'; +/** + * The Backend `Verification` object describes the state of the verification process of a sign-in or sign-up attempt. + */ +export declare class Verification { + /** + * The state of the verification. + * + *
    + *
  • `unverified`: The verification has not been verified yet.
  • + *
  • `verified`: The verification has been verified.
  • + *
  • `transferable`: The verification is transferable to between sign-in and sign-up flows.
  • + *
  • `failed`: The verification has failed.
  • + *
  • `expired`: The verification has expired.
  • + *
+ */ + readonly status: VerificationStatus; + /** + * The strategy pertaining to the parent sign-up or sign-in attempt. + */ + readonly strategy: string; + /** + * The redirect URL for an external verification. + */ + readonly externalVerificationRedirectURL: URL | null; + /** + * The number of attempts related to the verification. + */ + readonly attempts: number | null; + /** + * The time the verification will expire at. + */ + readonly expireAt: number | null; + /** + * The [nonce](https://en.wikipedia.org/wiki/Cryptographic_nonce) pertaining to the verification. + */ + readonly nonce: string | null; + /** + * The message that will be presented to the user's Web3 wallet for signing during authentication. This follows the [Sign-In with Ethereum (SIWE) protocol format](https://docs.login.xyz/general-information/siwe-overview/eip-4361#example-message-to-be-signed), which typically includes details like the requesting service, wallet address, terms acceptance, nonce, timestamp, and any additional resources. + */ + readonly message: string | null; + constructor( + /** + * The state of the verification. + * + *
    + *
  • `unverified`: The verification has not been verified yet.
  • + *
  • `verified`: The verification has been verified.
  • + *
  • `transferable`: The verification is transferable to between sign-in and sign-up flows.
  • + *
  • `failed`: The verification has failed.
  • + *
  • `expired`: The verification has expired.
  • + *
+ */ + status: VerificationStatus, + /** + * The strategy pertaining to the parent sign-up or sign-in attempt. + */ + strategy: string, + /** + * The redirect URL for an external verification. + */ + externalVerificationRedirectURL?: URL | null, + /** + * The number of attempts related to the verification. + */ + attempts?: number | null, + /** + * The time the verification will expire at. + */ + expireAt?: number | null, + /** + * The [nonce](https://en.wikipedia.org/wiki/Cryptographic_nonce) pertaining to the verification. + */ + nonce?: string | null, + /** + * The message that will be presented to the user's Web3 wallet for signing during authentication. This follows the [Sign-In with Ethereum (SIWE) protocol format](https://docs.login.xyz/general-information/siwe-overview/eip-4361#example-message-to-be-signed), which typically includes details like the requesting service, wallet address, terms acceptance, nonce, timestamp, and any additional resources. + */ + message?: string | null); + static fromJSON(data: VerificationJSON): Verification; +} +export declare class OrganizationDomainVerification { + readonly status: string; + readonly strategy: string; + readonly attempts: number | null; + readonly expireAt: number | null; + constructor(status: string, strategy: string, attempts?: number | null, expireAt?: number | null); + static fromJSON(data: OrganizationDomainVerificationJSON): OrganizationDomainVerification; +} +//# sourceMappingURL=Verification.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/Verification.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/resources/Verification.d.ts.map new file mode 100644 index 000000000..926c0826f --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/Verification.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"Verification.d.ts","sourceRoot":"","sources":["../../../src/api/resources/Verification.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAEvD,OAAO,KAAK,EAAE,kCAAkC,EAAE,gBAAgB,EAAE,MAAM,QAAQ,CAAC;AAEnF;;GAEG;AACH,qBAAa,YAAY;IAErB;;;;;;;;;;OAUG;IACH,QAAQ,CAAC,MAAM,EAAE,kBAAkB;IACnC;;OAEG;IACH,QAAQ,CAAC,QAAQ,EAAE,MAAM;IACzB;;OAEG;IACH,QAAQ,CAAC,+BAA+B,EAAE,GAAG,GAAG,IAAI;IACpD;;OAEG;IACH,QAAQ,CAAC,QAAQ,EAAE,MAAM,GAAG,IAAI;IAChC;;OAEG;IACH,QAAQ,CAAC,QAAQ,EAAE,MAAM,GAAG,IAAI;IAChC;;OAEG;IACH,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI;IAC7B;;OAEG;IACH,QAAQ,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI;;IAnC/B;;;;;;;;;;OAUG;IACM,MAAM,EAAE,kBAAkB;IACnC;;OAEG;IACM,QAAQ,EAAE,MAAM;IACzB;;OAEG;IACM,+BAA+B,GAAE,GAAG,GAAG,IAAW;IAC3D;;OAEG;IACM,QAAQ,GAAE,MAAM,GAAG,IAAW;IACvC;;OAEG;IACM,QAAQ,GAAE,MAAM,GAAG,IAAW;IACvC;;OAEG;IACM,KAAK,GAAE,MAAM,GAAG,IAAW;IACpC;;OAEG;IACM,OAAO,GAAE,MAAM,GAAG,IAAW;IAGxC,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,gBAAgB,GAAG,YAAY;CAUtD;AAED,qBAAa,8BAA8B;IAEvC,QAAQ,CAAC,MAAM,EAAE,MAAM;IACvB,QAAQ,CAAC,QAAQ,EAAE,MAAM;IACzB,QAAQ,CAAC,QAAQ,EAAE,MAAM,GAAG,IAAI;IAChC,QAAQ,CAAC,QAAQ,EAAE,MAAM,GAAG,IAAI;gBAHvB,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,MAAM,EAChB,QAAQ,GAAE,MAAM,GAAG,IAAW,EAC9B,QAAQ,GAAE,MAAM,GAAG,IAAW;IAGzC,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,kCAAkC,GAAG,8BAA8B;CAG1F"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/WaitlistEntry.d.ts b/backend/node_modules/@clerk/backend/dist/api/resources/WaitlistEntry.d.ts new file mode 100644 index 000000000..525c5f6fc --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/WaitlistEntry.d.ts @@ -0,0 +1,15 @@ +import type { WaitlistEntryStatus } from './Enums'; +import { Invitation } from './Invitation'; +import type { WaitlistEntryJSON } from './JSON'; +export declare class WaitlistEntry { + readonly id: string; + readonly emailAddress: string; + readonly status: WaitlistEntryStatus; + readonly invitation: Invitation | null; + readonly createdAt: number; + readonly updatedAt: number; + readonly isLocked?: boolean | undefined; + constructor(id: string, emailAddress: string, status: WaitlistEntryStatus, invitation: Invitation | null, createdAt: number, updatedAt: number, isLocked?: boolean | undefined); + static fromJSON(data: WaitlistEntryJSON): WaitlistEntry; +} +//# sourceMappingURL=WaitlistEntry.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/WaitlistEntry.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/resources/WaitlistEntry.d.ts.map new file mode 100644 index 000000000..0bad70373 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/WaitlistEntry.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"WaitlistEntry.d.ts","sourceRoot":"","sources":["../../../src/api/resources/WaitlistEntry.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AACnD,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,QAAQ,CAAC;AAEhD,qBAAa,aAAa;IAEtB,QAAQ,CAAC,EAAE,EAAE,MAAM;IACnB,QAAQ,CAAC,YAAY,EAAE,MAAM;IAC7B,QAAQ,CAAC,MAAM,EAAE,mBAAmB;IACpC,QAAQ,CAAC,UAAU,EAAE,UAAU,GAAG,IAAI;IACtC,QAAQ,CAAC,SAAS,EAAE,MAAM;IAC1B,QAAQ,CAAC,SAAS,EAAE,MAAM;IAC1B,QAAQ,CAAC,QAAQ,CAAC,EAAE,OAAO;gBANlB,EAAE,EAAE,MAAM,EACV,YAAY,EAAE,MAAM,EACpB,MAAM,EAAE,mBAAmB,EAC3B,UAAU,EAAE,UAAU,GAAG,IAAI,EAC7B,SAAS,EAAE,MAAM,EACjB,SAAS,EAAE,MAAM,EACjB,QAAQ,CAAC,EAAE,OAAO,YAAA;IAG7B,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,iBAAiB,GAAG,aAAa;CAWxD"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/Web3Wallet.d.ts b/backend/node_modules/@clerk/backend/dist/api/resources/Web3Wallet.d.ts new file mode 100644 index 000000000..f81299161 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/Web3Wallet.d.ts @@ -0,0 +1,36 @@ +import type { Web3WalletJSON } from './JSON'; +import { Verification } from './Verification'; +/** + * The Backend `Web3Wallet` object describes a Web3 wallet address. The address can be used as a proof of identification for users. + * + * Web3 addresses must be verified to ensure that they can be assigned to their rightful owners. The verification is completed via Web3 wallet browser extensions, such as [Metamask](https://metamask.io/), [Coinbase Wallet](https://www.coinbase.com/wallet), and [OKX Wallet](https://www.okx.com/help/section/faq-web3-wallet). The `Web3Wallet3` object holds all the necessary state around the verification process. + */ +export declare class Web3Wallet { + /** + * The unique ID for the Web3 wallet. + */ + readonly id: string; + /** + * The Web3 wallet address, made up of 0x + 40 hexadecimal characters. + */ + readonly web3Wallet: string; + /** + * An object holding information on the verification of this Web3 wallet. + */ + readonly verification: Verification | null; + constructor( + /** + * The unique ID for the Web3 wallet. + */ + id: string, + /** + * The Web3 wallet address, made up of 0x + 40 hexadecimal characters. + */ + web3Wallet: string, + /** + * An object holding information on the verification of this Web3 wallet. + */ + verification: Verification | null); + static fromJSON(data: Web3WalletJSON): Web3Wallet; +} +//# sourceMappingURL=Web3Wallet.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/Web3Wallet.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/resources/Web3Wallet.d.ts.map new file mode 100644 index 000000000..29ada592e --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/Web3Wallet.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"Web3Wallet.d.ts","sourceRoot":"","sources":["../../../src/api/resources/Web3Wallet.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,QAAQ,CAAC;AAC7C,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAE9C;;;;GAIG;AACH,qBAAa,UAAU;IAEnB;;OAEG;IACH,QAAQ,CAAC,EAAE,EAAE,MAAM;IACnB;;OAEG;IACH,QAAQ,CAAC,UAAU,EAAE,MAAM;IAC3B;;OAEG;IACH,QAAQ,CAAC,YAAY,EAAE,YAAY,GAAG,IAAI;;IAX1C;;OAEG;IACM,EAAE,EAAE,MAAM;IACnB;;OAEG;IACM,UAAU,EAAE,MAAM;IAC3B;;OAEG;IACM,YAAY,EAAE,YAAY,GAAG,IAAI;IAG5C,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,cAAc,GAAG,UAAU;CAGlD"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/Webhooks.d.ts b/backend/node_modules/@clerk/backend/dist/api/resources/Webhooks.d.ts new file mode 100644 index 000000000..c78f5c8ec --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/Webhooks.d.ts @@ -0,0 +1,31 @@ +import type { BillingPaymentAttemptWebhookEventJSON, BillingSubscriptionItemWebhookEventJSON, BillingSubscriptionWebhookEventJSON, DeletedObjectJSON, EmailJSON, OrganizationDomainJSON, OrganizationInvitationJSON, OrganizationJSON, OrganizationMembershipJSON, PermissionJSON, RoleJSON, SessionJSON, SMSMessageJSON, UserJSON, WaitlistEntryJSON } from './JSON'; +type WebhookEventAttributes = { + http_request: { + client_ip: string; + user_agent: string; + }; +}; +type Webhook = { + type: EvtType; + object: 'event'; + data: Data; + event_attributes: WebhookEventAttributes; +}; +export type UserWebhookEvent = Webhook<'user.created' | 'user.updated', UserJSON> | Webhook<'user.deleted', DeletedObjectJSON>; +export type EmailWebhookEvent = Webhook<'email.created', EmailJSON>; +export type SMSWebhookEvent = Webhook<'sms.created', SMSMessageJSON>; +export type SessionWebhookEvent = Webhook<'session.created' | 'session.ended' | 'session.removed' | 'session.revoked', SessionJSON>; +export type OrganizationWebhookEvent = Webhook<'organization.created' | 'organization.updated', OrganizationJSON> | Webhook<'organization.deleted', DeletedObjectJSON>; +export type OrganizationDomainWebhookEvent = Webhook<'organizationDomain.created' | 'organizationDomain.updated', OrganizationDomainJSON> | Webhook<'organizationDomain.deleted', DeletedObjectJSON>; +export type OrganizationMembershipWebhookEvent = Webhook<'organizationMembership.created' | 'organizationMembership.deleted' | 'organizationMembership.updated', OrganizationMembershipJSON>; +export type OrganizationInvitationWebhookEvent = Webhook<'organizationInvitation.accepted' | 'organizationInvitation.created' | 'organizationInvitation.revoked', OrganizationInvitationJSON>; +export type RoleWebhookEvent = Webhook<'role.created' | 'role.updated' | 'role.deleted', RoleJSON>; +export type PermissionWebhookEvent = Webhook<'permission.created' | 'permission.updated' | 'permission.deleted', PermissionJSON>; +export type WaitlistEntryWebhookEvent = Webhook<'waitlistEntry.created' | 'waitlistEntry.updated', WaitlistEntryJSON>; +export type BillingPaymentAttemptWebhookEvent = Webhook<'paymentAttempt.created' | 'paymentAttempt.updated', BillingPaymentAttemptWebhookEventJSON>; +export type BillingSubscriptionWebhookEvent = Webhook<'subscription.created' | 'subscription.updated' | 'subscription.active' | 'subscription.pastDue', BillingSubscriptionWebhookEventJSON>; +export type BillingSubscriptionItemWebhookEvent = Webhook<'subscriptionItem.created' | 'subscriptionItem.updated' | 'subscriptionItem.active' | 'subscriptionItem.canceled' | 'subscriptionItem.upcoming' | 'subscriptionItem.ended' | 'subscriptionItem.abandoned' | 'subscriptionItem.incomplete' | 'subscriptionItem.pastDue' | 'subscriptionItem.freeTrialEnding', BillingSubscriptionItemWebhookEventJSON>; +export type WebhookEvent = UserWebhookEvent | SessionWebhookEvent | EmailWebhookEvent | SMSWebhookEvent | OrganizationWebhookEvent | OrganizationDomainWebhookEvent | OrganizationMembershipWebhookEvent | OrganizationInvitationWebhookEvent | RoleWebhookEvent | PermissionWebhookEvent | WaitlistEntryWebhookEvent | BillingPaymentAttemptWebhookEvent | BillingSubscriptionWebhookEvent | BillingSubscriptionItemWebhookEvent; +export type WebhookEventType = WebhookEvent['type']; +export {}; +//# sourceMappingURL=Webhooks.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/Webhooks.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/resources/Webhooks.d.ts.map new file mode 100644 index 000000000..308191e6d --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/Webhooks.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"Webhooks.d.ts","sourceRoot":"","sources":["../../../src/api/resources/Webhooks.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,qCAAqC,EACrC,uCAAuC,EACvC,mCAAmC,EACnC,iBAAiB,EACjB,SAAS,EACT,sBAAsB,EACtB,0BAA0B,EAC1B,gBAAgB,EAChB,0BAA0B,EAC1B,cAAc,EACd,QAAQ,EACR,WAAW,EACX,cAAc,EACd,QAAQ,EACR,iBAAiB,EAClB,MAAM,QAAQ,CAAC;AAEhB,KAAK,sBAAsB,GAAG;IAC5B,YAAY,EAAE;QACZ,SAAS,EAAE,MAAM,CAAC;QAClB,UAAU,EAAE,MAAM,CAAC;KACpB,CAAC;CACH,CAAC;AAEF,KAAK,OAAO,CAAC,OAAO,EAAE,IAAI,IAAI;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,MAAM,EAAE,OAAO,CAAC;IAAC,IAAI,EAAE,IAAI,CAAC;IAAC,gBAAgB,EAAE,sBAAsB,CAAA;CAAE,CAAC;AAEvH,MAAM,MAAM,gBAAgB,GACxB,OAAO,CAAC,cAAc,GAAG,cAAc,EAAE,QAAQ,CAAC,GAClD,OAAO,CAAC,cAAc,EAAE,iBAAiB,CAAC,CAAC;AAE/C,MAAM,MAAM,iBAAiB,GAAG,OAAO,CAAC,eAAe,EAAE,SAAS,CAAC,CAAC;AAEpE,MAAM,MAAM,eAAe,GAAG,OAAO,CAAC,aAAa,EAAE,cAAc,CAAC,CAAC;AAErE,MAAM,MAAM,mBAAmB,GAAG,OAAO,CACvC,iBAAiB,GAAG,eAAe,GAAG,iBAAiB,GAAG,iBAAiB,EAC3E,WAAW,CACZ,CAAC;AAEF,MAAM,MAAM,wBAAwB,GAChC,OAAO,CAAC,sBAAsB,GAAG,sBAAsB,EAAE,gBAAgB,CAAC,GAC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f,wBAAwB,GACxB,8BAA8B,GAC9B,kCAAkC,GAClC,kCAAkC,GAClC,gBAAgB,GAChB,sBAAsB,GACtB,yBAAyB,GACzB,iCAAiC,GACjC,+BAA+B,GAC/B,mCAAmC,CAAC;AAExC,MAAM,MAAM,gBAAgB,GAAG,YAAY,CAAC,MAAM,CAAC,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/index.d.ts b/backend/node_modules/@clerk/backend/dist/api/resources/index.d.ts new file mode 100644 index 000000000..d2e942978 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/index.d.ts @@ -0,0 +1,55 @@ +export * from './AccountlessApplication'; +export * from './ActorToken'; +export * from './AllowlistIdentifier'; +export * from './APIKey'; +export * from './BlocklistIdentifier'; +export * from './Client'; +export * from './CnameTarget'; +export * from './Cookies'; +export * from './DeletedObject'; +export * from './Domain'; +export * from './Email'; +export * from './EmailAddress'; +export type { InvitationStatus, OAuthProvider, OAuthStrategy, OrganizationInvitationStatus, OrganizationMembershipRole, SignInStatus, } from './Enums'; +export type { SignUpStatus } from '@clerk/types'; +export * from './ExternalAccount'; +export * from './IdentificationLink'; +export * from './IdPOAuthAccessToken'; +export * from './Instance'; +export * from './InstanceRestrictions'; +export * from './InstanceSettings'; +export * from './Invitation'; +export * from './JSON'; +export * from './Machine'; +export * from './MachineScope'; +export * from './MachineSecretKey'; +export * from './M2MToken'; +export * from './JwtTemplate'; +export * from './OauthAccessToken'; +export * from './OAuthApplication'; +export * from './Organization'; +export * from './OrganizationDomain'; +export * from './OrganizationInvitation'; +export * from './OrganizationMembership'; +export * from './OrganizationSettings'; +export * from './PhoneNumber'; +export * from './ProxyCheck'; +export * from './RedirectUrl'; +export * from './SamlAccount'; +export * from './SamlConnection'; +export * from './Session'; +export * from './SignInTokens'; +export * from './SignUpAttempt'; +export * from './SMSMessage'; +export * from './TestingToken'; +export * from './Token'; +export * from './User'; +export * from './Verification'; +export * from './WaitlistEntry'; +export * from './Web3Wallet'; +export * from './CommercePlan'; +export * from './CommerceSubscription'; +export * from './CommerceSubscriptionItem'; +export * from './Feature'; +export type { EmailWebhookEvent, OrganizationWebhookEvent, OrganizationDomainWebhookEvent, OrganizationInvitationWebhookEvent, OrganizationMembershipWebhookEvent, PermissionWebhookEvent, RoleWebhookEvent, SessionWebhookEvent, SMSWebhookEvent, UserWebhookEvent, WaitlistEntryWebhookEvent, WebhookEvent, WebhookEventType, } from './Webhooks'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/api/resources/index.d.ts.map b/backend/node_modules/@clerk/backend/dist/api/resources/index.d.ts.map new file mode 100644 index 000000000..8b3b593a2 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/api/resources/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/api/resources/index.ts"],"names":[],"mappings":"AAAA,cAAc,0BAA0B,CAAC;AACzC,cAAc,cAAc,CAAC;AAC7B,cAAc,uBAAuB,CAAC;AACtC,cAAc,UAAU,CAAC;AACzB,cAAc,uBAAuB,CAAC;AACtC,cAAc,UAAU,CAAC;AACzB,cAAc,eAAe,CAAC;AAC9B,cAAc,WAAW,CAAC;AAC1B,cAAc,iBAAiB,CAAC;AAChC,cAAc,UAAU,CAAC;AACzB,cAAc,SAAS,CAAC;AACxB,cAAc,gBAAgB,CAAC;AAE/B,YAAY,EACV,gBAAgB,EAChB,aAAa,EACb,aAAa,EACb,4BAA4B,EAC5B,0BAA0B,EAC1B,YAAY,GACb,MAAM,SAAS,CAAC;AAEjB,YAAY,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAEjD,cAAc,mBAAmB,CAAC;AAClC,cAAc,sBAAsB,CAAC;AACrC,cAAc,uBAAuB,CAAC;AACtC,cAAc,YAAY,CAAC;AAC3B,cAAc,wBAAwB,CAAC;AACvC,cAAc,oBAAoB,CAAC;AACnC,cAAc,cAAc,CAAC;AAC7B,cAAc,QAAQ,CAAC;AACvB,cAAc,WAAW,CAAC;AAC1B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,oBAAoB,CAAC;AACnC,cAAc,YAAY,CAAC;AAC3B,cAAc,eAAe,CAAC;AAC9B,cAAc,oBAAoB,CAAC;AACnC,cAAc,oBAAoB,CAAC;AACnC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,sBAAsB,CAAC;AACrC,cAAc,0BAA0B,CAAC;AACzC,cAAc,0BAA0B,CAAC;AACzC,cAAc,wBAAwB,CAAC;AACvC,cAAc,eAAe,CAAC;AAC9B,cAAc,cAAc,CAAC;AAC7B,cAAc,eAAe,CAAC;AAC9B,cAAc,eAAe,CAAC;AAC9B,cAAc,kBAAkB,CAAC;AACjC,cAAc,WAAW,CAAC;AAC1B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,iBAAiB,CAAC;AAChC,cAAc,cAAc,CAAC;AAC7B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,SAAS,CAAC;AACxB,cAAc,QAAQ,CAAC;AACvB,cAAc,gBAAgB,CAAC;AAC/B,cAAc,iBAAiB,CAAC;AAChC,cAAc,cAAc,CAAC;AAC7B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,wBAAwB,CAAC;AACvC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,WAAW,CAAC;AAE1B,YAAY,EACV,iBAAiB,EACjB,wBAAwB,EACxB,8BAA8B,EAC9B,kCAAkC,EAClC,kCAAkC,EAClC,sBAAsB,EACtB,gBAAgB,EAChB,mBAAmB,EACnB,eAAe,EACf,gBAAgB,EAChB,yBAAyB,EACzB,YAAY,EACZ,gBAAgB,GACjB,MAAM,YAAY,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/chunk-EEWX6LTS.mjs b/backend/node_modules/@clerk/backend/dist/chunk-EEWX6LTS.mjs new file mode 100644 index 000000000..d1ccd05b9 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/chunk-EEWX6LTS.mjs @@ -0,0 +1,5581 @@ +import { + deprecated, + errorThrower, + getCookieSuffix, + getSuffixedCookieName, + isDevelopmentFromSecretKey, + parsePublishableKey, + retry +} from "./chunk-LWOXHF4E.mjs"; +import { + assertHeaderAlgorithm, + assertHeaderType, + decodeJwt, + hasValidSignature, + runtime, + verifyJwt +} from "./chunk-XJ4RTXJG.mjs"; +import { + MachineTokenVerificationError, + MachineTokenVerificationErrorCode, + TokenVerificationError, + TokenVerificationErrorAction, + TokenVerificationErrorCode, + TokenVerificationErrorReason +} from "./chunk-YW6OOOXM.mjs"; +import { + __privateAdd, + __privateMethod +} from "./chunk-RPS7XK5K.mjs"; + +// src/constants.ts +var API_URL = "https://api.clerk.com"; +var API_VERSION = "v1"; +var USER_AGENT = `${"@clerk/backend"}@${"2.15.0"}`; +var MAX_CACHE_LAST_UPDATED_AT_SECONDS = 5 * 60; +var SUPPORTED_BAPI_VERSION = "2025-04-10"; +var Attributes = { + AuthToken: "__clerkAuthToken", + AuthSignature: "__clerkAuthSignature", + AuthStatus: "__clerkAuthStatus", + AuthReason: "__clerkAuthReason", + AuthMessage: "__clerkAuthMessage", + ClerkUrl: "__clerkUrl" +}; +var Cookies = { + Session: "__session", + Refresh: "__refresh", + ClientUat: "__client_uat", + Handshake: "__clerk_handshake", + DevBrowser: "__clerk_db_jwt", + RedirectCount: "__clerk_redirect_count", + HandshakeNonce: "__clerk_handshake_nonce" +}; +var QueryParameters = { + ClerkSynced: "__clerk_synced", + SuffixedCookies: "suffixed_cookies", + ClerkRedirectUrl: "__clerk_redirect_url", + // use the reference to Cookies to indicate that it's the same value + DevBrowser: Cookies.DevBrowser, + Handshake: Cookies.Handshake, + HandshakeHelp: "__clerk_help", + LegacyDevBrowser: "__dev_session", + HandshakeReason: "__clerk_hs_reason", + HandshakeNonce: Cookies.HandshakeNonce, + HandshakeFormat: "format" +}; +var Headers2 = { + Accept: "accept", + AuthMessage: "x-clerk-auth-message", + Authorization: "authorization", + AuthReason: "x-clerk-auth-reason", + AuthSignature: "x-clerk-auth-signature", + AuthStatus: "x-clerk-auth-status", + AuthToken: "x-clerk-auth-token", + CacheControl: "cache-control", + ClerkRedirectTo: "x-clerk-redirect-to", + ClerkRequestData: "x-clerk-request-data", + ClerkUrl: "x-clerk-clerk-url", + CloudFrontForwardedProto: "cloudfront-forwarded-proto", + ContentType: "content-type", + ContentSecurityPolicy: "content-security-policy", + ContentSecurityPolicyReportOnly: "content-security-policy-report-only", + EnableDebug: "x-clerk-debug", + ForwardedHost: "x-forwarded-host", + ForwardedPort: "x-forwarded-port", + ForwardedProto: "x-forwarded-proto", + Host: "host", + Location: "location", + Nonce: "x-nonce", + Origin: "origin", + Referrer: "referer", + SecFetchDest: "sec-fetch-dest", + SecFetchSite: "sec-fetch-site", + UserAgent: "user-agent", + ReportingEndpoints: "reporting-endpoints" +}; +var ContentTypes = { + Json: "application/json" +}; +var constants = { + Attributes, + Cookies, + Headers: Headers2, + ContentTypes, + QueryParameters +}; + +// src/createRedirect.ts +import { buildAccountsBaseUrl } from "@clerk/shared/buildAccountsBaseUrl"; +var buildUrl = (_baseUrl, _targetUrl, _returnBackUrl, _devBrowserToken) => { + if (_baseUrl === "") { + return legacyBuildUrl(_targetUrl.toString(), _returnBackUrl?.toString()); + } + const baseUrl = new URL(_baseUrl); + const returnBackUrl = _returnBackUrl ? new URL(_returnBackUrl, baseUrl) : void 0; + const res = new URL(_targetUrl, baseUrl); + const isCrossOriginRedirect = `${baseUrl.hostname}:${baseUrl.port}` !== `${res.hostname}:${res.port}`; + if (returnBackUrl) { + if (isCrossOriginRedirect) { + returnBackUrl.searchParams.delete(constants.QueryParameters.ClerkSynced); + } + res.searchParams.set("redirect_url", returnBackUrl.toString()); + } + if (isCrossOriginRedirect && _devBrowserToken) { + res.searchParams.set(constants.QueryParameters.DevBrowser, _devBrowserToken); + } + return res.toString(); +}; +var legacyBuildUrl = (targetUrl, redirectUrl) => { + let url; + if (!targetUrl.startsWith("http")) { + if (!redirectUrl || !redirectUrl.startsWith("http")) { + throw new Error("destination url or return back url should be an absolute path url!"); + } + const baseURL = new URL(redirectUrl); + url = new URL(targetUrl, baseURL.origin); + } else { + url = new URL(targetUrl); + } + if (redirectUrl) { + url.searchParams.set("redirect_url", redirectUrl); + } + return url.toString(); +}; +var createRedirect = (params) => { + const { publishableKey, redirectAdapter, signInUrl, signUpUrl, baseUrl, sessionStatus } = params; + const parsedPublishableKey = parsePublishableKey(publishableKey); + const frontendApi = parsedPublishableKey?.frontendApi; + const isDevelopment = parsedPublishableKey?.instanceType === "development"; + const accountsBaseUrl = buildAccountsBaseUrl(frontendApi); + const hasPendingStatus = sessionStatus === "pending"; + const redirectToTasks = (url, { returnBackUrl }) => { + return redirectAdapter( + buildUrl(baseUrl, `${url}/tasks`, returnBackUrl, isDevelopment ? params.devBrowserToken : null) + ); + }; + const redirectToSignUp = ({ returnBackUrl } = {}) => { + if (!signUpUrl && !accountsBaseUrl) { + errorThrower.throwMissingPublishableKeyError(); + } + const accountsSignUpUrl = `${accountsBaseUrl}/sign-up`; + function buildSignUpUrl(signIn) { + if (!signIn) { + return; + } + const url = new URL(signIn, baseUrl); + url.pathname = `${url.pathname}/create`; + return url.toString(); + } + const targetUrl = signUpUrl || buildSignUpUrl(signInUrl) || accountsSignUpUrl; + if (hasPendingStatus) { + return redirectToTasks(targetUrl, { returnBackUrl }); + } + return redirectAdapter(buildUrl(baseUrl, targetUrl, returnBackUrl, isDevelopment ? params.devBrowserToken : null)); + }; + const redirectToSignIn = ({ returnBackUrl } = {}) => { + if (!signInUrl && !accountsBaseUrl) { + errorThrower.throwMissingPublishableKeyError(); + } + const accountsSignInUrl = `${accountsBaseUrl}/sign-in`; + const targetUrl = signInUrl || accountsSignInUrl; + if (hasPendingStatus) { + return redirectToTasks(targetUrl, { returnBackUrl }); + } + return redirectAdapter(buildUrl(baseUrl, targetUrl, returnBackUrl, isDevelopment ? params.devBrowserToken : null)); + }; + return { redirectToSignUp, redirectToSignIn }; +}; + +// src/util/mergePreDefinedOptions.ts +function mergePreDefinedOptions(preDefinedOptions, options) { + return Object.keys(preDefinedOptions).reduce( + (obj, key) => { + return { ...obj, [key]: options[key] || obj[key] }; + }, + { ...preDefinedOptions } + ); +} + +// src/util/optionsAssertions.ts +function assertValidSecretKey(val) { + if (!val || typeof val !== "string") { + throw Error("Missing Clerk Secret Key. Go to https://dashboard.clerk.com and get your key for your instance."); + } +} +function assertValidPublishableKey(val) { + parsePublishableKey(val, { fatal: true }); +} + +// src/tokens/authenticateContext.ts +import { buildAccountsBaseUrl as buildAccountsBaseUrl2 } from "@clerk/shared/buildAccountsBaseUrl"; +import { isCurrentDevAccountPortalOrigin, isLegacyDevAccountPortalOrigin } from "@clerk/shared/url"; + +// src/tokens/tokenTypes.ts +var TokenType = { + SessionToken: "session_token", + ApiKey: "api_key", + M2MToken: "m2m_token", + OAuthToken: "oauth_token" +}; + +// src/tokens/authenticateContext.ts +var AuthenticateContext = class { + constructor(cookieSuffix, clerkRequest, options) { + this.cookieSuffix = cookieSuffix; + this.clerkRequest = clerkRequest; + /** + * The original Clerk frontend API URL, extracted from publishable key before proxy URL override. + * Used for backend operations like token validation and issuer checking. + */ + this.originalFrontendApi = ""; + if (options.acceptsToken === TokenType.M2MToken || options.acceptsToken === TokenType.ApiKey) { + this.initHeaderValues(); + } else { + this.initPublishableKeyValues(options); + this.initHeaderValues(); + this.initCookieValues(); + this.initHandshakeValues(); + } + Object.assign(this, options); + this.clerkUrl = this.clerkRequest.clerkUrl; + } + /** + * Retrieves the session token from either the cookie or the header. + * + * @returns {string | undefined} The session token if available, otherwise undefined. + */ + get sessionToken() { + return this.sessionTokenInCookie || this.tokenInHeader; + } + usesSuffixedCookies() { + const suffixedClientUat = this.getSuffixedCookie(constants.Cookies.ClientUat); + const clientUat = this.getCookie(constants.Cookies.ClientUat); + const suffixedSession = this.getSuffixedCookie(constants.Cookies.Session) || ""; + const session = this.getCookie(constants.Cookies.Session) || ""; + if (session && !this.tokenHasIssuer(session)) { + return false; + } + if (session && !this.tokenBelongsToInstance(session)) { + return true; + } + if (!suffixedClientUat && !suffixedSession) { + return false; + } + const { data: sessionData } = decodeJwt(session); + const sessionIat = sessionData?.payload.iat || 0; + const { data: suffixedSessionData } = decodeJwt(suffixedSession); + const suffixedSessionIat = suffixedSessionData?.payload.iat || 0; + if (suffixedClientUat !== "0" && clientUat !== "0" && sessionIat > suffixedSessionIat) { + return false; + } + if (suffixedClientUat === "0" && clientUat !== "0") { + return false; + } + if (this.instanceType !== "production") { + const isSuffixedSessionExpired = this.sessionExpired(suffixedSessionData); + if (suffixedClientUat !== "0" && clientUat === "0" && isSuffixedSessionExpired) { + return false; + } + } + if (!suffixedClientUat && suffixedSession) { + return false; + } + return true; + } + /** + * Determines if the request came from a different origin based on the referrer header. + * Used for cross-origin detection in multi-domain authentication flows. + * + * @returns {boolean} True if referrer exists and is from a different origin, false otherwise. + */ + isCrossOriginReferrer() { + if (!this.referrer || !this.clerkUrl.origin) { + return false; + } + try { + const referrerOrigin = new URL(this.referrer).origin; + return referrerOrigin !== this.clerkUrl.origin; + } catch { + return false; + } + } + /** + * Determines if the referrer URL is from a Clerk domain (accounts portal or FAPI). + * This includes both development and production account portal domains, as well as FAPI domains + * used for redirect-based authentication flows. + * + * @returns {boolean} True if the referrer is from a Clerk accounts portal or FAPI domain, false otherwise + */ + isKnownClerkReferrer() { + if (!this.referrer) { + return false; + } + try { + const referrerOrigin = new URL(this.referrer); + const referrerHost = referrerOrigin.hostname; + if (this.frontendApi) { + const fapiHost = this.frontendApi.startsWith("http") ? new URL(this.frontendApi).hostname : this.frontendApi; + if (referrerHost === fapiHost) { + return true; + } + } + if (isLegacyDevAccountPortalOrigin(referrerHost) || isCurrentDevAccountPortalOrigin(referrerHost)) { + return true; + } + const expectedAccountsUrl = buildAccountsBaseUrl2(this.frontendApi); + if (expectedAccountsUrl) { + const expectedAccountsOrigin = new URL(expectedAccountsUrl).origin; + if (referrerOrigin.origin === expectedAccountsOrigin) { + return true; + } + } + if (referrerHost.startsWith("accounts.")) { + return true; + } + return false; + } catch { + return false; + } + } + initPublishableKeyValues(options) { + assertValidPublishableKey(options.publishableKey); + this.publishableKey = options.publishableKey; + const originalPk = parsePublishableKey(this.publishableKey, { + fatal: true, + domain: options.domain, + isSatellite: options.isSatellite + }); + this.originalFrontendApi = originalPk.frontendApi; + const pk = parsePublishableKey(this.publishableKey, { + fatal: true, + proxyUrl: options.proxyUrl, + domain: options.domain, + isSatellite: options.isSatellite + }); + this.instanceType = pk.instanceType; + this.frontendApi = pk.frontendApi; + } + initHeaderValues() { + this.tokenInHeader = this.parseAuthorizationHeader(this.getHeader(constants.Headers.Authorization)); + this.origin = this.getHeader(constants.Headers.Origin); + this.host = this.getHeader(constants.Headers.Host); + this.forwardedHost = this.getHeader(constants.Headers.ForwardedHost); + this.forwardedProto = this.getHeader(constants.Headers.CloudFrontForwardedProto) || this.getHeader(constants.Headers.ForwardedProto); + this.referrer = this.getHeader(constants.Headers.Referrer); + this.userAgent = this.getHeader(constants.Headers.UserAgent); + this.secFetchDest = this.getHeader(constants.Headers.SecFetchDest); + this.accept = this.getHeader(constants.Headers.Accept); + } + initCookieValues() { + this.sessionTokenInCookie = this.getSuffixedOrUnSuffixedCookie(constants.Cookies.Session); + this.refreshTokenInCookie = this.getSuffixedCookie(constants.Cookies.Refresh); + this.clientUat = Number.parseInt(this.getSuffixedOrUnSuffixedCookie(constants.Cookies.ClientUat) || "") || 0; + } + initHandshakeValues() { + this.devBrowserToken = this.getQueryParam(constants.QueryParameters.DevBrowser) || this.getSuffixedOrUnSuffixedCookie(constants.Cookies.DevBrowser); + this.handshakeToken = this.getQueryParam(constants.QueryParameters.Handshake) || this.getCookie(constants.Cookies.Handshake); + this.handshakeRedirectLoopCounter = Number(this.getCookie(constants.Cookies.RedirectCount)) || 0; + this.handshakeNonce = this.getQueryParam(constants.QueryParameters.HandshakeNonce) || this.getCookie(constants.Cookies.HandshakeNonce); + } + getQueryParam(name) { + return this.clerkRequest.clerkUrl.searchParams.get(name); + } + getHeader(name) { + return this.clerkRequest.headers.get(name) || void 0; + } + getCookie(name) { + return this.clerkRequest.cookies.get(name) || void 0; + } + getSuffixedCookie(name) { + return this.getCookie(getSuffixedCookieName(name, this.cookieSuffix)) || void 0; + } + getSuffixedOrUnSuffixedCookie(cookieName) { + if (this.usesSuffixedCookies()) { + return this.getSuffixedCookie(cookieName); + } + return this.getCookie(cookieName); + } + parseAuthorizationHeader(authorizationHeader) { + if (!authorizationHeader) { + return void 0; + } + const [scheme, token] = authorizationHeader.split(" ", 2); + if (!token) { + return scheme; + } + if (scheme === "Bearer") { + return token; + } + return void 0; + } + tokenHasIssuer(token) { + const { data, errors } = decodeJwt(token); + if (errors) { + return false; + } + return !!data.payload.iss; + } + tokenBelongsToInstance(token) { + if (!token) { + return false; + } + const { data, errors } = decodeJwt(token); + if (errors) { + return false; + } + const tokenIssuer = data.payload.iss.replace(/https?:\/\//gi, ""); + return this.originalFrontendApi === tokenIssuer; + } + sessionExpired(jwt) { + return !!jwt && jwt?.payload.exp <= Date.now() / 1e3 >> 0; + } +}; +var createAuthenticateContext = async (clerkRequest, options) => { + const cookieSuffix = options.publishableKey ? await getCookieSuffix(options.publishableKey, runtime.crypto.subtle) : ""; + return new AuthenticateContext(cookieSuffix, clerkRequest, options); +}; + +// src/tokens/authObjects.ts +import { createCheckAuthorization } from "@clerk/shared/authorization"; +import { __experimental_JWTPayloadToAuthObjectProperties } from "@clerk/shared/jwtPayloadParser"; + +// src/util/path.ts +var SEPARATOR = "/"; +var MULTIPLE_SEPARATOR_REGEX = new RegExp("(? p).join(SEPARATOR).replace(MULTIPLE_SEPARATOR_REGEX, SEPARATOR); +} + +// src/api/endpoints/AbstractApi.ts +var AbstractAPI = class { + constructor(request) { + this.request = request; + } + requireId(id) { + if (!id) { + throw new Error("A valid resource ID is required."); + } + } +}; + +// src/api/endpoints/ActorTokenApi.ts +var basePath = "/actor_tokens"; +var ActorTokenAPI = class extends AbstractAPI { + async create(params) { + return this.request({ + method: "POST", + path: basePath, + bodyParams: params + }); + } + async revoke(actorTokenId) { + this.requireId(actorTokenId); + return this.request({ + method: "POST", + path: joinPaths(basePath, actorTokenId, "revoke") + }); + } +}; + +// src/api/endpoints/AccountlessApplicationsAPI.ts +var basePath2 = "/accountless_applications"; +var AccountlessApplicationAPI = class extends AbstractAPI { + async createAccountlessApplication(params) { + const headerParams = params?.requestHeaders ? Object.fromEntries(params.requestHeaders.entries()) : void 0; + return this.request({ + method: "POST", + path: basePath2, + headerParams + }); + } + async completeAccountlessApplicationOnboarding(params) { + const headerParams = params?.requestHeaders ? Object.fromEntries(params.requestHeaders.entries()) : void 0; + return this.request({ + method: "POST", + path: joinPaths(basePath2, "complete"), + headerParams + }); + } +}; + +// src/api/endpoints/AllowlistIdentifierApi.ts +var basePath3 = "/allowlist_identifiers"; +var AllowlistIdentifierAPI = class extends AbstractAPI { + async getAllowlistIdentifierList(params = {}) { + return this.request({ + method: "GET", + path: basePath3, + queryParams: { ...params, paginated: true } + }); + } + async createAllowlistIdentifier(params) { + return this.request({ + method: "POST", + path: basePath3, + bodyParams: params + }); + } + async deleteAllowlistIdentifier(allowlistIdentifierId) { + this.requireId(allowlistIdentifierId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath3, allowlistIdentifierId) + }); + } +}; + +// src/api/endpoints/APIKeysApi.ts +var basePath4 = "/api_keys"; +var APIKeysAPI = class extends AbstractAPI { + async create(params) { + return this.request({ + method: "POST", + path: basePath4, + bodyParams: params + }); + } + async revoke(params) { + const { apiKeyId, ...bodyParams } = params; + this.requireId(apiKeyId); + return this.request({ + method: "POST", + path: joinPaths(basePath4, apiKeyId, "revoke"), + bodyParams + }); + } + async getSecret(apiKeyId) { + this.requireId(apiKeyId); + return this.request({ + method: "GET", + path: joinPaths(basePath4, apiKeyId, "secret") + }); + } + async verifySecret(secret) { + return this.request({ + method: "POST", + path: joinPaths(basePath4, "verify"), + bodyParams: { secret } + }); + } +}; + +// src/api/endpoints/BetaFeaturesApi.ts +var basePath5 = "/beta_features"; +var BetaFeaturesAPI = class extends AbstractAPI { + /** + * Change the domain of a production instance. + * + * Changing the domain requires updating the DNS records accordingly, deploying new SSL certificates, + * updating your Social Connection's redirect URLs and setting the new keys in your code. + * + * @remarks + * WARNING: Changing your domain will invalidate all current user sessions (i.e. users will be logged out). + * Also, while your application is being deployed, a small downtime is expected to occur. + */ + async changeDomain(params) { + return this.request({ + method: "POST", + path: joinPaths(basePath5, "change_domain"), + bodyParams: params + }); + } +}; + +// src/api/endpoints/BlocklistIdentifierApi.ts +var basePath6 = "/blocklist_identifiers"; +var BlocklistIdentifierAPI = class extends AbstractAPI { + async getBlocklistIdentifierList(params = {}) { + return this.request({ + method: "GET", + path: basePath6, + queryParams: params + }); + } + async createBlocklistIdentifier(params) { + return this.request({ + method: "POST", + path: basePath6, + bodyParams: params + }); + } + async deleteBlocklistIdentifier(blocklistIdentifierId) { + this.requireId(blocklistIdentifierId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath6, blocklistIdentifierId) + }); + } +}; + +// src/api/endpoints/ClientApi.ts +var basePath7 = "/clients"; +var ClientAPI = class extends AbstractAPI { + async getClientList(params = {}) { + return this.request({ + method: "GET", + path: basePath7, + queryParams: { ...params, paginated: true } + }); + } + async getClient(clientId) { + this.requireId(clientId); + return this.request({ + method: "GET", + path: joinPaths(basePath7, clientId) + }); + } + verifyClient(token) { + return this.request({ + method: "POST", + path: joinPaths(basePath7, "verify"), + bodyParams: { token } + }); + } + async getHandshakePayload(queryParams) { + return this.request({ + method: "GET", + path: joinPaths(basePath7, "handshake_payload"), + queryParams + }); + } +}; + +// src/api/endpoints/DomainApi.ts +var basePath8 = "/domains"; +var DomainAPI = class extends AbstractAPI { + async list() { + return this.request({ + method: "GET", + path: basePath8 + }); + } + async add(params) { + return this.request({ + method: "POST", + path: basePath8, + bodyParams: params + }); + } + async update(params) { + const { domainId, ...bodyParams } = params; + this.requireId(domainId); + return this.request({ + method: "PATCH", + path: joinPaths(basePath8, domainId), + bodyParams + }); + } + /** + * Deletes a satellite domain for the instance. + * It is currently not possible to delete the instance's primary domain. + */ + async delete(satelliteDomainId) { + return this.deleteDomain(satelliteDomainId); + } + /** + * @deprecated Use `delete` instead + */ + async deleteDomain(satelliteDomainId) { + this.requireId(satelliteDomainId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath8, satelliteDomainId) + }); + } +}; + +// src/api/endpoints/EmailAddressApi.ts +var basePath9 = "/email_addresses"; +var EmailAddressAPI = class extends AbstractAPI { + async getEmailAddress(emailAddressId) { + this.requireId(emailAddressId); + return this.request({ + method: "GET", + path: joinPaths(basePath9, emailAddressId) + }); + } + async createEmailAddress(params) { + return this.request({ + method: "POST", + path: basePath9, + bodyParams: params + }); + } + async updateEmailAddress(emailAddressId, params = {}) { + this.requireId(emailAddressId); + return this.request({ + method: "PATCH", + path: joinPaths(basePath9, emailAddressId), + bodyParams: params + }); + } + async deleteEmailAddress(emailAddressId) { + this.requireId(emailAddressId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath9, emailAddressId) + }); + } +}; + +// src/api/endpoints/IdPOAuthAccessTokenApi.ts +var basePath10 = "/oauth_applications/access_tokens"; +var IdPOAuthAccessTokenApi = class extends AbstractAPI { + async verifyAccessToken(accessToken) { + return this.request({ + method: "POST", + path: joinPaths(basePath10, "verify"), + bodyParams: { access_token: accessToken } + }); + } +}; + +// src/api/endpoints/InstanceApi.ts +var basePath11 = "/instance"; +var InstanceAPI = class extends AbstractAPI { + async get() { + return this.request({ + method: "GET", + path: basePath11 + }); + } + async update(params) { + return this.request({ + method: "PATCH", + path: basePath11, + bodyParams: params + }); + } + async updateRestrictions(params) { + return this.request({ + method: "PATCH", + path: joinPaths(basePath11, "restrictions"), + bodyParams: params + }); + } + async updateOrganizationSettings(params) { + return this.request({ + method: "PATCH", + path: joinPaths(basePath11, "organization_settings"), + bodyParams: params + }); + } +}; + +// src/api/endpoints/InvitationApi.ts +var basePath12 = "/invitations"; +var InvitationAPI = class extends AbstractAPI { + async getInvitationList(params = {}) { + return this.request({ + method: "GET", + path: basePath12, + queryParams: { ...params, paginated: true } + }); + } + async createInvitation(params) { + return this.request({ + method: "POST", + path: basePath12, + bodyParams: params + }); + } + async createInvitationBulk(params) { + return this.request({ + method: "POST", + path: joinPaths(basePath12, "bulk"), + bodyParams: params + }); + } + async revokeInvitation(invitationId) { + this.requireId(invitationId); + return this.request({ + method: "POST", + path: joinPaths(basePath12, invitationId, "revoke") + }); + } +}; + +// src/api/endpoints/MachineApi.ts +var basePath13 = "/machines"; +var MachineApi = class extends AbstractAPI { + async get(machineId) { + this.requireId(machineId); + return this.request({ + method: "GET", + path: joinPaths(basePath13, machineId) + }); + } + async list(queryParams = {}) { + return this.request({ + method: "GET", + path: basePath13, + queryParams + }); + } + async create(bodyParams) { + return this.request({ + method: "POST", + path: basePath13, + bodyParams + }); + } + async update(params) { + const { machineId, ...bodyParams } = params; + this.requireId(machineId); + return this.request({ + method: "PATCH", + path: joinPaths(basePath13, machineId), + bodyParams + }); + } + async delete(machineId) { + this.requireId(machineId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath13, machineId) + }); + } + async getSecretKey(machineId) { + this.requireId(machineId); + return this.request({ + method: "GET", + path: joinPaths(basePath13, machineId, "secret_key") + }); + } + async rotateSecretKey(params) { + const { machineId, previousTokenTtl } = params; + this.requireId(machineId); + return this.request({ + method: "POST", + path: joinPaths(basePath13, machineId, "secret_key", "rotate"), + bodyParams: { + previousTokenTtl + } + }); + } + /** + * Creates a new machine scope, allowing the specified machine to access another machine. + * + * @param machineId - The ID of the machine that will have access to another machine. + * @param toMachineId - The ID of the machine that will be scoped to the current machine. + */ + async createScope(machineId, toMachineId) { + this.requireId(machineId); + return this.request({ + method: "POST", + path: joinPaths(basePath13, machineId, "scopes"), + bodyParams: { + toMachineId + } + }); + } + /** + * Deletes a machine scope, removing access from one machine to another. + * + * @param machineId - The ID of the machine that has access to another machine. + * @param otherMachineId - The ID of the machine that is being accessed. + */ + async deleteScope(machineId, otherMachineId) { + this.requireId(machineId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath13, machineId, "scopes", otherMachineId) + }); + } +}; + +// src/api/endpoints/M2MTokenApi.ts +var basePath14 = "/m2m_tokens"; +var _M2MTokenApi_instances, createRequestOptions_fn; +var M2MTokenApi = class extends AbstractAPI { + constructor() { + super(...arguments); + __privateAdd(this, _M2MTokenApi_instances); + } + async createToken(params) { + const { claims = null, machineSecretKey, secondsUntilExpiration = null } = params || {}; + const requestOptions = __privateMethod(this, _M2MTokenApi_instances, createRequestOptions_fn).call(this, { + method: "POST", + path: basePath14, + bodyParams: { + secondsUntilExpiration, + claims + } + }, machineSecretKey); + return this.request(requestOptions); + } + async revokeToken(params) { + const { m2mTokenId, revocationReason = null, machineSecretKey } = params; + this.requireId(m2mTokenId); + const requestOptions = __privateMethod(this, _M2MTokenApi_instances, createRequestOptions_fn).call(this, { + method: "POST", + path: joinPaths(basePath14, m2mTokenId, "revoke"), + bodyParams: { + revocationReason + } + }, machineSecretKey); + return this.request(requestOptions); + } + async verifyToken(params) { + const { token, machineSecretKey } = params; + const requestOptions = __privateMethod(this, _M2MTokenApi_instances, createRequestOptions_fn).call(this, { + method: "POST", + path: joinPaths(basePath14, "verify"), + bodyParams: { token } + }, machineSecretKey); + return this.request(requestOptions); + } +}; +_M2MTokenApi_instances = new WeakSet(); +createRequestOptions_fn = function(options, machineSecretKey) { + if (machineSecretKey) { + return { + ...options, + headerParams: { + ...options.headerParams, + Authorization: `Bearer ${machineSecretKey}` + } + }; + } + return options; +}; + +// src/api/endpoints/JwksApi.ts +var basePath15 = "/jwks"; +var JwksAPI = class extends AbstractAPI { + async getJwks() { + return this.request({ + method: "GET", + path: basePath15 + }); + } +}; + +// src/api/endpoints/JwtTemplatesApi.ts +var basePath16 = "/jwt_templates"; +var JwtTemplatesApi = class extends AbstractAPI { + async list(params = {}) { + return this.request({ + method: "GET", + path: basePath16, + queryParams: { ...params, paginated: true } + }); + } + async get(templateId) { + this.requireId(templateId); + return this.request({ + method: "GET", + path: joinPaths(basePath16, templateId) + }); + } + async create(params) { + return this.request({ + method: "POST", + path: basePath16, + bodyParams: params + }); + } + async update(params) { + const { templateId, ...bodyParams } = params; + this.requireId(templateId); + return this.request({ + method: "PATCH", + path: joinPaths(basePath16, templateId), + bodyParams + }); + } + async delete(templateId) { + this.requireId(templateId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath16, templateId) + }); + } +}; + +// src/api/endpoints/OrganizationApi.ts +var basePath17 = "/organizations"; +var OrganizationAPI = class extends AbstractAPI { + async getOrganizationList(params) { + return this.request({ + method: "GET", + path: basePath17, + queryParams: params + }); + } + async createOrganization(params) { + return this.request({ + method: "POST", + path: basePath17, + bodyParams: params + }); + } + async getOrganization(params) { + const { includeMembersCount } = params; + const organizationIdOrSlug = "organizationId" in params ? params.organizationId : params.slug; + this.requireId(organizationIdOrSlug); + return this.request({ + method: "GET", + path: joinPaths(basePath17, organizationIdOrSlug), + queryParams: { + includeMembersCount + } + }); + } + async updateOrganization(organizationId, params) { + this.requireId(organizationId); + return this.request({ + method: "PATCH", + path: joinPaths(basePath17, organizationId), + bodyParams: params + }); + } + async updateOrganizationLogo(organizationId, params) { + this.requireId(organizationId); + const formData = new runtime.FormData(); + formData.append("file", params?.file); + if (params?.uploaderUserId) { + formData.append("uploader_user_id", params?.uploaderUserId); + } + return this.request({ + method: "PUT", + path: joinPaths(basePath17, organizationId, "logo"), + formData + }); + } + async deleteOrganizationLogo(organizationId) { + this.requireId(organizationId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath17, organizationId, "logo") + }); + } + async updateOrganizationMetadata(organizationId, params) { + this.requireId(organizationId); + return this.request({ + method: "PATCH", + path: joinPaths(basePath17, organizationId, "metadata"), + bodyParams: params + }); + } + async deleteOrganization(organizationId) { + return this.request({ + method: "DELETE", + path: joinPaths(basePath17, organizationId) + }); + } + async getOrganizationMembershipList(params) { + const { organizationId, ...queryParams } = params; + this.requireId(organizationId); + return this.request({ + method: "GET", + path: joinPaths(basePath17, organizationId, "memberships"), + queryParams + }); + } + async getInstanceOrganizationMembershipList(params) { + return this.request({ + method: "GET", + path: "/organization_memberships", + queryParams: params + }); + } + async createOrganizationMembership(params) { + const { organizationId, ...bodyParams } = params; + this.requireId(organizationId); + return this.request({ + method: "POST", + path: joinPaths(basePath17, organizationId, "memberships"), + bodyParams + }); + } + async updateOrganizationMembership(params) { + const { organizationId, userId, ...bodyParams } = params; + this.requireId(organizationId); + return this.request({ + method: "PATCH", + path: joinPaths(basePath17, organizationId, "memberships", userId), + bodyParams + }); + } + async updateOrganizationMembershipMetadata(params) { + const { organizationId, userId, ...bodyParams } = params; + return this.request({ + method: "PATCH", + path: joinPaths(basePath17, organizationId, "memberships", userId, "metadata"), + bodyParams + }); + } + async deleteOrganizationMembership(params) { + const { organizationId, userId } = params; + this.requireId(organizationId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath17, organizationId, "memberships", userId) + }); + } + async getOrganizationInvitationList(params) { + const { organizationId, ...queryParams } = params; + this.requireId(organizationId); + return this.request({ + method: "GET", + path: joinPaths(basePath17, organizationId, "invitations"), + queryParams + }); + } + async createOrganizationInvitation(params) { + const { organizationId, ...bodyParams } = params; + this.requireId(organizationId); + return this.request({ + method: "POST", + path: joinPaths(basePath17, organizationId, "invitations"), + bodyParams + }); + } + async createOrganizationInvitationBulk(organizationId, params) { + this.requireId(organizationId); + return this.request({ + method: "POST", + path: joinPaths(basePath17, organizationId, "invitations", "bulk"), + bodyParams: params + }); + } + async getOrganizationInvitation(params) { + const { organizationId, invitationId } = params; + this.requireId(organizationId); + this.requireId(invitationId); + return this.request({ + method: "GET", + path: joinPaths(basePath17, organizationId, "invitations", invitationId) + }); + } + async revokeOrganizationInvitation(params) { + const { organizationId, invitationId, ...bodyParams } = params; + this.requireId(organizationId); + return this.request({ + method: "POST", + path: joinPaths(basePath17, organizationId, "invitations", invitationId, "revoke"), + bodyParams + }); + } + async getOrganizationDomainList(params) { + const { organizationId, ...queryParams } = params; + this.requireId(organizationId); + return this.request({ + method: "GET", + path: joinPaths(basePath17, organizationId, "domains"), + queryParams + }); + } + async createOrganizationDomain(params) { + const { organizationId, ...bodyParams } = params; + this.requireId(organizationId); + return this.request({ + method: "POST", + path: joinPaths(basePath17, organizationId, "domains"), + bodyParams: { + ...bodyParams, + verified: bodyParams.verified ?? true + } + }); + } + async updateOrganizationDomain(params) { + const { organizationId, domainId, ...bodyParams } = params; + this.requireId(organizationId); + this.requireId(domainId); + return this.request({ + method: "PATCH", + path: joinPaths(basePath17, organizationId, "domains", domainId), + bodyParams + }); + } + async deleteOrganizationDomain(params) { + const { organizationId, domainId } = params; + this.requireId(organizationId); + this.requireId(domainId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath17, organizationId, "domains", domainId) + }); + } +}; + +// src/api/endpoints/OAuthApplicationsApi.ts +var basePath18 = "/oauth_applications"; +var OAuthApplicationsApi = class extends AbstractAPI { + async list(params = {}) { + return this.request({ + method: "GET", + path: basePath18, + queryParams: params + }); + } + async get(oauthApplicationId) { + this.requireId(oauthApplicationId); + return this.request({ + method: "GET", + path: joinPaths(basePath18, oauthApplicationId) + }); + } + async create(params) { + return this.request({ + method: "POST", + path: basePath18, + bodyParams: params + }); + } + async update(params) { + const { oauthApplicationId, ...bodyParams } = params; + this.requireId(oauthApplicationId); + return this.request({ + method: "PATCH", + path: joinPaths(basePath18, oauthApplicationId), + bodyParams + }); + } + async delete(oauthApplicationId) { + this.requireId(oauthApplicationId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath18, oauthApplicationId) + }); + } + async rotateSecret(oauthApplicationId) { + this.requireId(oauthApplicationId); + return this.request({ + method: "POST", + path: joinPaths(basePath18, oauthApplicationId, "rotate_secret") + }); + } +}; + +// src/api/endpoints/PhoneNumberApi.ts +var basePath19 = "/phone_numbers"; +var PhoneNumberAPI = class extends AbstractAPI { + async getPhoneNumber(phoneNumberId) { + this.requireId(phoneNumberId); + return this.request({ + method: "GET", + path: joinPaths(basePath19, phoneNumberId) + }); + } + async createPhoneNumber(params) { + return this.request({ + method: "POST", + path: basePath19, + bodyParams: params + }); + } + async updatePhoneNumber(phoneNumberId, params = {}) { + this.requireId(phoneNumberId); + return this.request({ + method: "PATCH", + path: joinPaths(basePath19, phoneNumberId), + bodyParams: params + }); + } + async deletePhoneNumber(phoneNumberId) { + this.requireId(phoneNumberId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath19, phoneNumberId) + }); + } +}; + +// src/api/endpoints/ProxyCheckApi.ts +var basePath20 = "/proxy_checks"; +var ProxyCheckAPI = class extends AbstractAPI { + async verify(params) { + return this.request({ + method: "POST", + path: basePath20, + bodyParams: params + }); + } +}; + +// src/api/endpoints/RedirectUrlApi.ts +var basePath21 = "/redirect_urls"; +var RedirectUrlAPI = class extends AbstractAPI { + async getRedirectUrlList() { + return this.request({ + method: "GET", + path: basePath21, + queryParams: { paginated: true } + }); + } + async getRedirectUrl(redirectUrlId) { + this.requireId(redirectUrlId); + return this.request({ + method: "GET", + path: joinPaths(basePath21, redirectUrlId) + }); + } + async createRedirectUrl(params) { + return this.request({ + method: "POST", + path: basePath21, + bodyParams: params + }); + } + async deleteRedirectUrl(redirectUrlId) { + this.requireId(redirectUrlId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath21, redirectUrlId) + }); + } +}; + +// src/api/endpoints/SamlConnectionApi.ts +var basePath22 = "/saml_connections"; +var SamlConnectionAPI = class extends AbstractAPI { + async getSamlConnectionList(params = {}) { + return this.request({ + method: "GET", + path: basePath22, + queryParams: params + }); + } + async createSamlConnection(params) { + return this.request({ + method: "POST", + path: basePath22, + bodyParams: params, + options: { + deepSnakecaseBodyParamKeys: true + } + }); + } + async getSamlConnection(samlConnectionId) { + this.requireId(samlConnectionId); + return this.request({ + method: "GET", + path: joinPaths(basePath22, samlConnectionId) + }); + } + async updateSamlConnection(samlConnectionId, params = {}) { + this.requireId(samlConnectionId); + return this.request({ + method: "PATCH", + path: joinPaths(basePath22, samlConnectionId), + bodyParams: params, + options: { + deepSnakecaseBodyParamKeys: true + } + }); + } + async deleteSamlConnection(samlConnectionId) { + this.requireId(samlConnectionId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath22, samlConnectionId) + }); + } +}; + +// src/api/endpoints/SessionApi.ts +var basePath23 = "/sessions"; +var SessionAPI = class extends AbstractAPI { + async getSessionList(params = {}) { + return this.request({ + method: "GET", + path: basePath23, + queryParams: { ...params, paginated: true } + }); + } + async getSession(sessionId) { + this.requireId(sessionId); + return this.request({ + method: "GET", + path: joinPaths(basePath23, sessionId) + }); + } + async createSession(params) { + return this.request({ + method: "POST", + path: basePath23, + bodyParams: params + }); + } + async revokeSession(sessionId) { + this.requireId(sessionId); + return this.request({ + method: "POST", + path: joinPaths(basePath23, sessionId, "revoke") + }); + } + async verifySession(sessionId, token) { + this.requireId(sessionId); + return this.request({ + method: "POST", + path: joinPaths(basePath23, sessionId, "verify"), + bodyParams: { token } + }); + } + /** + * Retrieves a session token or generates a JWT using a specified template. + * + * @param sessionId - The ID of the session for which to generate the token + * @param template - Optional name of the JWT template configured in the Clerk Dashboard. + * @param expiresInSeconds - Optional expiration time for the token in seconds. + * If not provided, uses the default expiration. + * + * @returns A promise that resolves to the generated token + * + * @throws {Error} When sessionId is invalid or empty + */ + async getToken(sessionId, template, expiresInSeconds) { + this.requireId(sessionId); + const path = template ? joinPaths(basePath23, sessionId, "tokens", template) : joinPaths(basePath23, sessionId, "tokens"); + const requestOptions = { + method: "POST", + path + }; + if (expiresInSeconds !== void 0) { + requestOptions.bodyParams = { expires_in_seconds: expiresInSeconds }; + } + return this.request(requestOptions); + } + async refreshSession(sessionId, params) { + this.requireId(sessionId); + const { suffixed_cookies, ...restParams } = params; + return this.request({ + method: "POST", + path: joinPaths(basePath23, sessionId, "refresh"), + bodyParams: restParams, + queryParams: { suffixed_cookies } + }); + } +}; + +// src/api/endpoints/SignInTokenApi.ts +var basePath24 = "/sign_in_tokens"; +var SignInTokenAPI = class extends AbstractAPI { + async createSignInToken(params) { + return this.request({ + method: "POST", + path: basePath24, + bodyParams: params + }); + } + async revokeSignInToken(signInTokenId) { + this.requireId(signInTokenId); + return this.request({ + method: "POST", + path: joinPaths(basePath24, signInTokenId, "revoke") + }); + } +}; + +// src/api/endpoints/SignUpApi.ts +var basePath25 = "/sign_ups"; +var SignUpAPI = class extends AbstractAPI { + async get(signUpAttemptId) { + this.requireId(signUpAttemptId); + return this.request({ + method: "GET", + path: joinPaths(basePath25, signUpAttemptId) + }); + } + async update(params) { + const { signUpAttemptId, ...bodyParams } = params; + return this.request({ + method: "PATCH", + path: joinPaths(basePath25, signUpAttemptId), + bodyParams + }); + } +}; + +// src/api/endpoints/TestingTokenApi.ts +var basePath26 = "/testing_tokens"; +var TestingTokenAPI = class extends AbstractAPI { + async createTestingToken() { + return this.request({ + method: "POST", + path: basePath26 + }); + } +}; + +// src/api/endpoints/UserApi.ts +var basePath27 = "/users"; +var UserAPI = class extends AbstractAPI { + async getUserList(params = {}) { + const { limit, offset, orderBy, ...userCountParams } = params; + const [data, totalCount] = await Promise.all([ + this.request({ + method: "GET", + path: basePath27, + queryParams: params + }), + this.getCount(userCountParams) + ]); + return { data, totalCount }; + } + async getUser(userId) { + this.requireId(userId); + return this.request({ + method: "GET", + path: joinPaths(basePath27, userId) + }); + } + async createUser(params) { + return this.request({ + method: "POST", + path: basePath27, + bodyParams: params + }); + } + async updateUser(userId, params = {}) { + this.requireId(userId); + return this.request({ + method: "PATCH", + path: joinPaths(basePath27, userId), + bodyParams: params + }); + } + async updateUserProfileImage(userId, params) { + this.requireId(userId); + const formData = new runtime.FormData(); + formData.append("file", params?.file); + return this.request({ + method: "POST", + path: joinPaths(basePath27, userId, "profile_image"), + formData + }); + } + async updateUserMetadata(userId, params) { + this.requireId(userId); + return this.request({ + method: "PATCH", + path: joinPaths(basePath27, userId, "metadata"), + bodyParams: params + }); + } + async deleteUser(userId) { + this.requireId(userId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath27, userId) + }); + } + async getCount(params = {}) { + return this.request({ + method: "GET", + path: joinPaths(basePath27, "count"), + queryParams: params + }); + } + async getUserOauthAccessToken(userId, provider) { + this.requireId(userId); + const hasPrefix = provider.startsWith("oauth_"); + const _provider = hasPrefix ? provider : `oauth_${provider}`; + if (hasPrefix) { + deprecated( + "getUserOauthAccessToken(userId, provider)", + "Remove the `oauth_` prefix from the `provider` argument." + ); + } + return this.request({ + method: "GET", + path: joinPaths(basePath27, userId, "oauth_access_tokens", _provider), + queryParams: { paginated: true } + }); + } + async disableUserMFA(userId) { + this.requireId(userId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath27, userId, "mfa") + }); + } + async getOrganizationMembershipList(params) { + const { userId, limit, offset } = params; + this.requireId(userId); + return this.request({ + method: "GET", + path: joinPaths(basePath27, userId, "organization_memberships"), + queryParams: { limit, offset } + }); + } + async getOrganizationInvitationList(params) { + const { userId, ...queryParams } = params; + this.requireId(userId); + return this.request({ + method: "GET", + path: joinPaths(basePath27, userId, "organization_invitations"), + queryParams + }); + } + async verifyPassword(params) { + const { userId, password } = params; + this.requireId(userId); + return this.request({ + method: "POST", + path: joinPaths(basePath27, userId, "verify_password"), + bodyParams: { password } + }); + } + async verifyTOTP(params) { + const { userId, code } = params; + this.requireId(userId); + return this.request({ + method: "POST", + path: joinPaths(basePath27, userId, "verify_totp"), + bodyParams: { code } + }); + } + async banUser(userId) { + this.requireId(userId); + return this.request({ + method: "POST", + path: joinPaths(basePath27, userId, "ban") + }); + } + async unbanUser(userId) { + this.requireId(userId); + return this.request({ + method: "POST", + path: joinPaths(basePath27, userId, "unban") + }); + } + async lockUser(userId) { + this.requireId(userId); + return this.request({ + method: "POST", + path: joinPaths(basePath27, userId, "lock") + }); + } + async unlockUser(userId) { + this.requireId(userId); + return this.request({ + method: "POST", + path: joinPaths(basePath27, userId, "unlock") + }); + } + async deleteUserProfileImage(userId) { + this.requireId(userId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath27, userId, "profile_image") + }); + } + async deleteUserPasskey(params) { + this.requireId(params.userId); + this.requireId(params.passkeyIdentificationId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath27, params.userId, "passkeys", params.passkeyIdentificationId) + }); + } + async deleteUserWeb3Wallet(params) { + this.requireId(params.userId); + this.requireId(params.web3WalletIdentificationId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath27, params.userId, "web3_wallets", params.web3WalletIdentificationId) + }); + } + async deleteUserExternalAccount(params) { + this.requireId(params.userId); + this.requireId(params.externalAccountId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath27, params.userId, "external_accounts", params.externalAccountId) + }); + } + async deleteUserBackupCodes(userId) { + this.requireId(userId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath27, userId, "backup_code") + }); + } + async deleteUserTOTP(userId) { + this.requireId(userId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath27, userId, "totp") + }); + } +}; + +// src/api/endpoints/WaitlistEntryApi.ts +var basePath28 = "/waitlist_entries"; +var WaitlistEntryAPI = class extends AbstractAPI { + /** + * List waitlist entries. + * @param params Optional parameters (e.g., `query`, `status`, `orderBy`). + */ + async list(params = {}) { + return this.request({ + method: "GET", + path: basePath28, + queryParams: params + }); + } + /** + * Create a waitlist entry. + * @param params The parameters for creating a waitlist entry. + */ + async create(params) { + return this.request({ + method: "POST", + path: basePath28, + bodyParams: params + }); + } + /** + * Invite a waitlist entry. + * @param id The waitlist entry ID. + * @param params Optional parameters (e.g., `ignoreExisting`). + */ + async invite(id, params = {}) { + this.requireId(id); + return this.request({ + method: "POST", + path: joinPaths(basePath28, id, "invite"), + bodyParams: params + }); + } + /** + * Reject a waitlist entry. + * @param id The waitlist entry ID. + */ + async reject(id) { + this.requireId(id); + return this.request({ + method: "POST", + path: joinPaths(basePath28, id, "reject") + }); + } + /** + * Delete a waitlist entry. + * @param id The waitlist entry ID. + */ + async delete(id) { + this.requireId(id); + return this.request({ + method: "DELETE", + path: joinPaths(basePath28, id) + }); + } +}; + +// src/api/endpoints/WebhookApi.ts +var basePath29 = "/webhooks"; +var WebhookAPI = class extends AbstractAPI { + async createSvixApp() { + return this.request({ + method: "POST", + path: joinPaths(basePath29, "svix") + }); + } + async generateSvixAuthURL() { + return this.request({ + method: "POST", + path: joinPaths(basePath29, "svix_url") + }); + } + async deleteSvixApp() { + return this.request({ + method: "DELETE", + path: joinPaths(basePath29, "svix") + }); + } +}; + +// src/api/endpoints/BillingApi.ts +var basePath30 = "/commerce"; +var organizationBasePath = "/organizations"; +var userBasePath = "/users"; +var BillingAPI = class extends AbstractAPI { + /** + * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. + */ + async getPlanList(params) { + return this.request({ + method: "GET", + path: joinPaths(basePath30, "plans"), + queryParams: params + }); + } + /** + * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. + */ + async cancelSubscriptionItem(subscriptionItemId, params) { + this.requireId(subscriptionItemId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath30, "subscription_items", subscriptionItemId), + queryParams: params + }); + } + /** + * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. + */ + async extendSubscriptionItemFreeTrial(subscriptionItemId, params) { + this.requireId(subscriptionItemId); + return this.request({ + method: "POST", + path: joinPaths("/billing", "subscription_items", subscriptionItemId, "extend_free_trial"), + bodyParams: params + }); + } + /** + * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. + */ + async getOrganizationBillingSubscription(organizationId) { + this.requireId(organizationId); + return this.request({ + method: "GET", + path: joinPaths(organizationBasePath, organizationId, "billing", "subscription") + }); + } + /** + * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. + */ + async getUserBillingSubscription(userId) { + this.requireId(userId); + return this.request({ + method: "GET", + path: joinPaths(userBasePath, userId, "billing", "subscription") + }); + } +}; + +// src/api/request.ts +import { ClerkAPIResponseError, parseError } from "@clerk/shared/error"; + +// ../../node_modules/.pnpm/map-obj@5.0.2/node_modules/map-obj/index.js +var isObject = (value) => typeof value === "object" && value !== null; +var isObjectCustom = (value) => isObject(value) && !(value instanceof RegExp) && !(value instanceof Error) && !(value instanceof Date) && !(globalThis.Blob && value instanceof globalThis.Blob); +var mapObjectSkip = Symbol("mapObjectSkip"); +var _mapObject = (object, mapper, options, isSeen = /* @__PURE__ */ new WeakMap()) => { + options = { + deep: false, + target: {}, + ...options + }; + if (isSeen.has(object)) { + return isSeen.get(object); + } + isSeen.set(object, options.target); + const { target } = options; + delete options.target; + const mapArray = (array) => array.map((element) => isObjectCustom(element) ? _mapObject(element, mapper, options, isSeen) : element); + if (Array.isArray(object)) { + return mapArray(object); + } + for (const [key, value] of Object.entries(object)) { + const mapResult = mapper(key, value, object); + if (mapResult === mapObjectSkip) { + continue; + } + let [newKey, newValue, { shouldRecurse = true } = {}] = mapResult; + if (newKey === "__proto__") { + continue; + } + if (options.deep && shouldRecurse && isObjectCustom(newValue)) { + newValue = Array.isArray(newValue) ? mapArray(newValue) : _mapObject(newValue, mapper, options, isSeen); + } + target[newKey] = newValue; + } + return target; +}; +function mapObject(object, mapper, options) { + if (!isObject(object)) { + throw new TypeError(`Expected an object, got \`${object}\` (${typeof object})`); + } + if (Array.isArray(object)) { + throw new TypeError("Expected an object, got an array"); + } + return _mapObject(object, mapper, options); +} + +// ../../node_modules/.pnpm/change-case@5.4.4/node_modules/change-case/dist/index.js +var SPLIT_LOWER_UPPER_RE = /([\p{Ll}\d])(\p{Lu})/gu; +var SPLIT_UPPER_UPPER_RE = /(\p{Lu})([\p{Lu}][\p{Ll}])/gu; +var SPLIT_SEPARATE_NUMBER_RE = /(\d)\p{Ll}|(\p{L})\d/u; +var DEFAULT_STRIP_REGEXP = /[^\p{L}\d]+/giu; +var SPLIT_REPLACE_VALUE = "$1\0$2"; +var DEFAULT_PREFIX_SUFFIX_CHARACTERS = ""; +function split(value) { + let result = value.trim(); + result = result.replace(SPLIT_LOWER_UPPER_RE, SPLIT_REPLACE_VALUE).replace(SPLIT_UPPER_UPPER_RE, SPLIT_REPLACE_VALUE); + result = result.replace(DEFAULT_STRIP_REGEXP, "\0"); + let start = 0; + let end = result.length; + while (result.charAt(start) === "\0") + start++; + if (start === end) + return []; + while (result.charAt(end - 1) === "\0") + end--; + return result.slice(start, end).split(/\0/g); +} +function splitSeparateNumbers(value) { + const words = split(value); + for (let i = 0; i < words.length; i++) { + const word = words[i]; + const match2 = SPLIT_SEPARATE_NUMBER_RE.exec(word); + if (match2) { + const offset = match2.index + (match2[1] ?? match2[2]).length; + words.splice(i, 1, word.slice(0, offset), word.slice(offset)); + } + } + return words; +} +function noCase(input, options) { + const [prefix, words, suffix] = splitPrefixSuffix(input, options); + return prefix + words.map(lowerFactory(options?.locale)).join(options?.delimiter ?? " ") + suffix; +} +function snakeCase(input, options) { + return noCase(input, { delimiter: "_", ...options }); +} +function lowerFactory(locale) { + return locale === false ? (input) => input.toLowerCase() : (input) => input.toLocaleLowerCase(locale); +} +function splitPrefixSuffix(input, options = {}) { + const splitFn = options.split ?? (options.separateNumbers ? splitSeparateNumbers : split); + const prefixCharacters = options.prefixCharacters ?? DEFAULT_PREFIX_SUFFIX_CHARACTERS; + const suffixCharacters = options.suffixCharacters ?? DEFAULT_PREFIX_SUFFIX_CHARACTERS; + let prefixIndex = 0; + let suffixIndex = input.length; + while (prefixIndex < input.length) { + const char = input.charAt(prefixIndex); + if (!prefixCharacters.includes(char)) + break; + prefixIndex++; + } + while (suffixIndex > prefixIndex) { + const index = suffixIndex - 1; + const char = input.charAt(index); + if (!suffixCharacters.includes(char)) + break; + suffixIndex = index; + } + return [ + input.slice(0, prefixIndex), + splitFn(input.slice(prefixIndex, suffixIndex)), + input.slice(suffixIndex) + ]; +} + +// ../../node_modules/.pnpm/snakecase-keys@9.0.2/node_modules/snakecase-keys/index.js +var PlainObjectConstructor = {}.constructor; +function snakecaseKeys(obj, options) { + if (Array.isArray(obj)) { + if (obj.some((item) => item.constructor !== PlainObjectConstructor)) { + throw new Error("obj must be array of plain objects"); + } + options = { deep: true, exclude: [], parsingOptions: {}, ...options }; + const convertCase2 = options.snakeCase || ((key) => snakeCase(key, options.parsingOptions)); + return obj.map((item) => { + return mapObject(item, (key, val) => { + return [ + matches(options.exclude, key) ? key : convertCase2(key), + val, + mapperOptions(key, val, options) + ]; + }, options); + }); + } else { + if (obj.constructor !== PlainObjectConstructor) { + throw new Error("obj must be an plain object"); + } + } + options = { deep: true, exclude: [], parsingOptions: {}, ...options }; + const convertCase = options.snakeCase || ((key) => snakeCase(key, options.parsingOptions)); + return mapObject(obj, (key, val) => { + return [ + matches(options.exclude, key) ? key : convertCase(key), + val, + mapperOptions(key, val, options) + ]; + }, options); +} +function matches(patterns, value) { + return patterns.some((pattern) => { + return typeof pattern === "string" ? pattern === value : pattern.test(value); + }); +} +function mapperOptions(key, val, options) { + return options.shouldRecurse ? { shouldRecurse: options.shouldRecurse(key, val) } : void 0; +} +var snakecase_keys_default = snakecaseKeys; + +// src/api/resources/AccountlessApplication.ts +var AccountlessApplication = class _AccountlessApplication { + constructor(publishableKey, secretKey, claimUrl, apiKeysUrl) { + this.publishableKey = publishableKey; + this.secretKey = secretKey; + this.claimUrl = claimUrl; + this.apiKeysUrl = apiKeysUrl; + } + static fromJSON(data) { + return new _AccountlessApplication(data.publishable_key, data.secret_key, data.claim_url, data.api_keys_url); + } +}; + +// src/api/resources/ActorToken.ts +var ActorToken = class _ActorToken { + constructor(id, status, userId, actor, token, url, createdAt, updatedAt) { + this.id = id; + this.status = status; + this.userId = userId; + this.actor = actor; + this.token = token; + this.url = url; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + } + static fromJSON(data) { + return new _ActorToken( + data.id, + data.status, + data.user_id, + data.actor, + data.token, + data.url, + data.created_at, + data.updated_at + ); + } +}; + +// src/api/resources/AllowlistIdentifier.ts +var AllowlistIdentifier = class _AllowlistIdentifier { + constructor(id, identifier, identifierType, createdAt, updatedAt, instanceId, invitationId) { + this.id = id; + this.identifier = identifier; + this.identifierType = identifierType; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + this.instanceId = instanceId; + this.invitationId = invitationId; + } + static fromJSON(data) { + return new _AllowlistIdentifier( + data.id, + data.identifier, + data.identifier_type, + data.created_at, + data.updated_at, + data.instance_id, + data.invitation_id + ); + } +}; + +// src/api/resources/APIKey.ts +var APIKey = class _APIKey { + constructor(id, type, name, subject, scopes, claims, revoked, revocationReason, expired, expiration, createdBy, description, lastUsedAt, createdAt, updatedAt, secret) { + this.id = id; + this.type = type; + this.name = name; + this.subject = subject; + this.scopes = scopes; + this.claims = claims; + this.revoked = revoked; + this.revocationReason = revocationReason; + this.expired = expired; + this.expiration = expiration; + this.createdBy = createdBy; + this.description = description; + this.lastUsedAt = lastUsedAt; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + this.secret = secret; + } + static fromJSON(data) { + return new _APIKey( + data.id, + data.type, + data.name, + data.subject, + data.scopes, + data.claims, + data.revoked, + data.revocation_reason, + data.expired, + data.expiration, + data.created_by, + data.description, + data.last_used_at, + data.created_at, + data.updated_at, + data.secret + ); + } +}; + +// src/api/resources/BlocklistIdentifier.ts +var BlocklistIdentifier = class _BlocklistIdentifier { + constructor(id, identifier, identifierType, createdAt, updatedAt, instanceId) { + this.id = id; + this.identifier = identifier; + this.identifierType = identifierType; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + this.instanceId = instanceId; + } + static fromJSON(data) { + return new _BlocklistIdentifier( + data.id, + data.identifier, + data.identifier_type, + data.created_at, + data.updated_at, + data.instance_id + ); + } +}; + +// src/api/resources/Session.ts +var SessionActivity = class _SessionActivity { + constructor(id, isMobile, ipAddress, city, country, browserVersion, browserName, deviceType) { + this.id = id; + this.isMobile = isMobile; + this.ipAddress = ipAddress; + this.city = city; + this.country = country; + this.browserVersion = browserVersion; + this.browserName = browserName; + this.deviceType = deviceType; + } + static fromJSON(data) { + return new _SessionActivity( + data.id, + data.is_mobile, + data.ip_address, + data.city, + data.country, + data.browser_version, + data.browser_name, + data.device_type + ); + } +}; +var Session = class _Session { + constructor(id, clientId, userId, status, lastActiveAt, expireAt, abandonAt, createdAt, updatedAt, lastActiveOrganizationId, latestActivity, actor = null) { + this.id = id; + this.clientId = clientId; + this.userId = userId; + this.status = status; + this.lastActiveAt = lastActiveAt; + this.expireAt = expireAt; + this.abandonAt = abandonAt; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + this.lastActiveOrganizationId = lastActiveOrganizationId; + this.latestActivity = latestActivity; + this.actor = actor; + } + static fromJSON(data) { + return new _Session( + data.id, + data.client_id, + data.user_id, + data.status, + data.last_active_at, + data.expire_at, + data.abandon_at, + data.created_at, + data.updated_at, + data.last_active_organization_id, + data.latest_activity && SessionActivity.fromJSON(data.latest_activity), + data.actor + ); + } +}; + +// src/api/resources/Client.ts +var Client = class _Client { + constructor(id, sessionIds, sessions, signInId, signUpId, lastActiveSessionId, lastAuthenticationStrategy, createdAt, updatedAt) { + this.id = id; + this.sessionIds = sessionIds; + this.sessions = sessions; + this.signInId = signInId; + this.signUpId = signUpId; + this.lastActiveSessionId = lastActiveSessionId; + this.lastAuthenticationStrategy = lastAuthenticationStrategy; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + } + static fromJSON(data) { + return new _Client( + data.id, + data.session_ids, + data.sessions.map((x) => Session.fromJSON(x)), + data.sign_in_id, + data.sign_up_id, + data.last_active_session_id, + data.last_authentication_strategy, + data.created_at, + data.updated_at + ); + } +}; + +// src/api/resources/CnameTarget.ts +var CnameTarget = class _CnameTarget { + constructor(host, value, required) { + this.host = host; + this.value = value; + this.required = required; + } + static fromJSON(data) { + return new _CnameTarget(data.host, data.value, data.required); + } +}; + +// src/api/resources/Cookies.ts +var Cookies2 = class _Cookies { + constructor(cookies) { + this.cookies = cookies; + } + static fromJSON(data) { + return new _Cookies(data.cookies); + } +}; + +// src/api/resources/DeletedObject.ts +var DeletedObject = class _DeletedObject { + constructor(object, id, slug, deleted) { + this.object = object; + this.id = id; + this.slug = slug; + this.deleted = deleted; + } + static fromJSON(data) { + return new _DeletedObject(data.object, data.id || null, data.slug || null, data.deleted); + } +}; + +// src/api/resources/Domain.ts +var Domain = class _Domain { + constructor(id, name, isSatellite, frontendApiUrl, developmentOrigin, cnameTargets, accountsPortalUrl, proxyUrl) { + this.id = id; + this.name = name; + this.isSatellite = isSatellite; + this.frontendApiUrl = frontendApiUrl; + this.developmentOrigin = developmentOrigin; + this.cnameTargets = cnameTargets; + this.accountsPortalUrl = accountsPortalUrl; + this.proxyUrl = proxyUrl; + } + static fromJSON(data) { + return new _Domain( + data.id, + data.name, + data.is_satellite, + data.frontend_api_url, + data.development_origin, + data.cname_targets && data.cname_targets.map((x) => CnameTarget.fromJSON(x)), + data.accounts_portal_url, + data.proxy_url + ); + } +}; + +// src/api/resources/Email.ts +var Email = class _Email { + constructor(id, fromEmailName, emailAddressId, toEmailAddress, subject, body, bodyPlain, status, slug, data, deliveredByClerk) { + this.id = id; + this.fromEmailName = fromEmailName; + this.emailAddressId = emailAddressId; + this.toEmailAddress = toEmailAddress; + this.subject = subject; + this.body = body; + this.bodyPlain = bodyPlain; + this.status = status; + this.slug = slug; + this.data = data; + this.deliveredByClerk = deliveredByClerk; + } + static fromJSON(data) { + return new _Email( + data.id, + data.from_email_name, + data.email_address_id, + data.to_email_address, + data.subject, + data.body, + data.body_plain, + data.status, + data.slug, + data.data, + data.delivered_by_clerk + ); + } +}; + +// src/api/resources/IdentificationLink.ts +var IdentificationLink = class _IdentificationLink { + constructor(id, type) { + this.id = id; + this.type = type; + } + static fromJSON(data) { + return new _IdentificationLink(data.id, data.type); + } +}; + +// src/api/resources/Verification.ts +var Verification = class _Verification { + constructor(status, strategy, externalVerificationRedirectURL = null, attempts = null, expireAt = null, nonce = null, message = null) { + this.status = status; + this.strategy = strategy; + this.externalVerificationRedirectURL = externalVerificationRedirectURL; + this.attempts = attempts; + this.expireAt = expireAt; + this.nonce = nonce; + this.message = message; + } + static fromJSON(data) { + return new _Verification( + data.status, + data.strategy, + data.external_verification_redirect_url ? new URL(data.external_verification_redirect_url) : null, + data.attempts, + data.expire_at, + data.nonce + ); + } +}; + +// src/api/resources/EmailAddress.ts +var EmailAddress = class _EmailAddress { + constructor(id, emailAddress, verification, linkedTo) { + this.id = id; + this.emailAddress = emailAddress; + this.verification = verification; + this.linkedTo = linkedTo; + } + static fromJSON(data) { + return new _EmailAddress( + data.id, + data.email_address, + data.verification && Verification.fromJSON(data.verification), + data.linked_to.map((link) => IdentificationLink.fromJSON(link)) + ); + } +}; + +// src/api/resources/ExternalAccount.ts +var ExternalAccount = class _ExternalAccount { + constructor(id, provider, identificationId, externalId, approvedScopes, emailAddress, firstName, lastName, imageUrl, username, phoneNumber, publicMetadata = {}, label, verification) { + this.id = id; + this.provider = provider; + this.identificationId = identificationId; + this.externalId = externalId; + this.approvedScopes = approvedScopes; + this.emailAddress = emailAddress; + this.firstName = firstName; + this.lastName = lastName; + this.imageUrl = imageUrl; + this.username = username; + this.phoneNumber = phoneNumber; + this.publicMetadata = publicMetadata; + this.label = label; + this.verification = verification; + } + static fromJSON(data) { + return new _ExternalAccount( + data.id, + data.provider, + data.identification_id, + data.provider_user_id, + data.approved_scopes, + data.email_address, + data.first_name, + data.last_name, + data.image_url || "", + data.username, + data.phone_number, + data.public_metadata, + data.label, + data.verification && Verification.fromJSON(data.verification) + ); + } +}; + +// src/api/resources/IdPOAuthAccessToken.ts +var IdPOAuthAccessToken = class _IdPOAuthAccessToken { + constructor(id, clientId, type, subject, scopes, revoked, revocationReason, expired, expiration, createdAt, updatedAt) { + this.id = id; + this.clientId = clientId; + this.type = type; + this.subject = subject; + this.scopes = scopes; + this.revoked = revoked; + this.revocationReason = revocationReason; + this.expired = expired; + this.expiration = expiration; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + } + static fromJSON(data) { + return new _IdPOAuthAccessToken( + data.id, + data.client_id, + data.type, + data.subject, + data.scopes, + data.revoked, + data.revocation_reason, + data.expired, + data.expiration, + data.created_at, + data.updated_at + ); + } +}; + +// src/api/resources/Instance.ts +var Instance = class _Instance { + constructor(id, environmentType, allowedOrigins) { + this.id = id; + this.environmentType = environmentType; + this.allowedOrigins = allowedOrigins; + } + static fromJSON(data) { + return new _Instance(data.id, data.environment_type, data.allowed_origins); + } +}; + +// src/api/resources/InstanceRestrictions.ts +var InstanceRestrictions = class _InstanceRestrictions { + constructor(allowlist, blocklist, blockEmailSubaddresses, blockDisposableEmailDomains, ignoreDotsForGmailAddresses) { + this.allowlist = allowlist; + this.blocklist = blocklist; + this.blockEmailSubaddresses = blockEmailSubaddresses; + this.blockDisposableEmailDomains = blockDisposableEmailDomains; + this.ignoreDotsForGmailAddresses = ignoreDotsForGmailAddresses; + } + static fromJSON(data) { + return new _InstanceRestrictions( + data.allowlist, + data.blocklist, + data.block_email_subaddresses, + data.block_disposable_email_domains, + data.ignore_dots_for_gmail_addresses + ); + } +}; + +// src/api/resources/InstanceSettings.ts +var InstanceSettings = class _InstanceSettings { + constructor(id, restrictedToAllowlist, fromEmailAddress, progressiveSignUp, enhancedEmailDeliverability) { + this.id = id; + this.restrictedToAllowlist = restrictedToAllowlist; + this.fromEmailAddress = fromEmailAddress; + this.progressiveSignUp = progressiveSignUp; + this.enhancedEmailDeliverability = enhancedEmailDeliverability; + } + static fromJSON(data) { + return new _InstanceSettings( + data.id, + data.restricted_to_allowlist, + data.from_email_address, + data.progressive_sign_up, + data.enhanced_email_deliverability + ); + } +}; + +// src/api/resources/Invitation.ts +var Invitation = class _Invitation { + constructor(id, emailAddress, publicMetadata, createdAt, updatedAt, status, url, revoked) { + this.id = id; + this.emailAddress = emailAddress; + this.publicMetadata = publicMetadata; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + this.status = status; + this.url = url; + this.revoked = revoked; + this._raw = null; + } + get raw() { + return this._raw; + } + static fromJSON(data) { + const res = new _Invitation( + data.id, + data.email_address, + data.public_metadata, + data.created_at, + data.updated_at, + data.status, + data.url, + data.revoked + ); + res._raw = data; + return res; + } +}; + +// src/api/resources/JSON.ts +var ObjectType = { + AccountlessApplication: "accountless_application", + ActorToken: "actor_token", + AllowlistIdentifier: "allowlist_identifier", + ApiKey: "api_key", + BlocklistIdentifier: "blocklist_identifier", + Client: "client", + Cookies: "cookies", + Domain: "domain", + Email: "email", + EmailAddress: "email_address", + ExternalAccount: "external_account", + FacebookAccount: "facebook_account", + GoogleAccount: "google_account", + Instance: "instance", + InstanceRestrictions: "instance_restrictions", + InstanceSettings: "instance_settings", + Invitation: "invitation", + Machine: "machine", + MachineScope: "machine_scope", + MachineSecretKey: "machine_secret_key", + M2MToken: "machine_to_machine_token", + JwtTemplate: "jwt_template", + OauthAccessToken: "oauth_access_token", + IdpOAuthAccessToken: "clerk_idp_oauth_access_token", + OAuthApplication: "oauth_application", + Organization: "organization", + OrganizationDomain: "organization_domain", + OrganizationInvitation: "organization_invitation", + OrganizationMembership: "organization_membership", + OrganizationSettings: "organization_settings", + PhoneNumber: "phone_number", + ProxyCheck: "proxy_check", + RedirectUrl: "redirect_url", + SamlAccount: "saml_account", + SamlConnection: "saml_connection", + Session: "session", + SignInAttempt: "sign_in_attempt", + SignInToken: "sign_in_token", + SignUpAttempt: "sign_up_attempt", + SmsMessage: "sms_message", + User: "user", + WaitlistEntry: "waitlist_entry", + Web3Wallet: "web3_wallet", + Token: "token", + TotalCount: "total_count", + TestingToken: "testing_token", + Role: "role", + Permission: "permission", + BillingPayer: "commerce_payer", + BillingPaymentAttempt: "commerce_payment_attempt", + BillingSubscription: "commerce_subscription", + BillingSubscriptionItem: "commerce_subscription_item", + BillingPlan: "commerce_plan", + Feature: "feature" +}; + +// src/api/resources/Machine.ts +var Machine = class _Machine { + constructor(id, name, instanceId, createdAt, updatedAt, scopedMachines, defaultTokenTtl, secretKey) { + this.id = id; + this.name = name; + this.instanceId = instanceId; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + this.scopedMachines = scopedMachines; + this.defaultTokenTtl = defaultTokenTtl; + this.secretKey = secretKey; + } + static fromJSON(data) { + return new _Machine( + data.id, + data.name, + data.instance_id, + data.created_at, + data.updated_at, + data.scoped_machines.map( + (m) => new _Machine( + m.id, + m.name, + m.instance_id, + m.created_at, + m.updated_at, + [], + // Nested machines don't have scoped_machines + m.default_token_ttl + ) + ), + data.default_token_ttl, + data.secret_key + ); + } +}; + +// src/api/resources/MachineScope.ts +var MachineScope = class _MachineScope { + constructor(fromMachineId, toMachineId, createdAt, deleted) { + this.fromMachineId = fromMachineId; + this.toMachineId = toMachineId; + this.createdAt = createdAt; + this.deleted = deleted; + } + static fromJSON(data) { + return new _MachineScope(data.from_machine_id, data.to_machine_id, data.created_at, data.deleted); + } +}; + +// src/api/resources/MachineSecretKey.ts +var MachineSecretKey = class _MachineSecretKey { + constructor(secret) { + this.secret = secret; + } + static fromJSON(data) { + return new _MachineSecretKey(data.secret); + } +}; + +// src/api/resources/M2MToken.ts +var M2MToken = class _M2MToken { + constructor(id, subject, scopes, claims, revoked, revocationReason, expired, expiration, createdAt, updatedAt, token) { + this.id = id; + this.subject = subject; + this.scopes = scopes; + this.claims = claims; + this.revoked = revoked; + this.revocationReason = revocationReason; + this.expired = expired; + this.expiration = expiration; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + this.token = token; + } + static fromJSON(data) { + return new _M2MToken( + data.id, + data.subject, + data.scopes, + data.claims, + data.revoked, + data.revocation_reason, + data.expired, + data.expiration, + data.created_at, + data.updated_at, + data.token + ); + } +}; + +// src/api/resources/JwtTemplate.ts +var JwtTemplate = class _JwtTemplate { + constructor(id, name, claims, lifetime, allowedClockSkew, customSigningKey, signingAlgorithm, createdAt, updatedAt) { + this.id = id; + this.name = name; + this.claims = claims; + this.lifetime = lifetime; + this.allowedClockSkew = allowedClockSkew; + this.customSigningKey = customSigningKey; + this.signingAlgorithm = signingAlgorithm; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + } + static fromJSON(data) { + return new _JwtTemplate( + data.id, + data.name, + data.claims, + data.lifetime, + data.allowed_clock_skew, + data.custom_signing_key, + data.signing_algorithm, + data.created_at, + data.updated_at + ); + } +}; + +// src/api/resources/OauthAccessToken.ts +var OauthAccessToken = class _OauthAccessToken { + constructor(externalAccountId, provider, token, publicMetadata = {}, label, scopes, tokenSecret, expiresAt) { + this.externalAccountId = externalAccountId; + this.provider = provider; + this.token = token; + this.publicMetadata = publicMetadata; + this.label = label; + this.scopes = scopes; + this.tokenSecret = tokenSecret; + this.expiresAt = expiresAt; + } + static fromJSON(data) { + return new _OauthAccessToken( + data.external_account_id, + data.provider, + data.token, + data.public_metadata, + data.label || "", + data.scopes, + data.token_secret, + data.expires_at + ); + } +}; + +// src/api/resources/OAuthApplication.ts +var OAuthApplication = class _OAuthApplication { + constructor(id, instanceId, name, clientId, clientUri, clientImageUrl, dynamicallyRegistered, consentScreenEnabled, pkceRequired, isPublic, scopes, redirectUris, authorizeUrl, tokenFetchUrl, userInfoUrl, discoveryUrl, tokenIntrospectionUrl, createdAt, updatedAt, clientSecret) { + this.id = id; + this.instanceId = instanceId; + this.name = name; + this.clientId = clientId; + this.clientUri = clientUri; + this.clientImageUrl = clientImageUrl; + this.dynamicallyRegistered = dynamicallyRegistered; + this.consentScreenEnabled = consentScreenEnabled; + this.pkceRequired = pkceRequired; + this.isPublic = isPublic; + this.scopes = scopes; + this.redirectUris = redirectUris; + this.authorizeUrl = authorizeUrl; + this.tokenFetchUrl = tokenFetchUrl; + this.userInfoUrl = userInfoUrl; + this.discoveryUrl = discoveryUrl; + this.tokenIntrospectionUrl = tokenIntrospectionUrl; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + this.clientSecret = clientSecret; + } + static fromJSON(data) { + return new _OAuthApplication( + data.id, + data.instance_id, + data.name, + data.client_id, + data.client_uri, + data.client_image_url, + data.dynamically_registered, + data.consent_screen_enabled, + data.pkce_required, + data.public, + data.scopes, + data.redirect_uris, + data.authorize_url, + data.token_fetch_url, + data.user_info_url, + data.discovery_url, + data.token_introspection_url, + data.created_at, + data.updated_at, + data.client_secret + ); + } +}; + +// src/api/resources/Organization.ts +var Organization = class _Organization { + constructor(id, name, slug, imageUrl, hasImage, createdAt, updatedAt, publicMetadata = {}, privateMetadata = {}, maxAllowedMemberships, adminDeleteEnabled, membersCount, createdBy) { + this.id = id; + this.name = name; + this.slug = slug; + this.imageUrl = imageUrl; + this.hasImage = hasImage; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + this.publicMetadata = publicMetadata; + this.privateMetadata = privateMetadata; + this.maxAllowedMemberships = maxAllowedMemberships; + this.adminDeleteEnabled = adminDeleteEnabled; + this.membersCount = membersCount; + this.createdBy = createdBy; + this._raw = null; + } + get raw() { + return this._raw; + } + static fromJSON(data) { + const res = new _Organization( + data.id, + data.name, + data.slug, + data.image_url || "", + data.has_image, + data.created_at, + data.updated_at, + data.public_metadata, + data.private_metadata, + data.max_allowed_memberships, + data.admin_delete_enabled, + data.members_count, + data.created_by + ); + res._raw = data; + return res; + } +}; + +// src/api/resources/OrganizationInvitation.ts +var OrganizationInvitation = class _OrganizationInvitation { + constructor(id, emailAddress, role, roleName, organizationId, createdAt, updatedAt, expiresAt, url, status, publicMetadata = {}, privateMetadata = {}, publicOrganizationData) { + this.id = id; + this.emailAddress = emailAddress; + this.role = role; + this.roleName = roleName; + this.organizationId = organizationId; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + this.expiresAt = expiresAt; + this.url = url; + this.status = status; + this.publicMetadata = publicMetadata; + this.privateMetadata = privateMetadata; + this.publicOrganizationData = publicOrganizationData; + this._raw = null; + } + get raw() { + return this._raw; + } + static fromJSON(data) { + const res = new _OrganizationInvitation( + data.id, + data.email_address, + data.role, + data.role_name, + data.organization_id, + data.created_at, + data.updated_at, + data.expires_at, + data.url, + data.status, + data.public_metadata, + data.private_metadata, + data.public_organization_data + ); + res._raw = data; + return res; + } +}; + +// src/api/resources/OrganizationMembership.ts +var OrganizationMembership = class _OrganizationMembership { + constructor(id, role, permissions, publicMetadata = {}, privateMetadata = {}, createdAt, updatedAt, organization, publicUserData) { + this.id = id; + this.role = role; + this.permissions = permissions; + this.publicMetadata = publicMetadata; + this.privateMetadata = privateMetadata; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + this.organization = organization; + this.publicUserData = publicUserData; + this._raw = null; + } + get raw() { + return this._raw; + } + static fromJSON(data) { + const res = new _OrganizationMembership( + data.id, + data.role, + data.permissions, + data.public_metadata, + data.private_metadata, + data.created_at, + data.updated_at, + Organization.fromJSON(data.organization), + OrganizationMembershipPublicUserData.fromJSON(data.public_user_data) + ); + res._raw = data; + return res; + } +}; +var OrganizationMembershipPublicUserData = class _OrganizationMembershipPublicUserData { + constructor(identifier, firstName, lastName, imageUrl, hasImage, userId) { + this.identifier = identifier; + this.firstName = firstName; + this.lastName = lastName; + this.imageUrl = imageUrl; + this.hasImage = hasImage; + this.userId = userId; + } + static fromJSON(data) { + return new _OrganizationMembershipPublicUserData( + data.identifier, + data.first_name, + data.last_name, + data.image_url, + data.has_image, + data.user_id + ); + } +}; + +// src/api/resources/OrganizationSettings.ts +var OrganizationSettings = class _OrganizationSettings { + constructor(enabled, maxAllowedMemberships, maxAllowedRoles, maxAllowedPermissions, creatorRole, adminDeleteEnabled, domainsEnabled, domainsEnrollmentModes, domainsDefaultRole) { + this.enabled = enabled; + this.maxAllowedMemberships = maxAllowedMemberships; + this.maxAllowedRoles = maxAllowedRoles; + this.maxAllowedPermissions = maxAllowedPermissions; + this.creatorRole = creatorRole; + this.adminDeleteEnabled = adminDeleteEnabled; + this.domainsEnabled = domainsEnabled; + this.domainsEnrollmentModes = domainsEnrollmentModes; + this.domainsDefaultRole = domainsDefaultRole; + } + static fromJSON(data) { + return new _OrganizationSettings( + data.enabled, + data.max_allowed_memberships, + data.max_allowed_roles, + data.max_allowed_permissions, + data.creator_role, + data.admin_delete_enabled, + data.domains_enabled, + data.domains_enrollment_modes, + data.domains_default_role + ); + } +}; + +// src/api/resources/PhoneNumber.ts +var PhoneNumber = class _PhoneNumber { + constructor(id, phoneNumber, reservedForSecondFactor, defaultSecondFactor, verification, linkedTo) { + this.id = id; + this.phoneNumber = phoneNumber; + this.reservedForSecondFactor = reservedForSecondFactor; + this.defaultSecondFactor = defaultSecondFactor; + this.verification = verification; + this.linkedTo = linkedTo; + } + static fromJSON(data) { + return new _PhoneNumber( + data.id, + data.phone_number, + data.reserved_for_second_factor, + data.default_second_factor, + data.verification && Verification.fromJSON(data.verification), + data.linked_to.map((link) => IdentificationLink.fromJSON(link)) + ); + } +}; + +// src/api/resources/ProxyCheck.ts +var ProxyCheck = class _ProxyCheck { + constructor(id, domainId, lastRunAt, proxyUrl, successful, createdAt, updatedAt) { + this.id = id; + this.domainId = domainId; + this.lastRunAt = lastRunAt; + this.proxyUrl = proxyUrl; + this.successful = successful; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + } + static fromJSON(data) { + return new _ProxyCheck( + data.id, + data.domain_id, + data.last_run_at, + data.proxy_url, + data.successful, + data.created_at, + data.updated_at + ); + } +}; + +// src/api/resources/RedirectUrl.ts +var RedirectUrl = class _RedirectUrl { + constructor(id, url, createdAt, updatedAt) { + this.id = id; + this.url = url; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + } + static fromJSON(data) { + return new _RedirectUrl(data.id, data.url, data.created_at, data.updated_at); + } +}; + +// src/api/resources/SamlConnection.ts +var SamlConnection = class _SamlConnection { + constructor(id, name, domain, organizationId, idpEntityId, idpSsoUrl, idpCertificate, idpMetadataUrl, idpMetadata, acsUrl, spEntityId, spMetadataUrl, active, provider, userCount, syncUserAttributes, allowSubdomains, allowIdpInitiated, createdAt, updatedAt, attributeMapping) { + this.id = id; + this.name = name; + this.domain = domain; + this.organizationId = organizationId; + this.idpEntityId = idpEntityId; + this.idpSsoUrl = idpSsoUrl; + this.idpCertificate = idpCertificate; + this.idpMetadataUrl = idpMetadataUrl; + this.idpMetadata = idpMetadata; + this.acsUrl = acsUrl; + this.spEntityId = spEntityId; + this.spMetadataUrl = spMetadataUrl; + this.active = active; + this.provider = provider; + this.userCount = userCount; + this.syncUserAttributes = syncUserAttributes; + this.allowSubdomains = allowSubdomains; + this.allowIdpInitiated = allowIdpInitiated; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + this.attributeMapping = attributeMapping; + } + static fromJSON(data) { + return new _SamlConnection( + data.id, + data.name, + data.domain, + data.organization_id, + data.idp_entity_id, + data.idp_sso_url, + data.idp_certificate, + data.idp_metadata_url, + data.idp_metadata, + data.acs_url, + data.sp_entity_id, + data.sp_metadata_url, + data.active, + data.provider, + data.user_count, + data.sync_user_attributes, + data.allow_subdomains, + data.allow_idp_initiated, + data.created_at, + data.updated_at, + data.attribute_mapping && AttributeMapping.fromJSON(data.attribute_mapping) + ); + } +}; +var SamlAccountConnection = class _SamlAccountConnection { + constructor(id, name, domain, active, provider, syncUserAttributes, allowSubdomains, allowIdpInitiated, createdAt, updatedAt) { + this.id = id; + this.name = name; + this.domain = domain; + this.active = active; + this.provider = provider; + this.syncUserAttributes = syncUserAttributes; + this.allowSubdomains = allowSubdomains; + this.allowIdpInitiated = allowIdpInitiated; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + } + static fromJSON(data) { + return new _SamlAccountConnection( + data.id, + data.name, + data.domain, + data.active, + data.provider, + data.sync_user_attributes, + data.allow_subdomains, + data.allow_idp_initiated, + data.created_at, + data.updated_at + ); + } +}; +var AttributeMapping = class _AttributeMapping { + constructor(userId, emailAddress, firstName, lastName) { + this.userId = userId; + this.emailAddress = emailAddress; + this.firstName = firstName; + this.lastName = lastName; + } + static fromJSON(data) { + return new _AttributeMapping(data.user_id, data.email_address, data.first_name, data.last_name); + } +}; + +// src/api/resources/SamlAccount.ts +var SamlAccount = class _SamlAccount { + constructor(id, provider, providerUserId, active, emailAddress, firstName, lastName, verification, samlConnection) { + this.id = id; + this.provider = provider; + this.providerUserId = providerUserId; + this.active = active; + this.emailAddress = emailAddress; + this.firstName = firstName; + this.lastName = lastName; + this.verification = verification; + this.samlConnection = samlConnection; + } + static fromJSON(data) { + return new _SamlAccount( + data.id, + data.provider, + data.provider_user_id, + data.active, + data.email_address, + data.first_name, + data.last_name, + data.verification && Verification.fromJSON(data.verification), + data.saml_connection && SamlAccountConnection.fromJSON(data.saml_connection) + ); + } +}; + +// src/api/resources/SignInTokens.ts +var SignInToken = class _SignInToken { + constructor(id, userId, token, status, url, createdAt, updatedAt) { + this.id = id; + this.userId = userId; + this.token = token; + this.status = status; + this.url = url; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + } + static fromJSON(data) { + return new _SignInToken(data.id, data.user_id, data.token, data.status, data.url, data.created_at, data.updated_at); + } +}; + +// src/api/resources/SignUpAttempt.ts +var SignUpAttemptVerification = class _SignUpAttemptVerification { + constructor(nextAction, supportedStrategies) { + this.nextAction = nextAction; + this.supportedStrategies = supportedStrategies; + } + static fromJSON(data) { + return new _SignUpAttemptVerification(data.next_action, data.supported_strategies); + } +}; +var SignUpAttemptVerifications = class _SignUpAttemptVerifications { + constructor(emailAddress, phoneNumber, web3Wallet, externalAccount) { + this.emailAddress = emailAddress; + this.phoneNumber = phoneNumber; + this.web3Wallet = web3Wallet; + this.externalAccount = externalAccount; + } + static fromJSON(data) { + return new _SignUpAttemptVerifications( + data.email_address && SignUpAttemptVerification.fromJSON(data.email_address), + data.phone_number && SignUpAttemptVerification.fromJSON(data.phone_number), + data.web3_wallet && SignUpAttemptVerification.fromJSON(data.web3_wallet), + data.external_account + ); + } +}; +var SignUpAttempt = class _SignUpAttempt { + constructor(id, status, requiredFields, optionalFields, missingFields, unverifiedFields, verifications, username, emailAddress, phoneNumber, web3Wallet, passwordEnabled, firstName, lastName, customAction, externalId, createdSessionId, createdUserId, abandonAt, legalAcceptedAt, publicMetadata, unsafeMetadata) { + this.id = id; + this.status = status; + this.requiredFields = requiredFields; + this.optionalFields = optionalFields; + this.missingFields = missingFields; + this.unverifiedFields = unverifiedFields; + this.verifications = verifications; + this.username = username; + this.emailAddress = emailAddress; + this.phoneNumber = phoneNumber; + this.web3Wallet = web3Wallet; + this.passwordEnabled = passwordEnabled; + this.firstName = firstName; + this.lastName = lastName; + this.customAction = customAction; + this.externalId = externalId; + this.createdSessionId = createdSessionId; + this.createdUserId = createdUserId; + this.abandonAt = abandonAt; + this.legalAcceptedAt = legalAcceptedAt; + this.publicMetadata = publicMetadata; + this.unsafeMetadata = unsafeMetadata; + } + static fromJSON(data) { + return new _SignUpAttempt( + data.id, + data.status, + data.required_fields, + data.optional_fields, + data.missing_fields, + data.unverified_fields, + data.verifications ? SignUpAttemptVerifications.fromJSON(data.verifications) : null, + data.username, + data.email_address, + data.phone_number, + data.web3_wallet, + data.password_enabled, + data.first_name, + data.last_name, + data.custom_action, + data.external_id, + data.created_session_id, + data.created_user_id, + data.abandon_at, + data.legal_accepted_at, + data.public_metadata, + data.unsafe_metadata + ); + } +}; + +// src/api/resources/SMSMessage.ts +var SMSMessage = class _SMSMessage { + constructor(id, fromPhoneNumber, toPhoneNumber, message, status, phoneNumberId, data) { + this.id = id; + this.fromPhoneNumber = fromPhoneNumber; + this.toPhoneNumber = toPhoneNumber; + this.message = message; + this.status = status; + this.phoneNumberId = phoneNumberId; + this.data = data; + } + static fromJSON(data) { + return new _SMSMessage( + data.id, + data.from_phone_number, + data.to_phone_number, + data.message, + data.status, + data.phone_number_id, + data.data + ); + } +}; + +// src/api/resources/Token.ts +var Token = class _Token { + constructor(jwt) { + this.jwt = jwt; + } + static fromJSON(data) { + return new _Token(data.jwt); + } +}; + +// src/api/resources/Web3Wallet.ts +var Web3Wallet = class _Web3Wallet { + constructor(id, web3Wallet, verification) { + this.id = id; + this.web3Wallet = web3Wallet; + this.verification = verification; + } + static fromJSON(data) { + return new _Web3Wallet(data.id, data.web3_wallet, data.verification && Verification.fromJSON(data.verification)); + } +}; + +// src/api/resources/User.ts +var User = class _User { + constructor(id, passwordEnabled, totpEnabled, backupCodeEnabled, twoFactorEnabled, banned, locked, createdAt, updatedAt, imageUrl, hasImage, primaryEmailAddressId, primaryPhoneNumberId, primaryWeb3WalletId, lastSignInAt, externalId, username, firstName, lastName, publicMetadata = {}, privateMetadata = {}, unsafeMetadata = {}, emailAddresses = [], phoneNumbers = [], web3Wallets = [], externalAccounts = [], samlAccounts = [], lastActiveAt, createOrganizationEnabled, createOrganizationsLimit = null, deleteSelfEnabled, legalAcceptedAt) { + this.id = id; + this.passwordEnabled = passwordEnabled; + this.totpEnabled = totpEnabled; + this.backupCodeEnabled = backupCodeEnabled; + this.twoFactorEnabled = twoFactorEnabled; + this.banned = banned; + this.locked = locked; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + this.imageUrl = imageUrl; + this.hasImage = hasImage; + this.primaryEmailAddressId = primaryEmailAddressId; + this.primaryPhoneNumberId = primaryPhoneNumberId; + this.primaryWeb3WalletId = primaryWeb3WalletId; + this.lastSignInAt = lastSignInAt; + this.externalId = externalId; + this.username = username; + this.firstName = firstName; + this.lastName = lastName; + this.publicMetadata = publicMetadata; + this.privateMetadata = privateMetadata; + this.unsafeMetadata = unsafeMetadata; + this.emailAddresses = emailAddresses; + this.phoneNumbers = phoneNumbers; + this.web3Wallets = web3Wallets; + this.externalAccounts = externalAccounts; + this.samlAccounts = samlAccounts; + this.lastActiveAt = lastActiveAt; + this.createOrganizationEnabled = createOrganizationEnabled; + this.createOrganizationsLimit = createOrganizationsLimit; + this.deleteSelfEnabled = deleteSelfEnabled; + this.legalAcceptedAt = legalAcceptedAt; + this._raw = null; + } + get raw() { + return this._raw; + } + static fromJSON(data) { + const res = new _User( + data.id, + data.password_enabled, + data.totp_enabled, + data.backup_code_enabled, + data.two_factor_enabled, + data.banned, + data.locked, + data.created_at, + data.updated_at, + data.image_url, + data.has_image, + data.primary_email_address_id, + data.primary_phone_number_id, + data.primary_web3_wallet_id, + data.last_sign_in_at, + data.external_id, + data.username, + data.first_name, + data.last_name, + data.public_metadata, + data.private_metadata, + data.unsafe_metadata, + (data.email_addresses || []).map((x) => EmailAddress.fromJSON(x)), + (data.phone_numbers || []).map((x) => PhoneNumber.fromJSON(x)), + (data.web3_wallets || []).map((x) => Web3Wallet.fromJSON(x)), + (data.external_accounts || []).map((x) => ExternalAccount.fromJSON(x)), + (data.saml_accounts || []).map((x) => SamlAccount.fromJSON(x)), + data.last_active_at, + data.create_organization_enabled, + data.create_organizations_limit, + data.delete_self_enabled, + data.legal_accepted_at + ); + res._raw = data; + return res; + } + /** + * The primary email address of the user. + */ + get primaryEmailAddress() { + return this.emailAddresses.find(({ id }) => id === this.primaryEmailAddressId) ?? null; + } + /** + * The primary phone number of the user. + */ + get primaryPhoneNumber() { + return this.phoneNumbers.find(({ id }) => id === this.primaryPhoneNumberId) ?? null; + } + /** + * The primary web3 wallet of the user. + */ + get primaryWeb3Wallet() { + return this.web3Wallets.find(({ id }) => id === this.primaryWeb3WalletId) ?? null; + } + /** + * The full name of the user. + */ + get fullName() { + return [this.firstName, this.lastName].join(" ").trim() || null; + } +}; + +// src/api/resources/WaitlistEntry.ts +var WaitlistEntry = class _WaitlistEntry { + constructor(id, emailAddress, status, invitation, createdAt, updatedAt, isLocked) { + this.id = id; + this.emailAddress = emailAddress; + this.status = status; + this.invitation = invitation; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + this.isLocked = isLocked; + } + static fromJSON(data) { + return new _WaitlistEntry( + data.id, + data.email_address, + data.status, + data.invitation && Invitation.fromJSON(data.invitation), + data.created_at, + data.updated_at, + data.is_locked + ); + } +}; + +// src/api/resources/Feature.ts +var Feature = class _Feature { + constructor(id, name, description, slug, avatarUrl) { + this.id = id; + this.name = name; + this.description = description; + this.slug = slug; + this.avatarUrl = avatarUrl; + } + static fromJSON(data) { + return new _Feature(data.id, data.name, data.description, data.slug, data.avatar_url); + } +}; + +// src/api/resources/CommercePlan.ts +var BillingPlan = class _BillingPlan { + constructor(id, productId, name, slug, description, isDefault, isRecurring, hasBaseFee, publiclyVisible, fee, annualFee, annualMonthlyFee, forPayerType, features) { + this.id = id; + this.productId = productId; + this.name = name; + this.slug = slug; + this.description = description; + this.isDefault = isDefault; + this.isRecurring = isRecurring; + this.hasBaseFee = hasBaseFee; + this.publiclyVisible = publiclyVisible; + this.fee = fee; + this.annualFee = annualFee; + this.annualMonthlyFee = annualMonthlyFee; + this.forPayerType = forPayerType; + this.features = features; + } + static fromJSON(data) { + const formatAmountJSON = (fee) => { + return { + amount: fee.amount, + amountFormatted: fee.amount_formatted, + currency: fee.currency, + currencySymbol: fee.currency_symbol + }; + }; + return new _BillingPlan( + data.id, + data.product_id, + data.name, + data.slug, + data.description, + data.is_default, + data.is_recurring, + data.has_base_fee, + data.publicly_visible, + formatAmountJSON(data.fee), + formatAmountJSON(data.annual_fee), + formatAmountJSON(data.annual_monthly_fee), + data.for_payer_type, + data.features.map((feature) => Feature.fromJSON(feature)) + ); + } +}; + +// src/api/resources/CommerceSubscriptionItem.ts +var BillingSubscriptionItem = class _BillingSubscriptionItem { + constructor(id, status, planPeriod, periodStart, nextPayment, amount, plan, planId, createdAt, updatedAt, periodEnd, canceledAt, pastDueAt, endedAt, payerId, isFreeTrial, lifetimePaid) { + this.id = id; + this.status = status; + this.planPeriod = planPeriod; + this.periodStart = periodStart; + this.nextPayment = nextPayment; + this.amount = amount; + this.plan = plan; + this.planId = planId; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + this.periodEnd = periodEnd; + this.canceledAt = canceledAt; + this.pastDueAt = pastDueAt; + this.endedAt = endedAt; + this.payerId = payerId; + this.isFreeTrial = isFreeTrial; + this.lifetimePaid = lifetimePaid; + } + static fromJSON(data) { + function formatAmountJSON(amount) { + if (!amount) { + return amount; + } + return { + amount: amount.amount, + amountFormatted: amount.amount_formatted, + currency: amount.currency, + currencySymbol: amount.currency_symbol + }; + } + return new _BillingSubscriptionItem( + data.id, + data.status, + data.plan_period, + data.period_start, + data.next_payment, + formatAmountJSON(data.amount), + BillingPlan.fromJSON(data.plan), + data.plan_id, + data.created_at, + data.updated_at, + data.period_end, + data.canceled_at, + data.past_due_at, + data.ended_at, + data.payer_id, + data.is_free_trial, + formatAmountJSON(data.lifetime_paid) + ); + } +}; + +// src/api/resources/CommerceSubscription.ts +var BillingSubscription = class _BillingSubscription { + constructor(id, status, payerId, createdAt, updatedAt, activeAt, pastDueAt, subscriptionItems, nextPayment, eligibleForFreeTrial) { + this.id = id; + this.status = status; + this.payerId = payerId; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + this.activeAt = activeAt; + this.pastDueAt = pastDueAt; + this.subscriptionItems = subscriptionItems; + this.nextPayment = nextPayment; + this.eligibleForFreeTrial = eligibleForFreeTrial; + } + static fromJSON(data) { + const nextPayment = data.next_payment ? { + date: data.next_payment.date, + amount: { + amount: data.next_payment.amount.amount, + amountFormatted: data.next_payment.amount.amount_formatted, + currency: data.next_payment.amount.currency, + currencySymbol: data.next_payment.amount.currency_symbol + } + } : null; + return new _BillingSubscription( + data.id, + data.status, + data.payer_id, + data.created_at, + data.updated_at, + data.active_at ?? null, + data.past_due_at ?? null, + data.subscription_items.map((item) => BillingSubscriptionItem.fromJSON(item)), + nextPayment, + data.eligible_for_free_trial ?? false + ); + } +}; + +// src/api/resources/Deserializer.ts +function deserialize(payload) { + let data, totalCount; + if (Array.isArray(payload)) { + const data2 = payload.map((item) => jsonToObject(item)); + return { data: data2 }; + } else if (isPaginated(payload)) { + data = payload.data.map((item) => jsonToObject(item)); + totalCount = payload.total_count; + return { data, totalCount }; + } else { + return { data: jsonToObject(payload) }; + } +} +function isPaginated(payload) { + if (!payload || typeof payload !== "object" || !("data" in payload)) { + return false; + } + return Array.isArray(payload.data) && payload.data !== void 0; +} +function getCount(item) { + return item.total_count; +} +function jsonToObject(item) { + if (typeof item !== "string" && "object" in item && "deleted" in item) { + return DeletedObject.fromJSON(item); + } + switch (item.object) { + case ObjectType.AccountlessApplication: + return AccountlessApplication.fromJSON(item); + case ObjectType.ActorToken: + return ActorToken.fromJSON(item); + case ObjectType.AllowlistIdentifier: + return AllowlistIdentifier.fromJSON(item); + case ObjectType.ApiKey: + return APIKey.fromJSON(item); + case ObjectType.BlocklistIdentifier: + return BlocklistIdentifier.fromJSON(item); + case ObjectType.Client: + return Client.fromJSON(item); + case ObjectType.Cookies: + return Cookies2.fromJSON(item); + case ObjectType.Domain: + return Domain.fromJSON(item); + case ObjectType.EmailAddress: + return EmailAddress.fromJSON(item); + case ObjectType.Email: + return Email.fromJSON(item); + case ObjectType.IdpOAuthAccessToken: + return IdPOAuthAccessToken.fromJSON(item); + case ObjectType.Instance: + return Instance.fromJSON(item); + case ObjectType.InstanceRestrictions: + return InstanceRestrictions.fromJSON(item); + case ObjectType.InstanceSettings: + return InstanceSettings.fromJSON(item); + case ObjectType.Invitation: + return Invitation.fromJSON(item); + case ObjectType.JwtTemplate: + return JwtTemplate.fromJSON(item); + case ObjectType.Machine: + return Machine.fromJSON(item); + case ObjectType.MachineScope: + return MachineScope.fromJSON(item); + case ObjectType.MachineSecretKey: + return MachineSecretKey.fromJSON(item); + case ObjectType.M2MToken: + return M2MToken.fromJSON(item); + case ObjectType.OauthAccessToken: + return OauthAccessToken.fromJSON(item); + case ObjectType.OAuthApplication: + return OAuthApplication.fromJSON(item); + case ObjectType.Organization: + return Organization.fromJSON(item); + case ObjectType.OrganizationInvitation: + return OrganizationInvitation.fromJSON(item); + case ObjectType.OrganizationMembership: + return OrganizationMembership.fromJSON(item); + case ObjectType.OrganizationSettings: + return OrganizationSettings.fromJSON(item); + case ObjectType.PhoneNumber: + return PhoneNumber.fromJSON(item); + case ObjectType.ProxyCheck: + return ProxyCheck.fromJSON(item); + case ObjectType.RedirectUrl: + return RedirectUrl.fromJSON(item); + case ObjectType.SamlConnection: + return SamlConnection.fromJSON(item); + case ObjectType.SignInToken: + return SignInToken.fromJSON(item); + case ObjectType.SignUpAttempt: + return SignUpAttempt.fromJSON(item); + case ObjectType.Session: + return Session.fromJSON(item); + case ObjectType.SmsMessage: + return SMSMessage.fromJSON(item); + case ObjectType.Token: + return Token.fromJSON(item); + case ObjectType.TotalCount: + return getCount(item); + case ObjectType.User: + return User.fromJSON(item); + case ObjectType.WaitlistEntry: + return WaitlistEntry.fromJSON(item); + case ObjectType.BillingPlan: + return BillingPlan.fromJSON(item); + case ObjectType.BillingSubscription: + return BillingSubscription.fromJSON(item); + case ObjectType.BillingSubscriptionItem: + return BillingSubscriptionItem.fromJSON(item); + case ObjectType.Feature: + return Feature.fromJSON(item); + default: + return item; + } +} + +// src/api/request.ts +function buildRequest(options) { + const requestFn = async (requestOptions) => { + const { + secretKey, + machineSecretKey, + useMachineSecretKey = false, + requireSecretKey = true, + apiUrl = API_URL, + apiVersion = API_VERSION, + userAgent = USER_AGENT, + skipApiVersionInUrl = false + } = options; + const { path, method, queryParams, headerParams, bodyParams, formData, options: opts } = requestOptions; + const { deepSnakecaseBodyParamKeys = false } = opts || {}; + if (requireSecretKey) { + assertValidSecretKey(secretKey); + } + const url = skipApiVersionInUrl ? joinPaths(apiUrl, path) : joinPaths(apiUrl, apiVersion, path); + const finalUrl = new URL(url); + if (queryParams) { + const snakecasedQueryParams = snakecase_keys_default({ ...queryParams }); + for (const [key, val] of Object.entries(snakecasedQueryParams)) { + if (val) { + [val].flat().forEach((v) => finalUrl.searchParams.append(key, v)); + } + } + } + const headers = new Headers({ + "Clerk-API-Version": SUPPORTED_BAPI_VERSION, + [constants.Headers.UserAgent]: userAgent, + ...headerParams + }); + const authorizationHeader = constants.Headers.Authorization; + if (!headers.has(authorizationHeader)) { + if (useMachineSecretKey && machineSecretKey) { + headers.set(authorizationHeader, `Bearer ${machineSecretKey}`); + } else if (secretKey) { + headers.set(authorizationHeader, `Bearer ${secretKey}`); + } + } + let res; + try { + if (formData) { + res = await runtime.fetch(finalUrl.href, { + method, + headers, + body: formData + }); + } else { + headers.set("Content-Type", "application/json"); + const buildBody = () => { + const hasBody = method !== "GET" && bodyParams && Object.keys(bodyParams).length > 0; + if (!hasBody) { + return null; + } + const formatKeys = (object) => snakecase_keys_default(object, { deep: deepSnakecaseBodyParamKeys }); + return { + body: JSON.stringify(Array.isArray(bodyParams) ? bodyParams.map(formatKeys) : formatKeys(bodyParams)) + }; + }; + res = await runtime.fetch(finalUrl.href, { + method, + headers, + ...buildBody() + }); + } + const isJSONResponse = res?.headers && res.headers?.get(constants.Headers.ContentType) === constants.ContentTypes.Json; + const responseBody = await (isJSONResponse ? res.json() : res.text()); + if (!res.ok) { + return { + data: null, + errors: parseErrors(responseBody), + status: res?.status, + statusText: res?.statusText, + clerkTraceId: getTraceId(responseBody, res?.headers), + retryAfter: getRetryAfter(res?.headers) + }; + } + return { + ...deserialize(responseBody), + errors: null + }; + } catch (err) { + if (err instanceof Error) { + return { + data: null, + errors: [ + { + code: "unexpected_error", + message: err.message || "Unexpected error" + } + ], + clerkTraceId: getTraceId(err, res?.headers) + }; + } + return { + data: null, + errors: parseErrors(err), + status: res?.status, + statusText: res?.statusText, + clerkTraceId: getTraceId(err, res?.headers), + retryAfter: getRetryAfter(res?.headers) + }; + } + }; + return withLegacyRequestReturn(requestFn); +} +function getTraceId(data, headers) { + if (data && typeof data === "object" && "clerk_trace_id" in data && typeof data.clerk_trace_id === "string") { + return data.clerk_trace_id; + } + const cfRay = headers?.get("cf-ray"); + return cfRay || ""; +} +function getRetryAfter(headers) { + const retryAfter = headers?.get("Retry-After"); + if (!retryAfter) { + return; + } + const value = parseInt(retryAfter, 10); + if (isNaN(value)) { + return; + } + return value; +} +function parseErrors(data) { + if (!!data && typeof data === "object" && "errors" in data) { + const errors = data.errors; + return errors.length > 0 ? errors.map(parseError) : []; + } + return []; +} +function withLegacyRequestReturn(cb) { + return async (...args) => { + const { data, errors, totalCount, status, statusText, clerkTraceId, retryAfter } = await cb(...args); + if (errors) { + const error = new ClerkAPIResponseError(statusText || "", { + data: [], + status, + clerkTraceId, + retryAfter + }); + error.errors = errors; + throw error; + } + if (typeof totalCount !== "undefined") { + return { data, totalCount }; + } + return data; + }; +} + +// src/api/factory.ts +function createBackendApiClient(options) { + const request = buildRequest(options); + return { + __experimental_accountlessApplications: new AccountlessApplicationAPI( + buildRequest({ ...options, requireSecretKey: false }) + ), + actorTokens: new ActorTokenAPI(request), + allowlistIdentifiers: new AllowlistIdentifierAPI(request), + apiKeys: new APIKeysAPI( + buildRequest({ + ...options, + skipApiVersionInUrl: true + }) + ), + betaFeatures: new BetaFeaturesAPI(request), + blocklistIdentifiers: new BlocklistIdentifierAPI(request), + /** + * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. + */ + billing: new BillingAPI(request), + clients: new ClientAPI(request), + domains: new DomainAPI(request), + emailAddresses: new EmailAddressAPI(request), + idPOAuthAccessToken: new IdPOAuthAccessTokenApi( + buildRequest({ + ...options, + skipApiVersionInUrl: true + }) + ), + instance: new InstanceAPI(request), + invitations: new InvitationAPI(request), + jwks: new JwksAPI(request), + jwtTemplates: new JwtTemplatesApi(request), + machines: new MachineApi(request), + m2m: new M2MTokenApi( + buildRequest({ + ...options, + skipApiVersionInUrl: true, + requireSecretKey: false, + useMachineSecretKey: true + }) + ), + oauthApplications: new OAuthApplicationsApi(request), + organizations: new OrganizationAPI(request), + phoneNumbers: new PhoneNumberAPI(request), + proxyChecks: new ProxyCheckAPI(request), + redirectUrls: new RedirectUrlAPI(request), + samlConnections: new SamlConnectionAPI(request), + sessions: new SessionAPI(request), + signInTokens: new SignInTokenAPI(request), + signUps: new SignUpAPI(request), + testingTokens: new TestingTokenAPI(request), + users: new UserAPI(request), + waitlistEntries: new WaitlistEntryAPI(request), + webhooks: new WebhookAPI(request) + }; +} + +// src/tokens/machine.ts +var M2M_TOKEN_PREFIX = "mt_"; +var OAUTH_TOKEN_PREFIX = "oat_"; +var API_KEY_PREFIX = "ak_"; +var MACHINE_TOKEN_PREFIXES = [M2M_TOKEN_PREFIX, OAUTH_TOKEN_PREFIX, API_KEY_PREFIX]; +function isMachineTokenByPrefix(token) { + return MACHINE_TOKEN_PREFIXES.some((prefix) => token.startsWith(prefix)); +} +function getMachineTokenType(token) { + if (token.startsWith(M2M_TOKEN_PREFIX)) { + return TokenType.M2MToken; + } + if (token.startsWith(OAUTH_TOKEN_PREFIX)) { + return TokenType.OAuthToken; + } + if (token.startsWith(API_KEY_PREFIX)) { + return TokenType.ApiKey; + } + throw new Error("Unknown machine token type"); +} +var isTokenTypeAccepted = (tokenType, acceptsToken) => { + if (!tokenType) { + return false; + } + if (acceptsToken === "any") { + return true; + } + const tokenTypes = Array.isArray(acceptsToken) ? acceptsToken : [acceptsToken]; + return tokenTypes.includes(tokenType); +}; +function isMachineTokenType(type) { + return type === TokenType.ApiKey || type === TokenType.M2MToken || type === TokenType.OAuthToken; +} + +// src/tokens/authObjects.ts +var createDebug = (data) => { + return () => { + const res = { ...data }; + res.secretKey = (res.secretKey || "").substring(0, 7); + res.jwtKey = (res.jwtKey || "").substring(0, 7); + return { ...res }; + }; +}; +function signedInAuthObject(authenticateContext, sessionToken, sessionClaims) { + const { actor, sessionId, sessionStatus, userId, orgId, orgRole, orgSlug, orgPermissions, factorVerificationAge } = __experimental_JWTPayloadToAuthObjectProperties(sessionClaims); + const apiClient = createBackendApiClient(authenticateContext); + const getToken = createGetToken({ + sessionId, + sessionToken, + fetcher: async (sessionId2, template, expiresInSeconds) => (await apiClient.sessions.getToken(sessionId2, template || "", expiresInSeconds)).jwt + }); + return { + tokenType: TokenType.SessionToken, + actor, + sessionClaims, + sessionId, + sessionStatus, + userId, + orgId, + orgRole, + orgSlug, + orgPermissions, + factorVerificationAge, + getToken, + has: createCheckAuthorization({ + orgId, + orgRole, + orgPermissions, + userId, + factorVerificationAge, + features: sessionClaims.fea || "", + plans: sessionClaims.pla || "" + }), + debug: createDebug({ ...authenticateContext, sessionToken }), + isAuthenticated: true + }; +} +function signedOutAuthObject(debugData, initialSessionStatus) { + return { + tokenType: TokenType.SessionToken, + sessionClaims: null, + sessionId: null, + sessionStatus: initialSessionStatus ?? null, + userId: null, + actor: null, + orgId: null, + orgRole: null, + orgSlug: null, + orgPermissions: null, + factorVerificationAge: null, + getToken: () => Promise.resolve(null), + has: () => false, + debug: createDebug(debugData), + isAuthenticated: false + }; +} +function authenticatedMachineObject(tokenType, token, verificationResult, debugData) { + const baseObject = { + id: verificationResult.id, + subject: verificationResult.subject, + getToken: () => Promise.resolve(token), + has: () => false, + debug: createDebug(debugData), + isAuthenticated: true + }; + switch (tokenType) { + case TokenType.ApiKey: { + const result = verificationResult; + return { + ...baseObject, + tokenType, + name: result.name, + claims: result.claims, + scopes: result.scopes, + userId: result.subject.startsWith("user_") ? result.subject : null, + orgId: result.subject.startsWith("org_") ? result.subject : null + }; + } + case TokenType.M2MToken: { + const result = verificationResult; + return { + ...baseObject, + tokenType, + claims: result.claims, + scopes: result.scopes, + machineId: result.subject + }; + } + case TokenType.OAuthToken: { + const result = verificationResult; + return { + ...baseObject, + tokenType, + scopes: result.scopes, + userId: result.subject, + clientId: result.clientId + }; + } + default: + throw new Error(`Invalid token type: ${tokenType}`); + } +} +function unauthenticatedMachineObject(tokenType, debugData) { + const baseObject = { + id: null, + subject: null, + scopes: null, + has: () => false, + getToken: () => Promise.resolve(null), + debug: createDebug(debugData), + isAuthenticated: false + }; + switch (tokenType) { + case TokenType.ApiKey: { + return { + ...baseObject, + tokenType, + name: null, + claims: null, + scopes: null, + userId: null, + orgId: null + }; + } + case TokenType.M2MToken: { + return { + ...baseObject, + tokenType, + claims: null, + scopes: null, + machineId: null + }; + } + case TokenType.OAuthToken: { + return { + ...baseObject, + tokenType, + scopes: null, + userId: null, + clientId: null + }; + } + default: + throw new Error(`Invalid token type: ${tokenType}`); + } +} +function invalidTokenAuthObject() { + return { + isAuthenticated: false, + tokenType: null, + getToken: () => Promise.resolve(null), + has: () => false, + debug: () => ({}) + }; +} +var makeAuthObjectSerializable = (obj) => { + const { debug, getToken, has, ...rest } = obj; + return rest; +}; +var createGetToken = (params) => { + const { fetcher, sessionToken, sessionId } = params || {}; + return async (options = {}) => { + if (!sessionId) { + return null; + } + if (options.template || options.expiresInSeconds !== void 0) { + return fetcher(sessionId, options.template, options.expiresInSeconds); + } + return sessionToken; + }; +}; +var getAuthObjectFromJwt = (jwt, { treatPendingAsSignedOut = true, ...options }) => { + const authObject = signedInAuthObject(options, jwt.raw.text, jwt.payload); + if (treatPendingAsSignedOut && authObject.sessionStatus === "pending") { + return signedOutAuthObject(options, authObject.sessionStatus); + } + return authObject; +}; +var getAuthObjectForAcceptedToken = ({ + authObject, + acceptsToken = TokenType.SessionToken +}) => { + if (acceptsToken === "any") { + return authObject; + } + if (Array.isArray(acceptsToken)) { + if (!isTokenTypeAccepted(authObject.tokenType, acceptsToken)) { + return invalidTokenAuthObject(); + } + return authObject; + } + if (!isTokenTypeAccepted(authObject.tokenType, acceptsToken)) { + if (isMachineTokenType(acceptsToken)) { + return unauthenticatedMachineObject(acceptsToken, authObject.debug); + } + return signedOutAuthObject(authObject.debug); + } + return authObject; +}; + +// src/tokens/authStatus.ts +var AuthStatus = { + SignedIn: "signed-in", + SignedOut: "signed-out", + Handshake: "handshake" +}; +var AuthErrorReason = { + ClientUATWithoutSessionToken: "client-uat-but-no-session-token", + DevBrowserMissing: "dev-browser-missing", + DevBrowserSync: "dev-browser-sync", + PrimaryRespondsToSyncing: "primary-responds-to-syncing", + PrimaryDomainCrossOriginSync: "primary-domain-cross-origin-sync", + SatelliteCookieNeedsSyncing: "satellite-needs-syncing", + SessionTokenAndUATMissing: "session-token-and-uat-missing", + SessionTokenMissing: "session-token-missing", + SessionTokenExpired: "session-token-expired", + SessionTokenIATBeforeClientUAT: "session-token-iat-before-client-uat", + SessionTokenNBF: "session-token-nbf", + SessionTokenIatInTheFuture: "session-token-iat-in-the-future", + SessionTokenWithoutClientUAT: "session-token-but-no-client-uat", + ActiveOrganizationMismatch: "active-organization-mismatch", + TokenTypeMismatch: "token-type-mismatch", + UnexpectedError: "unexpected-error" +}; +function signedIn(params) { + const { authenticateContext, headers = new Headers(), token } = params; + const toAuth = ({ treatPendingAsSignedOut = true } = {}) => { + if (params.tokenType === TokenType.SessionToken) { + const { sessionClaims } = params; + const authObject = signedInAuthObject(authenticateContext, token, sessionClaims); + if (treatPendingAsSignedOut && authObject.sessionStatus === "pending") { + return signedOutAuthObject(void 0, authObject.sessionStatus); + } + return authObject; + } + const { machineData } = params; + return authenticatedMachineObject(params.tokenType, token, machineData, authenticateContext); + }; + return { + status: AuthStatus.SignedIn, + reason: null, + message: null, + proxyUrl: authenticateContext.proxyUrl || "", + publishableKey: authenticateContext.publishableKey || "", + isSatellite: authenticateContext.isSatellite || false, + domain: authenticateContext.domain || "", + signInUrl: authenticateContext.signInUrl || "", + signUpUrl: authenticateContext.signUpUrl || "", + afterSignInUrl: authenticateContext.afterSignInUrl || "", + afterSignUpUrl: authenticateContext.afterSignUpUrl || "", + isSignedIn: true, + isAuthenticated: true, + tokenType: params.tokenType, + toAuth, + headers, + token + }; +} +function signedOut(params) { + const { authenticateContext, headers = new Headers(), reason, message = "", tokenType } = params; + const toAuth = () => { + if (tokenType === TokenType.SessionToken) { + return signedOutAuthObject({ ...authenticateContext, status: AuthStatus.SignedOut, reason, message }); + } + return unauthenticatedMachineObject(tokenType, { reason, message, headers }); + }; + return withDebugHeaders({ + status: AuthStatus.SignedOut, + reason, + message, + proxyUrl: authenticateContext.proxyUrl || "", + publishableKey: authenticateContext.publishableKey || "", + isSatellite: authenticateContext.isSatellite || false, + domain: authenticateContext.domain || "", + signInUrl: authenticateContext.signInUrl || "", + signUpUrl: authenticateContext.signUpUrl || "", + afterSignInUrl: authenticateContext.afterSignInUrl || "", + afterSignUpUrl: authenticateContext.afterSignUpUrl || "", + isSignedIn: false, + isAuthenticated: false, + tokenType, + toAuth, + headers, + token: null + }); +} +function handshake(authenticateContext, reason, message = "", headers) { + return withDebugHeaders({ + status: AuthStatus.Handshake, + reason, + message, + publishableKey: authenticateContext.publishableKey || "", + isSatellite: authenticateContext.isSatellite || false, + domain: authenticateContext.domain || "", + proxyUrl: authenticateContext.proxyUrl || "", + signInUrl: authenticateContext.signInUrl || "", + signUpUrl: authenticateContext.signUpUrl || "", + afterSignInUrl: authenticateContext.afterSignInUrl || "", + afterSignUpUrl: authenticateContext.afterSignUpUrl || "", + isSignedIn: false, + isAuthenticated: false, + tokenType: TokenType.SessionToken, + toAuth: () => null, + headers, + token: null + }); +} +function signedOutInvalidToken() { + const authObject = invalidTokenAuthObject(); + return withDebugHeaders({ + status: AuthStatus.SignedOut, + reason: AuthErrorReason.TokenTypeMismatch, + message: "", + proxyUrl: "", + publishableKey: "", + isSatellite: false, + domain: "", + signInUrl: "", + signUpUrl: "", + afterSignInUrl: "", + afterSignUpUrl: "", + isSignedIn: false, + isAuthenticated: false, + tokenType: null, + toAuth: () => authObject, + headers: new Headers(), + token: null + }); +} +var withDebugHeaders = (requestState) => { + const headers = new Headers(requestState.headers || {}); + if (requestState.message) { + try { + headers.set(constants.Headers.AuthMessage, requestState.message); + } catch { + } + } + if (requestState.reason) { + try { + headers.set(constants.Headers.AuthReason, requestState.reason); + } catch { + } + } + if (requestState.status) { + try { + headers.set(constants.Headers.AuthStatus, requestState.status); + } catch { + } + } + requestState.headers = headers; + return requestState; +}; + +// src/tokens/clerkRequest.ts +import { parse } from "cookie"; + +// src/tokens/clerkUrl.ts +var ClerkUrl = class extends URL { + isCrossOrigin(other) { + return this.origin !== new URL(other.toString()).origin; + } +}; +var createClerkUrl = (...args) => { + return new ClerkUrl(...args); +}; + +// src/tokens/clerkRequest.ts +var ClerkRequest = class extends Request { + constructor(input, init) { + const url = typeof input !== "string" && "url" in input ? input.url : String(input); + super(url, init || typeof input === "string" ? void 0 : input); + this.clerkUrl = this.deriveUrlFromHeaders(this); + this.cookies = this.parseCookies(this); + } + toJSON() { + return { + url: this.clerkUrl.href, + method: this.method, + headers: JSON.stringify(Object.fromEntries(this.headers)), + clerkUrl: this.clerkUrl.toString(), + cookies: JSON.stringify(Object.fromEntries(this.cookies)) + }; + } + /** + * Used to fix request.url using the x-forwarded-* headers + * TODO add detailed description of the issues this solves + */ + deriveUrlFromHeaders(req) { + const initialUrl = new URL(req.url); + const forwardedProto = req.headers.get(constants.Headers.ForwardedProto); + const forwardedHost = req.headers.get(constants.Headers.ForwardedHost); + const host = req.headers.get(constants.Headers.Host); + const protocol = initialUrl.protocol; + const resolvedHost = this.getFirstValueFromHeader(forwardedHost) ?? host; + const resolvedProtocol = this.getFirstValueFromHeader(forwardedProto) ?? protocol?.replace(/[:/]/, ""); + const origin = resolvedHost && resolvedProtocol ? `${resolvedProtocol}://${resolvedHost}` : initialUrl.origin; + if (origin === initialUrl.origin) { + return createClerkUrl(initialUrl); + } + return createClerkUrl(initialUrl.pathname + initialUrl.search, origin); + } + getFirstValueFromHeader(value) { + return value?.split(",")[0]; + } + parseCookies(req) { + const cookiesRecord = parse(this.decodeCookieValue(req.headers.get("cookie") || "")); + return new Map(Object.entries(cookiesRecord)); + } + decodeCookieValue(str) { + return str ? str.replace(/(%[0-9A-Z]{2})+/g, decodeURIComponent) : str; + } +}; +var createClerkRequest = (...args) => { + return args[0] instanceof ClerkRequest ? args[0] : new ClerkRequest(...args); +}; + +// src/tokens/cookie.ts +var getCookieName = (cookieDirective) => { + return cookieDirective.split(";")[0]?.split("=")[0]; +}; +var getCookieValue = (cookieDirective) => { + return cookieDirective.split(";")[0]?.split("=")[1]; +}; + +// src/tokens/keys.ts +var cache = {}; +var lastUpdatedAt = 0; +function getFromCache(kid) { + return cache[kid]; +} +function getCacheValues() { + return Object.values(cache); +} +function setInCache(jwk, shouldExpire = true) { + cache[jwk.kid] = jwk; + lastUpdatedAt = shouldExpire ? Date.now() : -1; +} +var LocalJwkKid = "local"; +var PEM_HEADER = "-----BEGIN PUBLIC KEY-----"; +var PEM_TRAILER = "-----END PUBLIC KEY-----"; +var RSA_PREFIX = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA"; +var RSA_SUFFIX = "IDAQAB"; +function loadClerkJWKFromLocal(localKey) { + if (!getFromCache(LocalJwkKid)) { + if (!localKey) { + throw new TokenVerificationError({ + action: TokenVerificationErrorAction.SetClerkJWTKey, + message: "Missing local JWK.", + reason: TokenVerificationErrorReason.LocalJWKMissing + }); + } + const modulus = localKey.replace(/\r\n|\n|\r/g, "").replace(PEM_HEADER, "").replace(PEM_TRAILER, "").replace(RSA_PREFIX, "").replace(RSA_SUFFIX, "").replace(/\+/g, "-").replace(/\//g, "_"); + setInCache( + { + kid: "local", + kty: "RSA", + alg: "RS256", + n: modulus, + e: "AQAB" + }, + false + // local key never expires in cache + ); + } + return getFromCache(LocalJwkKid); +} +async function loadClerkJWKFromRemote({ + secretKey, + apiUrl = API_URL, + apiVersion = API_VERSION, + kid, + skipJwksCache +}) { + if (skipJwksCache || cacheHasExpired() || !getFromCache(kid)) { + if (!secretKey) { + throw new TokenVerificationError({ + action: TokenVerificationErrorAction.ContactSupport, + message: "Failed to load JWKS from Clerk Backend or Frontend API.", + reason: TokenVerificationErrorReason.RemoteJWKFailedToLoad + }); + } + const fetcher = () => fetchJWKSFromBAPI(apiUrl, secretKey, apiVersion); + const { keys } = await retry(fetcher); + if (!keys || !keys.length) { + throw new TokenVerificationError({ + action: TokenVerificationErrorAction.ContactSupport, + message: "The JWKS endpoint did not contain any signing keys. Contact support@clerk.com.", + reason: TokenVerificationErrorReason.RemoteJWKFailedToLoad + }); + } + keys.forEach((key) => setInCache(key)); + } + const jwk = getFromCache(kid); + if (!jwk) { + const cacheValues = getCacheValues(); + const jwkKeys = cacheValues.map((jwk2) => jwk2.kid).sort().join(", "); + throw new TokenVerificationError({ + action: `Go to your Dashboard and validate your secret and public keys are correct. ${TokenVerificationErrorAction.ContactSupport} if the issue persists.`, + message: `Unable to find a signing key in JWKS that matches the kid='${kid}' of the provided session token. Please make sure that the __session cookie or the HTTP authorization header contain a Clerk-generated session JWT. The following kid is available: ${jwkKeys}`, + reason: TokenVerificationErrorReason.JWKKidMismatch + }); + } + return jwk; +} +async function fetchJWKSFromBAPI(apiUrl, key, apiVersion) { + if (!key) { + throw new TokenVerificationError({ + action: TokenVerificationErrorAction.SetClerkSecretKey, + message: "Missing Clerk Secret Key or API Key. Go to https://dashboard.clerk.com and get your key for your instance.", + reason: TokenVerificationErrorReason.RemoteJWKFailedToLoad + }); + } + const url = new URL(apiUrl); + url.pathname = joinPaths(url.pathname, apiVersion, "/jwks"); + const response = await runtime.fetch(url.href, { + headers: { + Authorization: `Bearer ${key}`, + "Clerk-API-Version": SUPPORTED_BAPI_VERSION, + "Content-Type": "application/json", + "User-Agent": USER_AGENT + } + }); + if (!response.ok) { + const json = await response.json(); + const invalidSecretKeyError = getErrorObjectByCode(json?.errors, TokenVerificationErrorCode.InvalidSecretKey); + if (invalidSecretKeyError) { + const reason = TokenVerificationErrorReason.InvalidSecretKey; + throw new TokenVerificationError({ + action: TokenVerificationErrorAction.ContactSupport, + message: invalidSecretKeyError.message, + reason + }); + } + throw new TokenVerificationError({ + action: TokenVerificationErrorAction.ContactSupport, + message: `Error loading Clerk JWKS from ${url.href} with code=${response.status}`, + reason: TokenVerificationErrorReason.RemoteJWKFailedToLoad + }); + } + return response.json(); +} +function cacheHasExpired() { + if (lastUpdatedAt === -1) { + return false; + } + const isExpired = Date.now() - lastUpdatedAt >= MAX_CACHE_LAST_UPDATED_AT_SECONDS * 1e3; + if (isExpired) { + cache = {}; + } + return isExpired; +} +var getErrorObjectByCode = (errors, code) => { + if (!errors) { + return null; + } + return errors.find((err) => err.code === code); +}; + +// src/tokens/verify.ts +import { isClerkAPIResponseError } from "@clerk/shared/error"; +async function verifyToken(token, options) { + const { data: decodedResult, errors } = decodeJwt(token); + if (errors) { + return { errors }; + } + const { header } = decodedResult; + const { kid } = header; + try { + let key; + if (options.jwtKey) { + key = loadClerkJWKFromLocal(options.jwtKey); + } else if (options.secretKey) { + key = await loadClerkJWKFromRemote({ ...options, kid }); + } else { + return { + errors: [ + new TokenVerificationError({ + action: TokenVerificationErrorAction.SetClerkJWTKey, + message: "Failed to resolve JWK during verification.", + reason: TokenVerificationErrorReason.JWKFailedToResolve + }) + ] + }; + } + return await verifyJwt(token, { ...options, key }); + } catch (error) { + return { errors: [error] }; + } +} +function handleClerkAPIError(tokenType, err, notFoundMessage) { + if (isClerkAPIResponseError(err)) { + let code; + let message; + switch (err.status) { + case 401: + code = MachineTokenVerificationErrorCode.InvalidSecretKey; + message = err.errors[0]?.message || "Invalid secret key"; + break; + case 404: + code = MachineTokenVerificationErrorCode.TokenInvalid; + message = notFoundMessage; + break; + default: + code = MachineTokenVerificationErrorCode.UnexpectedError; + message = "Unexpected error"; + } + return { + data: void 0, + tokenType, + errors: [ + new MachineTokenVerificationError({ + message, + code, + status: err.status + }) + ] + }; + } + return { + data: void 0, + tokenType, + errors: [ + new MachineTokenVerificationError({ + message: "Unexpected error", + code: MachineTokenVerificationErrorCode.UnexpectedError, + status: err.status + }) + ] + }; +} +async function verifyM2MToken(token, options) { + try { + const client = createBackendApiClient(options); + const verifiedToken = await client.m2m.verifyToken({ token }); + return { data: verifiedToken, tokenType: TokenType.M2MToken, errors: void 0 }; + } catch (err) { + return handleClerkAPIError(TokenType.M2MToken, err, "Machine token not found"); + } +} +async function verifyOAuthToken(accessToken, options) { + try { + const client = createBackendApiClient(options); + const verifiedToken = await client.idPOAuthAccessToken.verifyAccessToken(accessToken); + return { data: verifiedToken, tokenType: TokenType.OAuthToken, errors: void 0 }; + } catch (err) { + return handleClerkAPIError(TokenType.OAuthToken, err, "OAuth token not found"); + } +} +async function verifyAPIKey(secret, options) { + try { + const client = createBackendApiClient(options); + const verifiedToken = await client.apiKeys.verifySecret(secret); + return { data: verifiedToken, tokenType: TokenType.ApiKey, errors: void 0 }; + } catch (err) { + return handleClerkAPIError(TokenType.ApiKey, err, "API key not found"); + } +} +async function verifyMachineAuthToken(token, options) { + if (token.startsWith(M2M_TOKEN_PREFIX)) { + return verifyM2MToken(token, options); + } + if (token.startsWith(OAUTH_TOKEN_PREFIX)) { + return verifyOAuthToken(token, options); + } + if (token.startsWith(API_KEY_PREFIX)) { + return verifyAPIKey(token, options); + } + throw new Error("Unknown machine token type"); +} + +// src/tokens/handshake.ts +async function verifyHandshakeJwt(token, { key }) { + const { data: decoded, errors } = decodeJwt(token); + if (errors) { + throw errors[0]; + } + const { header, payload } = decoded; + const { typ, alg } = header; + assertHeaderType(typ); + assertHeaderAlgorithm(alg); + const { data: signatureValid, errors: signatureErrors } = await hasValidSignature(decoded, key); + if (signatureErrors) { + throw new TokenVerificationError({ + reason: TokenVerificationErrorReason.TokenVerificationFailed, + message: `Error verifying handshake token. ${signatureErrors[0]}` + }); + } + if (!signatureValid) { + throw new TokenVerificationError({ + reason: TokenVerificationErrorReason.TokenInvalidSignature, + message: "Handshake signature is invalid." + }); + } + return payload; +} +async function verifyHandshakeToken(token, options) { + const { secretKey, apiUrl, apiVersion, jwksCacheTtlInMs, jwtKey, skipJwksCache } = options; + const { data, errors } = decodeJwt(token); + if (errors) { + throw errors[0]; + } + const { kid } = data.header; + let key; + if (jwtKey) { + key = loadClerkJWKFromLocal(jwtKey); + } else if (secretKey) { + key = await loadClerkJWKFromRemote({ secretKey, apiUrl, apiVersion, kid, jwksCacheTtlInMs, skipJwksCache }); + } else { + throw new TokenVerificationError({ + action: TokenVerificationErrorAction.SetClerkJWTKey, + message: "Failed to resolve JWK during handshake verification.", + reason: TokenVerificationErrorReason.JWKFailedToResolve + }); + } + return await verifyHandshakeJwt(token, { + key + }); +} +var HandshakeService = class { + constructor(authenticateContext, options, organizationMatcher) { + this.authenticateContext = authenticateContext; + this.options = options; + this.organizationMatcher = organizationMatcher; + } + /** + * Determines if a request is eligible for handshake based on its headers + * + * Currently, a request is only eligible for a handshake if we can say it's *probably* a request for a document, not a fetch or some other exotic request. + * This heuristic should give us a reliable enough signal for browsers that support `Sec-Fetch-Dest` and for those that don't. + * + * @returns boolean indicating if the request is eligible for handshake + */ + isRequestEligibleForHandshake() { + const { accept, secFetchDest } = this.authenticateContext; + if (secFetchDest === "document" || secFetchDest === "iframe") { + return true; + } + if (!secFetchDest && accept?.startsWith("text/html")) { + return true; + } + return false; + } + /** + * Builds the redirect headers for a handshake request + * @param reason - The reason for the handshake (e.g. 'session-token-expired') + * @returns Headers object containing the Location header for redirect + * @throws Error if clerkUrl is missing in authenticateContext + */ + buildRedirectToHandshake(reason) { + if (!this.authenticateContext?.clerkUrl) { + throw new Error("Missing clerkUrl in authenticateContext"); + } + const redirectUrl = this.removeDevBrowserFromURL(this.authenticateContext.clerkUrl); + let baseUrl = this.authenticateContext.frontendApi.startsWith("http") ? this.authenticateContext.frontendApi : `https://${this.authenticateContext.frontendApi}`; + baseUrl = baseUrl.replace(/\/+$/, "") + "/"; + const url = new URL("v1/client/handshake", baseUrl); + url.searchParams.append("redirect_url", redirectUrl?.href || ""); + url.searchParams.append("__clerk_api_version", SUPPORTED_BAPI_VERSION); + url.searchParams.append( + constants.QueryParameters.SuffixedCookies, + this.authenticateContext.usesSuffixedCookies().toString() + ); + url.searchParams.append(constants.QueryParameters.HandshakeReason, reason); + url.searchParams.append(constants.QueryParameters.HandshakeFormat, "nonce"); + if (this.authenticateContext.instanceType === "development" && this.authenticateContext.devBrowserToken) { + url.searchParams.append(constants.QueryParameters.DevBrowser, this.authenticateContext.devBrowserToken); + } + const toActivate = this.getOrganizationSyncTarget(this.authenticateContext.clerkUrl, this.organizationMatcher); + if (toActivate) { + const params = this.getOrganizationSyncQueryParams(toActivate); + params.forEach((value, key) => { + url.searchParams.append(key, value); + }); + } + return new Headers({ [constants.Headers.Location]: url.href }); + } + /** + * Gets cookies from either a handshake nonce or a handshake token + * @returns Promise resolving to string array of cookie directives + */ + async getCookiesFromHandshake() { + const cookiesToSet = []; + if (this.authenticateContext.handshakeNonce) { + try { + const handshakePayload = await this.authenticateContext.apiClient?.clients.getHandshakePayload({ + nonce: this.authenticateContext.handshakeNonce + }); + if (handshakePayload) { + cookiesToSet.push(...handshakePayload.directives); + } + } catch (error) { + console.error("Clerk: HandshakeService: error getting handshake payload:", error); + } + } else if (this.authenticateContext.handshakeToken) { + const handshakePayload = await verifyHandshakeToken( + this.authenticateContext.handshakeToken, + this.authenticateContext + ); + if (handshakePayload && Array.isArray(handshakePayload.handshake)) { + cookiesToSet.push(...handshakePayload.handshake); + } + } + return cookiesToSet; + } + /** + * Resolves a handshake request by verifying the handshake token and setting appropriate cookies + * @returns Promise resolving to either a SignedInState or SignedOutState + * @throws Error if handshake verification fails or if there are issues with the session token + */ + async resolveHandshake() { + const headers = new Headers({ + "Access-Control-Allow-Origin": "null", + "Access-Control-Allow-Credentials": "true" + }); + const cookiesToSet = await this.getCookiesFromHandshake(); + let sessionToken = ""; + cookiesToSet.forEach((x) => { + headers.append("Set-Cookie", x); + if (getCookieName(x).startsWith(constants.Cookies.Session)) { + sessionToken = getCookieValue(x); + } + }); + if (this.authenticateContext.instanceType === "development") { + const newUrl = new URL(this.authenticateContext.clerkUrl); + newUrl.searchParams.delete(constants.QueryParameters.Handshake); + newUrl.searchParams.delete(constants.QueryParameters.HandshakeHelp); + newUrl.searchParams.delete(constants.QueryParameters.DevBrowser); + headers.append(constants.Headers.Location, newUrl.toString()); + headers.set(constants.Headers.CacheControl, "no-store"); + } + if (sessionToken === "") { + return signedOut({ + tokenType: TokenType.SessionToken, + authenticateContext: this.authenticateContext, + reason: AuthErrorReason.SessionTokenMissing, + message: "", + headers + }); + } + const { data, errors: [error] = [] } = await verifyToken(sessionToken, this.authenticateContext); + if (data) { + return signedIn({ + tokenType: TokenType.SessionToken, + authenticateContext: this.authenticateContext, + sessionClaims: data, + headers, + token: sessionToken + }); + } + if (this.authenticateContext.instanceType === "development" && (error?.reason === TokenVerificationErrorReason.TokenExpired || error?.reason === TokenVerificationErrorReason.TokenNotActiveYet || error?.reason === TokenVerificationErrorReason.TokenIatInTheFuture)) { + const developmentError = new TokenVerificationError({ + action: error.action, + message: error.message, + reason: error.reason + }); + developmentError.tokenCarrier = "cookie"; + console.error( + `Clerk: Clock skew detected. This usually means that your system clock is inaccurate. Clerk will attempt to account for the clock skew in development. + +To resolve this issue, make sure your system's clock is set to the correct time (e.g. turn off and on automatic time synchronization). + +--- + +${developmentError.getFullMessage()}` + ); + const { data: retryResult, errors: [retryError] = [] } = await verifyToken(sessionToken, { + ...this.authenticateContext, + clockSkewInMs: 864e5 + }); + if (retryResult) { + return signedIn({ + tokenType: TokenType.SessionToken, + authenticateContext: this.authenticateContext, + sessionClaims: retryResult, + headers, + token: sessionToken + }); + } + throw new Error(retryError?.message || "Clerk: Handshake retry failed."); + } + throw new Error(error?.message || "Clerk: Handshake failed."); + } + /** + * Handles handshake token verification errors in development mode + * @param error - The TokenVerificationError that occurred + * @throws Error with a descriptive message about the verification failure + */ + handleTokenVerificationErrorInDevelopment(error) { + if (error.reason === TokenVerificationErrorReason.TokenInvalidSignature) { + const msg = `Clerk: Handshake token verification failed due to an invalid signature. If you have switched Clerk keys locally, clear your cookies and try again.`; + throw new Error(msg); + } + throw new Error(`Clerk: Handshake token verification failed: ${error.getFullMessage()}.`); + } + /** + * Checks if a redirect loop is detected and sets headers to track redirect count + * @param headers - The Headers object to modify + * @returns boolean indicating if a redirect loop was detected (true) or if the request can proceed (false) + */ + checkAndTrackRedirectLoop(headers) { + if (this.authenticateContext.handshakeRedirectLoopCounter === 3) { + return true; + } + const newCounterValue = this.authenticateContext.handshakeRedirectLoopCounter + 1; + const cookieName = constants.Cookies.RedirectCount; + headers.append("Set-Cookie", `${cookieName}=${newCounterValue}; SameSite=Lax; HttpOnly; Max-Age=2`); + return false; + } + removeDevBrowserFromURL(url) { + const updatedURL = new URL(url); + updatedURL.searchParams.delete(constants.QueryParameters.DevBrowser); + updatedURL.searchParams.delete(constants.QueryParameters.LegacyDevBrowser); + return updatedURL; + } + getOrganizationSyncTarget(url, matchers) { + return matchers.findTarget(url); + } + getOrganizationSyncQueryParams(toActivate) { + const ret = /* @__PURE__ */ new Map(); + if (toActivate.type === "personalAccount") { + ret.set("organization_id", ""); + } + if (toActivate.type === "organization") { + if (toActivate.organizationId) { + ret.set("organization_id", toActivate.organizationId); + } + if (toActivate.organizationSlug) { + ret.set("organization_id", toActivate.organizationSlug); + } + } + return ret; + } +}; + +// src/tokens/organizationMatcher.ts +import { match } from "@clerk/shared/pathToRegexp"; +var OrganizationMatcher = class { + constructor(options) { + this.organizationPattern = this.createMatcher(options?.organizationPatterns); + this.personalAccountPattern = this.createMatcher(options?.personalAccountPatterns); + } + createMatcher(pattern) { + if (!pattern) { + return null; + } + try { + return match(pattern); + } catch (e) { + throw new Error(`Invalid pattern "${pattern}": ${e}`); + } + } + findTarget(url) { + const orgTarget = this.findOrganizationTarget(url); + if (orgTarget) { + return orgTarget; + } + return this.findPersonalAccountTarget(url); + } + findOrganizationTarget(url) { + if (!this.organizationPattern) { + return null; + } + try { + const result = this.organizationPattern(url.pathname); + if (!result || !("params" in result)) { + return null; + } + const params = result.params; + if (params.id) { + return { type: "organization", organizationId: params.id }; + } + if (params.slug) { + return { type: "organization", organizationSlug: params.slug }; + } + return null; + } catch (e) { + console.error("Failed to match organization pattern:", e); + return null; + } + } + findPersonalAccountTarget(url) { + if (!this.personalAccountPattern) { + return null; + } + try { + const result = this.personalAccountPattern(url.pathname); + return result ? { type: "personalAccount" } : null; + } catch (e) { + console.error("Failed to match personal account pattern:", e); + return null; + } + } +}; + +// src/tokens/request.ts +var RefreshTokenErrorReason = { + NonEligibleNoCookie: "non-eligible-no-refresh-cookie", + NonEligibleNonGet: "non-eligible-non-get", + InvalidSessionToken: "invalid-session-token", + MissingApiClient: "missing-api-client", + MissingSessionToken: "missing-session-token", + MissingRefreshToken: "missing-refresh-token", + ExpiredSessionTokenDecodeFailed: "expired-session-token-decode-failed", + ExpiredSessionTokenMissingSidClaim: "expired-session-token-missing-sid-claim", + FetchError: "fetch-error", + UnexpectedSDKError: "unexpected-sdk-error", + UnexpectedBAPIError: "unexpected-bapi-error" +}; +function assertSignInUrlExists(signInUrl, key) { + if (!signInUrl && isDevelopmentFromSecretKey(key)) { + throw new Error(`Missing signInUrl. Pass a signInUrl for dev instances if an app is satellite`); + } +} +function assertProxyUrlOrDomain(proxyUrlOrDomain) { + if (!proxyUrlOrDomain) { + throw new Error(`Missing domain and proxyUrl. A satellite application needs to specify a domain or a proxyUrl`); + } +} +function assertSignInUrlFormatAndOrigin(_signInUrl, origin) { + let signInUrl; + try { + signInUrl = new URL(_signInUrl); + } catch { + throw new Error(`The signInUrl needs to have a absolute url format.`); + } + if (signInUrl.origin === origin) { + throw new Error(`The signInUrl needs to be on a different origin than your satellite application.`); + } +} +function assertMachineSecretOrSecretKey(authenticateContext) { + if (!authenticateContext.machineSecretKey && !authenticateContext.secretKey) { + throw new Error( + "Machine token authentication requires either a Machine secret key or a Clerk secret key. Ensure a Clerk secret key or Machine secret key is set." + ); + } +} +function isRequestEligibleForRefresh(err, authenticateContext, request) { + return err.reason === TokenVerificationErrorReason.TokenExpired && !!authenticateContext.refreshTokenInCookie && request.method === "GET"; +} +function checkTokenTypeMismatch(parsedTokenType, acceptsToken, authenticateContext) { + const mismatch = !isTokenTypeAccepted(parsedTokenType, acceptsToken); + if (mismatch) { + const tokenTypeToReturn = typeof acceptsToken === "string" ? acceptsToken : parsedTokenType; + return signedOut({ + tokenType: tokenTypeToReturn, + authenticateContext, + reason: AuthErrorReason.TokenTypeMismatch + }); + } + return null; +} +function isTokenTypeInAcceptedArray(acceptsToken, authenticateContext) { + let parsedTokenType = null; + const { tokenInHeader } = authenticateContext; + if (tokenInHeader) { + if (isMachineTokenByPrefix(tokenInHeader)) { + parsedTokenType = getMachineTokenType(tokenInHeader); + } else { + parsedTokenType = TokenType.SessionToken; + } + } + const typeToCheck = parsedTokenType ?? TokenType.SessionToken; + return isTokenTypeAccepted(typeToCheck, acceptsToken); +} +var authenticateRequest = async (request, options) => { + const authenticateContext = await createAuthenticateContext(createClerkRequest(request), options); + const acceptsToken = options.acceptsToken ?? TokenType.SessionToken; + if (acceptsToken !== TokenType.M2MToken) { + assertValidSecretKey(authenticateContext.secretKey); + if (authenticateContext.isSatellite) { + assertSignInUrlExists(authenticateContext.signInUrl, authenticateContext.secretKey); + if (authenticateContext.signInUrl && authenticateContext.origin) { + assertSignInUrlFormatAndOrigin(authenticateContext.signInUrl, authenticateContext.origin); + } + assertProxyUrlOrDomain(authenticateContext.proxyUrl || authenticateContext.domain); + } + } + if (acceptsToken === TokenType.M2MToken) { + assertMachineSecretOrSecretKey(authenticateContext); + } + const organizationMatcher = new OrganizationMatcher(options.organizationSyncOptions); + const handshakeService = new HandshakeService( + authenticateContext, + { organizationSyncOptions: options.organizationSyncOptions }, + organizationMatcher + ); + async function refreshToken(authenticateContext2) { + if (!options.apiClient) { + return { + data: null, + error: { + message: "An apiClient is needed to perform token refresh.", + cause: { reason: RefreshTokenErrorReason.MissingApiClient } + } + }; + } + const { sessionToken: expiredSessionToken, refreshTokenInCookie: refreshToken2 } = authenticateContext2; + if (!expiredSessionToken) { + return { + data: null, + error: { + message: "Session token must be provided.", + cause: { reason: RefreshTokenErrorReason.MissingSessionToken } + } + }; + } + if (!refreshToken2) { + return { + data: null, + error: { + message: "Refresh token must be provided.", + cause: { reason: RefreshTokenErrorReason.MissingRefreshToken } + } + }; + } + const { data: decodeResult, errors: decodedErrors } = decodeJwt(expiredSessionToken); + if (!decodeResult || decodedErrors) { + return { + data: null, + error: { + message: "Unable to decode the expired session token.", + cause: { reason: RefreshTokenErrorReason.ExpiredSessionTokenDecodeFailed, errors: decodedErrors } + } + }; + } + if (!decodeResult?.payload?.sid) { + return { + data: null, + error: { + message: "Expired session token is missing the `sid` claim.", + cause: { reason: RefreshTokenErrorReason.ExpiredSessionTokenMissingSidClaim } + } + }; + } + try { + const response = await options.apiClient.sessions.refreshSession(decodeResult.payload.sid, { + format: "cookie", + suffixed_cookies: authenticateContext2.usesSuffixedCookies(), + expired_token: expiredSessionToken || "", + refresh_token: refreshToken2 || "", + request_origin: authenticateContext2.clerkUrl.origin, + // The refresh endpoint expects headers as Record, so we need to transform it. + request_headers: Object.fromEntries(Array.from(request.headers.entries()).map(([k, v]) => [k, [v]])) + }); + return { data: response.cookies, error: null }; + } catch (err) { + if (err?.errors?.length) { + if (err.errors[0].code === "unexpected_error") { + return { + data: null, + error: { + message: `Fetch unexpected error`, + cause: { reason: RefreshTokenErrorReason.FetchError, errors: err.errors } + } + }; + } + return { + data: null, + error: { + message: err.errors[0].code, + cause: { reason: err.errors[0].code, errors: err.errors } + } + }; + } else { + return { + data: null, + error: { + message: `Unexpected Server/BAPI error`, + cause: { reason: RefreshTokenErrorReason.UnexpectedBAPIError, errors: [err] } + } + }; + } + } + } + async function attemptRefresh(authenticateContext2) { + const { data: cookiesToSet, error } = await refreshToken(authenticateContext2); + if (!cookiesToSet || cookiesToSet.length === 0) { + return { data: null, error }; + } + const headers = new Headers(); + let sessionToken = ""; + cookiesToSet.forEach((x) => { + headers.append("Set-Cookie", x); + if (getCookieName(x).startsWith(constants.Cookies.Session)) { + sessionToken = getCookieValue(x); + } + }); + const { data: jwtPayload, errors } = await verifyToken(sessionToken, authenticateContext2); + if (errors) { + return { + data: null, + error: { + message: `Clerk: unable to verify refreshed session token.`, + cause: { reason: RefreshTokenErrorReason.InvalidSessionToken, errors } + } + }; + } + return { data: { jwtPayload, sessionToken, headers }, error: null }; + } + function handleMaybeHandshakeStatus(authenticateContext2, reason, message, headers) { + if (!handshakeService.isRequestEligibleForHandshake()) { + return signedOut({ + tokenType: TokenType.SessionToken, + authenticateContext: authenticateContext2, + reason, + message + }); + } + const handshakeHeaders = headers ?? handshakeService.buildRedirectToHandshake(reason); + if (handshakeHeaders.get(constants.Headers.Location)) { + handshakeHeaders.set(constants.Headers.CacheControl, "no-store"); + } + const isRedirectLoop = handshakeService.checkAndTrackRedirectLoop(handshakeHeaders); + if (isRedirectLoop) { + const msg = `Clerk: Refreshing the session token resulted in an infinite redirect loop. This usually means that your Clerk instance keys do not match - make sure to copy the correct publishable and secret keys from the Clerk dashboard.`; + console.log(msg); + return signedOut({ + tokenType: TokenType.SessionToken, + authenticateContext: authenticateContext2, + reason, + message + }); + } + return handshake(authenticateContext2, reason, message, handshakeHeaders); + } + function handleMaybeOrganizationSyncHandshake(authenticateContext2, auth) { + const organizationSyncTarget = organizationMatcher.findTarget(authenticateContext2.clerkUrl); + if (!organizationSyncTarget) { + return null; + } + let mustActivate = false; + if (organizationSyncTarget.type === "organization") { + if (organizationSyncTarget.organizationSlug && organizationSyncTarget.organizationSlug !== auth.orgSlug) { + mustActivate = true; + } + if (organizationSyncTarget.organizationId && organizationSyncTarget.organizationId !== auth.orgId) { + mustActivate = true; + } + } + if (organizationSyncTarget.type === "personalAccount" && auth.orgId) { + mustActivate = true; + } + if (!mustActivate) { + return null; + } + if (authenticateContext2.handshakeRedirectLoopCounter >= 3) { + console.warn( + "Clerk: Organization activation handshake loop detected. This is likely due to an invalid organization ID or slug. Skipping organization activation." + ); + return null; + } + const handshakeState = handleMaybeHandshakeStatus( + authenticateContext2, + AuthErrorReason.ActiveOrganizationMismatch, + "" + ); + if (handshakeState.status !== "handshake") { + return null; + } + return handshakeState; + } + async function authenticateRequestWithTokenInHeader() { + const { tokenInHeader } = authenticateContext; + try { + const { data, errors } = await verifyToken(tokenInHeader, authenticateContext); + if (errors) { + throw errors[0]; + } + return signedIn({ + tokenType: TokenType.SessionToken, + authenticateContext, + sessionClaims: data, + headers: new Headers(), + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + token: tokenInHeader + }); + } catch (err) { + return handleSessionTokenError(err, "header"); + } + } + async function authenticateRequestWithTokenInCookie() { + const hasActiveClient = authenticateContext.clientUat; + const hasSessionToken = !!authenticateContext.sessionTokenInCookie; + const hasDevBrowserToken = !!authenticateContext.devBrowserToken; + if (authenticateContext.handshakeNonce || authenticateContext.handshakeToken) { + try { + return await handshakeService.resolveHandshake(); + } catch (error) { + if (error instanceof TokenVerificationError && authenticateContext.instanceType === "development") { + handshakeService.handleTokenVerificationErrorInDevelopment(error); + } else { + console.error("Clerk: unable to resolve handshake:", error); + } + } + } + if (authenticateContext.instanceType === "development" && authenticateContext.clerkUrl.searchParams.has(constants.QueryParameters.DevBrowser)) { + return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.DevBrowserSync, ""); + } + const isRequestEligibleForMultiDomainSync = authenticateContext.isSatellite && authenticateContext.secFetchDest === "document"; + if (authenticateContext.instanceType === "production" && isRequestEligibleForMultiDomainSync) { + return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.SatelliteCookieNeedsSyncing, ""); + } + if (authenticateContext.instanceType === "development" && isRequestEligibleForMultiDomainSync && !authenticateContext.clerkUrl.searchParams.has(constants.QueryParameters.ClerkSynced)) { + const redirectURL = new URL(authenticateContext.signInUrl); + redirectURL.searchParams.append( + constants.QueryParameters.ClerkRedirectUrl, + authenticateContext.clerkUrl.toString() + ); + const headers = new Headers({ [constants.Headers.Location]: redirectURL.toString() }); + return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.SatelliteCookieNeedsSyncing, "", headers); + } + const redirectUrl = new URL(authenticateContext.clerkUrl).searchParams.get( + constants.QueryParameters.ClerkRedirectUrl + ); + if (authenticateContext.instanceType === "development" && !authenticateContext.isSatellite && redirectUrl) { + const redirectBackToSatelliteUrl = new URL(redirectUrl); + if (authenticateContext.devBrowserToken) { + redirectBackToSatelliteUrl.searchParams.append( + constants.QueryParameters.DevBrowser, + authenticateContext.devBrowserToken + ); + } + redirectBackToSatelliteUrl.searchParams.append(constants.QueryParameters.ClerkSynced, "true"); + const headers = new Headers({ [constants.Headers.Location]: redirectBackToSatelliteUrl.toString() }); + return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.PrimaryRespondsToSyncing, "", headers); + } + if (authenticateContext.instanceType === "development" && !hasDevBrowserToken) { + return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.DevBrowserMissing, ""); + } + if (!hasActiveClient && !hasSessionToken) { + return signedOut({ + tokenType: TokenType.SessionToken, + authenticateContext, + reason: AuthErrorReason.SessionTokenAndUATMissing + }); + } + if (!hasActiveClient && hasSessionToken) { + return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.SessionTokenWithoutClientUAT, ""); + } + if (hasActiveClient && !hasSessionToken) { + return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.ClientUATWithoutSessionToken, ""); + } + const { data: decodeResult, errors: decodedErrors } = decodeJwt(authenticateContext.sessionTokenInCookie); + if (decodedErrors) { + return handleSessionTokenError(decodedErrors[0], "cookie"); + } + if (decodeResult.payload.iat < authenticateContext.clientUat) { + return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.SessionTokenIATBeforeClientUAT, ""); + } + try { + const { data, errors } = await verifyToken(authenticateContext.sessionTokenInCookie, authenticateContext); + if (errors) { + throw errors[0]; + } + const signedInRequestState = signedIn({ + tokenType: TokenType.SessionToken, + authenticateContext, + sessionClaims: data, + headers: new Headers(), + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + token: authenticateContext.sessionTokenInCookie + }); + const shouldForceHandshakeForCrossDomain = !authenticateContext.isSatellite && // We're on primary + authenticateContext.secFetchDest === "document" && // Document navigation + authenticateContext.isCrossOriginReferrer() && // Came from different domain + !authenticateContext.isKnownClerkReferrer() && // Not from Clerk accounts portal or FAPI + authenticateContext.handshakeRedirectLoopCounter === 0; + if (shouldForceHandshakeForCrossDomain) { + return handleMaybeHandshakeStatus( + authenticateContext, + AuthErrorReason.PrimaryDomainCrossOriginSync, + "Cross-origin request from satellite domain requires handshake" + ); + } + const authObject = signedInRequestState.toAuth(); + if (authObject.userId) { + const handshakeRequestState = handleMaybeOrganizationSyncHandshake(authenticateContext, authObject); + if (handshakeRequestState) { + return handshakeRequestState; + } + } + return signedInRequestState; + } catch (err) { + return handleSessionTokenError(err, "cookie"); + } + return signedOut({ + tokenType: TokenType.SessionToken, + authenticateContext, + reason: AuthErrorReason.UnexpectedError + }); + } + async function handleSessionTokenError(err, tokenCarrier) { + if (!(err instanceof TokenVerificationError)) { + return signedOut({ + tokenType: TokenType.SessionToken, + authenticateContext, + reason: AuthErrorReason.UnexpectedError + }); + } + let refreshError; + if (isRequestEligibleForRefresh(err, authenticateContext, request)) { + const { data, error } = await attemptRefresh(authenticateContext); + if (data) { + return signedIn({ + tokenType: TokenType.SessionToken, + authenticateContext, + sessionClaims: data.jwtPayload, + headers: data.headers, + token: data.sessionToken + }); + } + if (error?.cause?.reason) { + refreshError = error.cause.reason; + } else { + refreshError = RefreshTokenErrorReason.UnexpectedSDKError; + } + } else { + if (request.method !== "GET") { + refreshError = RefreshTokenErrorReason.NonEligibleNonGet; + } else if (!authenticateContext.refreshTokenInCookie) { + refreshError = RefreshTokenErrorReason.NonEligibleNoCookie; + } else { + refreshError = null; + } + } + err.tokenCarrier = tokenCarrier; + const reasonToHandshake = [ + TokenVerificationErrorReason.TokenExpired, + TokenVerificationErrorReason.TokenNotActiveYet, + TokenVerificationErrorReason.TokenIatInTheFuture + ].includes(err.reason); + if (reasonToHandshake) { + return handleMaybeHandshakeStatus( + authenticateContext, + convertTokenVerificationErrorReasonToAuthErrorReason({ tokenError: err.reason, refreshError }), + err.getFullMessage() + ); + } + return signedOut({ + tokenType: TokenType.SessionToken, + authenticateContext, + reason: err.reason, + message: err.getFullMessage() + }); + } + function handleMachineError(tokenType, err) { + if (!(err instanceof MachineTokenVerificationError)) { + return signedOut({ + tokenType, + authenticateContext, + reason: AuthErrorReason.UnexpectedError + }); + } + return signedOut({ + tokenType, + authenticateContext, + reason: err.code, + message: err.getFullMessage() + }); + } + async function authenticateMachineRequestWithTokenInHeader() { + const { tokenInHeader } = authenticateContext; + if (!tokenInHeader) { + return handleSessionTokenError(new Error("Missing token in header"), "header"); + } + if (!isMachineTokenByPrefix(tokenInHeader)) { + return signedOut({ + tokenType: acceptsToken, + authenticateContext, + reason: AuthErrorReason.TokenTypeMismatch, + message: "" + }); + } + const parsedTokenType = getMachineTokenType(tokenInHeader); + const mismatchState = checkTokenTypeMismatch(parsedTokenType, acceptsToken, authenticateContext); + if (mismatchState) { + return mismatchState; + } + const { data, tokenType, errors } = await verifyMachineAuthToken(tokenInHeader, authenticateContext); + if (errors) { + return handleMachineError(tokenType, errors[0]); + } + return signedIn({ + tokenType, + authenticateContext, + machineData: data, + token: tokenInHeader + }); + } + async function authenticateAnyRequestWithTokenInHeader() { + const { tokenInHeader } = authenticateContext; + if (!tokenInHeader) { + return handleSessionTokenError(new Error("Missing token in header"), "header"); + } + if (isMachineTokenByPrefix(tokenInHeader)) { + const parsedTokenType = getMachineTokenType(tokenInHeader); + const mismatchState = checkTokenTypeMismatch(parsedTokenType, acceptsToken, authenticateContext); + if (mismatchState) { + return mismatchState; + } + const { data: data2, tokenType, errors: errors2 } = await verifyMachineAuthToken(tokenInHeader, authenticateContext); + if (errors2) { + return handleMachineError(tokenType, errors2[0]); + } + return signedIn({ + tokenType, + authenticateContext, + machineData: data2, + token: tokenInHeader + }); + } + const { data, errors } = await verifyToken(tokenInHeader, authenticateContext); + if (errors) { + return handleSessionTokenError(errors[0], "header"); + } + return signedIn({ + tokenType: TokenType.SessionToken, + authenticateContext, + sessionClaims: data, + token: tokenInHeader + }); + } + if (Array.isArray(acceptsToken)) { + if (!isTokenTypeInAcceptedArray(acceptsToken, authenticateContext)) { + return signedOutInvalidToken(); + } + } + if (authenticateContext.tokenInHeader) { + if (acceptsToken === "any") { + return authenticateAnyRequestWithTokenInHeader(); + } + if (acceptsToken === TokenType.SessionToken) { + return authenticateRequestWithTokenInHeader(); + } + return authenticateMachineRequestWithTokenInHeader(); + } + if (acceptsToken === TokenType.OAuthToken || acceptsToken === TokenType.ApiKey || acceptsToken === TokenType.M2MToken) { + return signedOut({ + tokenType: acceptsToken, + authenticateContext, + reason: "No token in header" + }); + } + return authenticateRequestWithTokenInCookie(); +}; +var debugRequestState = (params) => { + const { isSignedIn, isAuthenticated, proxyUrl, reason, message, publishableKey, isSatellite, domain } = params; + return { isSignedIn, isAuthenticated, proxyUrl, reason, message, publishableKey, isSatellite, domain }; +}; +var convertTokenVerificationErrorReasonToAuthErrorReason = ({ + tokenError, + refreshError +}) => { + switch (tokenError) { + case TokenVerificationErrorReason.TokenExpired: + return `${AuthErrorReason.SessionTokenExpired}-refresh-${refreshError}`; + case TokenVerificationErrorReason.TokenNotActiveYet: + return AuthErrorReason.SessionTokenNBF; + case TokenVerificationErrorReason.TokenIatInTheFuture: + return AuthErrorReason.SessionTokenIatInTheFuture; + default: + return AuthErrorReason.UnexpectedError; + } +}; + +// src/tokens/factory.ts +var defaultOptions = { + secretKey: "", + machineSecretKey: "", + jwtKey: "", + apiUrl: void 0, + apiVersion: void 0, + proxyUrl: "", + publishableKey: "", + isSatellite: false, + domain: "", + audience: "" +}; +function createAuthenticateRequest(params) { + const buildTimeOptions = mergePreDefinedOptions(defaultOptions, params.options); + const apiClient = params.apiClient; + const authenticateRequest2 = (request, options = {}) => { + const { apiUrl, apiVersion } = buildTimeOptions; + const runTimeOptions = mergePreDefinedOptions(buildTimeOptions, options); + return authenticateRequest(request, { + ...options, + ...runTimeOptions, + // We should add all the omitted props from options here (eg apiUrl / apiVersion) + // to avoid runtime options override them. + apiUrl, + apiVersion, + apiClient + }); + }; + return { + authenticateRequest: authenticateRequest2, + debugRequestState + }; +} + +// src/util/decorateObjectWithResources.ts +var decorateObjectWithResources = async (obj, authObj, opts) => { + const { loadSession, loadUser, loadOrganization } = opts || {}; + const { userId, sessionId, orgId } = authObj; + const { sessions, users, organizations } = createBackendApiClient({ ...opts }); + const [sessionResp, userResp, organizationResp] = await Promise.all([ + loadSession && sessionId ? sessions.getSession(sessionId) : Promise.resolve(void 0), + loadUser && userId ? users.getUser(userId) : Promise.resolve(void 0), + loadOrganization && orgId ? organizations.getOrganization({ organizationId: orgId }) : Promise.resolve(void 0) + ]); + const resources = stripPrivateDataFromObject({ + session: sessionResp, + user: userResp, + organization: organizationResp + }); + return Object.assign(obj, resources); +}; +function stripPrivateDataFromObject(authObject) { + const user = authObject.user ? { ...authObject.user } : authObject.user; + const organization = authObject.organization ? { ...authObject.organization } : authObject.organization; + prunePrivateMetadata(user); + prunePrivateMetadata(organization); + return { ...authObject, user, organization }; +} +function prunePrivateMetadata(resource) { + if (resource) { + if ("privateMetadata" in resource) { + delete resource["privateMetadata"]; + } + if ("private_metadata" in resource) { + delete resource["private_metadata"]; + } + } + return resource; +} + +// src/internal.ts +import { reverificationError, reverificationErrorResponse } from "@clerk/shared/authorization-errors"; + +export { + constants, + createBackendApiClient, + TokenType, + createRedirect, + decorateObjectWithResources, + stripPrivateDataFromObject, + createClerkRequest, + isMachineTokenByPrefix, + getMachineTokenType, + isTokenTypeAccepted, + isMachineTokenType, + verifyToken, + verifyMachineAuthToken, + reverificationError, + reverificationErrorResponse, + signedInAuthObject, + signedOutAuthObject, + authenticatedMachineObject, + unauthenticatedMachineObject, + invalidTokenAuthObject, + makeAuthObjectSerializable, + getAuthObjectFromJwt, + getAuthObjectForAcceptedToken, + AuthStatus, + debugRequestState, + createAuthenticateRequest +}; +//# sourceMappingURL=chunk-EEWX6LTS.mjs.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/chunk-EEWX6LTS.mjs.map b/backend/node_modules/@clerk/backend/dist/chunk-EEWX6LTS.mjs.map new file mode 100644 index 000000000..6ba2d9a06 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/chunk-EEWX6LTS.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../src/constants.ts","../src/createRedirect.ts","../src/util/mergePreDefinedOptions.ts","../src/util/optionsAssertions.ts","../src/tokens/authenticateContext.ts","../src/tokens/tokenTypes.ts","../src/tokens/authObjects.ts","../src/util/path.ts","../src/api/endpoints/AbstractApi.ts","../src/api/endpoints/ActorTokenApi.ts","../src/api/endpoints/AccountlessApplicationsAPI.ts","../src/api/endpoints/AllowlistIdentifierApi.ts","../src/api/endpoints/APIKeysApi.ts","../src/api/endpoints/BetaFeaturesApi.ts","../src/api/endpoints/BlocklistIdentifierApi.ts","../src/api/endpoints/ClientApi.ts","../src/api/endpoints/DomainApi.ts","../src/api/endpoints/EmailAddressApi.ts","../src/api/endpoints/IdPOAuthAccessTokenApi.ts","../src/api/endpoints/InstanceApi.ts","../src/api/endpoints/InvitationApi.ts","../src/api/endpoints/MachineApi.ts","../src/api/endpoints/M2MTokenApi.ts","../src/api/endpoints/JwksApi.ts","../src/api/endpoints/JwtTemplatesApi.ts","../src/api/endpoints/OrganizationApi.ts","../src/api/endpoints/OAuthApplicationsApi.ts","../src/api/endpoints/PhoneNumberApi.ts","../src/api/endpoints/ProxyCheckApi.ts","../src/api/endpoints/RedirectUrlApi.ts","../src/api/endpoints/SamlConnectionApi.ts","../src/api/endpoints/SessionApi.ts","../src/api/endpoints/SignInTokenApi.ts","../src/api/endpoints/SignUpApi.ts","../src/api/endpoints/TestingTokenApi.ts","../src/api/endpoints/UserApi.ts","../src/api/endpoints/WaitlistEntryApi.ts","../src/api/endpoints/WebhookApi.ts","../src/api/endpoints/BillingApi.ts","../src/api/request.ts","../../../node_modules/.pnpm/map-obj@5.0.2/node_modules/map-obj/index.js","../../../node_modules/.pnpm/change-case@5.4.4/node_modules/change-case/src/index.ts","../../../node_modules/.pnpm/snakecase-keys@9.0.2/node_modules/snakecase-keys/index.js","../src/api/resources/AccountlessApplication.ts","../src/api/resources/ActorToken.ts","../src/api/resources/AllowlistIdentifier.ts","../src/api/resources/APIKey.ts","../src/api/resources/BlocklistIdentifier.ts","../src/api/resources/Session.ts","../src/api/resources/Client.ts","../src/api/resources/CnameTarget.ts","../src/api/resources/Cookies.ts","../src/api/resources/DeletedObject.ts","../src/api/resources/Domain.ts","../src/api/resources/Email.ts","../src/api/resources/IdentificationLink.ts","../src/api/resources/Verification.ts","../src/api/resources/EmailAddress.ts","../src/api/resources/ExternalAccount.ts","../src/api/resources/IdPOAuthAccessToken.ts","../src/api/resources/Instance.ts","../src/api/resources/InstanceRestrictions.ts","../src/api/resources/InstanceSettings.ts","../src/api/resources/Invitation.ts","../src/api/resources/JSON.ts","../src/api/resources/Machine.ts","../src/api/resources/MachineScope.ts","../src/api/resources/MachineSecretKey.ts","../src/api/resources/M2MToken.ts","../src/api/resources/JwtTemplate.ts","../src/api/resources/OauthAccessToken.ts","../src/api/resources/OAuthApplication.ts","../src/api/resources/Organization.ts","../src/api/resources/OrganizationInvitation.ts","../src/api/resources/OrganizationMembership.ts","../src/api/resources/OrganizationSettings.ts","../src/api/resources/PhoneNumber.ts","../src/api/resources/ProxyCheck.ts","../src/api/resources/RedirectUrl.ts","../src/api/resources/SamlConnection.ts","../src/api/resources/SamlAccount.ts","../src/api/resources/SignInTokens.ts","../src/api/resources/SignUpAttempt.ts","../src/api/resources/SMSMessage.ts","../src/api/resources/Token.ts","../src/api/resources/Web3Wallet.ts","../src/api/resources/User.ts","../src/api/resources/WaitlistEntry.ts","../src/api/resources/Feature.ts","../src/api/resources/CommercePlan.ts","../src/api/resources/CommerceSubscriptionItem.ts","../src/api/resources/CommerceSubscription.ts","../src/api/resources/Deserializer.ts","../src/api/factory.ts","../src/tokens/machine.ts","../src/tokens/authStatus.ts","../src/tokens/clerkRequest.ts","../src/tokens/clerkUrl.ts","../src/tokens/cookie.ts","../src/tokens/keys.ts","../src/tokens/verify.ts","../src/tokens/handshake.ts","../src/tokens/organizationMatcher.ts","../src/tokens/request.ts","../src/tokens/factory.ts","../src/util/decorateObjectWithResources.ts","../src/internal.ts"],"sourcesContent":["export const API_URL = 'https://api.clerk.com';\nexport const API_VERSION = 'v1';\n\nexport const USER_AGENT = `${PACKAGE_NAME}@${PACKAGE_VERSION}`;\nexport const MAX_CACHE_LAST_UPDATED_AT_SECONDS = 5 * 60;\nexport const SUPPORTED_BAPI_VERSION = '2025-04-10';\n\nconst Attributes = {\n AuthToken: '__clerkAuthToken',\n AuthSignature: '__clerkAuthSignature',\n AuthStatus: '__clerkAuthStatus',\n AuthReason: '__clerkAuthReason',\n AuthMessage: '__clerkAuthMessage',\n ClerkUrl: '__clerkUrl',\n} as const;\n\nconst Cookies = {\n Session: '__session',\n Refresh: '__refresh',\n ClientUat: '__client_uat',\n Handshake: '__clerk_handshake',\n DevBrowser: '__clerk_db_jwt',\n RedirectCount: '__clerk_redirect_count',\n HandshakeNonce: '__clerk_handshake_nonce',\n} as const;\n\nconst QueryParameters = {\n ClerkSynced: '__clerk_synced',\n SuffixedCookies: 'suffixed_cookies',\n ClerkRedirectUrl: '__clerk_redirect_url',\n // use the reference to Cookies to indicate that it's the same value\n DevBrowser: Cookies.DevBrowser,\n Handshake: Cookies.Handshake,\n HandshakeHelp: '__clerk_help',\n LegacyDevBrowser: '__dev_session',\n HandshakeReason: '__clerk_hs_reason',\n HandshakeNonce: Cookies.HandshakeNonce,\n HandshakeFormat: 'format',\n} as const;\n\nconst Headers = {\n Accept: 'accept',\n AuthMessage: 'x-clerk-auth-message',\n Authorization: 'authorization',\n AuthReason: 'x-clerk-auth-reason',\n AuthSignature: 'x-clerk-auth-signature',\n AuthStatus: 'x-clerk-auth-status',\n AuthToken: 'x-clerk-auth-token',\n CacheControl: 'cache-control',\n ClerkRedirectTo: 'x-clerk-redirect-to',\n ClerkRequestData: 'x-clerk-request-data',\n ClerkUrl: 'x-clerk-clerk-url',\n CloudFrontForwardedProto: 'cloudfront-forwarded-proto',\n ContentType: 'content-type',\n ContentSecurityPolicy: 'content-security-policy',\n ContentSecurityPolicyReportOnly: 'content-security-policy-report-only',\n EnableDebug: 'x-clerk-debug',\n ForwardedHost: 'x-forwarded-host',\n ForwardedPort: 'x-forwarded-port',\n ForwardedProto: 'x-forwarded-proto',\n Host: 'host',\n Location: 'location',\n Nonce: 'x-nonce',\n Origin: 'origin',\n Referrer: 'referer',\n SecFetchDest: 'sec-fetch-dest',\n SecFetchSite: 'sec-fetch-site',\n UserAgent: 'user-agent',\n ReportingEndpoints: 'reporting-endpoints',\n} as const;\n\nconst ContentTypes = {\n Json: 'application/json',\n} as const;\n\n/**\n * @internal\n */\nexport const constants = {\n Attributes,\n Cookies,\n Headers,\n ContentTypes,\n QueryParameters,\n} as const;\n\nexport type Constants = typeof constants;\n","import { buildAccountsBaseUrl } from '@clerk/shared/buildAccountsBaseUrl';\nimport type { SessionStatusClaim } from '@clerk/types';\n\nimport { constants } from './constants';\nimport { errorThrower, parsePublishableKey } from './util/shared';\n\nconst buildUrl = (\n _baseUrl: string | URL,\n _targetUrl: string | URL,\n _returnBackUrl?: string | URL | null,\n _devBrowserToken?: string | null,\n) => {\n if (_baseUrl === '') {\n return legacyBuildUrl(_targetUrl.toString(), _returnBackUrl?.toString());\n }\n\n const baseUrl = new URL(_baseUrl);\n const returnBackUrl = _returnBackUrl ? new URL(_returnBackUrl, baseUrl) : undefined;\n const res = new URL(_targetUrl, baseUrl);\n const isCrossOriginRedirect = `${baseUrl.hostname}:${baseUrl.port}` !== `${res.hostname}:${res.port}`;\n\n if (returnBackUrl) {\n if (isCrossOriginRedirect) {\n returnBackUrl.searchParams.delete(constants.QueryParameters.ClerkSynced);\n }\n\n res.searchParams.set('redirect_url', returnBackUrl.toString());\n }\n // For cross-origin redirects, we need to pass the dev browser token for URL session syncing\n if (isCrossOriginRedirect && _devBrowserToken) {\n res.searchParams.set(constants.QueryParameters.DevBrowser, _devBrowserToken);\n }\n return res.toString();\n};\n\n/**\n * In v5, we deprecated the top-level redirectToSignIn and redirectToSignUp functions\n * in favor of the new auth().redirectToSignIn helpers\n * In order to allow for a smooth transition, we need to support the legacy redirectToSignIn for now\n * as we will remove it in v6.\n * In order to make sure that the legacy function works as expected, we will use legacyBuildUrl\n * to build the url if baseUrl is not provided (which is the case for legacy redirectToSignIn)\n * This function can be safely removed when we remove the legacy redirectToSignIn function\n */\nconst legacyBuildUrl = (targetUrl: string, redirectUrl?: string) => {\n let url;\n if (!targetUrl.startsWith('http')) {\n if (!redirectUrl || !redirectUrl.startsWith('http')) {\n throw new Error('destination url or return back url should be an absolute path url!');\n }\n\n const baseURL = new URL(redirectUrl);\n url = new URL(targetUrl, baseURL.origin);\n } else {\n url = new URL(targetUrl);\n }\n\n if (redirectUrl) {\n url.searchParams.set('redirect_url', redirectUrl);\n }\n\n return url.toString();\n};\n\ntype RedirectAdapter = (url: string) => RedirectReturn;\ntype RedirectToParams = { returnBackUrl?: string | URL | null };\nexport type RedirectFun = (params?: RedirectToParams) => ReturnType;\n\n/**\n * @internal\n */\ntype CreateRedirect = (params: {\n publishableKey: string;\n devBrowserToken?: string;\n redirectAdapter: RedirectAdapter;\n baseUrl: URL | string;\n signInUrl?: URL | string;\n signUpUrl?: URL | string;\n sessionStatus?: SessionStatusClaim | null;\n}) => {\n redirectToSignIn: RedirectFun;\n redirectToSignUp: RedirectFun;\n};\n\nexport const createRedirect: CreateRedirect = params => {\n const { publishableKey, redirectAdapter, signInUrl, signUpUrl, baseUrl, sessionStatus } = params;\n const parsedPublishableKey = parsePublishableKey(publishableKey);\n const frontendApi = parsedPublishableKey?.frontendApi;\n const isDevelopment = parsedPublishableKey?.instanceType === 'development';\n const accountsBaseUrl = buildAccountsBaseUrl(frontendApi);\n const hasPendingStatus = sessionStatus === 'pending';\n\n const redirectToTasks = (url: string | URL, { returnBackUrl }: RedirectToParams) => {\n return redirectAdapter(\n buildUrl(baseUrl, `${url}/tasks`, returnBackUrl, isDevelopment ? params.devBrowserToken : null),\n );\n };\n\n const redirectToSignUp = ({ returnBackUrl }: RedirectToParams = {}) => {\n if (!signUpUrl && !accountsBaseUrl) {\n errorThrower.throwMissingPublishableKeyError();\n }\n\n const accountsSignUpUrl = `${accountsBaseUrl}/sign-up`;\n\n // Allows redirection to SignInOrUp path\n function buildSignUpUrl(signIn: string | URL | undefined) {\n if (!signIn) {\n return;\n }\n const url = new URL(signIn, baseUrl);\n url.pathname = `${url.pathname}/create`;\n return url.toString();\n }\n\n const targetUrl = signUpUrl || buildSignUpUrl(signInUrl) || accountsSignUpUrl;\n\n if (hasPendingStatus) {\n return redirectToTasks(targetUrl, { returnBackUrl });\n }\n\n return redirectAdapter(buildUrl(baseUrl, targetUrl, returnBackUrl, isDevelopment ? params.devBrowserToken : null));\n };\n\n const redirectToSignIn = ({ returnBackUrl }: RedirectToParams = {}) => {\n if (!signInUrl && !accountsBaseUrl) {\n errorThrower.throwMissingPublishableKeyError();\n }\n\n const accountsSignInUrl = `${accountsBaseUrl}/sign-in`;\n const targetUrl = signInUrl || accountsSignInUrl;\n\n if (hasPendingStatus) {\n return redirectToTasks(targetUrl, { returnBackUrl });\n }\n\n return redirectAdapter(buildUrl(baseUrl, targetUrl, returnBackUrl, isDevelopment ? params.devBrowserToken : null));\n };\n\n return { redirectToSignUp, redirectToSignIn };\n};\n","export function mergePreDefinedOptions>(preDefinedOptions: T, options: Partial): T {\n return Object.keys(preDefinedOptions).reduce(\n (obj: T, key: string) => {\n return { ...obj, [key]: options[key] || obj[key] };\n },\n { ...preDefinedOptions },\n );\n}\n","import { parsePublishableKey } from './shared';\n\nexport function assertValidSecretKey(val: unknown): asserts val is string {\n if (!val || typeof val !== 'string') {\n throw Error('Missing Clerk Secret Key. Go to https://dashboard.clerk.com and get your key for your instance.');\n }\n\n //TODO: Check if the key is invalid and throw error\n}\n\nexport function assertValidPublishableKey(val: unknown): asserts val is string {\n parsePublishableKey(val as string | undefined, { fatal: true });\n}\n","import { buildAccountsBaseUrl } from '@clerk/shared/buildAccountsBaseUrl';\nimport { isCurrentDevAccountPortalOrigin, isLegacyDevAccountPortalOrigin } from '@clerk/shared/url';\nimport type { Jwt } from '@clerk/types';\n\nimport { constants } from '../constants';\nimport { decodeJwt } from '../jwt/verifyJwt';\nimport { runtime } from '../runtime';\nimport { assertValidPublishableKey } from '../util/optionsAssertions';\nimport { getCookieSuffix, getSuffixedCookieName, parsePublishableKey } from '../util/shared';\nimport type { ClerkRequest } from './clerkRequest';\nimport { TokenType } from './tokenTypes';\nimport type { AuthenticateRequestOptions } from './types';\n\ninterface AuthenticateContext extends AuthenticateRequestOptions {\n // header-based values\n accept: string | undefined;\n forwardedHost: string | undefined;\n forwardedProto: string | undefined;\n host: string | undefined;\n origin: string | undefined;\n referrer: string | undefined;\n secFetchDest: string | undefined;\n tokenInHeader: string | undefined;\n userAgent: string | undefined;\n\n // cookie-based values\n clientUat: number;\n refreshTokenInCookie: string | undefined;\n sessionTokenInCookie: string | undefined;\n\n // handshake-related values\n devBrowserToken: string | undefined;\n handshakeNonce: string | undefined;\n handshakeRedirectLoopCounter: number;\n handshakeToken: string | undefined;\n\n // url derived from headers\n clerkUrl: URL;\n // enforce existence of the following props\n frontendApi: string;\n instanceType: string;\n publishableKey: string;\n}\n\n/**\n * All data required to authenticate a request.\n * This is the data we use to decide whether a request\n * is in a signed in or signed out state or if we need\n * to perform a handshake.\n */\nclass AuthenticateContext implements AuthenticateContext {\n /**\n * The original Clerk frontend API URL, extracted from publishable key before proxy URL override.\n * Used for backend operations like token validation and issuer checking.\n */\n private originalFrontendApi: string = '';\n\n /**\n * Retrieves the session token from either the cookie or the header.\n *\n * @returns {string | undefined} The session token if available, otherwise undefined.\n */\n public get sessionToken(): string | undefined {\n return this.sessionTokenInCookie || this.tokenInHeader;\n }\n\n public constructor(\n private cookieSuffix: string,\n private clerkRequest: ClerkRequest,\n options: AuthenticateRequestOptions,\n ) {\n if (options.acceptsToken === TokenType.M2MToken || options.acceptsToken === TokenType.ApiKey) {\n // For non-session tokens, we only want to set the header values.\n this.initHeaderValues();\n } else {\n // Even though the options are assigned to this later in this function\n // we set the publishableKey here because it is being used in cookies/headers/handshake-values\n // as part of getMultipleAppsCookie.\n this.initPublishableKeyValues(options);\n this.initHeaderValues();\n // initCookieValues should be used before initHandshakeValues because it depends on suffixedCookies\n this.initCookieValues();\n this.initHandshakeValues();\n }\n\n Object.assign(this, options);\n this.clerkUrl = this.clerkRequest.clerkUrl;\n }\n\n public usesSuffixedCookies(): boolean {\n const suffixedClientUat = this.getSuffixedCookie(constants.Cookies.ClientUat);\n const clientUat = this.getCookie(constants.Cookies.ClientUat);\n const suffixedSession = this.getSuffixedCookie(constants.Cookies.Session) || '';\n const session = this.getCookie(constants.Cookies.Session) || '';\n\n // In the case of malformed session cookies (eg missing the iss claim), we should\n // use the un-suffixed cookies to return signed-out state instead of triggering\n // handshake\n if (session && !this.tokenHasIssuer(session)) {\n return false;\n }\n\n // If there's a token in un-suffixed, and it doesn't belong to this\n // instance, then we must trust suffixed\n if (session && !this.tokenBelongsToInstance(session)) {\n return true;\n }\n\n // If there are no suffixed cookies use un-suffixed\n if (!suffixedClientUat && !suffixedSession) {\n return false;\n }\n\n const { data: sessionData } = decodeJwt(session);\n const sessionIat = sessionData?.payload.iat || 0;\n const { data: suffixedSessionData } = decodeJwt(suffixedSession);\n const suffixedSessionIat = suffixedSessionData?.payload.iat || 0;\n\n // Both indicate signed in, but un-suffixed is newer\n // Trust un-suffixed because it's newer\n if (suffixedClientUat !== '0' && clientUat !== '0' && sessionIat > suffixedSessionIat) {\n return false;\n }\n\n // Suffixed indicates signed out, but un-suffixed indicates signed in\n // Trust un-suffixed because it gets set with both new and old clerk.js,\n // so we can assume it's newer\n if (suffixedClientUat === '0' && clientUat !== '0') {\n return false;\n }\n\n // Suffixed indicates signed in, un-suffixed indicates signed out\n // This is the tricky one\n\n // In production, suffixed_uat should be set reliably, since it's\n // set by FAPI and not clerk.js. So in the scenario where a developer\n // downgrades, the state will look like this:\n // - un-suffixed session cookie: empty\n // - un-suffixed uat: 0\n // - suffixed session cookie: (possibly filled, possibly empty)\n // - suffixed uat: 0\n\n // Our SDK honors client_uat over the session cookie, so we don't\n // need a special case for production. We can rely on suffixed,\n // and the fact that the suffixed uat is set properly means and\n // suffixed session cookie will be ignored.\n\n // The important thing to make sure we have a test that confirms\n // the user ends up as signed out in this scenario, and the suffixed\n // session cookie is ignored\n\n // In development, suffixed_uat is not set reliably, since it's done\n // by clerk.js. If the developer downgrades to a pinned version of\n // clerk.js, the suffixed uat will no longer be updated\n\n // The best we can do is look to see if the suffixed token is expired.\n // This means that, if a developer downgrades, and then immediately\n // signs out, all in the span of 1 minute, then they will inadvertently\n // remain signed in for the rest of that minute. This is a known\n // limitation of the strategy but seems highly unlikely.\n if (this.instanceType !== 'production') {\n const isSuffixedSessionExpired = this.sessionExpired(suffixedSessionData);\n if (suffixedClientUat !== '0' && clientUat === '0' && isSuffixedSessionExpired) {\n return false;\n }\n }\n\n // If a suffixed session cookie exists but the corresponding client_uat cookie is missing, fallback to using\n // unsuffixed cookies.\n // This handles the scenario where an app has been deployed using an SDK version that supports suffixed\n // cookies, but FAPI for its Clerk instance has the feature disabled (eg: if we need to temporarily disable the feature).\n if (!suffixedClientUat && suffixedSession) {\n return false;\n }\n\n return true;\n }\n\n /**\n * Determines if the request came from a different origin based on the referrer header.\n * Used for cross-origin detection in multi-domain authentication flows.\n *\n * @returns {boolean} True if referrer exists and is from a different origin, false otherwise.\n */\n public isCrossOriginReferrer(): boolean {\n if (!this.referrer || !this.clerkUrl.origin) {\n return false;\n }\n\n try {\n const referrerOrigin = new URL(this.referrer).origin;\n return referrerOrigin !== this.clerkUrl.origin;\n } catch {\n // Invalid referrer URL format\n return false;\n }\n }\n\n /**\n * Determines if the referrer URL is from a Clerk domain (accounts portal or FAPI).\n * This includes both development and production account portal domains, as well as FAPI domains\n * used for redirect-based authentication flows.\n *\n * @returns {boolean} True if the referrer is from a Clerk accounts portal or FAPI domain, false otherwise\n */\n public isKnownClerkReferrer(): boolean {\n if (!this.referrer) {\n return false;\n }\n\n try {\n const referrerOrigin = new URL(this.referrer);\n const referrerHost = referrerOrigin.hostname;\n\n // Check if referrer is the FAPI domain itself (redirect-based auth flows)\n if (this.frontendApi) {\n const fapiHost = this.frontendApi.startsWith('http') ? new URL(this.frontendApi).hostname : this.frontendApi;\n if (referrerHost === fapiHost) {\n return true;\n }\n }\n\n // Check for development account portal patterns\n if (isLegacyDevAccountPortalOrigin(referrerHost) || isCurrentDevAccountPortalOrigin(referrerHost)) {\n return true;\n }\n\n // Check for production account portal by comparing with expected accounts URL\n const expectedAccountsUrl = buildAccountsBaseUrl(this.frontendApi);\n if (expectedAccountsUrl) {\n const expectedAccountsOrigin = new URL(expectedAccountsUrl).origin;\n if (referrerOrigin.origin === expectedAccountsOrigin) {\n return true;\n }\n }\n\n // Check for generic production accounts patterns (accounts.*)\n if (referrerHost.startsWith('accounts.')) {\n return true;\n }\n\n return false;\n } catch {\n // Invalid URL format\n return false;\n }\n }\n\n private initPublishableKeyValues(options: AuthenticateRequestOptions) {\n assertValidPublishableKey(options.publishableKey);\n this.publishableKey = options.publishableKey;\n\n const originalPk = parsePublishableKey(this.publishableKey, {\n fatal: true,\n domain: options.domain,\n isSatellite: options.isSatellite,\n });\n this.originalFrontendApi = originalPk.frontendApi;\n\n const pk = parsePublishableKey(this.publishableKey, {\n fatal: true,\n proxyUrl: options.proxyUrl,\n domain: options.domain,\n isSatellite: options.isSatellite,\n });\n this.instanceType = pk.instanceType;\n this.frontendApi = pk.frontendApi;\n }\n\n private initHeaderValues() {\n this.tokenInHeader = this.parseAuthorizationHeader(this.getHeader(constants.Headers.Authorization));\n this.origin = this.getHeader(constants.Headers.Origin);\n this.host = this.getHeader(constants.Headers.Host);\n this.forwardedHost = this.getHeader(constants.Headers.ForwardedHost);\n this.forwardedProto =\n this.getHeader(constants.Headers.CloudFrontForwardedProto) || this.getHeader(constants.Headers.ForwardedProto);\n this.referrer = this.getHeader(constants.Headers.Referrer);\n this.userAgent = this.getHeader(constants.Headers.UserAgent);\n this.secFetchDest = this.getHeader(constants.Headers.SecFetchDest);\n this.accept = this.getHeader(constants.Headers.Accept);\n }\n\n private initCookieValues() {\n // suffixedCookies needs to be set first because it's used in getMultipleAppsCookie\n this.sessionTokenInCookie = this.getSuffixedOrUnSuffixedCookie(constants.Cookies.Session);\n this.refreshTokenInCookie = this.getSuffixedCookie(constants.Cookies.Refresh);\n this.clientUat = Number.parseInt(this.getSuffixedOrUnSuffixedCookie(constants.Cookies.ClientUat) || '') || 0;\n }\n\n private initHandshakeValues() {\n this.devBrowserToken =\n this.getQueryParam(constants.QueryParameters.DevBrowser) ||\n this.getSuffixedOrUnSuffixedCookie(constants.Cookies.DevBrowser);\n // Using getCookie since we don't suffix the handshake token cookie\n this.handshakeToken =\n this.getQueryParam(constants.QueryParameters.Handshake) || this.getCookie(constants.Cookies.Handshake);\n this.handshakeRedirectLoopCounter = Number(this.getCookie(constants.Cookies.RedirectCount)) || 0;\n this.handshakeNonce =\n this.getQueryParam(constants.QueryParameters.HandshakeNonce) || this.getCookie(constants.Cookies.HandshakeNonce);\n }\n\n private getQueryParam(name: string) {\n return this.clerkRequest.clerkUrl.searchParams.get(name);\n }\n\n private getHeader(name: string) {\n return this.clerkRequest.headers.get(name) || undefined;\n }\n\n private getCookie(name: string) {\n return this.clerkRequest.cookies.get(name) || undefined;\n }\n\n private getSuffixedCookie(name: string) {\n return this.getCookie(getSuffixedCookieName(name, this.cookieSuffix)) || undefined;\n }\n\n private getSuffixedOrUnSuffixedCookie(cookieName: string) {\n if (this.usesSuffixedCookies()) {\n return this.getSuffixedCookie(cookieName);\n }\n return this.getCookie(cookieName);\n }\n\n private parseAuthorizationHeader(authorizationHeader: string | undefined | null): string | undefined {\n if (!authorizationHeader) {\n return undefined;\n }\n\n const [scheme, token] = authorizationHeader.split(' ', 2);\n\n if (!token) {\n // No scheme specified, treat the entire value as the token\n return scheme;\n }\n\n if (scheme === 'Bearer') {\n return token;\n }\n\n // Skip all other schemes\n return undefined;\n }\n\n private tokenHasIssuer(token: string): boolean {\n const { data, errors } = decodeJwt(token);\n if (errors) {\n return false;\n }\n return !!data.payload.iss;\n }\n\n private tokenBelongsToInstance(token: string): boolean {\n if (!token) {\n return false;\n }\n\n const { data, errors } = decodeJwt(token);\n if (errors) {\n return false;\n }\n const tokenIssuer = data.payload.iss.replace(/https?:\\/\\//gi, '');\n // Use original frontend API for token validation since tokens are issued by the actual Clerk API, not proxy\n return this.originalFrontendApi === tokenIssuer;\n }\n\n private sessionExpired(jwt: Jwt | undefined): boolean {\n return !!jwt && jwt?.payload.exp <= (Date.now() / 1000) >> 0;\n }\n}\n\nexport type { AuthenticateContext };\n\nexport const createAuthenticateContext = async (\n clerkRequest: ClerkRequest,\n options: AuthenticateRequestOptions,\n): Promise => {\n const cookieSuffix = options.publishableKey\n ? await getCookieSuffix(options.publishableKey, runtime.crypto.subtle)\n : '';\n return new AuthenticateContext(cookieSuffix, clerkRequest, options);\n};\n","export const TokenType = {\n SessionToken: 'session_token',\n ApiKey: 'api_key',\n M2MToken: 'm2m_token',\n OAuthToken: 'oauth_token',\n} as const;\n\n/**\n * @inline\n */\nexport type TokenType = (typeof TokenType)[keyof typeof TokenType];\n\n/**\n * @inline\n */\nexport type SessionTokenType = typeof TokenType.SessionToken;\n/**\n * @inline\n */\nexport type MachineTokenType = Exclude;\n","import { createCheckAuthorization } from '@clerk/shared/authorization';\nimport { __experimental_JWTPayloadToAuthObjectProperties } from '@clerk/shared/jwtPayloadParser';\nimport type {\n CheckAuthorizationFromSessionClaims,\n Jwt,\n JwtPayload,\n PendingSessionOptions,\n ServerGetToken,\n ServerGetTokenOptions,\n SessionStatusClaim,\n SharedSignedInAuthObjectProperties,\n} from '@clerk/types';\n\nimport type { APIKey, CreateBackendApiOptions, IdPOAuthAccessToken, M2MToken } from '../api';\nimport { createBackendApiClient } from '../api';\nimport { isTokenTypeAccepted } from '../internal';\nimport type { AuthenticateContext } from './authenticateContext';\nimport { isMachineTokenType } from './machine';\nimport type { MachineTokenType, SessionTokenType } from './tokenTypes';\nimport { TokenType } from './tokenTypes';\nimport type { AuthenticateRequestOptions, MachineAuthType } from './types';\n\n/**\n * @inline\n */\ntype AuthObjectDebugData = Record;\n/**\n * @inline\n */\ntype AuthObjectDebug = () => AuthObjectDebugData;\n\ntype Claims = Record;\n\n/**\n * @internal\n */\nexport type SignedInAuthObjectOptions = CreateBackendApiOptions & {\n token: string;\n};\n\n/**\n * @internal\n */\nexport type SignedInAuthObject = SharedSignedInAuthObjectProperties & {\n /**\n * The allowed token type.\n */\n tokenType: SessionTokenType;\n /**\n * A function that gets the current user's [session token](https://clerk.com/docs/backend-requests/resources/session-tokens) or a [custom JWT template](https://clerk.com/docs/backend-requests/jwt-templates).\n */\n getToken: ServerGetToken;\n /**\n * A function that checks if the user has an organization role or custom permission.\n */\n has: CheckAuthorizationFromSessionClaims;\n /**\n * Used to help debug issues when using Clerk in development.\n */\n debug: AuthObjectDebug;\n isAuthenticated: true;\n};\n\n/**\n * @internal\n */\nexport type SignedOutAuthObject = {\n sessionClaims: null;\n sessionId: null;\n sessionStatus: SessionStatusClaim | null;\n actor: null;\n tokenType: SessionTokenType;\n userId: null;\n orgId: null;\n orgRole: null;\n orgSlug: null;\n orgPermissions: null;\n factorVerificationAge: null;\n getToken: ServerGetToken;\n has: CheckAuthorizationFromSessionClaims;\n debug: AuthObjectDebug;\n isAuthenticated: false;\n};\n\n/**\n * Extended properties specific to each machine token type.\n * While all machine token types share common properties (id, name, subject, etc),\n * this type defines the additional properties that are unique to each token type.\n *\n * @template TAuthenticated - Whether the machine object is authenticated or not\n */\ntype MachineObjectExtendedProperties = {\n api_key: TAuthenticated extends true\n ?\n | { name: string; claims: Claims | null; userId: string; orgId: null }\n | { name: string; claims: Claims | null; userId: null; orgId: string }\n : { name: null; claims: null; userId: null; orgId: null };\n m2m_token: {\n claims: TAuthenticated extends true ? Claims | null : null;\n machineId: TAuthenticated extends true ? string : null;\n };\n oauth_token: {\n userId: TAuthenticated extends true ? string : null;\n clientId: TAuthenticated extends true ? string : null;\n };\n};\n\n/**\n * @internal\n *\n * Uses `T extends any` to create a distributive conditional type.\n * This ensures that union types like `'api_key' | 'oauth_token'` are processed\n * individually, creating proper discriminated unions where each token type\n * gets its own distinct properties (e.g., oauth_token won't have claims).\n */\nexport type AuthenticatedMachineObject = T extends any\n ? {\n id: string;\n subject: string;\n scopes: string[];\n getToken: () => Promise;\n has: CheckAuthorizationFromSessionClaims;\n debug: AuthObjectDebug;\n tokenType: T;\n isAuthenticated: true;\n } & MachineObjectExtendedProperties[T]\n : never;\n\n/**\n * @internal\n *\n * Uses `T extends any` to create a distributive conditional type.\n * This ensures that union types like `'api_key' | 'oauth_token'` are processed\n * individually, creating proper discriminated unions where each token type\n * gets its own distinct properties (e.g., oauth_token won't have claims).\n */\nexport type UnauthenticatedMachineObject = T extends any\n ? {\n id: null;\n subject: null;\n scopes: null;\n getToken: () => Promise;\n has: CheckAuthorizationFromSessionClaims;\n debug: AuthObjectDebug;\n tokenType: T;\n isAuthenticated: false;\n } & MachineObjectExtendedProperties[T]\n : never;\n\nexport type InvalidTokenAuthObject = {\n isAuthenticated: false;\n tokenType: null;\n getToken: () => Promise;\n has: () => false;\n debug: AuthObjectDebug;\n};\n\n/**\n * @interface\n */\nexport type AuthObject =\n | SignedInAuthObject\n | SignedOutAuthObject\n | AuthenticatedMachineObject\n | UnauthenticatedMachineObject\n | InvalidTokenAuthObject;\n\nconst createDebug = (data: AuthObjectDebugData | undefined) => {\n return () => {\n const res = { ...data };\n res.secretKey = (res.secretKey || '').substring(0, 7);\n res.jwtKey = (res.jwtKey || '').substring(0, 7);\n return { ...res };\n };\n};\n\n/**\n * @internal\n */\nexport function signedInAuthObject(\n authenticateContext: Partial,\n sessionToken: string,\n sessionClaims: JwtPayload,\n): SignedInAuthObject {\n const { actor, sessionId, sessionStatus, userId, orgId, orgRole, orgSlug, orgPermissions, factorVerificationAge } =\n __experimental_JWTPayloadToAuthObjectProperties(sessionClaims);\n const apiClient = createBackendApiClient(authenticateContext);\n const getToken = createGetToken({\n sessionId,\n sessionToken,\n fetcher: async (sessionId, template, expiresInSeconds) =>\n (await apiClient.sessions.getToken(sessionId, template || '', expiresInSeconds)).jwt,\n });\n return {\n tokenType: TokenType.SessionToken,\n actor,\n sessionClaims,\n sessionId,\n sessionStatus,\n userId,\n orgId,\n orgRole,\n orgSlug,\n orgPermissions,\n factorVerificationAge,\n getToken,\n has: createCheckAuthorization({\n orgId,\n orgRole,\n orgPermissions,\n userId,\n factorVerificationAge,\n features: (sessionClaims.fea as string) || '',\n plans: (sessionClaims.pla as string) || '',\n }),\n debug: createDebug({ ...authenticateContext, sessionToken }),\n isAuthenticated: true,\n };\n}\n\n/**\n * @internal\n */\nexport function signedOutAuthObject(\n debugData?: AuthObjectDebugData,\n initialSessionStatus?: SessionStatusClaim,\n): SignedOutAuthObject {\n return {\n tokenType: TokenType.SessionToken,\n sessionClaims: null,\n sessionId: null,\n sessionStatus: initialSessionStatus ?? null,\n userId: null,\n actor: null,\n orgId: null,\n orgRole: null,\n orgSlug: null,\n orgPermissions: null,\n factorVerificationAge: null,\n getToken: () => Promise.resolve(null),\n has: () => false,\n debug: createDebug(debugData),\n isAuthenticated: false,\n };\n}\n\n/**\n * @internal\n */\nexport function authenticatedMachineObject(\n tokenType: T,\n token: string,\n verificationResult: MachineAuthType,\n debugData?: AuthObjectDebugData,\n): AuthenticatedMachineObject {\n const baseObject = {\n id: verificationResult.id,\n subject: verificationResult.subject,\n getToken: () => Promise.resolve(token),\n has: () => false,\n debug: createDebug(debugData),\n isAuthenticated: true,\n };\n\n // Type assertions are safe here since we know the verification result type matches the tokenType.\n // We need these assertions because TS can't infer the specific type\n // just from the tokenType discriminator.\n\n switch (tokenType) {\n case TokenType.ApiKey: {\n const result = verificationResult as APIKey;\n return {\n ...baseObject,\n tokenType,\n name: result.name,\n claims: result.claims,\n scopes: result.scopes,\n userId: result.subject.startsWith('user_') ? result.subject : null,\n orgId: result.subject.startsWith('org_') ? result.subject : null,\n } as unknown as AuthenticatedMachineObject;\n }\n case TokenType.M2MToken: {\n const result = verificationResult as M2MToken;\n return {\n ...baseObject,\n tokenType,\n claims: result.claims,\n scopes: result.scopes,\n machineId: result.subject,\n } as unknown as AuthenticatedMachineObject;\n }\n case TokenType.OAuthToken: {\n const result = verificationResult as IdPOAuthAccessToken;\n return {\n ...baseObject,\n tokenType,\n scopes: result.scopes,\n userId: result.subject,\n clientId: result.clientId,\n } as unknown as AuthenticatedMachineObject;\n }\n default:\n throw new Error(`Invalid token type: ${tokenType}`);\n }\n}\n\n/**\n * @internal\n */\nexport function unauthenticatedMachineObject(\n tokenType: T,\n debugData?: AuthObjectDebugData,\n): UnauthenticatedMachineObject {\n const baseObject = {\n id: null,\n subject: null,\n scopes: null,\n has: () => false,\n getToken: () => Promise.resolve(null),\n debug: createDebug(debugData),\n isAuthenticated: false,\n };\n\n switch (tokenType) {\n case TokenType.ApiKey: {\n return {\n ...baseObject,\n tokenType,\n name: null,\n claims: null,\n scopes: null,\n userId: null,\n orgId: null,\n } as unknown as UnauthenticatedMachineObject;\n }\n case TokenType.M2MToken: {\n return {\n ...baseObject,\n tokenType,\n claims: null,\n scopes: null,\n machineId: null,\n } as unknown as UnauthenticatedMachineObject;\n }\n case TokenType.OAuthToken: {\n return {\n ...baseObject,\n tokenType,\n scopes: null,\n userId: null,\n clientId: null,\n } as unknown as UnauthenticatedMachineObject;\n }\n default:\n throw new Error(`Invalid token type: ${tokenType}`);\n }\n}\n\n/**\n * @internal\n */\nexport function invalidTokenAuthObject(): InvalidTokenAuthObject {\n return {\n isAuthenticated: false,\n tokenType: null,\n getToken: () => Promise.resolve(null),\n has: () => false,\n debug: () => ({}),\n };\n}\n\n/**\n * Auth objects moving through the server -> client boundary need to be serializable\n * as we need to ensure that they can be transferred via the network as pure strings.\n * Some frameworks like Remix or Next (/pages dir only) handle this serialization by simply\n * ignoring any non-serializable keys, however Nextjs /app directory is stricter and\n * throws an error if a non-serializable value is found.\n *\n * @internal\n */\nexport const makeAuthObjectSerializable = >(obj: T): T => {\n // remove any non-serializable props from the returned object\n\n const { debug, getToken, has, ...rest } = obj as unknown as AuthObject;\n return rest as unknown as T;\n};\n\n/**\n * A function that fetches a session token from the Clerk API.\n *\n * @param sessionId - The ID of the session\n * @param template - The JWT template name to use for token generation\n * @param expiresInSeconds - Optional expiration time in seconds for the token\n * @returns A promise that resolves to the token string\n */\ntype TokenFetcher = (sessionId: string, template?: string, expiresInSeconds?: number) => Promise;\n\n/**\n * Factory function type that creates a getToken function for auth objects.\n *\n * @param params - Configuration object containing session information and token fetcher\n * @returns A ServerGetToken function that can be used to retrieve tokens\n */\ntype CreateGetToken = (params: { sessionId: string; sessionToken: string; fetcher: TokenFetcher }) => ServerGetToken;\n\n/**\n * Creates a token retrieval function for authenticated sessions.\n *\n * This factory function returns a getToken function that can either return the raw session token\n * or generate a JWT using a specified template with optional custom expiration.\n *\n * @param params - Configuration object\n * @param params.sessionId - The session ID for token generation\n * @param params.sessionToken - The raw session token to return when no template is specified\n * @param params.fetcher - Function to fetch tokens from the Clerk API\n *\n * @returns A function that retrieves tokens based on the provided options\n */\nconst createGetToken: CreateGetToken = params => {\n const { fetcher, sessionToken, sessionId } = params || {};\n\n return async (options: ServerGetTokenOptions = {}) => {\n if (!sessionId) {\n return null;\n }\n\n if (options.template || options.expiresInSeconds !== undefined) {\n return fetcher(sessionId, options.template, options.expiresInSeconds);\n }\n\n return sessionToken;\n };\n};\n\n/**\n * @internal\n */\nexport const getAuthObjectFromJwt = (\n jwt: Jwt,\n { treatPendingAsSignedOut = true, ...options }: PendingSessionOptions & Partial,\n) => {\n const authObject = signedInAuthObject(options, jwt.raw.text, jwt.payload);\n\n if (treatPendingAsSignedOut && authObject.sessionStatus === 'pending') {\n return signedOutAuthObject(options, authObject.sessionStatus);\n }\n\n return authObject;\n};\n\n/**\n * @internal\n * Returns an auth object matching the requested token type(s).\n *\n * If the parsed token type does not match any in acceptsToken, returns:\n * - an invalid token auth object if the token is not in the accepted array\n * - an unauthenticated machine object for machine tokens, or\n * - a signed-out session object otherwise.\n *\n * This ensures the returned object always matches the developer's intent.\n */\nexport const getAuthObjectForAcceptedToken = ({\n authObject,\n acceptsToken = TokenType.SessionToken,\n}: {\n authObject: AuthObject;\n acceptsToken: AuthenticateRequestOptions['acceptsToken'];\n}): AuthObject => {\n // 1. any token: return as-is\n if (acceptsToken === 'any') {\n return authObject;\n }\n\n // 2. array of tokens: must match one of the accepted types\n if (Array.isArray(acceptsToken)) {\n if (!isTokenTypeAccepted(authObject.tokenType, acceptsToken)) {\n return invalidTokenAuthObject();\n }\n return authObject;\n }\n\n // 3. single token: must match exactly, else return appropriate unauthenticated object\n if (!isTokenTypeAccepted(authObject.tokenType, acceptsToken)) {\n if (isMachineTokenType(acceptsToken)) {\n return unauthenticatedMachineObject(acceptsToken, authObject.debug);\n }\n return signedOutAuthObject(authObject.debug);\n }\n\n // 4. default: return as-is\n return authObject;\n};\n","const SEPARATOR = '/';\nconst MULTIPLE_SEPARATOR_REGEX = new RegExp('(? p)\n .join(SEPARATOR)\n .replace(MULTIPLE_SEPARATOR_REGEX, SEPARATOR);\n}\n","import type { RequestFunction } from '../request';\n\nexport abstract class AbstractAPI {\n constructor(protected request: RequestFunction) {}\n\n protected requireId(id: string) {\n if (!id) {\n throw new Error('A valid resource ID is required.');\n }\n }\n}\n","import { joinPaths } from '../../util/path';\nimport type { ActorToken } from '../resources/ActorToken';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/actor_tokens';\n\ntype ActorTokenActorCreateParams = {\n /**\n * The ID of the actor.\n */\n sub: string;\n /**\n * Additional properties of the actor.\n */\n additionalProperties?: { [k: string]: any };\n};\n\ntype ActorTokenCreateParams = {\n /**\n * The ID of the user being impersonated.\n */\n userId: string;\n /**\n * The actor payload. It needs to include a sub property which should contain the ID of the actor.\n *\n * @remarks\n * This whole payload will be also included in the JWT session token.\n */\n actor: ActorTokenActorCreateParams;\n /**\n * Optional parameter to specify the life duration of the actor token in seconds.\n *\n * @remarks\n * By default, the duration is 1 hour.\n */\n expiresInSeconds?: number | undefined;\n /**\n * The maximum duration that the session which will be created by the generated actor token should last.\n *\n * @remarks\n * By default, the duration of a session created via an actor token, lasts 30 minutes.\n */\n sessionMaxDurationInSeconds?: number | undefined;\n};\n\nexport class ActorTokenAPI extends AbstractAPI {\n public async create(params: ActorTokenCreateParams) {\n return this.request({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async revoke(actorTokenId: string) {\n this.requireId(actorTokenId);\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, actorTokenId, 'revoke'),\n });\n }\n}\n","import { joinPaths } from '../../util/path';\nimport type { AccountlessApplication } from '../resources/AccountlessApplication';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/accountless_applications';\n\nexport class AccountlessApplicationAPI extends AbstractAPI {\n public async createAccountlessApplication(params?: { requestHeaders?: Headers }) {\n const headerParams = params?.requestHeaders ? Object.fromEntries(params.requestHeaders.entries()) : undefined;\n return this.request({\n method: 'POST',\n path: basePath,\n headerParams,\n });\n }\n\n public async completeAccountlessApplicationOnboarding(params?: { requestHeaders?: Headers }) {\n const headerParams = params?.requestHeaders ? Object.fromEntries(params.requestHeaders.entries()) : undefined;\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, 'complete'),\n headerParams,\n });\n }\n}\n","import type { ClerkPaginationRequest } from '@clerk/types';\n\nimport { joinPaths } from '../../util/path';\nimport type { AllowlistIdentifier } from '../resources/AllowlistIdentifier';\nimport type { DeletedObject } from '../resources/DeletedObject';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/allowlist_identifiers';\n\ntype AllowlistIdentifierCreateParams = {\n identifier: string;\n notify: boolean;\n};\n\nexport class AllowlistIdentifierAPI extends AbstractAPI {\n public async getAllowlistIdentifierList(params: ClerkPaginationRequest = {}) {\n return this.request>({\n method: 'GET',\n path: basePath,\n queryParams: { ...params, paginated: true },\n });\n }\n\n public async createAllowlistIdentifier(params: AllowlistIdentifierCreateParams) {\n return this.request({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async deleteAllowlistIdentifier(allowlistIdentifierId: string) {\n this.requireId(allowlistIdentifierId);\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, allowlistIdentifierId),\n });\n }\n}\n","import { joinPaths } from '../../util/path';\nimport type { APIKey } from '../resources/APIKey';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/api_keys';\n\ntype CreateAPIKeyParams = {\n type?: 'api_key';\n /**\n * API key name\n */\n name: string;\n /**\n * user or organization ID the API key is associated with\n */\n subject: string;\n /**\n * API key description\n */\n description?: string | null;\n claims?: Record | null;\n scopes?: string[];\n createdBy?: string | null;\n secondsUntilExpiration?: number | null;\n};\n\ntype RevokeAPIKeyParams = {\n /**\n * API key ID\n */\n apiKeyId: string;\n /**\n * Reason for revocation\n */\n revocationReason?: string | null;\n};\n\nexport class APIKeysAPI extends AbstractAPI {\n async create(params: CreateAPIKeyParams) {\n return this.request({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n async revoke(params: RevokeAPIKeyParams) {\n const { apiKeyId, ...bodyParams } = params;\n\n this.requireId(apiKeyId);\n\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, apiKeyId, 'revoke'),\n bodyParams,\n });\n }\n\n async getSecret(apiKeyId: string) {\n this.requireId(apiKeyId);\n\n return this.request<{ secret: string }>({\n method: 'GET',\n path: joinPaths(basePath, apiKeyId, 'secret'),\n });\n }\n\n async verifySecret(secret: string) {\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, 'verify'),\n bodyParams: { secret },\n });\n }\n}\n","import { joinPaths } from '../../util/path';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/beta_features';\n\ntype ChangeDomainParams = {\n /**\n * The new home URL of the production instance e.g. https://www.example.com\n */\n homeUrl?: string;\n /**\n * Whether this is a domain for a secondary app, meaning that any subdomain\n * provided is significant and will be stored as part of the domain. This is\n * useful for supporting multiple apps (one primary and multiple secondaries)\n * on the same root domain (eTLD+1).\n */\n isSecondary?: boolean;\n};\n\nexport class BetaFeaturesAPI extends AbstractAPI {\n /**\n * Change the domain of a production instance.\n *\n * Changing the domain requires updating the DNS records accordingly, deploying new SSL certificates,\n * updating your Social Connection's redirect URLs and setting the new keys in your code.\n *\n * @remarks\n * WARNING: Changing your domain will invalidate all current user sessions (i.e. users will be logged out).\n * Also, while your application is being deployed, a small downtime is expected to occur.\n */\n public async changeDomain(params: ChangeDomainParams) {\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, 'change_domain'),\n bodyParams: params,\n });\n }\n}\n","import type { ClerkPaginationRequest } from '@clerk/types';\n\nimport { joinPaths } from '../../util/path';\nimport type { BlocklistIdentifier } from '../resources/BlocklistIdentifier';\nimport type { DeletedObject } from '../resources/DeletedObject';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/blocklist_identifiers';\n\ntype BlocklistIdentifierCreateParams = {\n identifier: string;\n};\n\nexport class BlocklistIdentifierAPI extends AbstractAPI {\n public async getBlocklistIdentifierList(params: ClerkPaginationRequest = {}) {\n return this.request>({\n method: 'GET',\n path: basePath,\n queryParams: params,\n });\n }\n\n public async createBlocklistIdentifier(params: BlocklistIdentifierCreateParams) {\n return this.request({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async deleteBlocklistIdentifier(blocklistIdentifierId: string) {\n this.requireId(blocklistIdentifierId);\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, blocklistIdentifierId),\n });\n }\n}\n","import type { ClerkPaginationRequest } from '@clerk/types';\n\nimport { joinPaths } from '../../util/path';\nimport type { Client } from '../resources/Client';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport type { HandshakePayload } from '../resources/HandshakePayload';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/clients';\n\ntype GetHandshakePayloadParams = {\n nonce: string;\n};\n\nexport class ClientAPI extends AbstractAPI {\n public async getClientList(params: ClerkPaginationRequest = {}) {\n return this.request>({\n method: 'GET',\n path: basePath,\n queryParams: { ...params, paginated: true },\n });\n }\n\n public async getClient(clientId: string) {\n this.requireId(clientId);\n return this.request({\n method: 'GET',\n path: joinPaths(basePath, clientId),\n });\n }\n\n public verifyClient(token: string) {\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, 'verify'),\n bodyParams: { token },\n });\n }\n\n public async getHandshakePayload(queryParams: GetHandshakePayloadParams) {\n return this.request({\n method: 'GET',\n path: joinPaths(basePath, 'handshake_payload'),\n queryParams,\n });\n }\n}\n","import { joinPaths } from '../../util/path';\nimport type { DeletedObject } from '../resources/DeletedObject';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport type { Domain } from '../resources/Domain';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/domains';\n\ntype AddDomainParams = {\n /**\n * The new domain name. For development instances, can contain the port, i.e myhostname:3000. For production instances, must be a valid FQDN, i.e mysite.com. Cannot contain protocol scheme.\n */\n name: string;\n /**\n * Marks the new domain as satellite. Only true is accepted at the moment.\n */\n is_satellite: boolean;\n /**\n * The full URL of the proxy which will forward requests to the Clerk Frontend API for this domain. Applicable only to production instances.\n */\n proxy_url?: string | null;\n};\n\ntype UpdateDomainParams = Partial> & {\n /**\n * The ID of the domain that will be updated.\n */\n domainId: string;\n /**\n * Whether this is a domain for a secondary app, meaning that any subdomain provided is significant\n * and will be stored as part of the domain. This is useful for supporting multiple apps\n * (one primary and multiple secondaries) on the same root domain (eTLD+1).\n */\n is_secondary?: boolean | null;\n};\n\nexport class DomainAPI extends AbstractAPI {\n public async list() {\n return this.request>({\n method: 'GET',\n path: basePath,\n });\n }\n\n public async add(params: AddDomainParams) {\n return this.request({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async update(params: UpdateDomainParams) {\n const { domainId, ...bodyParams } = params;\n\n this.requireId(domainId);\n\n return this.request({\n method: 'PATCH',\n path: joinPaths(basePath, domainId),\n bodyParams: bodyParams,\n });\n }\n\n /**\n * Deletes a satellite domain for the instance.\n * It is currently not possible to delete the instance's primary domain.\n */\n public async delete(satelliteDomainId: string) {\n return this.deleteDomain(satelliteDomainId);\n }\n\n /**\n * @deprecated Use `delete` instead\n */\n public async deleteDomain(satelliteDomainId: string) {\n this.requireId(satelliteDomainId);\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, satelliteDomainId),\n });\n }\n}\n","import { joinPaths } from '../../util/path';\nimport type { DeletedObject, EmailAddress } from '../resources';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/email_addresses';\n\ntype CreateEmailAddressParams = {\n userId: string;\n emailAddress: string;\n verified?: boolean;\n primary?: boolean;\n};\n\ntype UpdateEmailAddressParams = {\n verified?: boolean;\n primary?: boolean;\n};\n\nexport class EmailAddressAPI extends AbstractAPI {\n public async getEmailAddress(emailAddressId: string) {\n this.requireId(emailAddressId);\n\n return this.request({\n method: 'GET',\n path: joinPaths(basePath, emailAddressId),\n });\n }\n\n public async createEmailAddress(params: CreateEmailAddressParams) {\n return this.request({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async updateEmailAddress(emailAddressId: string, params: UpdateEmailAddressParams = {}) {\n this.requireId(emailAddressId);\n\n return this.request({\n method: 'PATCH',\n path: joinPaths(basePath, emailAddressId),\n bodyParams: params,\n });\n }\n\n public async deleteEmailAddress(emailAddressId: string) {\n this.requireId(emailAddressId);\n\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, emailAddressId),\n });\n }\n}\n","import { joinPaths } from '../../util/path';\nimport type { IdPOAuthAccessToken } from '../resources';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/oauth_applications/access_tokens';\n\nexport class IdPOAuthAccessTokenApi extends AbstractAPI {\n async verifyAccessToken(accessToken: string) {\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, 'verify'),\n bodyParams: { access_token: accessToken },\n });\n }\n}\n","import { joinPaths } from '../../util/path';\nimport type { Instance } from '../resources/Instance';\nimport type { InstanceRestrictions } from '../resources/InstanceRestrictions';\nimport type { OrganizationSettings } from '../resources/OrganizationSettings';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/instance';\n\ntype UpdateParams = {\n /**\n * Toggles test mode for this instance, allowing the use of test email addresses and phone numbers.\n *\n * @remarks Defaults to true for development instances.\n */\n testMode?: boolean | null | undefined;\n /**\n * Whether the instance should be using the HIBP service to check passwords for breaches\n */\n hibp?: boolean | null | undefined;\n /**\n * The \"enhanced_email_deliverability\" feature will send emails from \"verifications@clerk.dev\" instead of your domain.\n *\n * @remarks This can be helpful if you do not have a high domain reputation.\n */\n enhancedEmailDeliverability?: boolean | null | undefined;\n supportEmail?: string | null | undefined;\n clerkJsVersion?: string | null | undefined;\n developmentOrigin?: string | null | undefined;\n /**\n * For browser-like stacks such as browser extensions, Electron, or Capacitor.js the instance allowed origins need to be updated with the request origin value.\n *\n * @remarks For Chrome extensions popup, background, or service worker pages the origin is chrome-extension://extension_uiid. For Electron apps the default origin is http://localhost:3000. For Capacitor, the origin is capacitor://localhost.\n */\n allowedOrigins?: Array | undefined;\n /**\n * Whether the instance should use URL-based session syncing in development mode (i.e. without third-party cookies).\n */\n urlBasedSessionSyncing?: boolean | null | undefined;\n};\n\ntype UpdateRestrictionsParams = {\n allowlist?: boolean | null | undefined;\n blocklist?: boolean | null | undefined;\n blockEmailSubaddresses?: boolean | null | undefined;\n blockDisposableEmailDomains?: boolean | null | undefined;\n ignoreDotsForGmailAddresses?: boolean | null | undefined;\n};\n\ntype UpdateOrganizationSettingsParams = {\n enabled?: boolean | null | undefined;\n maxAllowedMemberships?: number | null | undefined;\n adminDeleteEnabled?: boolean | null | undefined;\n domainsEnabled?: boolean | null | undefined;\n /**\n * Specifies which [enrollment modes](https://clerk.com/docs/organizations/verified-domains#enrollment-mode) to enable for your Organization Domains.\n *\n * @remarks Supported modes are 'automatic_invitation' & 'automatic_suggestion'.\n */\n domainsEnrollmentModes?: Array | undefined;\n /**\n * Specifies what the default organization role is for an organization creator.\n */\n creatorRoleId?: string | null | undefined;\n /**\n * Specifies what the default organization role is for the organization domains.\n */\n domainsDefaultRoleId?: string | null | undefined;\n};\n\nexport class InstanceAPI extends AbstractAPI {\n public async get() {\n return this.request({\n method: 'GET',\n path: basePath,\n });\n }\n\n public async update(params: UpdateParams) {\n return this.request({\n method: 'PATCH',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async updateRestrictions(params: UpdateRestrictionsParams) {\n return this.request({\n method: 'PATCH',\n path: joinPaths(basePath, 'restrictions'),\n bodyParams: params,\n });\n }\n\n public async updateOrganizationSettings(params: UpdateOrganizationSettingsParams) {\n return this.request({\n method: 'PATCH',\n path: joinPaths(basePath, 'organization_settings'),\n bodyParams: params,\n });\n }\n}\n","import type { ClerkPaginationRequest } from '@clerk/types';\n\nimport { joinPaths } from '../../util/path';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport type { InvitationStatus } from '../resources/Enums';\nimport type { Invitation } from '../resources/Invitation';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/invitations';\n\ntype TemplateSlug = 'invitation' | 'waitlist_invitation';\n\ntype CreateParams = {\n emailAddress: string;\n expiresInDays?: number;\n ignoreExisting?: boolean;\n notify?: boolean;\n publicMetadata?: UserPublicMetadata;\n redirectUrl?: string;\n templateSlug?: TemplateSlug;\n};\n\ntype CreateBulkParams = Array;\n\ntype GetInvitationListParams = ClerkPaginationRequest<{\n /**\n * Filters invitations based on their status.\n *\n * @example\n * Get all revoked invitations\n * ```ts\n * import { createClerkClient } from '@clerk/backend';\n * const clerkClient = createClerkClient(...)\n * await clerkClient.invitations.getInvitationList({ status: 'revoked' })\n * ```\n */\n status?: InvitationStatus;\n /**\n * Filters invitations based on `email_address` or `id`.\n *\n * @example\n * Get all invitations for a specific email address\n * ```ts\n * import { createClerkClient } from '@clerk/backend';\n * const clerkClient = createClerkClient(...)\n * await clerkClient.invitations.getInvitationList({ query: 'user@example.com' })\n * ```\n */\n query?: string;\n}>;\n\nexport class InvitationAPI extends AbstractAPI {\n public async getInvitationList(params: GetInvitationListParams = {}) {\n return this.request>({\n method: 'GET',\n path: basePath,\n queryParams: { ...params, paginated: true },\n });\n }\n\n public async createInvitation(params: CreateParams) {\n return this.request({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async createInvitationBulk(params: CreateBulkParams) {\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, 'bulk'),\n bodyParams: params,\n });\n }\n\n public async revokeInvitation(invitationId: string) {\n this.requireId(invitationId);\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, invitationId, 'revoke'),\n });\n }\n}\n","import type { ClerkPaginationRequest } from '@clerk/types';\n\nimport { joinPaths } from '../../util/path';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport type { Machine } from '../resources/Machine';\nimport type { MachineScope } from '../resources/MachineScope';\nimport type { MachineSecretKey } from '../resources/MachineSecretKey';\nimport { AbstractAPI } from './AbstractApi';\nimport type { WithSign } from './util-types';\n\nconst basePath = '/machines';\n\ntype CreateMachineParams = {\n /**\n * The name of the machine.\n */\n name: string;\n /**\n * Array of machine IDs that this machine will have access to.\n */\n scopedMachines?: string[];\n /**\n * The default time-to-live (TTL) in seconds for tokens created by this machine.\n */\n defaultTokenTtl?: number;\n};\n\ntype UpdateMachineParams = {\n /**\n * The ID of the machine to update.\n */\n machineId: string;\n /**\n * The name of the machine.\n */\n name?: string;\n /**\n * The default time-to-live (TTL) in seconds for tokens created by this machine.\n */\n defaultTokenTtl?: number;\n};\n\ntype GetMachineListParams = ClerkPaginationRequest<{\n /**\n * Sorts machines by name or created_at.\n * By prepending one of those values with + or -, we can choose to sort in ascending (ASC) or descending (DESC) order.\n */\n orderBy?: WithSign<'name' | 'created_at'>;\n /**\n * Returns machines that have a ID or name that matches the given query.\n */\n query?: string;\n}>;\n\ntype RotateMachineSecretKeyParams = {\n /**\n * The ID of the machine to rotate the secret key for.\n */\n machineId: string;\n /**\n * The time in seconds that the previous secret key will remain valid after rotation.\n */\n previousTokenTtl: number;\n};\n\nexport class MachineApi extends AbstractAPI {\n async get(machineId: string) {\n this.requireId(machineId);\n return this.request({\n method: 'GET',\n path: joinPaths(basePath, machineId),\n });\n }\n\n async list(queryParams: GetMachineListParams = {}) {\n return this.request>({\n method: 'GET',\n path: basePath,\n queryParams,\n });\n }\n\n async create(bodyParams: CreateMachineParams) {\n return this.request({\n method: 'POST',\n path: basePath,\n bodyParams,\n });\n }\n\n async update(params: UpdateMachineParams) {\n const { machineId, ...bodyParams } = params;\n this.requireId(machineId);\n return this.request({\n method: 'PATCH',\n path: joinPaths(basePath, machineId),\n bodyParams,\n });\n }\n\n async delete(machineId: string) {\n this.requireId(machineId);\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, machineId),\n });\n }\n\n async getSecretKey(machineId: string) {\n this.requireId(machineId);\n return this.request({\n method: 'GET',\n path: joinPaths(basePath, machineId, 'secret_key'),\n });\n }\n\n async rotateSecretKey(params: RotateMachineSecretKeyParams) {\n const { machineId, previousTokenTtl } = params;\n this.requireId(machineId);\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, machineId, 'secret_key', 'rotate'),\n bodyParams: {\n previousTokenTtl,\n },\n });\n }\n\n /**\n * Creates a new machine scope, allowing the specified machine to access another machine.\n *\n * @param machineId - The ID of the machine that will have access to another machine.\n * @param toMachineId - The ID of the machine that will be scoped to the current machine.\n */\n async createScope(machineId: string, toMachineId: string) {\n this.requireId(machineId);\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, machineId, 'scopes'),\n bodyParams: {\n toMachineId,\n },\n });\n }\n\n /**\n * Deletes a machine scope, removing access from one machine to another.\n *\n * @param machineId - The ID of the machine that has access to another machine.\n * @param otherMachineId - The ID of the machine that is being accessed.\n */\n async deleteScope(machineId: string, otherMachineId: string) {\n this.requireId(machineId);\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, machineId, 'scopes', otherMachineId),\n });\n }\n}\n","import { joinPaths } from '../../util/path';\nimport type { ClerkBackendApiRequestOptions } from '../request';\nimport type { M2MToken } from '../resources/M2MToken';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/m2m_tokens';\n\ntype CreateM2MTokenParams = {\n /**\n * Custom machine secret key for authentication.\n */\n machineSecretKey?: string;\n /**\n * Number of seconds until the token expires.\n *\n * @default null - Token does not expire\n */\n secondsUntilExpiration?: number | null;\n claims?: Record | null;\n};\n\ntype RevokeM2MTokenParams = {\n /**\n * Custom machine secret key for authentication.\n */\n machineSecretKey?: string;\n /**\n * Machine-to-machine token ID to revoke.\n */\n m2mTokenId: string;\n revocationReason?: string | null;\n};\n\ntype VerifyM2MTokenParams = {\n /**\n * Custom machine secret key for authentication.\n */\n machineSecretKey?: string;\n /**\n * Machine-to-machine token to verify.\n */\n token: string;\n};\n\nexport class M2MTokenApi extends AbstractAPI {\n #createRequestOptions(options: ClerkBackendApiRequestOptions, machineSecretKey?: string) {\n if (machineSecretKey) {\n return {\n ...options,\n headerParams: {\n ...options.headerParams,\n Authorization: `Bearer ${machineSecretKey}`,\n },\n };\n }\n\n return options;\n }\n\n async createToken(params?: CreateM2MTokenParams) {\n const { claims = null, machineSecretKey, secondsUntilExpiration = null } = params || {};\n\n const requestOptions = this.#createRequestOptions(\n {\n method: 'POST',\n path: basePath,\n bodyParams: {\n secondsUntilExpiration,\n claims,\n },\n },\n machineSecretKey,\n );\n\n return this.request(requestOptions);\n }\n\n async revokeToken(params: RevokeM2MTokenParams) {\n const { m2mTokenId, revocationReason = null, machineSecretKey } = params;\n\n this.requireId(m2mTokenId);\n\n const requestOptions = this.#createRequestOptions(\n {\n method: 'POST',\n path: joinPaths(basePath, m2mTokenId, 'revoke'),\n bodyParams: {\n revocationReason,\n },\n },\n machineSecretKey,\n );\n\n return this.request(requestOptions);\n }\n\n async verifyToken(params: VerifyM2MTokenParams) {\n const { token, machineSecretKey } = params;\n\n const requestOptions = this.#createRequestOptions(\n {\n method: 'POST',\n path: joinPaths(basePath, 'verify'),\n bodyParams: { token },\n },\n machineSecretKey,\n );\n\n return this.request(requestOptions);\n }\n}\n","import type { JwksJSON } from '../resources/JSON';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/jwks';\n\nexport class JwksAPI extends AbstractAPI {\n public async getJwks() {\n return this.request({\n method: 'GET',\n path: basePath,\n });\n }\n}\n","import type { ClerkPaginationRequest } from '@clerk/types';\nimport { joinPaths } from 'src/util/path';\n\nimport type { DeletedObject, JwtTemplate } from '../resources';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/jwt_templates';\n\ntype Claims = object;\n\ntype CreateJWTTemplateParams = {\n /**\n * JWT template name\n */\n name: string;\n /**\n * JWT template claims in JSON format\n */\n claims: Claims;\n /**\n * JWT token lifetime\n */\n lifetime?: number | null | undefined;\n /**\n * JWT token allowed clock skew\n */\n allowedClockSkew?: number | null | undefined;\n /**\n * Whether a custom signing key/algorithm is also provided for this template\n */\n customSigningKey?: boolean | undefined;\n /**\n * The custom signing algorithm to use when minting JWTs. Required if `custom_signing_key` is `true`.\n */\n signingAlgorithm?: string | null | undefined;\n /**\n * The custom signing private key to use when minting JWTs. Required if `custom_signing_key` is `true`.\n */\n signingKey?: string | null | undefined;\n};\n\ntype UpdateJWTTemplateParams = CreateJWTTemplateParams & {\n /**\n * JWT template ID\n */\n templateId: string;\n};\n\nexport class JwtTemplatesApi extends AbstractAPI {\n public async list(params: ClerkPaginationRequest = {}) {\n return this.request({\n method: 'GET',\n path: basePath,\n queryParams: { ...params, paginated: true },\n });\n }\n\n public async get(templateId: string) {\n this.requireId(templateId);\n\n return this.request({\n method: 'GET',\n path: joinPaths(basePath, templateId),\n });\n }\n\n public async create(params: CreateJWTTemplateParams) {\n return this.request({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async update(params: UpdateJWTTemplateParams) {\n const { templateId, ...bodyParams } = params;\n\n this.requireId(templateId);\n return this.request({\n method: 'PATCH',\n path: joinPaths(basePath, templateId),\n bodyParams,\n });\n }\n\n public async delete(templateId: string) {\n this.requireId(templateId);\n\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, templateId),\n });\n }\n}\n","import type { ClerkPaginationRequest, OrganizationEnrollmentMode } from '@clerk/types';\n\nimport { runtime } from '../../runtime';\nimport { joinPaths } from '../../util/path';\nimport type {\n Organization,\n OrganizationDomain,\n OrganizationInvitation,\n OrganizationInvitationStatus,\n OrganizationMembership,\n} from '../resources';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport type { OrganizationMembershipRole } from '../resources/Enums';\nimport { AbstractAPI } from './AbstractApi';\nimport type { WithSign } from './util-types';\n\nconst basePath = '/organizations';\n\ntype MetadataParams = {\n publicMetadata?: TPublic;\n privateMetadata?: TPrivate;\n};\n\ntype GetOrganizationListParams = ClerkPaginationRequest<{\n includeMembersCount?: boolean;\n query?: string;\n orderBy?: WithSign<'name' | 'created_at' | 'members_count'>;\n organizationId?: string[];\n}>;\n\ntype CreateParams = {\n name: string;\n slug?: string;\n /* The User id for the user creating the organization. The user will become an administrator for the organization. */\n createdBy?: string;\n maxAllowedMemberships?: number;\n} & MetadataParams;\n\ntype GetOrganizationParams = ({ organizationId: string } | { slug: string }) & {\n includeMembersCount?: boolean;\n};\n\ntype UpdateParams = {\n name?: string;\n slug?: string;\n maxAllowedMemberships?: number;\n} & MetadataParams;\n\ntype UpdateLogoParams = {\n file: Blob | File;\n uploaderUserId?: string;\n};\n\ntype UpdateMetadataParams = MetadataParams;\n\ntype GetOrganizationMembershipListParams = ClerkPaginationRequest<{\n organizationId: string;\n\n /**\n * Sorts organizations memberships by phone_number, email_address, created_at, first_name, last_name or username.\n * By prepending one of those values with + or -, we can choose to sort in ascending (ASC) or descending (DESC) order.\n */\n orderBy?: WithSign<'phone_number' | 'email_address' | 'created_at' | 'first_name' | 'last_name' | 'username'>;\n\n /**\n * Returns users with the user ids specified. For each user id, the `+` and `-` can be\n * prepended to the id, which denote whether the respective user id should be included or\n * excluded from the result set. Accepts up to 100 user ids. Any user ids not found are ignored.\n */\n userId?: string[];\n\n /* Returns users with the specified email addresses. Accepts up to 100 email addresses. Any email addresses not found are ignored. */\n emailAddress?: string[];\n\n /* Returns users with the specified phone numbers. Accepts up to 100 phone numbers. Any phone numbers not found are ignored. */\n phoneNumber?: string[];\n\n /* Returns users with the specified usernames. Accepts up to 100 usernames. Any usernames not found are ignored. */\n username?: string[];\n\n /* Returns users with the specified web3 wallet addresses. Accepts up to 100 web3 wallet addresses. Any web3 wallet addressed not found are ignored. */\n web3Wallet?: string[];\n\n /* Returns users with the specified roles. Accepts up to 100 roles. Any roles not found are ignored. */\n role?: OrganizationMembershipRole[];\n\n /**\n * Returns users that match the given query.\n * For possible matches, we check the email addresses, phone numbers, usernames, web3 wallets, user ids, first and last names.\n * The query value doesn't need to match the exact value you are looking for, it is capable of partial matches as well.\n */\n query?: string;\n\n /**\n * Returns users with emails that match the given query, via case-insensitive partial match.\n * For example, `email_address_query=ello` will match a user with the email `HELLO@example.com`.\n */\n emailAddressQuery?: string;\n\n /**\n * Returns users with phone numbers that match the given query, via case-insensitive partial match.\n * For example, `phone_number_query=555` will match a user with the phone number `+1555xxxxxxx`.\n */\n phoneNumberQuery?: string;\n\n /**\n * Returns users with usernames that match the given query, via case-insensitive partial match.\n * For example, `username_query=CoolUser` will match a user with the username `SomeCoolUser`.\n */\n usernameQuery?: string;\n\n /* Returns users with names that match the given query, via case-insensitive partial match. */\n nameQuery?: string;\n\n /**\n * Returns users whose last session activity was before the given date (with millisecond precision).\n * Example: use 1700690400000 to retrieve users whose last session activity was before 2023-11-23.\n */\n lastActiveAtBefore?: number;\n /**\n * Returns users whose last session activity was after the given date (with millisecond precision).\n * Example: use 1700690400000 to retrieve users whose last session activity was after 2023-11-23.\n */\n lastActiveAtAfter?: number;\n\n /**\n * Returns users who have been created before the given date (with millisecond precision).\n * Example: use 1730160000000 to retrieve users who have been created before 2024-10-29.\n */\n createdAtBefore?: number;\n\n /**\n * Returns users who have been created after the given date (with millisecond precision).\n * Example: use 1730160000000 to retrieve users who have been created after 2024-10-29.\n */\n createdAtAfter?: number;\n}>;\n\ntype GetInstanceOrganizationMembershipListParams = ClerkPaginationRequest<{\n /**\n * Sorts organizations memberships by phone_number, email_address, created_at, first_name, last_name or username.\n * By prepending one of those values with + or -, we can choose to sort in ascending (ASC) or descending (DESC) order.\n */\n orderBy?: WithSign<'phone_number' | 'email_address' | 'created_at' | 'first_name' | 'last_name' | 'username'>;\n}>;\n\ntype CreateOrganizationMembershipParams = {\n organizationId: string;\n userId: string;\n role: OrganizationMembershipRole;\n};\n\ntype UpdateOrganizationMembershipParams = CreateOrganizationMembershipParams;\n\ntype UpdateOrganizationMembershipMetadataParams = {\n organizationId: string;\n userId: string;\n} & MetadataParams;\n\ntype DeleteOrganizationMembershipParams = {\n organizationId: string;\n userId: string;\n};\n\ntype CreateOrganizationInvitationParams = {\n organizationId: string;\n emailAddress: string;\n role: OrganizationMembershipRole;\n expiresInDays?: number;\n inviterUserId?: string;\n privateMetadata?: OrganizationInvitationPrivateMetadata;\n publicMetadata?: OrganizationInvitationPublicMetadata;\n redirectUrl?: string;\n};\n\ntype CreateBulkOrganizationInvitationParams = Array<{\n emailAddress: string;\n role: OrganizationMembershipRole;\n expiresInDays?: number;\n inviterUserId?: string;\n privateMetadata?: OrganizationInvitationPrivateMetadata;\n publicMetadata?: OrganizationInvitationPublicMetadata;\n redirectUrl?: string;\n}>;\n\ntype GetOrganizationInvitationListParams = ClerkPaginationRequest<{\n organizationId: string;\n status?: OrganizationInvitationStatus[];\n}>;\n\ntype GetOrganizationInvitationParams = {\n organizationId: string;\n invitationId: string;\n};\n\ntype RevokeOrganizationInvitationParams = {\n organizationId: string;\n invitationId: string;\n requestingUserId?: string;\n};\n\ntype GetOrganizationDomainListParams = {\n organizationId: string;\n limit?: number;\n offset?: number;\n};\n\ntype CreateOrganizationDomainParams = {\n organizationId: string;\n name: string;\n enrollmentMode: OrganizationEnrollmentMode;\n verified?: boolean;\n};\n\ntype UpdateOrganizationDomainParams = {\n organizationId: string;\n domainId: string;\n} & Partial;\n\ntype DeleteOrganizationDomainParams = {\n organizationId: string;\n domainId: string;\n};\n\nexport class OrganizationAPI extends AbstractAPI {\n public async getOrganizationList(params?: GetOrganizationListParams) {\n return this.request>({\n method: 'GET',\n path: basePath,\n queryParams: params,\n });\n }\n\n public async createOrganization(params: CreateParams) {\n return this.request({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async getOrganization(params: GetOrganizationParams) {\n const { includeMembersCount } = params;\n const organizationIdOrSlug = 'organizationId' in params ? params.organizationId : params.slug;\n this.requireId(organizationIdOrSlug);\n\n return this.request({\n method: 'GET',\n path: joinPaths(basePath, organizationIdOrSlug),\n queryParams: {\n includeMembersCount,\n },\n });\n }\n\n public async updateOrganization(organizationId: string, params: UpdateParams) {\n this.requireId(organizationId);\n return this.request({\n method: 'PATCH',\n path: joinPaths(basePath, organizationId),\n bodyParams: params,\n });\n }\n\n public async updateOrganizationLogo(organizationId: string, params: UpdateLogoParams) {\n this.requireId(organizationId);\n\n const formData = new runtime.FormData();\n formData.append('file', params?.file);\n if (params?.uploaderUserId) {\n formData.append('uploader_user_id', params?.uploaderUserId);\n }\n\n return this.request({\n method: 'PUT',\n path: joinPaths(basePath, organizationId, 'logo'),\n formData,\n });\n }\n\n public async deleteOrganizationLogo(organizationId: string) {\n this.requireId(organizationId);\n\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, organizationId, 'logo'),\n });\n }\n\n public async updateOrganizationMetadata(organizationId: string, params: UpdateMetadataParams) {\n this.requireId(organizationId);\n\n return this.request({\n method: 'PATCH',\n path: joinPaths(basePath, organizationId, 'metadata'),\n bodyParams: params,\n });\n }\n\n public async deleteOrganization(organizationId: string) {\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, organizationId),\n });\n }\n\n public async getOrganizationMembershipList(params: GetOrganizationMembershipListParams) {\n const { organizationId, ...queryParams } = params;\n this.requireId(organizationId);\n\n return this.request>({\n method: 'GET',\n path: joinPaths(basePath, organizationId, 'memberships'),\n queryParams,\n });\n }\n\n public async getInstanceOrganizationMembershipList(params: GetInstanceOrganizationMembershipListParams) {\n return this.request>({\n method: 'GET',\n path: '/organization_memberships',\n queryParams: params,\n });\n }\n\n public async createOrganizationMembership(params: CreateOrganizationMembershipParams) {\n const { organizationId, ...bodyParams } = params;\n this.requireId(organizationId);\n\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, organizationId, 'memberships'),\n bodyParams,\n });\n }\n\n public async updateOrganizationMembership(params: UpdateOrganizationMembershipParams) {\n const { organizationId, userId, ...bodyParams } = params;\n this.requireId(organizationId);\n\n return this.request({\n method: 'PATCH',\n path: joinPaths(basePath, organizationId, 'memberships', userId),\n bodyParams,\n });\n }\n\n public async updateOrganizationMembershipMetadata(params: UpdateOrganizationMembershipMetadataParams) {\n const { organizationId, userId, ...bodyParams } = params;\n\n return this.request({\n method: 'PATCH',\n path: joinPaths(basePath, organizationId, 'memberships', userId, 'metadata'),\n bodyParams,\n });\n }\n\n public async deleteOrganizationMembership(params: DeleteOrganizationMembershipParams) {\n const { organizationId, userId } = params;\n this.requireId(organizationId);\n\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, organizationId, 'memberships', userId),\n });\n }\n\n public async getOrganizationInvitationList(params: GetOrganizationInvitationListParams) {\n const { organizationId, ...queryParams } = params;\n this.requireId(organizationId);\n\n return this.request>({\n method: 'GET',\n path: joinPaths(basePath, organizationId, 'invitations'),\n queryParams,\n });\n }\n\n public async createOrganizationInvitation(params: CreateOrganizationInvitationParams) {\n const { organizationId, ...bodyParams } = params;\n this.requireId(organizationId);\n\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, organizationId, 'invitations'),\n bodyParams,\n });\n }\n\n public async createOrganizationInvitationBulk(\n organizationId: string,\n params: CreateBulkOrganizationInvitationParams,\n ) {\n this.requireId(organizationId);\n\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, organizationId, 'invitations', 'bulk'),\n bodyParams: params,\n });\n }\n\n public async getOrganizationInvitation(params: GetOrganizationInvitationParams) {\n const { organizationId, invitationId } = params;\n this.requireId(organizationId);\n this.requireId(invitationId);\n\n return this.request({\n method: 'GET',\n path: joinPaths(basePath, organizationId, 'invitations', invitationId),\n });\n }\n\n public async revokeOrganizationInvitation(params: RevokeOrganizationInvitationParams) {\n const { organizationId, invitationId, ...bodyParams } = params;\n this.requireId(organizationId);\n\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, organizationId, 'invitations', invitationId, 'revoke'),\n bodyParams,\n });\n }\n\n public async getOrganizationDomainList(params: GetOrganizationDomainListParams) {\n const { organizationId, ...queryParams } = params;\n this.requireId(organizationId);\n\n return this.request>({\n method: 'GET',\n path: joinPaths(basePath, organizationId, 'domains'),\n queryParams,\n });\n }\n\n public async createOrganizationDomain(params: CreateOrganizationDomainParams) {\n const { organizationId, ...bodyParams } = params;\n this.requireId(organizationId);\n\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, organizationId, 'domains'),\n bodyParams: {\n ...bodyParams,\n verified: bodyParams.verified ?? true,\n },\n });\n }\n\n public async updateOrganizationDomain(params: UpdateOrganizationDomainParams) {\n const { organizationId, domainId, ...bodyParams } = params;\n this.requireId(organizationId);\n this.requireId(domainId);\n\n return this.request({\n method: 'PATCH',\n path: joinPaths(basePath, organizationId, 'domains', domainId),\n bodyParams,\n });\n }\n\n public async deleteOrganizationDomain(params: DeleteOrganizationDomainParams) {\n const { organizationId, domainId } = params;\n this.requireId(organizationId);\n this.requireId(domainId);\n\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, organizationId, 'domains', domainId),\n });\n }\n}\n","import type { ClerkPaginationRequest } from '@clerk/types';\n\nimport { joinPaths } from '../../util/path';\nimport type { DeletedObject } from '../resources';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport type { OAuthApplication } from '../resources/OAuthApplication';\nimport { AbstractAPI } from './AbstractApi';\nimport type { WithSign } from './util-types';\n\nconst basePath = '/oauth_applications';\n\ntype CreateOAuthApplicationParams = {\n /**\n * The name of the new OAuth application.\n *\n * @remarks Max length: 256\n */\n name: string;\n /**\n * An array of redirect URIs of the new OAuth application\n */\n redirectUris?: Array | null | undefined;\n /**\n * Define the allowed scopes for the new OAuth applications that dictate the user payload of the OAuth user info endpoint. Available scopes are `profile`, `email`, `public_metadata`, `private_metadata`. Provide the requested scopes as a string, separated by spaces.\n */\n scopes?: string | null | undefined;\n /**\n * If true, this client is public and you can use the Proof Key of Code Exchange (PKCE) flow.\n */\n public?: boolean | null | undefined;\n};\n\ntype UpdateOAuthApplicationParams = CreateOAuthApplicationParams & {\n /**\n * The ID of the OAuth application to update\n */\n oauthApplicationId: string;\n};\n\ntype GetOAuthApplicationListParams = ClerkPaginationRequest<{\n /**\n * Sorts OAuth applications by name or created_at.\n * By prepending one of those values with + or -, we can choose to sort in ascending (ASC) or descending (DESC) order.\n */\n orderBy?: WithSign<'name' | 'created_at'>;\n}>;\n\nexport class OAuthApplicationsApi extends AbstractAPI {\n public async list(params: GetOAuthApplicationListParams = {}) {\n return this.request>({\n method: 'GET',\n path: basePath,\n queryParams: params,\n });\n }\n\n public async get(oauthApplicationId: string) {\n this.requireId(oauthApplicationId);\n\n return this.request({\n method: 'GET',\n path: joinPaths(basePath, oauthApplicationId),\n });\n }\n\n public async create(params: CreateOAuthApplicationParams) {\n return this.request({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async update(params: UpdateOAuthApplicationParams) {\n const { oauthApplicationId, ...bodyParams } = params;\n\n this.requireId(oauthApplicationId);\n\n return this.request({\n method: 'PATCH',\n path: joinPaths(basePath, oauthApplicationId),\n bodyParams,\n });\n }\n\n public async delete(oauthApplicationId: string) {\n this.requireId(oauthApplicationId);\n\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, oauthApplicationId),\n });\n }\n\n public async rotateSecret(oauthApplicationId: string) {\n this.requireId(oauthApplicationId);\n\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, oauthApplicationId, 'rotate_secret'),\n });\n }\n}\n","import { joinPaths } from '../../util/path';\nimport type { DeletedObject, PhoneNumber } from '../resources';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/phone_numbers';\n\ntype CreatePhoneNumberParams = {\n userId: string;\n phoneNumber: string;\n verified?: boolean;\n primary?: boolean;\n reservedForSecondFactor?: boolean;\n};\n\ntype UpdatePhoneNumberParams = {\n verified?: boolean;\n primary?: boolean;\n reservedForSecondFactor?: boolean;\n};\n\nexport class PhoneNumberAPI extends AbstractAPI {\n public async getPhoneNumber(phoneNumberId: string) {\n this.requireId(phoneNumberId);\n\n return this.request({\n method: 'GET',\n path: joinPaths(basePath, phoneNumberId),\n });\n }\n\n public async createPhoneNumber(params: CreatePhoneNumberParams) {\n return this.request({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async updatePhoneNumber(phoneNumberId: string, params: UpdatePhoneNumberParams = {}) {\n this.requireId(phoneNumberId);\n\n return this.request({\n method: 'PATCH',\n path: joinPaths(basePath, phoneNumberId),\n bodyParams: params,\n });\n }\n\n public async deletePhoneNumber(phoneNumberId: string) {\n this.requireId(phoneNumberId);\n\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, phoneNumberId),\n });\n }\n}\n","import type { ProxyCheck } from '../resources';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/proxy_checks';\n\ntype VerifyParams = {\n domainId: string;\n proxyUrl: string;\n};\n\nexport class ProxyCheckAPI extends AbstractAPI {\n public async verify(params: VerifyParams) {\n return this.request({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n}\n","import { joinPaths } from '../../util/path';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport type { RedirectUrl } from '../resources/RedirectUrl';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/redirect_urls';\n\ntype CreateRedirectUrlParams = {\n url: string;\n};\n\nexport class RedirectUrlAPI extends AbstractAPI {\n public async getRedirectUrlList() {\n return this.request>({\n method: 'GET',\n path: basePath,\n queryParams: { paginated: true },\n });\n }\n\n public async getRedirectUrl(redirectUrlId: string) {\n this.requireId(redirectUrlId);\n return this.request({\n method: 'GET',\n path: joinPaths(basePath, redirectUrlId),\n });\n }\n\n public async createRedirectUrl(params: CreateRedirectUrlParams) {\n return this.request({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async deleteRedirectUrl(redirectUrlId: string) {\n this.requireId(redirectUrlId);\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, redirectUrlId),\n });\n }\n}\n","import type { ClerkPaginationRequest, SamlIdpSlug } from '@clerk/types';\n\nimport { joinPaths } from '../../util/path';\nimport type { SamlConnection } from '../resources';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport { AbstractAPI } from './AbstractApi';\nimport type { WithSign } from './util-types';\n\nconst basePath = '/saml_connections';\n\ntype SamlConnectionListParams = ClerkPaginationRequest<{\n /**\n * Returns SAML connections that have a name that matches the given query, via case-insensitive partial match.\n */\n query?: string;\n\n /**\n * Sorts SAML connections by phone_number, email_address, created_at, first_name, last_name or username.\n * By prepending one of those values with + or -, we can choose to sort in ascending (ASC) or descending (DESC) order.\n */\n orderBy?: WithSign<'phone_number' | 'email_address' | 'created_at' | 'first_name' | 'last_name' | 'username'>;\n\n /**\n * Returns SAML connections that have an associated organization ID to the given organizations.\n * For each organization id, the + and - can be prepended to the id, which denote whether the\n * respective organization should be included or excluded from the result set. Accepts up to 100 organization ids.\n */\n organizationId?: WithSign[];\n}>;\n\ntype CreateSamlConnectionParams = {\n name: string;\n provider: SamlIdpSlug;\n domain: string;\n organizationId?: string;\n idpEntityId?: string;\n idpSsoUrl?: string;\n idpCertificate?: string;\n idpMetadataUrl?: string;\n idpMetadata?: string;\n attributeMapping?: {\n emailAddress?: string;\n firstName?: string;\n lastName?: string;\n userId?: string;\n };\n};\n\ntype UpdateSamlConnectionParams = {\n name?: string;\n provider?: SamlIdpSlug;\n domain?: string;\n organizationId?: string;\n idpEntityId?: string;\n idpSsoUrl?: string;\n idpCertificate?: string;\n idpMetadataUrl?: string;\n idpMetadata?: string;\n attributeMapping?: {\n emailAddress?: string;\n firstName?: string;\n lastName?: string;\n userId?: string;\n };\n active?: boolean;\n syncUserAttributes?: boolean;\n allowSubdomains?: boolean;\n allowIdpInitiated?: boolean;\n};\n\nexport class SamlConnectionAPI extends AbstractAPI {\n public async getSamlConnectionList(params: SamlConnectionListParams = {}) {\n return this.request>({\n method: 'GET',\n path: basePath,\n queryParams: params,\n });\n }\n\n public async createSamlConnection(params: CreateSamlConnectionParams) {\n return this.request({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n options: {\n deepSnakecaseBodyParamKeys: true,\n },\n });\n }\n\n public async getSamlConnection(samlConnectionId: string) {\n this.requireId(samlConnectionId);\n return this.request({\n method: 'GET',\n path: joinPaths(basePath, samlConnectionId),\n });\n }\n\n public async updateSamlConnection(samlConnectionId: string, params: UpdateSamlConnectionParams = {}) {\n this.requireId(samlConnectionId);\n\n return this.request({\n method: 'PATCH',\n path: joinPaths(basePath, samlConnectionId),\n bodyParams: params,\n options: {\n deepSnakecaseBodyParamKeys: true,\n },\n });\n }\n public async deleteSamlConnection(samlConnectionId: string) {\n this.requireId(samlConnectionId);\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, samlConnectionId),\n });\n }\n}\n","import type { ClerkPaginationRequest, SessionStatus } from '@clerk/types';\n\nimport { joinPaths } from '../../util/path';\nimport type { Cookies } from '../resources/Cookies';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport type { Session } from '../resources/Session';\nimport type { Token } from '../resources/Token';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/sessions';\n\ntype SessionListParams = ClerkPaginationRequest<{\n clientId?: string;\n userId?: string;\n status?: SessionStatus;\n}>;\n\ntype RefreshTokenParams = {\n expired_token: string;\n refresh_token: string;\n request_origin: string;\n request_originating_ip?: string;\n request_headers?: Record;\n suffixed_cookies?: boolean;\n format?: 'token' | 'cookie';\n};\n\ntype CreateSessionParams = {\n userId: string;\n};\n\nexport class SessionAPI extends AbstractAPI {\n public async getSessionList(params: SessionListParams = {}) {\n return this.request>({\n method: 'GET',\n path: basePath,\n queryParams: { ...params, paginated: true },\n });\n }\n\n public async getSession(sessionId: string) {\n this.requireId(sessionId);\n return this.request({\n method: 'GET',\n path: joinPaths(basePath, sessionId),\n });\n }\n\n public async createSession(params: CreateSessionParams) {\n return this.request({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async revokeSession(sessionId: string) {\n this.requireId(sessionId);\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, sessionId, 'revoke'),\n });\n }\n\n public async verifySession(sessionId: string, token: string) {\n this.requireId(sessionId);\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, sessionId, 'verify'),\n bodyParams: { token },\n });\n }\n\n /**\n * Retrieves a session token or generates a JWT using a specified template.\n *\n * @param sessionId - The ID of the session for which to generate the token\n * @param template - Optional name of the JWT template configured in the Clerk Dashboard.\n * @param expiresInSeconds - Optional expiration time for the token in seconds.\n * If not provided, uses the default expiration.\n *\n * @returns A promise that resolves to the generated token\n *\n * @throws {Error} When sessionId is invalid or empty\n */\n public async getToken(sessionId: string, template?: string, expiresInSeconds?: number) {\n this.requireId(sessionId);\n\n const path = template\n ? joinPaths(basePath, sessionId, 'tokens', template)\n : joinPaths(basePath, sessionId, 'tokens');\n\n const requestOptions: any = {\n method: 'POST',\n path,\n };\n\n if (expiresInSeconds !== undefined) {\n requestOptions.bodyParams = { expires_in_seconds: expiresInSeconds };\n }\n\n return this.request(requestOptions);\n }\n\n public async refreshSession(sessionId: string, params: RefreshTokenParams & { format: 'token' }): Promise;\n public async refreshSession(sessionId: string, params: RefreshTokenParams & { format: 'cookie' }): Promise;\n public async refreshSession(sessionId: string, params: RefreshTokenParams): Promise;\n public async refreshSession(sessionId: string, params: RefreshTokenParams): Promise {\n this.requireId(sessionId);\n const { suffixed_cookies, ...restParams } = params;\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, sessionId, 'refresh'),\n bodyParams: restParams,\n queryParams: { suffixed_cookies },\n });\n }\n}\n","import { joinPaths } from '../../util/path';\nimport type { SignInToken } from '../resources/SignInTokens';\nimport { AbstractAPI } from './AbstractApi';\n\ntype CreateSignInTokensParams = {\n userId: string;\n expiresInSeconds: number;\n};\n\nconst basePath = '/sign_in_tokens';\n\nexport class SignInTokenAPI extends AbstractAPI {\n public async createSignInToken(params: CreateSignInTokensParams) {\n return this.request({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async revokeSignInToken(signInTokenId: string) {\n this.requireId(signInTokenId);\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, signInTokenId, 'revoke'),\n });\n }\n}\n","import { joinPaths } from '../../util/path';\nimport type { SignUpAttempt } from '../resources/SignUpAttempt';\nimport { AbstractAPI } from './AbstractApi';\n\ntype UpdateSignUpParams = {\n signUpAttemptId: string;\n externalId?: string | null;\n customAction?: boolean | null;\n};\n\nconst basePath = '/sign_ups';\n\nexport class SignUpAPI extends AbstractAPI {\n public async get(signUpAttemptId: string) {\n this.requireId(signUpAttemptId);\n\n return this.request({\n method: 'GET',\n path: joinPaths(basePath, signUpAttemptId),\n });\n }\n\n public async update(params: UpdateSignUpParams) {\n const { signUpAttemptId, ...bodyParams } = params;\n\n return this.request({\n method: 'PATCH',\n path: joinPaths(basePath, signUpAttemptId),\n bodyParams,\n });\n }\n}\n","import type { TestingToken } from '../resources/TestingToken';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/testing_tokens';\n\nexport class TestingTokenAPI extends AbstractAPI {\n public async createTestingToken() {\n return this.request({\n method: 'POST',\n path: basePath,\n });\n }\n}\n","import type { ClerkPaginationRequest, OAuthProvider, OrganizationInvitationStatus } from '@clerk/types';\n\nimport { runtime } from '../../runtime';\nimport { joinPaths } from '../../util/path';\nimport { deprecated } from '../../util/shared';\nimport type {\n DeletedObject,\n OauthAccessToken,\n OrganizationInvitation,\n OrganizationMembership,\n User,\n} from '../resources';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport { AbstractAPI } from './AbstractApi';\nimport type { WithSign } from './util-types';\n\nconst basePath = '/users';\n\ntype UserCountParams = {\n emailAddress?: string[];\n phoneNumber?: string[];\n username?: string[];\n web3Wallet?: string[];\n query?: string;\n userId?: string[];\n externalId?: string[];\n};\n\ntype UserListParams = ClerkPaginationRequest<\n UserCountParams & {\n orderBy?: WithSign<\n | 'created_at'\n | 'updated_at'\n | 'email_address'\n | 'web3wallet'\n | 'first_name'\n | 'last_name'\n | 'phone_number'\n | 'username'\n | 'last_active_at'\n | 'last_sign_in_at'\n >;\n last_active_at_since?: number;\n organizationId?: string[];\n }\n>;\n\ntype UserMetadataParams = {\n publicMetadata?: UserPublicMetadata;\n privateMetadata?: UserPrivateMetadata;\n unsafeMetadata?: UserUnsafeMetadata;\n};\n\ntype PasswordHasher =\n | 'argon2i'\n | 'argon2id'\n | 'awscognito'\n | 'bcrypt'\n | 'bcrypt_sha256_django'\n | 'md5'\n | 'pbkdf2_sha256'\n | 'pbkdf2_sha256_django'\n | 'pbkdf2_sha1'\n | 'phpass'\n | 'scrypt_firebase'\n | 'scrypt_werkzeug'\n | 'sha256'\n | 'md5_phpass'\n | 'ldap_ssha';\n\ntype UserPasswordHashingParams = {\n passwordDigest: string;\n passwordHasher: PasswordHasher;\n};\n\ntype CreateUserParams = {\n externalId?: string;\n emailAddress?: string[];\n phoneNumber?: string[];\n username?: string;\n password?: string;\n firstName?: string;\n lastName?: string;\n skipPasswordChecks?: boolean;\n skipPasswordRequirement?: boolean;\n skipLegalChecks?: boolean;\n legalAcceptedAt?: Date;\n totpSecret?: string;\n backupCodes?: string[];\n createdAt?: Date;\n} & UserMetadataParams &\n (UserPasswordHashingParams | object);\n\ntype UpdateUserParams = {\n /** The first name to assign to the user. */\n firstName?: string;\n\n /** The last name of the user. */\n lastName?: string;\n\n /** The username to give to the user. It must be unique across your instance. */\n username?: string;\n\n /** The plaintext password to give the user. Must be at least 8 characters long, and can not be in any list of hacked passwords. */\n password?: string;\n\n /** Set it to true if you're updating the user's password and want to skip any password policy settings check. This parameter can only be used when providing a password. */\n skipPasswordChecks?: boolean;\n\n /** Set to true to sign out the user from all their active sessions once their password is updated. This parameter can only be used when providing a password. */\n signOutOfOtherSessions?: boolean;\n\n /** The ID of the email address to set as primary. It must be verified, and present on the current user. */\n primaryEmailAddressID?: string;\n\n /** If set to true, the user will be notified that their primary email address has changed. By default, no notification is sent. */\n notifyPrimaryEmailAddressChanged?: boolean;\n\n /** The ID of the phone number to set as primary. It must be verified, and present on the current user. */\n primaryPhoneNumberID?: string;\n\n /** The ID of the web3 wallets to set as primary. It must be verified, and present on the current user. */\n primaryWeb3WalletID?: string;\n\n /** The ID of the image to set as the user's profile image */\n profileImageID?: string;\n\n /**\n * In case TOTP is configured on the instance, you can provide the secret to enable it on the specific user without the need to reset it.\n * Please note that currently the supported options are:\n * - Period: 30 seconds\n * - Code length: 6 digits\n * - Algorithm: SHA1\n */\n totpSecret?: string;\n\n /** If Backup Codes are configured on the instance, you can provide them to enable it on the specific user without the need to reset them. You must provide the backup codes in plain format or the corresponding bcrypt digest. */\n backupCodes?: string[];\n\n /** The ID of the user as used in your external systems or your previous authentication solution. Must be unique across your instance. */\n externalId?: string;\n\n /** A custom timestamp denoting when the user signed up to the application, specified in RFC3339 format (e.g. 2012-10-20T07:15:20.902Z). */\n createdAt?: Date;\n\n /** When set to true all legal checks are skipped. It is not recommended to skip legal checks unless you are migrating a user to Clerk. */\n skipLegalChecks?: boolean;\n\n /** A custom timestamp denoting when the user accepted legal requirements, specified in RFC3339 format (e.g. 2012-10-20T07:15:20.902Z). */\n legalAcceptedAt?: Date;\n\n /** If true, the user can delete themselves with the Frontend API. */\n deleteSelfEnabled?: boolean;\n\n /** If true, the user can create organizations with the Frontend API. */\n createOrganizationEnabled?: boolean;\n\n /** The maximum number of organizations the user can create. 0 means unlimited. */\n createOrganizationsLimit?: number;\n} & UserMetadataParams &\n (UserPasswordHashingParams | object);\n\ntype GetOrganizationMembershipListParams = ClerkPaginationRequest<{\n userId: string;\n}>;\n\ntype GetOrganizationInvitationListParams = ClerkPaginationRequest<{\n userId: string;\n status?: OrganizationInvitationStatus;\n}>;\n\ntype VerifyPasswordParams = {\n userId: string;\n password: string;\n};\n\ntype VerifyTOTPParams = {\n userId: string;\n code: string;\n};\n\ntype DeleteUserPasskeyParams = {\n userId: string;\n passkeyIdentificationId: string;\n};\n\ntype DeleteWeb3WalletParams = {\n userId: string;\n web3WalletIdentificationId: string;\n};\n\ntype DeleteUserExternalAccountParams = {\n userId: string;\n externalAccountId: string;\n};\n\ntype UserID = {\n userId: string;\n};\n\nexport class UserAPI extends AbstractAPI {\n public async getUserList(params: UserListParams = {}) {\n const { limit, offset, orderBy, ...userCountParams } = params;\n // TODO(dimkl): Temporary change to populate totalCount using a 2nd BAPI call to /users/count endpoint\n // until we update the /users endpoint to be paginated in a next BAPI version.\n // In some edge cases the data.length != totalCount due to a creation of a user between the 2 api responses\n const [data, totalCount] = await Promise.all([\n this.request({\n method: 'GET',\n path: basePath,\n queryParams: params,\n }),\n this.getCount(userCountParams),\n ]);\n return { data, totalCount } as PaginatedResourceResponse;\n }\n\n public async getUser(userId: string) {\n this.requireId(userId);\n return this.request({\n method: 'GET',\n path: joinPaths(basePath, userId),\n });\n }\n\n public async createUser(params: CreateUserParams) {\n return this.request({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async updateUser(userId: string, params: UpdateUserParams = {}) {\n this.requireId(userId);\n\n return this.request({\n method: 'PATCH',\n path: joinPaths(basePath, userId),\n bodyParams: params,\n });\n }\n\n public async updateUserProfileImage(userId: string, params: { file: Blob | File }) {\n this.requireId(userId);\n\n const formData = new runtime.FormData();\n formData.append('file', params?.file);\n\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, userId, 'profile_image'),\n formData,\n });\n }\n\n public async updateUserMetadata(userId: string, params: UserMetadataParams) {\n this.requireId(userId);\n\n return this.request({\n method: 'PATCH',\n path: joinPaths(basePath, userId, 'metadata'),\n bodyParams: params,\n });\n }\n\n public async deleteUser(userId: string) {\n this.requireId(userId);\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, userId),\n });\n }\n\n public async getCount(params: UserCountParams = {}) {\n return this.request({\n method: 'GET',\n path: joinPaths(basePath, 'count'),\n queryParams: params,\n });\n }\n\n /** @deprecated Use `getUserOauthAccessToken` without the `oauth_` provider prefix . */\n public async getUserOauthAccessToken(\n userId: string,\n provider: `oauth_${OAuthProvider}`,\n ): Promise>;\n public async getUserOauthAccessToken(\n userId: string,\n provider: OAuthProvider,\n ): Promise>;\n public async getUserOauthAccessToken(userId: string, provider: `oauth_${OAuthProvider}` | OAuthProvider) {\n this.requireId(userId);\n const hasPrefix = provider.startsWith('oauth_');\n const _provider = hasPrefix ? provider : `oauth_${provider}`;\n\n if (hasPrefix) {\n deprecated(\n 'getUserOauthAccessToken(userId, provider)',\n 'Remove the `oauth_` prefix from the `provider` argument.',\n );\n }\n\n return this.request>({\n method: 'GET',\n path: joinPaths(basePath, userId, 'oauth_access_tokens', _provider),\n queryParams: { paginated: true },\n });\n }\n\n public async disableUserMFA(userId: string) {\n this.requireId(userId);\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, userId, 'mfa'),\n });\n }\n\n public async getOrganizationMembershipList(params: GetOrganizationMembershipListParams) {\n const { userId, limit, offset } = params;\n this.requireId(userId);\n\n return this.request>({\n method: 'GET',\n path: joinPaths(basePath, userId, 'organization_memberships'),\n queryParams: { limit, offset },\n });\n }\n\n public async getOrganizationInvitationList(params: GetOrganizationInvitationListParams) {\n const { userId, ...queryParams } = params;\n this.requireId(userId);\n\n return this.request>({\n method: 'GET',\n path: joinPaths(basePath, userId, 'organization_invitations'),\n queryParams,\n });\n }\n\n public async verifyPassword(params: VerifyPasswordParams) {\n const { userId, password } = params;\n this.requireId(userId);\n\n return this.request<{ verified: true }>({\n method: 'POST',\n path: joinPaths(basePath, userId, 'verify_password'),\n bodyParams: { password },\n });\n }\n\n public async verifyTOTP(params: VerifyTOTPParams) {\n const { userId, code } = params;\n this.requireId(userId);\n\n return this.request<{ verified: true; code_type: 'totp' }>({\n method: 'POST',\n path: joinPaths(basePath, userId, 'verify_totp'),\n bodyParams: { code },\n });\n }\n\n public async banUser(userId: string) {\n this.requireId(userId);\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, userId, 'ban'),\n });\n }\n\n public async unbanUser(userId: string) {\n this.requireId(userId);\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, userId, 'unban'),\n });\n }\n\n public async lockUser(userId: string) {\n this.requireId(userId);\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, userId, 'lock'),\n });\n }\n\n public async unlockUser(userId: string) {\n this.requireId(userId);\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, userId, 'unlock'),\n });\n }\n\n public async deleteUserProfileImage(userId: string) {\n this.requireId(userId);\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, userId, 'profile_image'),\n });\n }\n\n public async deleteUserPasskey(params: DeleteUserPasskeyParams) {\n this.requireId(params.userId);\n this.requireId(params.passkeyIdentificationId);\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, params.userId, 'passkeys', params.passkeyIdentificationId),\n });\n }\n\n public async deleteUserWeb3Wallet(params: DeleteWeb3WalletParams) {\n this.requireId(params.userId);\n this.requireId(params.web3WalletIdentificationId);\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, params.userId, 'web3_wallets', params.web3WalletIdentificationId),\n });\n }\n\n public async deleteUserExternalAccount(params: DeleteUserExternalAccountParams) {\n this.requireId(params.userId);\n this.requireId(params.externalAccountId);\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, params.userId, 'external_accounts', params.externalAccountId),\n });\n }\n\n public async deleteUserBackupCodes(userId: string) {\n this.requireId(userId);\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, userId, 'backup_code'),\n });\n }\n\n public async deleteUserTOTP(userId: string) {\n this.requireId(userId);\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, userId, 'totp'),\n });\n }\n}\n","import type { ClerkPaginationRequest } from '@clerk/types';\nimport { joinPaths } from 'src/util/path';\n\nimport type { DeletedObject } from '../resources/DeletedObject';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport type { WaitlistEntryStatus } from '../resources/Enums';\nimport type { WaitlistEntry } from '../resources/WaitlistEntry';\nimport { AbstractAPI } from './AbstractApi';\nimport type { WithSign } from './util-types';\n\nconst basePath = '/waitlist_entries';\n\ntype WaitlistEntryListParams = ClerkPaginationRequest<{\n /**\n * Filter waitlist entries by `email_address` or `id`\n */\n query?: string;\n status?: WaitlistEntryStatus;\n orderBy?: WithSign<'created_at' | 'invited_at' | 'email_address'>;\n}>;\n\ntype WaitlistEntryCreateParams = {\n emailAddress: string;\n notify?: boolean;\n};\n\ntype WaitlistEntryInviteParams = {\n /**\n * When true, do not error if an invitation already exists. Default: false.\n */\n ignoreExisting?: boolean;\n};\n\nexport class WaitlistEntryAPI extends AbstractAPI {\n /**\n * List waitlist entries.\n * @param params Optional parameters (e.g., `query`, `status`, `orderBy`).\n */\n public async list(params: WaitlistEntryListParams = {}) {\n return this.request>({\n method: 'GET',\n path: basePath,\n queryParams: params,\n });\n }\n\n /**\n * Create a waitlist entry.\n * @param params The parameters for creating a waitlist entry.\n */\n public async create(params: WaitlistEntryCreateParams) {\n return this.request({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n /**\n * Invite a waitlist entry.\n * @param id The waitlist entry ID.\n * @param params Optional parameters (e.g., `ignoreExisting`).\n */\n public async invite(id: string, params: WaitlistEntryInviteParams = {}) {\n this.requireId(id);\n\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, id, 'invite'),\n bodyParams: params,\n });\n }\n\n /**\n * Reject a waitlist entry.\n * @param id The waitlist entry ID.\n */\n public async reject(id: string) {\n this.requireId(id);\n\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, id, 'reject'),\n });\n }\n\n /**\n * Delete a waitlist entry.\n * @param id The waitlist entry ID.\n */\n public async delete(id: string) {\n this.requireId(id);\n\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, id),\n });\n }\n}\n","import { joinPaths } from '../../util/path';\nimport type { WebhooksSvixJSON } from '../resources/JSON';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/webhooks';\n\nexport class WebhookAPI extends AbstractAPI {\n public async createSvixApp() {\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, 'svix'),\n });\n }\n\n public async generateSvixAuthURL() {\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, 'svix_url'),\n });\n }\n\n public async deleteSvixApp() {\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, 'svix'),\n });\n }\n}\n","import type { ClerkPaginationRequest } from '@clerk/types';\n\nimport { joinPaths } from '../../util/path';\nimport type { BillingPlan } from '../resources/CommercePlan';\nimport type { BillingSubscription } from '../resources/CommerceSubscription';\nimport type { BillingSubscriptionItem } from '../resources/CommerceSubscriptionItem';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/commerce';\nconst organizationBasePath = '/organizations';\nconst userBasePath = '/users';\n\ntype GetOrganizationListParams = ClerkPaginationRequest<{\n payerType: 'org' | 'user';\n}>;\n\ntype CancelSubscriptionItemParams = {\n /**\n * If true, the subscription item will be canceled immediately. If false or undefined, the subscription item will be canceled at the end of the current billing period.\n * @default undefined\n */\n endNow?: boolean;\n};\n\ntype ExtendSubscriptionItemFreeTrialParams = {\n /**\n * RFC3339 timestamp to extend the free trial to.\n * Must be in the future and not more than 365 days from the current trial end.\n */\n extendTo: Date;\n};\n\nexport class BillingAPI extends AbstractAPI {\n /**\n * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes.\n */\n public async getPlanList(params?: GetOrganizationListParams) {\n return this.request>({\n method: 'GET',\n path: joinPaths(basePath, 'plans'),\n queryParams: params,\n });\n }\n\n /**\n * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes.\n */\n public async cancelSubscriptionItem(subscriptionItemId: string, params?: CancelSubscriptionItemParams) {\n this.requireId(subscriptionItemId);\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, 'subscription_items', subscriptionItemId),\n queryParams: params,\n });\n }\n\n /**\n * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes.\n */\n public async extendSubscriptionItemFreeTrial(\n subscriptionItemId: string,\n params: ExtendSubscriptionItemFreeTrialParams,\n ) {\n this.requireId(subscriptionItemId);\n return this.request({\n method: 'POST',\n path: joinPaths('/billing', 'subscription_items', subscriptionItemId, 'extend_free_trial'),\n bodyParams: params,\n });\n }\n\n /**\n * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes.\n */\n public async getOrganizationBillingSubscription(organizationId: string) {\n this.requireId(organizationId);\n return this.request({\n method: 'GET',\n path: joinPaths(organizationBasePath, organizationId, 'billing', 'subscription'),\n });\n }\n\n /**\n * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes.\n */\n public async getUserBillingSubscription(userId: string) {\n this.requireId(userId);\n return this.request({\n method: 'GET',\n path: joinPaths(userBasePath, userId, 'billing', 'subscription'),\n });\n }\n}\n","import { ClerkAPIResponseError, parseError } from '@clerk/shared/error';\nimport type { ClerkAPIError, ClerkAPIErrorJSON } from '@clerk/types';\nimport snakecaseKeys from 'snakecase-keys';\n\nimport { API_URL, API_VERSION, constants, SUPPORTED_BAPI_VERSION, USER_AGENT } from '../constants';\nimport { runtime } from '../runtime';\nimport { assertValidSecretKey } from '../util/optionsAssertions';\nimport { joinPaths } from '../util/path';\nimport { deserialize } from './resources/Deserializer';\n\ntype ClerkBackendApiRequestOptionsUrlOrPath =\n | {\n url: string;\n path?: string;\n }\n | {\n url?: string;\n path: string;\n };\n\ntype ClerkBackendApiRequestOptionsBodyParams =\n | {\n bodyParams: Record | Array>;\n options?: {\n /**\n * If true, snakecases the keys of the bodyParams object recursively.\n * @default false\n */\n deepSnakecaseBodyParamKeys?: boolean;\n };\n }\n | {\n bodyParams?: never;\n options?: {\n deepSnakecaseBodyParamKeys?: never;\n };\n };\n\nexport type ClerkBackendApiRequestOptions = {\n method: 'GET' | 'POST' | 'PATCH' | 'DELETE' | 'PUT';\n queryParams?: Record;\n headerParams?: Record;\n formData?: FormData;\n} & ClerkBackendApiRequestOptionsUrlOrPath &\n ClerkBackendApiRequestOptionsBodyParams;\n\nexport type ClerkBackendApiResponse =\n | {\n data: T;\n errors: null;\n totalCount?: number;\n }\n | {\n data: null;\n errors: ClerkAPIError[];\n totalCount?: never;\n clerkTraceId?: string;\n status?: number;\n statusText?: string;\n retryAfter?: number;\n };\n\nexport type RequestFunction = ReturnType;\n\ntype BuildRequestOptions = {\n /* Secret Key */\n secretKey?: string;\n /* Backend API URL */\n apiUrl?: string;\n /* Backend API version */\n apiVersion?: string;\n /* Library/SDK name */\n userAgent?: string;\n /**\n * Allow requests without specifying a secret key. In most cases this should be set to `false`.\n * @default true\n */\n requireSecretKey?: boolean;\n /**\n * If true, omits the API version from the request URL path.\n * This is required for bapi-proxy endpoints, which do not use versioning in the URL.\n *\n * Note: API versioning for these endpoints is instead handled via the `Clerk-API-Version` HTTP header.\n *\n * @default false\n */\n skipApiVersionInUrl?: boolean;\n /* Machine secret key */\n machineSecretKey?: string;\n /**\n * If true, uses machineSecretKey for authorization instead of secretKey.\n *\n * Note: This is only used for machine-to-machine tokens.\n *\n * @default false\n */\n useMachineSecretKey?: boolean;\n};\n\nexport function buildRequest(options: BuildRequestOptions) {\n const requestFn = async (requestOptions: ClerkBackendApiRequestOptions): Promise> => {\n const {\n secretKey,\n machineSecretKey,\n useMachineSecretKey = false,\n requireSecretKey = true,\n apiUrl = API_URL,\n apiVersion = API_VERSION,\n userAgent = USER_AGENT,\n skipApiVersionInUrl = false,\n } = options;\n const { path, method, queryParams, headerParams, bodyParams, formData, options: opts } = requestOptions;\n const { deepSnakecaseBodyParamKeys = false } = opts || {};\n\n if (requireSecretKey) {\n assertValidSecretKey(secretKey);\n }\n\n const url = skipApiVersionInUrl ? joinPaths(apiUrl, path) : joinPaths(apiUrl, apiVersion, path);\n\n // Build final URL with search parameters\n const finalUrl = new URL(url);\n\n if (queryParams) {\n // Snakecase query parameters\n const snakecasedQueryParams = snakecaseKeys({ ...queryParams });\n\n // Support array values for queryParams such as { foo: [42, 43] }\n for (const [key, val] of Object.entries(snakecasedQueryParams)) {\n if (val) {\n [val].flat().forEach(v => finalUrl.searchParams.append(key, v as string));\n }\n }\n }\n\n // Build headers\n const headers = new Headers({\n 'Clerk-API-Version': SUPPORTED_BAPI_VERSION,\n [constants.Headers.UserAgent]: userAgent,\n ...headerParams,\n });\n\n // If Authorization header already exists, preserve it.\n // Otherwise, use machine secret key if enabled, or fall back to regular secret key\n const authorizationHeader = constants.Headers.Authorization;\n if (!headers.has(authorizationHeader)) {\n if (useMachineSecretKey && machineSecretKey) {\n headers.set(authorizationHeader, `Bearer ${machineSecretKey}`);\n } else if (secretKey) {\n headers.set(authorizationHeader, `Bearer ${secretKey}`);\n }\n }\n\n let res: Response | undefined;\n try {\n if (formData) {\n res = await runtime.fetch(finalUrl.href, {\n method,\n headers,\n body: formData,\n });\n } else {\n // Enforce application/json for all non form-data requests\n headers.set('Content-Type', 'application/json');\n\n const buildBody = () => {\n const hasBody = method !== 'GET' && bodyParams && Object.keys(bodyParams).length > 0;\n if (!hasBody) {\n return null;\n }\n\n const formatKeys = (object: Parameters[0]) =>\n snakecaseKeys(object, { deep: deepSnakecaseBodyParamKeys });\n\n return {\n body: JSON.stringify(Array.isArray(bodyParams) ? bodyParams.map(formatKeys) : formatKeys(bodyParams)),\n };\n };\n\n res = await runtime.fetch(finalUrl.href, {\n method,\n headers,\n ...buildBody(),\n });\n }\n\n // TODO: Parse JSON or Text response based on a response header\n const isJSONResponse =\n res?.headers && res.headers?.get(constants.Headers.ContentType) === constants.ContentTypes.Json;\n const responseBody = await (isJSONResponse ? res.json() : res.text());\n\n if (!res.ok) {\n return {\n data: null,\n errors: parseErrors(responseBody),\n status: res?.status,\n statusText: res?.statusText,\n clerkTraceId: getTraceId(responseBody, res?.headers),\n retryAfter: getRetryAfter(res?.headers),\n };\n }\n\n return {\n ...deserialize(responseBody),\n errors: null,\n };\n } catch (err) {\n if (err instanceof Error) {\n return {\n data: null,\n errors: [\n {\n code: 'unexpected_error',\n message: err.message || 'Unexpected error',\n },\n ],\n clerkTraceId: getTraceId(err, res?.headers),\n };\n }\n\n return {\n data: null,\n errors: parseErrors(err),\n status: res?.status,\n statusText: res?.statusText,\n clerkTraceId: getTraceId(err, res?.headers),\n retryAfter: getRetryAfter(res?.headers),\n };\n }\n };\n\n return withLegacyRequestReturn(requestFn);\n}\n\n// Returns either clerk_trace_id if present in response json, otherwise defaults to CF-Ray header\n// If the request failed before receiving a response, returns undefined\nfunction getTraceId(data: unknown, headers?: Headers): string {\n if (data && typeof data === 'object' && 'clerk_trace_id' in data && typeof data.clerk_trace_id === 'string') {\n return data.clerk_trace_id;\n }\n\n const cfRay = headers?.get('cf-ray');\n return cfRay || '';\n}\n\nfunction getRetryAfter(headers?: Headers): number | undefined {\n const retryAfter = headers?.get('Retry-After');\n if (!retryAfter) {\n return;\n }\n\n const value = parseInt(retryAfter, 10);\n if (isNaN(value)) {\n return;\n }\n\n return value;\n}\n\nfunction parseErrors(data: unknown): ClerkAPIError[] {\n if (!!data && typeof data === 'object' && 'errors' in data) {\n const errors = data.errors as ClerkAPIErrorJSON[];\n return errors.length > 0 ? errors.map(parseError) : [];\n }\n return [];\n}\n\ntype LegacyRequestFunction = (requestOptions: ClerkBackendApiRequestOptions) => Promise;\n\n// TODO(dimkl): Will be probably be dropped in next major version\nfunction withLegacyRequestReturn(cb: any): LegacyRequestFunction {\n return async (...args) => {\n const { data, errors, totalCount, status, statusText, clerkTraceId, retryAfter } = await cb(...args);\n if (errors) {\n // instead of passing `data: errors`, we have set the `error.errors` because\n // the errors returned from callback is already parsed and passing them as `data`\n // will not be able to assign them to the instance\n const error = new ClerkAPIResponseError(statusText || '', {\n data: [],\n status,\n clerkTraceId,\n retryAfter,\n });\n error.errors = errors;\n throw error;\n }\n\n if (typeof totalCount !== 'undefined') {\n return { data, totalCount };\n }\n\n return data;\n };\n}\n","const isObject = value => typeof value === 'object' && value !== null;\n\n// Customized for this use-case\nconst isObjectCustom = value =>\n\tisObject(value)\n\t&& !(value instanceof RegExp)\n\t&& !(value instanceof Error)\n\t&& !(value instanceof Date)\n\t&& !(globalThis.Blob && value instanceof globalThis.Blob);\n\nexport const mapObjectSkip = Symbol('mapObjectSkip');\n\nconst _mapObject = (object, mapper, options, isSeen = new WeakMap()) => {\n\toptions = {\n\t\tdeep: false,\n\t\ttarget: {},\n\t\t...options,\n\t};\n\n\tif (isSeen.has(object)) {\n\t\treturn isSeen.get(object);\n\t}\n\n\tisSeen.set(object, options.target);\n\n\tconst {target} = options;\n\tdelete options.target;\n\n\tconst mapArray = array => array.map(element => isObjectCustom(element) ? _mapObject(element, mapper, options, isSeen) : element);\n\tif (Array.isArray(object)) {\n\t\treturn mapArray(object);\n\t}\n\n\tfor (const [key, value] of Object.entries(object)) {\n\t\tconst mapResult = mapper(key, value, object);\n\n\t\tif (mapResult === mapObjectSkip) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tlet [newKey, newValue, {shouldRecurse = true} = {}] = mapResult;\n\n\t\t// Drop `__proto__` keys.\n\t\tif (newKey === '__proto__') {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (options.deep && shouldRecurse && isObjectCustom(newValue)) {\n\t\t\tnewValue = Array.isArray(newValue)\n\t\t\t\t? mapArray(newValue)\n\t\t\t\t: _mapObject(newValue, mapper, options, isSeen);\n\t\t}\n\n\t\ttarget[newKey] = newValue;\n\t}\n\n\treturn target;\n};\n\nexport default function mapObject(object, mapper, options) {\n\tif (!isObject(object)) {\n\t\tthrow new TypeError(`Expected an object, got \\`${object}\\` (${typeof object})`);\n\t}\n\n\tif (Array.isArray(object)) {\n\t\tthrow new TypeError('Expected an object, got an array');\n\t}\n\n\treturn _mapObject(object, mapper, options);\n}\n","// Regexps involved with splitting words in various case formats.\nconst SPLIT_LOWER_UPPER_RE = /([\\p{Ll}\\d])(\\p{Lu})/gu;\nconst SPLIT_UPPER_UPPER_RE = /(\\p{Lu})([\\p{Lu}][\\p{Ll}])/gu;\n\n// Used to iterate over the initial split result and separate numbers.\nconst SPLIT_SEPARATE_NUMBER_RE = /(\\d)\\p{Ll}|(\\p{L})\\d/u;\n\n// Regexp involved with stripping non-word characters from the result.\nconst DEFAULT_STRIP_REGEXP = /[^\\p{L}\\d]+/giu;\n\n// The replacement value for splits.\nconst SPLIT_REPLACE_VALUE = \"$1\\0$2\";\n\n// The default characters to keep after transforming case.\nconst DEFAULT_PREFIX_SUFFIX_CHARACTERS = \"\";\n\n/**\n * Supported locale values. Use `false` to ignore locale.\n * Defaults to `undefined`, which uses the host environment.\n */\nexport type Locale = string[] | string | false | undefined;\n\n/**\n * Options used for converting strings to pascal/camel case.\n */\nexport interface PascalCaseOptions extends Options {\n mergeAmbiguousCharacters?: boolean;\n}\n\n/**\n * Options used for converting strings to any case.\n */\nexport interface Options {\n locale?: Locale;\n split?: (value: string) => string[];\n /** @deprecated Pass `split: splitSeparateNumbers` instead. */\n separateNumbers?: boolean;\n delimiter?: string;\n prefixCharacters?: string;\n suffixCharacters?: string;\n}\n\n/**\n * Split any cased input strings into an array of words.\n */\nexport function split(value: string) {\n let result = value.trim();\n\n result = result\n .replace(SPLIT_LOWER_UPPER_RE, SPLIT_REPLACE_VALUE)\n .replace(SPLIT_UPPER_UPPER_RE, SPLIT_REPLACE_VALUE);\n\n result = result.replace(DEFAULT_STRIP_REGEXP, \"\\0\");\n\n let start = 0;\n let end = result.length;\n\n // Trim the delimiter from around the output string.\n while (result.charAt(start) === \"\\0\") start++;\n if (start === end) return [];\n while (result.charAt(end - 1) === \"\\0\") end--;\n\n return result.slice(start, end).split(/\\0/g);\n}\n\n/**\n * Split the input string into an array of words, separating numbers.\n */\nexport function splitSeparateNumbers(value: string) {\n const words = split(value);\n for (let i = 0; i < words.length; i++) {\n const word = words[i];\n const match = SPLIT_SEPARATE_NUMBER_RE.exec(word);\n if (match) {\n const offset = match.index + (match[1] ?? match[2]).length;\n words.splice(i, 1, word.slice(0, offset), word.slice(offset));\n }\n }\n return words;\n}\n\n/**\n * Convert a string to space separated lower case (`foo bar`).\n */\nexport function noCase(input: string, options?: Options) {\n const [prefix, words, suffix] = splitPrefixSuffix(input, options);\n return (\n prefix +\n words.map(lowerFactory(options?.locale)).join(options?.delimiter ?? \" \") +\n suffix\n );\n}\n\n/**\n * Convert a string to camel case (`fooBar`).\n */\nexport function camelCase(input: string, options?: PascalCaseOptions) {\n const [prefix, words, suffix] = splitPrefixSuffix(input, options);\n const lower = lowerFactory(options?.locale);\n const upper = upperFactory(options?.locale);\n const transform = options?.mergeAmbiguousCharacters\n ? capitalCaseTransformFactory(lower, upper)\n : pascalCaseTransformFactory(lower, upper);\n return (\n prefix +\n words\n .map((word, index) => {\n if (index === 0) return lower(word);\n return transform(word, index);\n })\n .join(options?.delimiter ?? \"\") +\n suffix\n );\n}\n\n/**\n * Convert a string to pascal case (`FooBar`).\n */\nexport function pascalCase(input: string, options?: PascalCaseOptions) {\n const [prefix, words, suffix] = splitPrefixSuffix(input, options);\n const lower = lowerFactory(options?.locale);\n const upper = upperFactory(options?.locale);\n const transform = options?.mergeAmbiguousCharacters\n ? capitalCaseTransformFactory(lower, upper)\n : pascalCaseTransformFactory(lower, upper);\n return prefix + words.map(transform).join(options?.delimiter ?? \"\") + suffix;\n}\n\n/**\n * Convert a string to pascal snake case (`Foo_Bar`).\n */\nexport function pascalSnakeCase(input: string, options?: Options) {\n return capitalCase(input, { delimiter: \"_\", ...options });\n}\n\n/**\n * Convert a string to capital case (`Foo Bar`).\n */\nexport function capitalCase(input: string, options?: Options) {\n const [prefix, words, suffix] = splitPrefixSuffix(input, options);\n const lower = lowerFactory(options?.locale);\n const upper = upperFactory(options?.locale);\n return (\n prefix +\n words\n .map(capitalCaseTransformFactory(lower, upper))\n .join(options?.delimiter ?? \" \") +\n suffix\n );\n}\n\n/**\n * Convert a string to constant case (`FOO_BAR`).\n */\nexport function constantCase(input: string, options?: Options) {\n const [prefix, words, suffix] = splitPrefixSuffix(input, options);\n return (\n prefix +\n words.map(upperFactory(options?.locale)).join(options?.delimiter ?? \"_\") +\n suffix\n );\n}\n\n/**\n * Convert a string to dot case (`foo.bar`).\n */\nexport function dotCase(input: string, options?: Options) {\n return noCase(input, { delimiter: \".\", ...options });\n}\n\n/**\n * Convert a string to kebab case (`foo-bar`).\n */\nexport function kebabCase(input: string, options?: Options) {\n return noCase(input, { delimiter: \"-\", ...options });\n}\n\n/**\n * Convert a string to path case (`foo/bar`).\n */\nexport function pathCase(input: string, options?: Options) {\n return noCase(input, { delimiter: \"/\", ...options });\n}\n\n/**\n * Convert a string to path case (`Foo bar`).\n */\nexport function sentenceCase(input: string, options?: Options) {\n const [prefix, words, suffix] = splitPrefixSuffix(input, options);\n const lower = lowerFactory(options?.locale);\n const upper = upperFactory(options?.locale);\n const transform = capitalCaseTransformFactory(lower, upper);\n return (\n prefix +\n words\n .map((word, index) => {\n if (index === 0) return transform(word);\n return lower(word);\n })\n .join(options?.delimiter ?? \" \") +\n suffix\n );\n}\n\n/**\n * Convert a string to snake case (`foo_bar`).\n */\nexport function snakeCase(input: string, options?: Options) {\n return noCase(input, { delimiter: \"_\", ...options });\n}\n\n/**\n * Convert a string to header case (`Foo-Bar`).\n */\nexport function trainCase(input: string, options?: Options) {\n return capitalCase(input, { delimiter: \"-\", ...options });\n}\n\nfunction lowerFactory(locale: Locale): (input: string) => string {\n return locale === false\n ? (input: string) => input.toLowerCase()\n : (input: string) => input.toLocaleLowerCase(locale);\n}\n\nfunction upperFactory(locale: Locale): (input: string) => string {\n return locale === false\n ? (input: string) => input.toUpperCase()\n : (input: string) => input.toLocaleUpperCase(locale);\n}\n\nfunction capitalCaseTransformFactory(\n lower: (input: string) => string,\n upper: (input: string) => string,\n) {\n return (word: string) => `${upper(word[0])}${lower(word.slice(1))}`;\n}\n\nfunction pascalCaseTransformFactory(\n lower: (input: string) => string,\n upper: (input: string) => string,\n) {\n return (word: string, index: number) => {\n const char0 = word[0];\n const initial =\n index > 0 && char0 >= \"0\" && char0 <= \"9\" ? \"_\" + char0 : upper(char0);\n return initial + lower(word.slice(1));\n };\n}\n\nfunction splitPrefixSuffix(\n input: string,\n options: Options = {},\n): [string, string[], string] {\n const splitFn =\n options.split ?? (options.separateNumbers ? splitSeparateNumbers : split);\n const prefixCharacters =\n options.prefixCharacters ?? DEFAULT_PREFIX_SUFFIX_CHARACTERS;\n const suffixCharacters =\n options.suffixCharacters ?? DEFAULT_PREFIX_SUFFIX_CHARACTERS;\n let prefixIndex = 0;\n let suffixIndex = input.length;\n\n while (prefixIndex < input.length) {\n const char = input.charAt(prefixIndex);\n if (!prefixCharacters.includes(char)) break;\n prefixIndex++;\n }\n\n while (suffixIndex > prefixIndex) {\n const index = suffixIndex - 1;\n const char = input.charAt(index);\n if (!suffixCharacters.includes(char)) break;\n suffixIndex = index;\n }\n\n return [\n input.slice(0, prefixIndex),\n splitFn(input.slice(prefixIndex, suffixIndex)),\n input.slice(suffixIndex),\n ];\n}\n","'use strict'\n\nimport map from 'map-obj'\nimport { snakeCase } from 'change-case'\n\nconst PlainObjectConstructor = {}.constructor\n\nfunction snakecaseKeys (obj, options) {\n if (Array.isArray(obj)) {\n if (obj.some(item => item.constructor !== PlainObjectConstructor)) {\n throw new Error('obj must be array of plain objects')\n }\n\n options = { deep: true, exclude: [], parsingOptions: {}, ...options }\n const convertCase = options.snakeCase || ((key) => snakeCase(key, options.parsingOptions))\n\n // Handle arrays by mapping each element\n return obj.map(item => {\n return map(item, (key, val) => {\n return [\n matches(options.exclude, key) ? key : convertCase(key),\n val,\n mapperOptions(key, val, options)\n ]\n }, options)\n })\n } else {\n if (obj.constructor !== PlainObjectConstructor) {\n throw new Error('obj must be an plain object')\n }\n }\n\n options = { deep: true, exclude: [], parsingOptions: {}, ...options }\n\n const convertCase = options.snakeCase || ((key) => snakeCase(key, options.parsingOptions))\n\n return map(obj, (key, val) => {\n return [\n matches(options.exclude, key) ? key : convertCase(key),\n val,\n mapperOptions(key, val, options)\n ]\n }, options)\n}\n\nfunction matches (patterns, value) {\n return patterns.some(pattern => {\n return typeof pattern === 'string'\n ? pattern === value\n : pattern.test(value)\n })\n}\n\nfunction mapperOptions (key, val, options) {\n return options.shouldRecurse\n ? { shouldRecurse: options.shouldRecurse(key, val) }\n : undefined\n}\n\nexport default snakecaseKeys\n","import type { AccountlessApplicationJSON } from './JSON';\n\nexport class AccountlessApplication {\n constructor(\n readonly publishableKey: string,\n readonly secretKey: string,\n readonly claimUrl: string,\n readonly apiKeysUrl: string,\n ) {}\n\n static fromJSON(data: AccountlessApplicationJSON): AccountlessApplication {\n return new AccountlessApplication(data.publishable_key, data.secret_key, data.claim_url, data.api_keys_url);\n }\n}\n","import type { ActorTokenStatus } from './Enums';\nimport type { ActorTokenJSON } from './JSON';\n\nexport class ActorToken {\n constructor(\n readonly id: string,\n readonly status: ActorTokenStatus,\n readonly userId: string,\n readonly actor: Record | null,\n readonly token: string | null | undefined,\n readonly url: string | null | undefined,\n readonly createdAt: number,\n readonly updatedAt: number,\n ) {}\n\n static fromJSON(data: ActorTokenJSON): ActorToken {\n return new ActorToken(\n data.id,\n data.status,\n data.user_id,\n data.actor,\n data.token,\n data.url,\n data.created_at,\n data.updated_at,\n );\n }\n}\n","import type { AllowlistIdentifierType } from './Enums';\nimport type { AllowlistIdentifierJSON } from './JSON';\n\n/**\n * The Backend `AllowlistIdentifier` object represents an identifier that has been added to the allowlist of your application. The Backend `AllowlistIdentifier` object is used in the [Backend API](https://clerk.com/docs/reference/backend-api/tag/Allow-list-Block-list#operation/ListAllowlistIdentifiers) and is not directly accessible from the Frontend API.\n */\nexport class AllowlistIdentifier {\n constructor(\n /**\n * A unique ID for the allowlist identifier.\n */\n readonly id: string,\n /**\n * The [identifier](https://clerk.com/docs/authentication/configuration/sign-up-sign-in-options#identifiers) that was added to the allowlist.\n */\n readonly identifier: string,\n /**\n * The type of the allowlist identifier.\n */\n readonly identifierType: AllowlistIdentifierType,\n /**\n * The date when the allowlist identifier was first created.\n */\n readonly createdAt: number,\n /**\n * The date when the allowlist identifier was last updated.\n */\n readonly updatedAt: number,\n /**\n * The ID of the instance that this allowlist identifier belongs to.\n */\n readonly instanceId?: string,\n /**\n * The ID of the invitation sent to the identifier.\n */\n readonly invitationId?: string,\n ) {}\n\n static fromJSON(data: AllowlistIdentifierJSON): AllowlistIdentifier {\n return new AllowlistIdentifier(\n data.id,\n data.identifier,\n data.identifier_type,\n data.created_at,\n data.updated_at,\n data.instance_id,\n data.invitation_id,\n );\n }\n}\n","import type { APIKeyJSON } from './JSON';\n\nexport class APIKey {\n constructor(\n readonly id: string,\n readonly type: string,\n readonly name: string,\n readonly subject: string,\n readonly scopes: string[],\n readonly claims: Record | null,\n readonly revoked: boolean,\n readonly revocationReason: string | null,\n readonly expired: boolean,\n readonly expiration: number | null,\n readonly createdBy: string | null,\n readonly description: string | null,\n readonly lastUsedAt: number | null,\n readonly createdAt: number,\n readonly updatedAt: number,\n readonly secret?: string,\n ) {}\n\n static fromJSON(data: APIKeyJSON) {\n return new APIKey(\n data.id,\n data.type,\n data.name,\n data.subject,\n data.scopes,\n data.claims,\n data.revoked,\n data.revocation_reason,\n data.expired,\n data.expiration,\n data.created_by,\n data.description,\n data.last_used_at,\n data.created_at,\n data.updated_at,\n data.secret,\n );\n }\n}\n","import type { BlocklistIdentifierType } from './Enums';\nimport type { BlocklistIdentifierJSON } from './JSON';\n\nexport class BlocklistIdentifier {\n constructor(\n readonly id: string,\n readonly identifier: string,\n readonly identifierType: BlocklistIdentifierType,\n readonly createdAt: number,\n readonly updatedAt: number,\n readonly instanceId?: string,\n ) {}\n\n static fromJSON(data: BlocklistIdentifierJSON): BlocklistIdentifier {\n return new BlocklistIdentifier(\n data.id,\n data.identifier,\n data.identifier_type,\n data.created_at,\n data.updated_at,\n data.instance_id,\n );\n }\n}\n","import type { SessionActivityJSON, SessionJSON } from './JSON';\n\n/**\n * The Backend `SessionActivity` object models the activity of a user session, capturing details such as the device type, browser information, and geographical location.\n */\nexport class SessionActivity {\n constructor(\n /**\n * The unique identifier for the session activity record.\n */\n readonly id: string,\n /**\n * Will be set to `true` if the session activity came from a mobile device. Set to `false` otherwise.\n */\n readonly isMobile: boolean,\n /**\n * The IP address from which this session activity originated.\n */\n readonly ipAddress?: string,\n /**\n * The city from which this session activity occurred. Resolved by IP address geo-location.\n */\n readonly city?: string,\n /**\n * The country from which this session activity occurred. Resolved by IP address geo-location.\n */\n readonly country?: string,\n /**\n * The version of the browser from which this session activity occurred.\n */\n readonly browserVersion?: string,\n /**\n * The name of the browser from which this session activity occurred.\n */\n readonly browserName?: string,\n /**\n * The type of the device which was used in this session activity.\n */\n readonly deviceType?: string,\n ) {}\n\n static fromJSON(data: SessionActivityJSON): SessionActivity {\n return new SessionActivity(\n data.id,\n data.is_mobile,\n data.ip_address,\n data.city,\n data.country,\n data.browser_version,\n data.browser_name,\n data.device_type,\n );\n }\n}\n\n/**\n * The Backend `Session` object is similar to the [`Session`](https://clerk.com/docs/references/javascript/session) object as it is an abstraction over an HTTP session and models the period of information exchange between a user and the server. However, the Backend `Session` object is different as it is used in the [Backend API](https://clerk.com/docs/reference/backend-api/tag/Sessions#operation/GetSessionList) and is not directly accessible from the Frontend API.\n */\nexport class Session {\n constructor(\n /**\n * The unique identifier for the `Session`.\n */\n readonly id: string,\n /**\n * The ID of the client associated with the `Session`.\n */\n readonly clientId: string,\n /**\n * The ID of the user associated with the `Session`.\n */\n readonly userId: string,\n /**\n * The current state of the `Session`.\n */\n readonly status: string,\n /**\n * The time the session was last active on the [`Client`](https://clerk.com/docs/references/backend/types/backend-client).\n */\n readonly lastActiveAt: number,\n /**\n * The date when the `Session` will expire.\n */\n readonly expireAt: number,\n /**\n * The date when the `Session` will be abandoned.\n */\n readonly abandonAt: number,\n /**\n * The date when the `Session` was first created.\n */\n readonly createdAt: number,\n /**\n * The date when the `Session` was last updated.\n */\n readonly updatedAt: number,\n /**\n * The ID of the last active organization.\n */\n readonly lastActiveOrganizationId?: string,\n /**\n * An object that provides additional information about this session, focused around user activity data.\n */\n readonly latestActivity?: SessionActivity,\n /**\n * The JWT actor for the session. Holds identifier for the user that is impersonating the current user. Read more about [impersonation](https://clerk.com/docs/users/user-impersonation).\n */\n readonly actor: Record | null = null,\n ) {}\n\n static fromJSON(data: SessionJSON): Session {\n return new Session(\n data.id,\n data.client_id,\n data.user_id,\n data.status,\n data.last_active_at,\n data.expire_at,\n data.abandon_at,\n data.created_at,\n data.updated_at,\n data.last_active_organization_id,\n data.latest_activity && SessionActivity.fromJSON(data.latest_activity),\n data.actor,\n );\n }\n}\n","import type { LastAuthenticationStrategy } from '@clerk/types';\n\nimport type { ClientJSON } from './JSON';\nimport { Session } from './Session';\n\n/**\n * The Backend `Client` object is similar to the [`Client`](https://clerk.com/docs/references/javascript/client) object as it holds information about the authenticated sessions in the current device. However, the Backend `Client` object is different from the `Client` object in that it is used in the [Backend API](https://clerk.com/docs/reference/backend-api/tag/Clients#operation/GetClient) and is not directly accessible from the Frontend API.\n */\nexport class Client {\n constructor(\n /**\n * The unique identifier for the `Client`.\n */\n readonly id: string,\n /**\n * An array of [Session](https://clerk.com/docs/references/backend/types/backend-session){{ target: '_blank' }} IDs associated with the `Client`.\n */\n readonly sessionIds: string[],\n /**\n * An array of [Session](https://clerk.com/docs/references/backend/types/backend-session){{ target: '_blank' }} objects associated with the `Client`.\n */\n readonly sessions: Session[],\n /**\n * The ID of the [`SignIn`](https://clerk.com/docs/references/javascript/sign-in){{ target: '_blank' }}.\n */\n readonly signInId: string | null,\n /**\n * The ID of the [`SignUp`](https://clerk.com/docs/references/javascript/sign-up){{ target: '_blank' }}.\n */\n readonly signUpId: string | null,\n /**\n * The ID of the last active [Session](https://clerk.com/docs/references/backend/types/backend-session).\n */\n readonly lastActiveSessionId: string | null,\n /**\n * The last authentication strategy used by the `Client`.\n */\n readonly lastAuthenticationStrategy: LastAuthenticationStrategy | null,\n /**\n * The date when the `Client` was first created.\n */\n readonly createdAt: number,\n /**\n * The date when the `Client` was last updated.\n */\n readonly updatedAt: number,\n ) {}\n\n static fromJSON(data: ClientJSON): Client {\n return new Client(\n data.id,\n data.session_ids,\n data.sessions.map(x => Session.fromJSON(x)),\n data.sign_in_id,\n data.sign_up_id,\n data.last_active_session_id,\n data.last_authentication_strategy,\n data.created_at,\n data.updated_at,\n );\n }\n}\n","import type { CnameTargetJSON } from './JSON';\n\nexport class CnameTarget {\n constructor(\n readonly host: string,\n readonly value: string,\n readonly required: boolean,\n ) {}\n\n static fromJSON(data: CnameTargetJSON): CnameTarget {\n return new CnameTarget(data.host, data.value, data.required);\n }\n}\n","import type { CookiesJSON } from './JSON';\n\nexport class Cookies {\n constructor(readonly cookies: string[]) {}\n\n static fromJSON(data: CookiesJSON): Cookies {\n return new Cookies(data.cookies);\n }\n}\n","import type { DeletedObjectJSON } from './JSON';\n\nexport class DeletedObject {\n constructor(\n readonly object: string,\n readonly id: string | null,\n readonly slug: string | null,\n readonly deleted: boolean,\n ) {}\n\n static fromJSON(data: DeletedObjectJSON) {\n return new DeletedObject(data.object, data.id || null, data.slug || null, data.deleted);\n }\n}\n","import { CnameTarget } from './CnameTarget';\nimport type { DomainJSON } from './JSON';\n\nexport class Domain {\n constructor(\n readonly id: string,\n readonly name: string,\n readonly isSatellite: boolean,\n readonly frontendApiUrl: string,\n readonly developmentOrigin: string,\n readonly cnameTargets: CnameTarget[],\n readonly accountsPortalUrl?: string | null,\n readonly proxyUrl?: string | null,\n ) {}\n\n static fromJSON(data: DomainJSON): Domain {\n return new Domain(\n data.id,\n data.name,\n data.is_satellite,\n data.frontend_api_url,\n data.development_origin,\n data.cname_targets && data.cname_targets.map(x => CnameTarget.fromJSON(x)),\n data.accounts_portal_url,\n data.proxy_url,\n );\n }\n}\n","import type { EmailJSON } from './JSON';\n\nexport class Email {\n constructor(\n readonly id: string,\n readonly fromEmailName: string,\n readonly emailAddressId: string | null,\n readonly toEmailAddress?: string,\n readonly subject?: string,\n readonly body?: string,\n readonly bodyPlain?: string | null,\n readonly status?: string,\n readonly slug?: string | null,\n readonly data?: Record | null,\n readonly deliveredByClerk?: boolean,\n ) {}\n\n static fromJSON(data: EmailJSON): Email {\n return new Email(\n data.id,\n data.from_email_name,\n data.email_address_id,\n data.to_email_address,\n data.subject,\n data.body,\n data.body_plain,\n data.status,\n data.slug,\n data.data,\n data.delivered_by_clerk,\n );\n }\n}\n","import type { IdentificationLinkJSON } from './JSON';\n\n/**\n * Contains information about any identifications that might be linked to the email address.\n */\nexport class IdentificationLink {\n constructor(\n /**\n * The unique identifier for the identification link.\n */\n readonly id: string,\n /**\n * The type of the identification link, e.g., `\"email_address\"`, `\"phone_number\"`, etc.\n */\n readonly type: string,\n ) {}\n\n static fromJSON(data: IdentificationLinkJSON): IdentificationLink {\n return new IdentificationLink(data.id, data.type);\n }\n}\n","import type { VerificationStatus } from '@clerk/types';\n\nimport type { OrganizationDomainVerificationJSON, VerificationJSON } from './JSON';\n\n/**\n * The Backend `Verification` object describes the state of the verification process of a sign-in or sign-up attempt.\n */\nexport class Verification {\n constructor(\n /**\n * The state of the verification.\n *\n *
    \n *
  • `unverified`: The verification has not been verified yet.
  • \n *
  • `verified`: The verification has been verified.
  • \n *
  • `transferable`: The verification is transferable to between sign-in and sign-up flows.
  • \n *
  • `failed`: The verification has failed.
  • \n *
  • `expired`: The verification has expired.
  • \n *
\n */\n readonly status: VerificationStatus,\n /**\n * The strategy pertaining to the parent sign-up or sign-in attempt.\n */\n readonly strategy: string,\n /**\n * The redirect URL for an external verification.\n */\n readonly externalVerificationRedirectURL: URL | null = null,\n /**\n * The number of attempts related to the verification.\n */\n readonly attempts: number | null = null,\n /**\n * The time the verification will expire at.\n */\n readonly expireAt: number | null = null,\n /**\n * The [nonce](https://en.wikipedia.org/wiki/Cryptographic_nonce) pertaining to the verification.\n */\n readonly nonce: string | null = null,\n /**\n * The message that will be presented to the user's Web3 wallet for signing during authentication. This follows the [Sign-In with Ethereum (SIWE) protocol format](https://docs.login.xyz/general-information/siwe-overview/eip-4361#example-message-to-be-signed), which typically includes details like the requesting service, wallet address, terms acceptance, nonce, timestamp, and any additional resources.\n */\n readonly message: string | null = null,\n ) {}\n\n static fromJSON(data: VerificationJSON): Verification {\n return new Verification(\n data.status,\n data.strategy,\n data.external_verification_redirect_url ? new URL(data.external_verification_redirect_url) : null,\n data.attempts,\n data.expire_at,\n data.nonce,\n );\n }\n}\n\nexport class OrganizationDomainVerification {\n constructor(\n readonly status: string,\n readonly strategy: string,\n readonly attempts: number | null = null,\n readonly expireAt: number | null = null,\n ) {}\n\n static fromJSON(data: OrganizationDomainVerificationJSON): OrganizationDomainVerification {\n return new OrganizationDomainVerification(data.status, data.strategy, data.attempts, data.expires_at);\n }\n}\n","import { IdentificationLink } from './IdentificationLink';\nimport type { EmailAddressJSON } from './JSON';\nimport { Verification } from './Verification';\n\n/**\n * The Backend `EmailAddress` object is a model around an email address. Email addresses are one of the [identifiers](https://clerk.com/docs/authentication/configuration/sign-up-sign-in-options#identifiers) used to provide identification for users.\n *\n * Email addresses must be **verified** to ensure that they are assigned to their rightful owners. The `EmailAddress` object holds all necessary state around the verification process.\n *\n * For implementation examples for adding and verifying email addresses, see the [email link custom flow](https://clerk.com/docs/custom-flows/email-links) and [email code custom flow](https://clerk.com/docs/custom-flows/add-email) guides.\n */\nexport class EmailAddress {\n constructor(\n /**\n * The unique identifier for the email address.\n */\n readonly id: string,\n /**\n * The value of the email address.\n */\n readonly emailAddress: string,\n /**\n * An object holding information on the verification of the email address.\n */\n readonly verification: Verification | null,\n /**\n * An array of objects containing information about any identifications that might be linked to the email address.\n */\n readonly linkedTo: IdentificationLink[],\n ) {}\n\n static fromJSON(data: EmailAddressJSON): EmailAddress {\n return new EmailAddress(\n data.id,\n data.email_address,\n data.verification && Verification.fromJSON(data.verification),\n data.linked_to.map(link => IdentificationLink.fromJSON(link)),\n );\n }\n}\n","import type { ExternalAccountJSON } from './JSON';\nimport { Verification } from './Verification';\n\n/**\n * The Backend `ExternalAccount` object is a model around an identification obtained by an external provider (e.g. a social provider such as Google).\n *\n * External account must be verified, so that you can make sure they can be assigned to their rightful owners. The `ExternalAccount` object holds all necessary state around the verification process.\n */\nexport class ExternalAccount {\n constructor(\n /**\n * The unique identifier for this external account.\n */\n readonly id: string,\n /**\n * The provider name (e.g., `google`).\n */\n readonly provider: string,\n /**\n * The identification with which this external account is associated.\n */\n readonly identificationId: string,\n /**\n * The unique ID of the user in the provider.\n */\n readonly externalId: string,\n /**\n * The scopes that the user has granted access to.\n */\n readonly approvedScopes: string,\n /**\n * The user's email address.\n */\n readonly emailAddress: string,\n /**\n * The user's first name.\n */\n readonly firstName: string,\n /**\n * The user's last name.\n */\n readonly lastName: string,\n /**\n * The user's image URL.\n */\n readonly imageUrl: string,\n /**\n * The user's username.\n */\n readonly username: string | null,\n /**\n * The phone number related to this specific external account.\n */\n readonly phoneNumber: string | null,\n /**\n * Metadata that can be read from the Frontend API and Backend API and can be set only from the Backend API.\n */\n readonly publicMetadata: Record | null = {},\n /**\n * A descriptive label to differentiate multiple external accounts of the same user for the same provider.\n */\n readonly label: string | null,\n /**\n * An object holding information on the verification of this external account.\n */\n readonly verification: Verification | null,\n ) {}\n\n static fromJSON(data: ExternalAccountJSON): ExternalAccount {\n return new ExternalAccount(\n data.id,\n data.provider,\n data.identification_id,\n data.provider_user_id,\n data.approved_scopes,\n data.email_address,\n data.first_name,\n data.last_name,\n data.image_url || '',\n data.username,\n data.phone_number,\n data.public_metadata,\n data.label,\n data.verification && Verification.fromJSON(data.verification),\n );\n }\n}\n","import type { IdPOAuthAccessTokenJSON } from './JSON';\n\nexport class IdPOAuthAccessToken {\n constructor(\n readonly id: string,\n readonly clientId: string,\n readonly type: string,\n readonly subject: string,\n readonly scopes: string[],\n readonly revoked: boolean,\n readonly revocationReason: string | null,\n readonly expired: boolean,\n readonly expiration: number | null,\n readonly createdAt: number,\n readonly updatedAt: number,\n ) {}\n\n static fromJSON(data: IdPOAuthAccessTokenJSON) {\n return new IdPOAuthAccessToken(\n data.id,\n data.client_id,\n data.type,\n data.subject,\n data.scopes,\n data.revoked,\n data.revocation_reason,\n data.expired,\n data.expiration,\n data.created_at,\n data.updated_at,\n );\n }\n}\n","import type { InstanceJSON } from './JSON';\n\nexport class Instance {\n constructor(\n readonly id: string,\n readonly environmentType: string,\n readonly allowedOrigins: Array | null,\n ) {}\n\n static fromJSON(data: InstanceJSON): Instance {\n return new Instance(data.id, data.environment_type, data.allowed_origins);\n }\n}\n","import type { InstanceRestrictionsJSON } from './JSON';\n\nexport class InstanceRestrictions {\n constructor(\n readonly allowlist: boolean,\n readonly blocklist: boolean,\n readonly blockEmailSubaddresses: boolean,\n readonly blockDisposableEmailDomains: boolean,\n readonly ignoreDotsForGmailAddresses: boolean,\n ) {}\n\n static fromJSON(data: InstanceRestrictionsJSON): InstanceRestrictions {\n return new InstanceRestrictions(\n data.allowlist,\n data.blocklist,\n data.block_email_subaddresses,\n data.block_disposable_email_domains,\n data.ignore_dots_for_gmail_addresses,\n );\n }\n}\n","import type { InstanceSettingsJSON } from './JSON';\n\nexport class InstanceSettings {\n constructor(\n readonly id?: string | undefined,\n readonly restrictedToAllowlist?: boolean | undefined,\n readonly fromEmailAddress?: string | undefined,\n readonly progressiveSignUp?: boolean | undefined,\n readonly enhancedEmailDeliverability?: boolean | undefined,\n ) {}\n\n static fromJSON(data: InstanceSettingsJSON): InstanceSettings {\n return new InstanceSettings(\n data.id,\n data.restricted_to_allowlist,\n data.from_email_address,\n data.progressive_sign_up,\n data.enhanced_email_deliverability,\n );\n }\n}\n","import type { InvitationStatus } from './Enums';\nimport type { InvitationJSON } from './JSON';\n\n/**\n * The Backend `Invitation` object represents an invitation to join your application.\n */\nexport class Invitation {\n private _raw: InvitationJSON | null = null;\n\n public get raw(): InvitationJSON | null {\n return this._raw;\n }\n\n constructor(\n /**\n * The unique identifier for the `Invitation`.\n */\n readonly id: string,\n /**\n * The email address that the invitation was sent to.\n */\n readonly emailAddress: string,\n /**\n * [Metadata](https://clerk.com/docs/references/javascript/types/metadata#user-public-metadata){{ target: '_blank' }} that can be read from the Frontend API and [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }} and can be set only from the Backend API. Once the user accepts the invitation and signs up, these metadata will end up in the user's public metadata.\n */\n readonly publicMetadata: Record | null,\n /**\n * The date when the `Invitation` was first created.\n */\n readonly createdAt: number,\n /**\n * The date when the `Invitation` was last updated.\n */\n readonly updatedAt: number,\n /**\n * The status of the `Invitation`.\n */\n readonly status: InvitationStatus,\n /**\n * The URL that the user can use to accept the invitation.\n */\n readonly url?: string,\n /**\n * Whether the `Invitation` has been revoked.\n */\n readonly revoked?: boolean,\n ) {}\n\n static fromJSON(data: InvitationJSON): Invitation {\n const res = new Invitation(\n data.id,\n data.email_address,\n data.public_metadata,\n data.created_at,\n data.updated_at,\n data.status,\n data.url,\n data.revoked,\n );\n res._raw = data;\n return res;\n }\n}\n","import type { LastAuthenticationStrategy, SignUpStatus, VerificationStatus } from '@clerk/types';\n\nimport type {\n ActorTokenStatus,\n AllowlistIdentifierType,\n BlocklistIdentifierType,\n DomainsEnrollmentModes,\n InvitationStatus,\n OrganizationDomainVerificationStatus,\n OrganizationDomainVerificationStrategy,\n OrganizationEnrollmentMode,\n OrganizationInvitationStatus,\n OrganizationMembershipRole,\n SignInStatus,\n SignUpVerificationNextAction,\n WaitlistEntryStatus,\n} from './Enums';\n\nexport const ObjectType = {\n AccountlessApplication: 'accountless_application',\n ActorToken: 'actor_token',\n AllowlistIdentifier: 'allowlist_identifier',\n ApiKey: 'api_key',\n BlocklistIdentifier: 'blocklist_identifier',\n Client: 'client',\n Cookies: 'cookies',\n Domain: 'domain',\n Email: 'email',\n EmailAddress: 'email_address',\n ExternalAccount: 'external_account',\n FacebookAccount: 'facebook_account',\n GoogleAccount: 'google_account',\n Instance: 'instance',\n InstanceRestrictions: 'instance_restrictions',\n InstanceSettings: 'instance_settings',\n Invitation: 'invitation',\n Machine: 'machine',\n MachineScope: 'machine_scope',\n MachineSecretKey: 'machine_secret_key',\n M2MToken: 'machine_to_machine_token',\n JwtTemplate: 'jwt_template',\n OauthAccessToken: 'oauth_access_token',\n IdpOAuthAccessToken: 'clerk_idp_oauth_access_token',\n OAuthApplication: 'oauth_application',\n Organization: 'organization',\n OrganizationDomain: 'organization_domain',\n OrganizationInvitation: 'organization_invitation',\n OrganizationMembership: 'organization_membership',\n OrganizationSettings: 'organization_settings',\n PhoneNumber: 'phone_number',\n ProxyCheck: 'proxy_check',\n RedirectUrl: 'redirect_url',\n SamlAccount: 'saml_account',\n SamlConnection: 'saml_connection',\n Session: 'session',\n SignInAttempt: 'sign_in_attempt',\n SignInToken: 'sign_in_token',\n SignUpAttempt: 'sign_up_attempt',\n SmsMessage: 'sms_message',\n User: 'user',\n WaitlistEntry: 'waitlist_entry',\n Web3Wallet: 'web3_wallet',\n Token: 'token',\n TotalCount: 'total_count',\n TestingToken: 'testing_token',\n Role: 'role',\n Permission: 'permission',\n BillingPayer: 'commerce_payer',\n BillingPaymentAttempt: 'commerce_payment_attempt',\n BillingSubscription: 'commerce_subscription',\n BillingSubscriptionItem: 'commerce_subscription_item',\n BillingPlan: 'commerce_plan',\n Feature: 'feature',\n} as const;\n\nexport type ObjectType = (typeof ObjectType)[keyof typeof ObjectType];\n\nexport interface ClerkResourceJSON {\n /**\n * The type of the resource.\n */\n object: ObjectType;\n /**\n * The unique identifier for the resource.\n */\n id: string;\n}\n\nexport interface CookiesJSON {\n object: typeof ObjectType.Cookies;\n cookies: string[];\n}\n\nexport interface TokenJSON {\n object: typeof ObjectType.Token;\n jwt: string;\n}\n\nexport interface AccountlessApplicationJSON extends ClerkResourceJSON {\n object: typeof ObjectType.AccountlessApplication;\n publishable_key: string;\n secret_key: string;\n claim_url: string;\n api_keys_url: string;\n}\n\nexport interface ActorTokenJSON extends ClerkResourceJSON {\n object: typeof ObjectType.ActorToken;\n id: string;\n status: ActorTokenStatus;\n user_id: string;\n actor: Record | null;\n token?: string | null;\n url?: string | null;\n created_at: number;\n updated_at: number;\n}\n\nexport interface AllowlistIdentifierJSON extends ClerkResourceJSON {\n object: typeof ObjectType.AllowlistIdentifier;\n identifier: string;\n identifier_type: AllowlistIdentifierType;\n instance_id?: string;\n invitation_id?: string;\n created_at: number;\n updated_at: number;\n}\n\nexport interface BlocklistIdentifierJSON extends ClerkResourceJSON {\n object: typeof ObjectType.BlocklistIdentifier;\n identifier: string;\n identifier_type: BlocklistIdentifierType;\n instance_id?: string;\n created_at: number;\n updated_at: number;\n}\n\nexport interface ClientJSON extends ClerkResourceJSON {\n object: typeof ObjectType.Client;\n session_ids: string[];\n sessions: SessionJSON[];\n sign_in_id: string | null;\n sign_up_id: string | null;\n last_active_session_id: string | null;\n last_authentication_strategy: LastAuthenticationStrategy | null;\n created_at: number;\n updated_at: number;\n}\n\nexport interface CnameTargetJSON {\n host: string;\n value: string;\n /**\n * Denotes whether this CNAME target is required to be set in order for the domain to be considered deployed.\n */\n required: boolean;\n}\n\nexport interface DomainJSON extends ClerkResourceJSON {\n object: typeof ObjectType.Domain;\n id: string;\n name: string;\n is_satellite: boolean;\n frontend_api_url: string;\n /**\n * null for satellite domains\n */\n accounts_portal_url?: string | null;\n proxy_url?: string;\n development_origin: string;\n cname_targets: CnameTargetJSON[];\n}\n\nexport interface EmailJSON extends ClerkResourceJSON {\n object: typeof ObjectType.Email;\n slug?: string | null;\n from_email_name: string;\n to_email_address?: string;\n email_address_id: string | null;\n user_id?: string | null;\n subject?: string;\n body?: string;\n body_plain?: string | null;\n status?: string;\n data?: Record | null;\n delivered_by_clerk: boolean;\n}\n\nexport interface EmailAddressJSON extends ClerkResourceJSON {\n object: typeof ObjectType.EmailAddress;\n email_address: string;\n verification: VerificationJSON | null;\n linked_to: IdentificationLinkJSON[];\n}\n\nexport interface ExternalAccountJSON extends ClerkResourceJSON {\n object: typeof ObjectType.ExternalAccount;\n provider: string;\n identification_id: string;\n provider_user_id: string;\n approved_scopes: string;\n email_address: string;\n first_name: string;\n last_name: string;\n image_url?: string;\n username: string | null;\n phone_number: string | null;\n public_metadata?: Record | null;\n label: string | null;\n verification: VerificationJSON | null;\n}\n\nexport interface JwksJSON {\n keys?: JwksKeyJSON[];\n}\n\nexport interface JwksKeyJSON {\n use: string;\n kty: string;\n kid: string;\n alg: string;\n n: string;\n e: string;\n}\n\nexport interface JwtTemplateJSON extends ClerkResourceJSON {\n object: typeof ObjectType.JwtTemplate;\n id: string;\n name: string;\n claims: object;\n lifetime: number;\n allowed_clock_skew: number;\n custom_signing_key: boolean;\n signing_algorithm: string;\n created_at: number;\n updated_at: number;\n}\n\nexport interface SamlAccountJSON extends ClerkResourceJSON {\n object: typeof ObjectType.SamlAccount;\n provider: string;\n provider_user_id: string | null;\n active: boolean;\n email_address: string;\n first_name: string;\n last_name: string;\n verification: VerificationJSON | null;\n saml_connection: SamlAccountConnectionJSON | null;\n}\n\nexport interface IdentificationLinkJSON extends ClerkResourceJSON {\n type: string;\n}\n\nexport interface OrganizationSettingsJSON extends ClerkResourceJSON {\n object: typeof ObjectType.OrganizationSettings;\n enabled: boolean;\n max_allowed_memberships: number;\n max_allowed_roles: number;\n max_allowed_permissions: number;\n creator_role: string;\n admin_delete_enabled: boolean;\n domains_enabled: boolean;\n domains_enrollment_modes: Array;\n domains_default_role: string;\n}\n\nexport interface InstanceJSON extends ClerkResourceJSON {\n object: typeof ObjectType.Instance;\n id: string;\n environment_type: string;\n allowed_origins: Array | null;\n}\n\nexport interface InstanceRestrictionsJSON extends ClerkResourceJSON {\n object: typeof ObjectType.InstanceRestrictions;\n allowlist: boolean;\n blocklist: boolean;\n block_email_subaddresses: boolean;\n block_disposable_email_domains: boolean;\n ignore_dots_for_gmail_addresses: boolean;\n}\n\nexport interface InstanceSettingsJSON extends ClerkResourceJSON {\n object: typeof ObjectType.InstanceSettings;\n id: string;\n restricted_to_allowlist: boolean;\n from_email_address: string;\n progressive_sign_up: boolean;\n enhanced_email_deliverability: boolean;\n}\n\nexport interface InvitationJSON extends ClerkResourceJSON {\n object: typeof ObjectType.Invitation;\n email_address: string;\n public_metadata: Record | null;\n revoked?: boolean;\n status: InvitationStatus;\n url?: string;\n created_at: number;\n updated_at: number;\n}\n\nexport interface OauthAccessTokenJSON {\n external_account_id: string;\n object: typeof ObjectType.OauthAccessToken;\n token: string;\n provider: string;\n public_metadata: Record;\n label: string | null;\n // Only set in OAuth 2.0 tokens\n scopes?: string[];\n // Only set in OAuth 1.0 tokens\n token_secret?: string;\n expires_at?: number;\n}\n\nexport interface OAuthApplicationJSON extends ClerkResourceJSON {\n object: typeof ObjectType.OAuthApplication;\n id: string;\n instance_id: string;\n name: string;\n client_id: string;\n client_uri: string | null;\n client_image_url: string | null;\n dynamically_registered: boolean;\n consent_screen_enabled: boolean;\n pkce_required: boolean;\n public: boolean;\n scopes: string;\n redirect_uris: Array;\n authorize_url: string;\n token_fetch_url: string;\n user_info_url: string;\n discovery_url: string;\n token_introspection_url: string;\n created_at: number;\n updated_at: number;\n client_secret?: string;\n}\n\nexport interface OrganizationJSON extends ClerkResourceJSON {\n object: typeof ObjectType.Organization;\n name: string;\n slug: string;\n image_url?: string;\n has_image: boolean;\n members_count?: number;\n pending_invitations_count?: number;\n max_allowed_memberships: number;\n admin_delete_enabled: boolean;\n public_metadata: OrganizationPublicMetadata | null;\n private_metadata?: OrganizationPrivateMetadata;\n created_by?: string;\n created_at: number;\n updated_at: number;\n}\n\nexport interface OrganizationDomainJSON extends ClerkResourceJSON {\n object: typeof ObjectType.OrganizationDomain;\n id: string;\n name: string;\n organization_id: string;\n enrollment_mode: OrganizationEnrollmentMode;\n verification: OrganizationDomainVerificationJSON | null;\n affiliation_email_address: string | null;\n created_at: number;\n updated_at: number;\n total_pending_invitations: number;\n total_pending_suggestions: number;\n}\n\nexport interface OrganizationDomainVerificationJSON {\n status: OrganizationDomainVerificationStatus;\n strategy: OrganizationDomainVerificationStrategy;\n attempts: number;\n expires_at: number;\n}\n\nexport interface OrganizationInvitationJSON extends ClerkResourceJSON {\n email_address: string;\n role: OrganizationMembershipRole;\n role_name: string;\n organization_id: string;\n public_organization_data?: PublicOrganizationDataJSON | null;\n status?: OrganizationInvitationStatus;\n public_metadata: OrganizationInvitationPublicMetadata;\n private_metadata: OrganizationInvitationPrivateMetadata;\n url: string | null;\n created_at: number;\n updated_at: number;\n expires_at: number;\n}\n\n/**\n * @interface\n */\nexport interface PublicOrganizationDataJSON extends ClerkResourceJSON {\n /**\n * The name of the organization.\n */\n name: string;\n /**\n * The slug of the organization.\n */\n slug: string;\n /**\n * Holds the default organization profile image. Compatible with Clerk's [Image Optimization](https://clerk.com/docs/guides/image-optimization).\n */\n image_url?: string;\n /**\n * Whether the organization has a profile image.\n */\n has_image: boolean;\n}\n\nexport interface OrganizationMembershipJSON extends ClerkResourceJSON {\n object: typeof ObjectType.OrganizationMembership;\n public_metadata: OrganizationMembershipPublicMetadata;\n private_metadata?: OrganizationMembershipPrivateMetadata;\n role: OrganizationMembershipRole;\n permissions: string[];\n created_at: number;\n updated_at: number;\n organization: OrganizationJSON;\n public_user_data: OrganizationMembershipPublicUserDataJSON;\n}\n\nexport interface OrganizationMembershipPublicUserDataJSON {\n identifier: string;\n first_name: string | null;\n last_name: string | null;\n image_url: string;\n has_image: boolean;\n user_id: string;\n}\n\nexport interface PhoneNumberJSON extends ClerkResourceJSON {\n object: typeof ObjectType.PhoneNumber;\n phone_number: string;\n reserved_for_second_factor: boolean;\n default_second_factor: boolean;\n reserved: boolean;\n verification: VerificationJSON | null;\n linked_to: IdentificationLinkJSON[];\n backup_codes: string[];\n}\n\nexport type ProxyCheckJSON = {\n object: typeof ObjectType.ProxyCheck;\n id: string;\n domain_id: string;\n last_run_at: number | null;\n proxy_url: string;\n successful: boolean;\n created_at: number;\n updated_at: number;\n};\n\nexport interface RedirectUrlJSON extends ClerkResourceJSON {\n object: typeof ObjectType.RedirectUrl;\n url: string;\n created_at: number;\n updated_at: number;\n}\n\nexport interface SessionActivityJSON extends ClerkResourceJSON {\n id: string;\n device_type?: string;\n is_mobile: boolean;\n browser_name?: string;\n browser_version?: string;\n ip_address?: string;\n city?: string;\n country?: string;\n}\n\nexport interface SessionJSON extends ClerkResourceJSON {\n object: typeof ObjectType.Session;\n client_id: string;\n user_id: string;\n status: string;\n last_active_organization_id?: string;\n actor: Record | null;\n latest_activity?: SessionActivityJSON;\n last_active_at: number;\n expire_at: number;\n abandon_at: number;\n created_at: number;\n updated_at: number;\n}\n\nexport interface SignInJSON extends ClerkResourceJSON {\n object: typeof ObjectType.SignInToken;\n status: SignInStatus;\n identifier: string;\n created_session_id: string | null;\n}\n\nexport interface SignInTokenJSON extends ClerkResourceJSON {\n object: typeof ObjectType.SignInToken;\n user_id: string;\n token: string;\n status: 'pending' | 'accepted' | 'revoked';\n url: string;\n created_at: number;\n updated_at: number;\n}\n\nexport interface SignUpJSON extends ClerkResourceJSON {\n object: typeof ObjectType.SignUpAttempt;\n id: string;\n status: SignUpStatus;\n required_fields: string[];\n optional_fields: string[];\n missing_fields: string[];\n unverified_fields: string[];\n verifications: SignUpVerificationsJSON;\n username: string | null;\n email_address: string | null;\n phone_number: string | null;\n web3_wallet: string | null;\n password_enabled: boolean;\n first_name: string | null;\n last_name: string | null;\n public_metadata?: Record | null;\n unsafe_metadata?: Record | null;\n custom_action: boolean;\n external_id: string | null;\n created_session_id: string | null;\n created_user_id: string | null;\n abandon_at: number | null;\n legal_accepted_at: number | null;\n\n /**\n * @deprecated Please use `verifications.external_account` instead\n */\n external_account: object | null;\n}\n\nexport interface SignUpVerificationsJSON {\n email_address: SignUpVerificationJSON;\n phone_number: SignUpVerificationJSON;\n web3_wallet: SignUpVerificationJSON;\n external_account: VerificationJSON;\n}\n\nexport interface SignUpVerificationJSON {\n next_action: SignUpVerificationNextAction;\n supported_strategies: string[];\n}\n\nexport interface SMSMessageJSON extends ClerkResourceJSON {\n object: typeof ObjectType.SmsMessage;\n from_phone_number: string;\n to_phone_number: string;\n phone_number_id: string | null;\n user_id?: string;\n message: string;\n status: string;\n slug?: string | null;\n data?: Record | null;\n delivered_by_clerk: boolean;\n}\n\nexport interface UserJSON extends ClerkResourceJSON {\n object: typeof ObjectType.User;\n username: string | null;\n first_name: string | null;\n last_name: string | null;\n image_url: string;\n has_image: boolean;\n primary_email_address_id: string | null;\n primary_phone_number_id: string | null;\n primary_web3_wallet_id: string | null;\n password_enabled: boolean;\n two_factor_enabled: boolean;\n totp_enabled: boolean;\n backup_code_enabled: boolean;\n email_addresses: EmailAddressJSON[];\n phone_numbers: PhoneNumberJSON[];\n web3_wallets: Web3WalletJSON[];\n organization_memberships: OrganizationMembershipJSON[] | null;\n external_accounts: ExternalAccountJSON[];\n saml_accounts: SamlAccountJSON[];\n password_last_updated_at: number | null;\n public_metadata: UserPublicMetadata;\n private_metadata: UserPrivateMetadata;\n unsafe_metadata: UserUnsafeMetadata;\n external_id: string | null;\n last_sign_in_at: number | null;\n banned: boolean;\n locked: boolean;\n lockout_expires_in_seconds: number | null;\n verification_attempts_remaining: number | null;\n created_at: number;\n updated_at: number;\n last_active_at: number | null;\n create_organization_enabled: boolean;\n create_organizations_limit: number | null;\n delete_self_enabled: boolean;\n legal_accepted_at: number | null;\n}\n\nexport interface VerificationJSON extends ClerkResourceJSON {\n status: VerificationStatus;\n strategy: string;\n attempts: number | null;\n expire_at: number | null;\n verified_at_client?: string;\n external_verification_redirect_url?: string | null;\n nonce?: string | null;\n message?: string | null;\n}\n\nexport interface WaitlistEntryJSON extends ClerkResourceJSON {\n object: typeof ObjectType.WaitlistEntry;\n id: string;\n status: WaitlistEntryStatus;\n email_address: string;\n invitation: InvitationJSON | null;\n is_locked: boolean;\n created_at: number;\n updated_at: number;\n}\n\nexport interface Web3WalletJSON extends ClerkResourceJSON {\n object: typeof ObjectType.Web3Wallet;\n web3_wallet: string;\n verification: VerificationJSON | null;\n}\n\nexport interface DeletedObjectJSON {\n object: string;\n id?: string;\n slug?: string;\n deleted: boolean;\n}\n\nexport interface PaginatedResponseJSON {\n data: object[];\n total_count?: number;\n}\n\nexport interface SamlConnectionJSON extends ClerkResourceJSON {\n object: typeof ObjectType.SamlConnection;\n name: string;\n domain: string;\n organization_id: string | null;\n idp_entity_id: string;\n idp_sso_url: string;\n idp_certificate: string;\n idp_metadata_url: string;\n idp_metadata: string;\n acs_url: string;\n sp_entity_id: string;\n sp_metadata_url: string;\n active: boolean;\n provider: string;\n user_count: number;\n sync_user_attributes: boolean;\n allow_subdomains: boolean;\n allow_idp_initiated: boolean;\n created_at: number;\n updated_at: number;\n attribute_mapping: AttributeMappingJSON;\n}\n\nexport interface AttributeMappingJSON {\n user_id: string;\n email_address: string;\n first_name: string;\n last_name: string;\n}\n\nexport interface TestingTokenJSON {\n object: typeof ObjectType.TestingToken;\n token: string;\n expires_at: number;\n}\n\nexport interface RoleJSON extends ClerkResourceJSON {\n object: typeof ObjectType.Role;\n key: string;\n name: string;\n description: string;\n permissions: PermissionJSON[];\n is_creator_eligible: boolean;\n created_at: number;\n updated_at: number;\n}\n\nexport interface PermissionJSON extends ClerkResourceJSON {\n object: typeof ObjectType.Permission;\n key: string;\n name: string;\n description: string;\n created_at: number;\n updated_at: number;\n}\n\nexport interface SamlAccountConnectionJSON extends ClerkResourceJSON {\n id: string;\n name: string;\n domain: string;\n active: boolean;\n provider: string;\n sync_user_attributes: boolean;\n allow_subdomains: boolean;\n allow_idp_initiated: boolean;\n disable_additional_identifications: boolean;\n created_at: number;\n updated_at: number;\n}\n\nexport interface MachineJSON extends ClerkResourceJSON {\n object: typeof ObjectType.Machine;\n id: string;\n name: string;\n instance_id: string;\n created_at: number;\n updated_at: number;\n default_token_ttl: number;\n scoped_machines: MachineJSON[];\n secret_key?: string;\n}\n\nexport interface MachineScopeJSON {\n object: typeof ObjectType.MachineScope;\n from_machine_id: string;\n to_machine_id: string;\n created_at?: number;\n deleted?: boolean;\n}\n\nexport interface MachineSecretKeyJSON {\n object: typeof ObjectType.MachineSecretKey;\n secret: string;\n}\n\nexport interface M2MTokenJSON extends ClerkResourceJSON {\n object: typeof ObjectType.M2MToken;\n token?: string;\n subject: string;\n scopes: string[];\n claims: Record | null;\n revoked: boolean;\n revocation_reason: string | null;\n expired: boolean;\n expiration: number | null;\n created_at: number;\n updated_at: number;\n}\n\nexport interface APIKeyJSON extends ClerkResourceJSON {\n object: typeof ObjectType.ApiKey;\n type: string;\n name: string;\n secret?: string;\n subject: string;\n scopes: string[];\n claims: Record | null;\n revoked: boolean;\n revocation_reason: string | null;\n expired: boolean;\n expiration: number | null;\n created_by: string | null;\n description: string | null;\n last_used_at: number | null;\n created_at: number;\n updated_at: number;\n}\n\nexport interface IdPOAuthAccessTokenJSON extends ClerkResourceJSON {\n object: typeof ObjectType.IdpOAuthAccessToken;\n client_id: string;\n type: string;\n subject: string;\n scopes: string[];\n revoked: boolean;\n revocation_reason: string | null;\n expired: boolean;\n expiration: number | null;\n created_at: number;\n updated_at: number;\n}\n\nexport interface BillingPayerJSON extends ClerkResourceJSON {\n object: typeof ObjectType.BillingPayer;\n instance_id: string;\n user_id?: string;\n first_name?: string;\n last_name?: string;\n email: string;\n organization_id?: string;\n organization_name?: string;\n image_url: string;\n created_at: number;\n updated_at: number;\n}\n\ninterface BillingPayeeJSON {\n id: string;\n gateway_type: string;\n gateway_external_id: string;\n gateway_status: 'active' | 'pending' | 'restricted' | 'disconnected';\n}\n\ninterface BillingMoneyAmountJSON {\n amount: number;\n amount_formatted: string;\n currency: string;\n currency_symbol: string;\n}\n\ninterface BillingTotalsJSON {\n subtotal: BillingMoneyAmountJSON;\n tax_total: BillingMoneyAmountJSON;\n grand_total: BillingMoneyAmountJSON;\n}\n\nexport interface FeatureJSON extends ClerkResourceJSON {\n object: typeof ObjectType.Feature;\n name: string;\n description: string;\n slug: string;\n avatar_url: string;\n}\n\n/**\n * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes.\n */\nexport interface BillingPlanJSON extends ClerkResourceJSON {\n object: typeof ObjectType.BillingPlan;\n id: string;\n product_id: string;\n name: string;\n slug: string;\n description?: string;\n is_default: boolean;\n is_recurring: boolean;\n has_base_fee: boolean;\n publicly_visible: boolean;\n fee: BillingMoneyAmountJSON;\n annual_fee: BillingMoneyAmountJSON;\n annual_monthly_fee: BillingMoneyAmountJSON;\n for_payer_type: 'org' | 'user';\n features: FeatureJSON[];\n}\n\ntype BillingSubscriptionItemStatus =\n | 'abandoned'\n | 'active'\n | 'canceled'\n | 'ended'\n | 'expired'\n | 'incomplete'\n | 'past_due'\n | 'upcoming';\n\n/**\n * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes.\n */\nexport interface BillingSubscriptionItemJSON extends ClerkResourceJSON {\n object: typeof ObjectType.BillingSubscriptionItem;\n status: BillingSubscriptionItemStatus;\n plan_period: 'month' | 'annual';\n payer_id: string;\n period_start: number;\n period_end: number | null;\n is_free_trial?: boolean;\n ended_at: number | null;\n created_at: number;\n updated_at: number;\n canceled_at: number | null;\n past_due_at: number | null;\n lifetime_paid: BillingMoneyAmountJSON;\n next_payment: {\n amount: number;\n date: number;\n } | null;\n amount: BillingMoneyAmountJSON | null;\n plan: BillingPlanJSON;\n plan_id: string;\n}\n\n/**\n * Webhooks specific interface for BillingSubscriptionItem.\n */\nexport interface BillingSubscriptionItemWebhookEventJSON extends ClerkResourceJSON {\n object: typeof ObjectType.BillingSubscriptionItem;\n status: BillingSubscriptionItemStatus;\n credit: {\n amount: BillingMoneyAmountJSON;\n cycle_days_remaining: number;\n cycle_days_total: number;\n cycle_remaining_percent: number;\n };\n proration_date: string;\n plan_period: 'month' | 'annual';\n period_start: number;\n period_end?: number;\n canceled_at?: number;\n past_due_at?: number;\n lifetime_paid: number;\n next_payment_amount: number;\n next_payment_date: number;\n amount: BillingMoneyAmountJSON;\n plan: {\n id: string;\n instance_id: string;\n product_id: string;\n name: string;\n slug: string;\n description?: string;\n is_default: boolean;\n is_recurring: boolean;\n amount: number;\n period: 'month' | 'annual';\n interval: number;\n has_base_fee: boolean;\n currency: string;\n annual_monthly_amount: number;\n publicly_visible: boolean;\n };\n plan_id: string;\n}\n\n/**\n * Webhooks specific interface for BillingPaymentAttempt.\n */\nexport interface BillingPaymentAttemptWebhookEventJSON extends ClerkResourceJSON {\n object: typeof ObjectType.BillingPaymentAttempt;\n instance_id: string;\n payment_id: string;\n statement_id: string;\n gateway_external_id: string;\n status: 'pending' | 'paid' | 'failed';\n created_at: number;\n updated_at: number;\n paid_at?: number;\n failed_at?: number;\n failed_reason?: {\n code: string;\n decline_code: string;\n };\n billing_date: number;\n charge_type: 'checkout' | 'recurring';\n payee: BillingPayeeJSON;\n payer: BillingPayerJSON;\n totals: BillingTotalsJSON;\n payment_source: {\n id: string;\n gateway: string;\n gateway_external_id: string;\n gateway_external_account_id?: string;\n payment_method: string;\n status: 'active' | 'disconnected';\n card_type?: string;\n last4?: string;\n };\n subscription_items: BillingSubscriptionItemWebhookEventJSON[];\n}\n\n/**\n * Webhooks specific interface for BillingSubscription.\n */\nexport interface BillingSubscriptionWebhookEventJSON extends ClerkResourceJSON {\n object: typeof ObjectType.BillingSubscription;\n status: 'abandoned' | 'active' | 'canceled' | 'ended' | 'expired' | 'incomplete' | 'past_due' | 'upcoming';\n active_at?: number;\n canceled_at?: number;\n created_at: number;\n ended_at?: number;\n past_due_at?: number;\n updated_at: number;\n latest_payment_id: string;\n payer_id: string;\n payer: BillingPayerJSON;\n payment_source_id: string;\n items: BillingSubscriptionItemWebhookEventJSON[];\n}\n\nexport interface BillingSubscriptionJSON extends ClerkResourceJSON {\n object: typeof ObjectType.BillingSubscription;\n status: 'active' | 'past_due' | 'canceled' | 'ended' | 'abandoned' | 'incomplete';\n payer_id: string;\n created_at: number;\n updated_at: number;\n active_at: number | null;\n past_due_at: number | null;\n subscription_items: BillingSubscriptionItemJSON[];\n next_payment?: {\n date: number;\n amount: BillingMoneyAmountJSON;\n };\n eligible_for_free_trial?: boolean;\n}\n\nexport interface WebhooksSvixJSON {\n svix_url: string;\n}\n","import type { MachineJSON } from './JSON';\n\n/**\n * The Backend `Machine` object holds information about a machine.\n */\nexport class Machine {\n constructor(\n readonly id: string,\n readonly name: string,\n readonly instanceId: string,\n readonly createdAt: number,\n readonly updatedAt: number,\n readonly scopedMachines: Machine[],\n readonly defaultTokenTtl: number,\n readonly secretKey?: string,\n ) {}\n\n static fromJSON(data: MachineJSON): Machine {\n return new Machine(\n data.id,\n data.name,\n data.instance_id,\n data.created_at,\n data.updated_at,\n data.scoped_machines.map(\n m =>\n new Machine(\n m.id,\n m.name,\n m.instance_id,\n m.created_at,\n m.updated_at,\n [], // Nested machines don't have scoped_machines\n m.default_token_ttl,\n ),\n ),\n data.default_token_ttl,\n data.secret_key,\n );\n }\n}\n","import type { MachineScopeJSON } from './JSON';\n\n/**\n * The Backend `MachineScope` object holds information about a machine scope.\n */\nexport class MachineScope {\n constructor(\n readonly fromMachineId: string,\n readonly toMachineId: string,\n readonly createdAt?: number,\n readonly deleted?: boolean,\n ) {}\n\n static fromJSON(data: MachineScopeJSON): MachineScope {\n return new MachineScope(data.from_machine_id, data.to_machine_id, data.created_at, data.deleted);\n }\n}\n","import type { MachineSecretKeyJSON } from './JSON';\n\n/**\n * The Backend `MachineSecretKey` object holds information about a machine secret key.\n */\nexport class MachineSecretKey {\n constructor(readonly secret: string) {}\n\n static fromJSON(data: MachineSecretKeyJSON): MachineSecretKey {\n return new MachineSecretKey(data.secret);\n }\n}\n","import type { M2MTokenJSON } from './JSON';\n\n/**\n * The Backend `M2MToken` object holds information about a machine-to-machine token.\n */\nexport class M2MToken {\n constructor(\n readonly id: string,\n readonly subject: string,\n readonly scopes: string[],\n readonly claims: Record | null,\n readonly revoked: boolean,\n readonly revocationReason: string | null,\n readonly expired: boolean,\n readonly expiration: number | null,\n readonly createdAt: number,\n readonly updatedAt: number,\n readonly token?: string,\n ) {}\n\n static fromJSON(data: M2MTokenJSON): M2MToken {\n return new M2MToken(\n data.id,\n data.subject,\n data.scopes,\n data.claims,\n data.revoked,\n data.revocation_reason,\n data.expired,\n data.expiration,\n data.created_at,\n data.updated_at,\n data.token,\n );\n }\n}\n","import type { JwtTemplateJSON } from './JSON';\n\nexport class JwtTemplate {\n constructor(\n readonly id: string,\n readonly name: string,\n readonly claims: object,\n readonly lifetime: number,\n readonly allowedClockSkew: number,\n readonly customSigningKey: boolean,\n readonly signingAlgorithm: string,\n readonly createdAt: number,\n readonly updatedAt: number,\n ) {}\n\n static fromJSON(data: JwtTemplateJSON): JwtTemplate {\n return new JwtTemplate(\n data.id,\n data.name,\n data.claims,\n data.lifetime,\n data.allowed_clock_skew,\n data.custom_signing_key,\n data.signing_algorithm,\n data.created_at,\n data.updated_at,\n );\n }\n}\n","import type { OauthAccessTokenJSON } from './JSON';\n\nexport class OauthAccessToken {\n constructor(\n readonly externalAccountId: string,\n readonly provider: string,\n readonly token: string,\n readonly publicMetadata: Record = {},\n readonly label: string,\n readonly scopes?: string[],\n readonly tokenSecret?: string,\n readonly expiresAt?: number,\n ) {}\n\n static fromJSON(data: OauthAccessTokenJSON) {\n return new OauthAccessToken(\n data.external_account_id,\n data.provider,\n data.token,\n data.public_metadata,\n data.label || '',\n data.scopes,\n data.token_secret,\n data.expires_at,\n );\n }\n}\n","import type { OAuthApplicationJSON } from './JSON';\n\n/**\n * The Backend `OAuthApplication` object holds information about an OAuth application.\n */\nexport class OAuthApplication {\n constructor(\n /**\n * The unique identifier for the OAuth application.\n */\n readonly id: string,\n /**\n * The ID of the instance that this OAuth application belongs to.\n */\n readonly instanceId: string,\n /**\n * The name of the new OAuth application.\n */\n readonly name: string,\n /**\n * The ID of the client associated with the OAuth application.\n */\n readonly clientId: string,\n /**\n * The public-facing URL of the OAuth application, often shown on consent screens.\n */\n readonly clientUri: string | null,\n /**\n * The URL of the image or logo representing the OAuth application.\n */\n readonly clientImageUrl: string | null,\n /**\n * Specifies whether the OAuth application is dynamically registered.\n */\n readonly dynamicallyRegistered: boolean,\n /**\n * Specifies whether the consent screen should be displayed in the authentication flow. Cannot be disabled for dynamically registered OAuth applications.\n */\n readonly consentScreenEnabled: boolean,\n /**\n * Specifies whether the Proof Key of Code Exchange (PKCE) flow should be required in the authentication flow.\n */\n readonly pkceRequired: boolean,\n /**\n * Indicates whether the client is public. If true, the Proof Key of Code Exchange (PKCE) flow can be used.\n */\n readonly isPublic: boolean, // NOTE: `public` is reserved\n /**\n * Scopes for the new OAuth application.\n */\n readonly scopes: string,\n /**\n * An array of redirect URIs of the new OAuth application.\n */\n readonly redirectUris: Array,\n /**\n * The URL used to authorize the user and obtain an authorization code.\n */\n readonly authorizeUrl: string,\n /**\n * The URL used by the client to exchange an authorization code for an access token.\n */\n readonly tokenFetchUrl: string,\n /**\n * The URL where the client can retrieve user information using an access token.\n */\n readonly userInfoUrl: string,\n /**\n * The OpenID Connect discovery endpoint URL for this OAuth application.\n */\n readonly discoveryUrl: string,\n /**\n * The URL used to introspect and validate issued access tokens.\n */\n readonly tokenIntrospectionUrl: string,\n /**\n * The date when the OAuth application was first created.\n */\n readonly createdAt: number,\n /**\n * The date when the OAuth application was last updated.\n */\n readonly updatedAt: number,\n /**\n * The client secret associated with the OAuth application. Empty if public client.\n */\n readonly clientSecret?: string,\n ) {}\n\n static fromJSON(data: OAuthApplicationJSON) {\n return new OAuthApplication(\n data.id,\n data.instance_id,\n data.name,\n data.client_id,\n data.client_uri,\n data.client_image_url,\n data.dynamically_registered,\n data.consent_screen_enabled,\n data.pkce_required,\n data.public,\n data.scopes,\n data.redirect_uris,\n data.authorize_url,\n data.token_fetch_url,\n data.user_info_url,\n data.discovery_url,\n data.token_introspection_url,\n data.created_at,\n data.updated_at,\n data.client_secret,\n );\n }\n}\n","import type { OrganizationJSON } from './JSON';\n\n/**\n * The Backend `Organization` object is similar to the [`Organization`](https://clerk.com/docs/references/javascript/organization) object as it holds information about an organization, as well as methods for managing it. However, the Backend `Organization` object is different in that it is used in the [Backend API](https://clerk.com/docs/reference/backend-api/tag/Organizations#operation/ListOrganizations){{ target: '_blank' }} and is not directly accessible from the Frontend API.\n */\nexport class Organization {\n private _raw: OrganizationJSON | null = null;\n\n public get raw(): OrganizationJSON | null {\n return this._raw;\n }\n\n constructor(\n /**\n * The unique identifier for the organization.\n */\n readonly id: string,\n /**\n * The name of the organization.\n */\n readonly name: string,\n /**\n * The URL-friendly identifier of the user's active organization. If supplied, it must be unique for the instance.\n */\n readonly slug: string,\n /**\n * Holds the organization's logo. Compatible with Clerk's [Image Optimization](https://clerk.com/docs/guides/image-optimization).\n */\n readonly imageUrl: string,\n /**\n * Whether the organization has an image.\n */\n readonly hasImage: boolean,\n /**\n * The date when the organization was first created.\n */\n readonly createdAt: number,\n /**\n * The date when the organization was last updated.\n */\n readonly updatedAt: number,\n /**\n * Metadata that can be read from the Frontend API and [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }} and can be set only from the Backend API.\n */\n readonly publicMetadata: OrganizationPublicMetadata | null = {},\n /**\n * Metadata that can be read and set only from the [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }}.\n */\n readonly privateMetadata: OrganizationPrivateMetadata = {},\n /**\n * The maximum number of memberships allowed in the organization.\n */\n readonly maxAllowedMemberships: number,\n /**\n * Whether the organization allows admins to delete users.\n */\n readonly adminDeleteEnabled: boolean,\n /**\n * The number of members in the organization.\n */\n readonly membersCount?: number,\n /**\n * The ID of the user who created the organization.\n */\n readonly createdBy?: string,\n ) {}\n\n static fromJSON(data: OrganizationJSON): Organization {\n const res = new Organization(\n data.id,\n data.name,\n data.slug,\n data.image_url || '',\n data.has_image,\n data.created_at,\n data.updated_at,\n data.public_metadata,\n data.private_metadata,\n data.max_allowed_memberships,\n data.admin_delete_enabled,\n data.members_count,\n data.created_by,\n );\n res._raw = data;\n return res;\n }\n}\n","import type { OrganizationInvitationStatus, OrganizationMembershipRole } from './Enums';\nimport type { OrganizationInvitationJSON, PublicOrganizationDataJSON } from './JSON';\n\n/**\n * The Backend `OrganizationInvitation` object is similar to the [`OrganizationInvitation`](https://clerk.com/docs/references/javascript/types/organization-invitation) object as it's the model around an organization invitation. However, the Backend `OrganizationInvitation` object is different in that it's used in the [Backend API](https://clerk.com/docs/reference/backend-api/tag/Organization-Invitations#operation/CreateOrganizationInvitation){{ target: '_blank' }} and is not directly accessible from the Frontend API.\n */\nexport class OrganizationInvitation {\n private _raw: OrganizationInvitationJSON | null = null;\n\n public get raw(): OrganizationInvitationJSON | null {\n return this._raw;\n }\n\n constructor(\n /**\n * The unique identifier for the `OrganizationInvitation`.\n */\n readonly id: string,\n /**\n * The email address of the user who is invited to the [`Organization`](https://clerk.com/docs/references/backend/types/backend-organization).\n */\n readonly emailAddress: string,\n /**\n * The role of the invited user.\n */\n readonly role: OrganizationMembershipRole,\n /**\n * The name of the role of the invited user.\n */\n readonly roleName: string,\n /**\n * The ID of the [`Organization`](https://clerk.com/docs/references/backend/types/backend-organization) that the user is invited to.\n */\n readonly organizationId: string,\n /**\n * The date when the invitation was first created.\n */\n readonly createdAt: number,\n /**\n * The date when the invitation was last updated.\n */\n readonly updatedAt: number,\n /**\n * The date when the invitation expires.\n */\n readonly expiresAt: number,\n /**\n * The URL that the user can use to accept the invitation.\n */\n readonly url: string | null,\n /**\n * The status of the invitation.\n */\n readonly status?: OrganizationInvitationStatus,\n /**\n * Metadata that can be read from the Frontend API and [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }} and can be set only from the Backend API.\n */\n readonly publicMetadata: OrganizationInvitationPublicMetadata = {},\n /**\n * Metadata that can be read and set only from the [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }}.\n */\n readonly privateMetadata: OrganizationInvitationPrivateMetadata = {},\n /**\n * Public data about the organization that the user is invited to.\n */\n readonly publicOrganizationData?: PublicOrganizationDataJSON | null,\n ) {}\n\n static fromJSON(data: OrganizationInvitationJSON) {\n const res = new OrganizationInvitation(\n data.id,\n data.email_address,\n data.role,\n data.role_name,\n data.organization_id,\n data.created_at,\n data.updated_at,\n data.expires_at,\n data.url,\n data.status,\n data.public_metadata,\n data.private_metadata,\n data.public_organization_data,\n );\n res._raw = data;\n return res;\n }\n}\n","import { Organization } from '../resources';\nimport type { OrganizationMembershipRole } from './Enums';\nimport type { OrganizationMembershipJSON, OrganizationMembershipPublicUserDataJSON } from './JSON';\n\n/**\n * The Backend `OrganizationMembership` object is similar to the [`OrganizationMembership`](https://clerk.com/docs/references/javascript/types/organization-membership) object as it's the model around an organization membership entity and describes the relationship between users and organizations. However, the Backend `OrganizationMembership` object is different in that it's used in the [Backend API](https://clerk.com/docs/reference/backend-api/tag/Organization-Memberships#operation/CreateOrganizationMembership){{ target: '_blank' }} and is not directly accessible from the Frontend API.\n */\nexport class OrganizationMembership {\n private _raw: OrganizationMembershipJSON | null = null;\n\n public get raw(): OrganizationMembershipJSON | null {\n return this._raw;\n }\n\n constructor(\n /**\n * The unique identifier for the membership.\n */\n readonly id: string,\n /**\n * The role of the user.\n */\n readonly role: OrganizationMembershipRole,\n /**\n * The permissions granted to the user in the organization.\n */\n readonly permissions: string[],\n /**\n * Metadata that can be read from the Frontend API and [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }} and can be set only from the Backend API.\n */\n readonly publicMetadata: OrganizationMembershipPublicMetadata = {},\n /**\n * Metadata that can be read and set only from the [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }}.\n */\n readonly privateMetadata: OrganizationMembershipPrivateMetadata = {},\n /**\n * The date when the membership was first created.\n */\n readonly createdAt: number,\n /**\n * The date when the membership was last updated.\n */\n readonly updatedAt: number,\n /**\n * The organization that the user is a member of.\n */\n readonly organization: Organization,\n /**\n * Public information about the user that this membership belongs to.\n */\n readonly publicUserData?: OrganizationMembershipPublicUserData | null,\n ) {}\n\n static fromJSON(data: OrganizationMembershipJSON) {\n const res = new OrganizationMembership(\n data.id,\n data.role,\n data.permissions,\n data.public_metadata,\n data.private_metadata,\n data.created_at,\n data.updated_at,\n Organization.fromJSON(data.organization),\n OrganizationMembershipPublicUserData.fromJSON(data.public_user_data),\n );\n res._raw = data;\n return res;\n }\n}\n\n/**\n * @class\n */\nexport class OrganizationMembershipPublicUserData {\n constructor(\n /**\n * The [identifier](https://clerk.com/docs/authentication/configuration/sign-up-sign-in-options#identifiers) of the user.\n */\n readonly identifier: string,\n /**\n * The first name of the user.\n */\n readonly firstName: string | null,\n /**\n * The last name of the user.\n */\n readonly lastName: string | null,\n /**\n * Holds the default avatar or user's uploaded profile image. Compatible with Clerk's [Image Optimization](https://clerk.com/docs/guides/image-optimization).\n */\n readonly imageUrl: string,\n /**\n * Whether the user has a profile picture.\n */\n readonly hasImage: boolean,\n /**\n * The ID of the user that this public data belongs to.\n */\n readonly userId: string,\n ) {}\n\n static fromJSON(data: OrganizationMembershipPublicUserDataJSON) {\n return new OrganizationMembershipPublicUserData(\n data.identifier,\n data.first_name,\n data.last_name,\n data.image_url,\n data.has_image,\n data.user_id,\n );\n }\n}\n","import type { DomainsEnrollmentModes } from './Enums';\nimport type { OrganizationSettingsJSON } from './JSON';\n\nexport class OrganizationSettings {\n constructor(\n readonly enabled: boolean,\n readonly maxAllowedMemberships: number,\n readonly maxAllowedRoles: number,\n readonly maxAllowedPermissions: number,\n readonly creatorRole: string,\n readonly adminDeleteEnabled: boolean,\n readonly domainsEnabled: boolean,\n readonly domainsEnrollmentModes: Array,\n readonly domainsDefaultRole: string,\n ) {}\n\n static fromJSON(data: OrganizationSettingsJSON): OrganizationSettings {\n return new OrganizationSettings(\n data.enabled,\n data.max_allowed_memberships,\n data.max_allowed_roles,\n data.max_allowed_permissions,\n data.creator_role,\n data.admin_delete_enabled,\n data.domains_enabled,\n data.domains_enrollment_modes,\n data.domains_default_role,\n );\n }\n}\n","import { IdentificationLink } from './IdentificationLink';\nimport type { PhoneNumberJSON } from './JSON';\nimport { Verification } from './Verification';\n\n/**\n * The Backend `PhoneNumber` object describes a phone number. Phone numbers can be used as a proof of identification for users, or simply as a means of contacting users.\n *\n * Phone numbers must be **verified** to ensure that they can be assigned to their rightful owners. The `PhoneNumber` object holds all the necessary state around the verification process.\n *\n * Finally, phone numbers can be used as part of [multi-factor authentication](https://clerk.com/docs/authentication/configuration/sign-up-sign-in-options#multi-factor-authentication). During sign in, users can opt in to an extra verification step where they will receive an SMS message with a one-time code. This code must be entered to complete the sign in process.\n */\nexport class PhoneNumber {\n constructor(\n /**\n * The unique identifier for this phone number.\n */\n readonly id: string,\n /**\n * The value of this phone number, in [E.164 format](https://en.wikipedia.org/wiki/E.164).\n */\n readonly phoneNumber: string,\n /**\n * Set to `true` if this phone number is reserved for multi-factor authentication (2FA). Set to `false` otherwise.\n */\n readonly reservedForSecondFactor: boolean,\n /**\n * Set to `true` if this phone number is the default second factor. Set to `false` otherwise. A user must have exactly one default second factor, if multi-factor authentication (2FA) is enabled.\n */\n readonly defaultSecondFactor: boolean,\n /**\n * An object holding information on the verification of this phone number.\n */\n readonly verification: Verification | null,\n /**\n * An object containing information about any other identification that might be linked to this phone number.\n */\n readonly linkedTo: IdentificationLink[],\n ) {}\n\n static fromJSON(data: PhoneNumberJSON): PhoneNumber {\n return new PhoneNumber(\n data.id,\n data.phone_number,\n data.reserved_for_second_factor,\n data.default_second_factor,\n data.verification && Verification.fromJSON(data.verification),\n data.linked_to.map(link => IdentificationLink.fromJSON(link)),\n );\n }\n}\n","import type { ProxyCheckJSON } from './JSON';\n\nexport class ProxyCheck {\n constructor(\n readonly id: string,\n readonly domainId: string,\n readonly lastRunAt: number | null,\n readonly proxyUrl: string,\n readonly successful: boolean,\n readonly createdAt: number,\n readonly updatedAt: number,\n ) {}\n\n static fromJSON(data: ProxyCheckJSON): ProxyCheck {\n return new ProxyCheck(\n data.id,\n data.domain_id,\n data.last_run_at,\n data.proxy_url,\n data.successful,\n data.created_at,\n data.updated_at,\n );\n }\n}\n","import type { RedirectUrlJSON } from './JSON';\n\n/**\n * Redirect URLs are whitelisted URLs that facilitate secure authentication flows in native applications (e.g. React Native, Expo). In these contexts, Clerk ensures that security-critical nonces are passed only to the whitelisted URLs.\n\nThe Backend `RedirectUrl` object represents a redirect URL in your application. This object is used in the Backend API.\n */\nexport class RedirectUrl {\n constructor(\n /**\n * The unique identifier for the redirect URL.\n */\n readonly id: string,\n /**\n * The full URL value prefixed with `https://` or a custom scheme.\n * @example https://my-app.com/oauth-callback\n * @example my-app://oauth-callback\n */\n readonly url: string,\n /**\n * The date when the redirect URL was first created.\n */\n readonly createdAt: number,\n /**\n * The date when the redirect URL was last updated.\n */\n readonly updatedAt: number,\n ) {}\n\n static fromJSON(data: RedirectUrlJSON): RedirectUrl {\n return new RedirectUrl(data.id, data.url, data.created_at, data.updated_at);\n }\n}\n","import type { AttributeMappingJSON, SamlAccountConnectionJSON, SamlConnectionJSON } from './JSON';\n\n/**\n * The Backend `SamlConnection` object holds information about a SAML connection for an organization.\n */\nexport class SamlConnection {\n constructor(\n /**\n * The unique identifier for the connection.\n */\n readonly id: string,\n /**\n * The name to use as a label for the connection.\n */\n readonly name: string,\n /**\n * The domain of your organization. Sign in flows using an email with this domain will use the connection.\n */\n readonly domain: string,\n /**\n * The organization ID of the organization.\n */\n readonly organizationId: string | null,\n /**\n * The Entity ID as provided by the Identity Provider (IdP).\n */\n readonly idpEntityId: string | null,\n /**\n * The Single-Sign On URL as provided by the Identity Provider (IdP).\n */\n readonly idpSsoUrl: string | null,\n /**\n * The X.509 certificate as provided by the Identity Provider (IdP).\n */\n readonly idpCertificate: string | null,\n /**\n * The URL which serves the Identity Provider (IdP) metadata. If present, it takes priority over the corresponding individual properties.\n */\n readonly idpMetadataUrl: string | null,\n /**\n * The XML content of the Identity Provider (IdP) metadata file. If present, it takes priority over the corresponding individual properties.\n */\n readonly idpMetadata: string | null,\n /**\n * The Assertion Consumer Service (ACS) URL of the connection.\n */\n readonly acsUrl: string,\n /**\n * The Entity ID as provided by the Service Provider (Clerk).\n */\n readonly spEntityId: string,\n /**\n * The metadata URL as provided by the Service Provider (Clerk).\n */\n readonly spMetadataUrl: string,\n /**\n * Indicates whether the connection is active or not.\n */\n readonly active: boolean,\n /**\n * The Identity Provider (IdP) of the connection.\n */\n readonly provider: string,\n /**\n * The number of users associated with the connection.\n */\n readonly userCount: number,\n /**\n * Indicates whether the connection syncs user attributes between the Service Provider (SP) and Identity Provider (IdP) or not.\n */\n readonly syncUserAttributes: boolean,\n /**\n * Indicates whether users with an email address subdomain are allowed to use this connection in order to authenticate or not.\n */\n readonly allowSubdomains: boolean,\n /**\n * Indicates whether the connection allows Identity Provider (IdP) initiated flows or not.\n */\n readonly allowIdpInitiated: boolean,\n /**\n * The date when the connection was first created.\n */\n readonly createdAt: number,\n /**\n * The date when the SAML connection was last updated.\n */\n readonly updatedAt: number,\n /**\n * Defines the attribute name mapping between the Identity Provider (IdP) and Clerk's [`User`](https://clerk.com/docs/references/javascript/user) properties.\n */\n readonly attributeMapping: AttributeMapping,\n ) {}\n static fromJSON(data: SamlConnectionJSON): SamlConnection {\n return new SamlConnection(\n data.id,\n data.name,\n data.domain,\n data.organization_id,\n data.idp_entity_id,\n data.idp_sso_url,\n data.idp_certificate,\n data.idp_metadata_url,\n data.idp_metadata,\n data.acs_url,\n data.sp_entity_id,\n data.sp_metadata_url,\n data.active,\n data.provider,\n data.user_count,\n data.sync_user_attributes,\n data.allow_subdomains,\n data.allow_idp_initiated,\n data.created_at,\n data.updated_at,\n data.attribute_mapping && AttributeMapping.fromJSON(data.attribute_mapping),\n );\n }\n}\n\nexport class SamlAccountConnection {\n constructor(\n readonly id: string,\n readonly name: string,\n readonly domain: string,\n readonly active: boolean,\n readonly provider: string,\n readonly syncUserAttributes: boolean,\n readonly allowSubdomains: boolean,\n readonly allowIdpInitiated: boolean,\n readonly createdAt: number,\n readonly updatedAt: number,\n ) {}\n static fromJSON(data: SamlAccountConnectionJSON): SamlAccountConnection {\n return new SamlAccountConnection(\n data.id,\n data.name,\n data.domain,\n data.active,\n data.provider,\n data.sync_user_attributes,\n data.allow_subdomains,\n data.allow_idp_initiated,\n data.created_at,\n data.updated_at,\n );\n }\n}\n\nclass AttributeMapping {\n constructor(\n /**\n * The user ID attribute name.\n */\n readonly userId: string,\n /**\n * The email address attribute name.\n */\n readonly emailAddress: string,\n /**\n * The first name attribute name.\n */\n readonly firstName: string,\n /**\n * The last name attribute name.\n */\n readonly lastName: string,\n ) {}\n\n static fromJSON(data: AttributeMappingJSON): AttributeMapping {\n return new AttributeMapping(data.user_id, data.email_address, data.first_name, data.last_name);\n }\n}\n","import type { SamlAccountJSON } from './JSON';\nimport { SamlAccountConnection } from './SamlConnection';\nimport { Verification } from './Verification';\n\n/**\n * The Backend `SamlAccount` object describes a SAML account.\n */\nexport class SamlAccount {\n constructor(\n /**\n * The unique identifier for the SAML account.\n */\n readonly id: string,\n /**\n * The provider of the SAML account.\n */\n readonly provider: string,\n /**\n * The user's ID as used in the provider.\n */\n readonly providerUserId: string | null,\n /**\n * A boolean that indicates whether the SAML account is active.\n */\n readonly active: boolean,\n /**\n * The email address of the SAML account.\n */\n readonly emailAddress: string,\n /**\n * The first name of the SAML account.\n */\n readonly firstName: string,\n /**\n * The last name of the SAML account.\n */\n readonly lastName: string,\n /**\n * The verification of the SAML account.\n */\n readonly verification: Verification | null,\n /**\n * The SAML connection of the SAML account.\n */\n readonly samlConnection: SamlAccountConnection | null,\n ) {}\n\n static fromJSON(data: SamlAccountJSON): SamlAccount {\n return new SamlAccount(\n data.id,\n data.provider,\n data.provider_user_id,\n data.active,\n data.email_address,\n data.first_name,\n data.last_name,\n data.verification && Verification.fromJSON(data.verification),\n data.saml_connection && SamlAccountConnection.fromJSON(data.saml_connection),\n );\n }\n}\n","import type { SignInTokenJSON } from './JSON';\n\nexport class SignInToken {\n constructor(\n readonly id: string,\n readonly userId: string,\n readonly token: string,\n readonly status: string,\n readonly url: string,\n readonly createdAt: number,\n readonly updatedAt: number,\n ) {}\n\n static fromJSON(data: SignInTokenJSON): SignInToken {\n return new SignInToken(data.id, data.user_id, data.token, data.status, data.url, data.created_at, data.updated_at);\n }\n}\n","import type { SignUpStatus } from '@clerk/types';\n\nimport type { SignUpVerificationNextAction } from './Enums';\nimport type { SignUpJSON, SignUpVerificationJSON, SignUpVerificationsJSON } from './JSON';\n\nexport class SignUpAttemptVerification {\n constructor(\n readonly nextAction: SignUpVerificationNextAction,\n readonly supportedStrategies: string[],\n ) {}\n\n static fromJSON(data: SignUpVerificationJSON): SignUpAttemptVerification {\n return new SignUpAttemptVerification(data.next_action, data.supported_strategies);\n }\n}\n\nexport class SignUpAttemptVerifications {\n constructor(\n readonly emailAddress: SignUpAttemptVerification | null,\n readonly phoneNumber: SignUpAttemptVerification | null,\n readonly web3Wallet: SignUpAttemptVerification | null,\n readonly externalAccount: object | null,\n ) {}\n\n static fromJSON(data: SignUpVerificationsJSON): SignUpAttemptVerifications {\n return new SignUpAttemptVerifications(\n data.email_address && SignUpAttemptVerification.fromJSON(data.email_address),\n data.phone_number && SignUpAttemptVerification.fromJSON(data.phone_number),\n data.web3_wallet && SignUpAttemptVerification.fromJSON(data.web3_wallet),\n data.external_account,\n );\n }\n}\n\nexport class SignUpAttempt {\n constructor(\n readonly id: string,\n readonly status: SignUpStatus,\n readonly requiredFields: string[],\n readonly optionalFields: string[],\n readonly missingFields: string[],\n readonly unverifiedFields: string[],\n readonly verifications: SignUpAttemptVerifications | null,\n readonly username: string | null,\n readonly emailAddress: string | null,\n readonly phoneNumber: string | null,\n readonly web3Wallet: string | null,\n readonly passwordEnabled: boolean,\n readonly firstName: string | null,\n readonly lastName: string | null,\n readonly customAction: boolean,\n readonly externalId: string | null,\n readonly createdSessionId: string | null,\n readonly createdUserId: string | null,\n readonly abandonAt: number | null,\n readonly legalAcceptedAt: number | null,\n readonly publicMetadata?: Record | null,\n readonly unsafeMetadata?: Record | null,\n ) {}\n\n static fromJSON(data: SignUpJSON): SignUpAttempt {\n return new SignUpAttempt(\n data.id,\n data.status,\n data.required_fields,\n data.optional_fields,\n data.missing_fields,\n data.unverified_fields,\n data.verifications ? SignUpAttemptVerifications.fromJSON(data.verifications) : null,\n data.username,\n data.email_address,\n data.phone_number,\n data.web3_wallet,\n data.password_enabled,\n data.first_name,\n data.last_name,\n data.custom_action,\n data.external_id,\n data.created_session_id,\n data.created_user_id,\n data.abandon_at,\n data.legal_accepted_at,\n data.public_metadata,\n data.unsafe_metadata,\n );\n }\n}\n","import type { SMSMessageJSON } from './JSON';\n\nexport class SMSMessage {\n constructor(\n readonly id: string,\n readonly fromPhoneNumber: string,\n readonly toPhoneNumber: string,\n readonly message: string,\n readonly status: string,\n readonly phoneNumberId: string | null,\n readonly data?: Record | null,\n ) {}\n\n static fromJSON(data: SMSMessageJSON): SMSMessage {\n return new SMSMessage(\n data.id,\n data.from_phone_number,\n data.to_phone_number,\n data.message,\n data.status,\n data.phone_number_id,\n data.data,\n );\n }\n}\n","import type { TokenJSON } from './JSON';\n\nexport class Token {\n constructor(readonly jwt: string) {}\n\n static fromJSON(data: TokenJSON): Token {\n return new Token(data.jwt);\n }\n}\n","import type { Web3WalletJSON } from './JSON';\nimport { Verification } from './Verification';\n\n/**\n * The Backend `Web3Wallet` object describes a Web3 wallet address. The address can be used as a proof of identification for users.\n *\n * Web3 addresses must be verified to ensure that they can be assigned to their rightful owners. The verification is completed via Web3 wallet browser extensions, such as [Metamask](https://metamask.io/), [Coinbase Wallet](https://www.coinbase.com/wallet), and [OKX Wallet](https://www.okx.com/help/section/faq-web3-wallet). The `Web3Wallet3` object holds all the necessary state around the verification process.\n */\nexport class Web3Wallet {\n constructor(\n /**\n * The unique ID for the Web3 wallet.\n */\n readonly id: string,\n /**\n * The Web3 wallet address, made up of 0x + 40 hexadecimal characters.\n */\n readonly web3Wallet: string,\n /**\n * An object holding information on the verification of this Web3 wallet.\n */\n readonly verification: Verification | null,\n ) {}\n\n static fromJSON(data: Web3WalletJSON): Web3Wallet {\n return new Web3Wallet(data.id, data.web3_wallet, data.verification && Verification.fromJSON(data.verification));\n }\n}\n","import { EmailAddress } from './EmailAddress';\nimport { ExternalAccount } from './ExternalAccount';\nimport type { ExternalAccountJSON, SamlAccountJSON, UserJSON } from './JSON';\nimport { PhoneNumber } from './PhoneNumber';\nimport { SamlAccount } from './SamlAccount';\nimport { Web3Wallet } from './Web3Wallet';\n\n/**\n * The Backend `User` object is similar to the `User` object as it holds information about a user of your application, such as their unique identifier, name, email addresses, phone numbers, and more. However, the Backend `User` object is different from the `User` object in that it is used in the [Backend API](https://clerk.com/docs/reference/backend-api/tag/Users#operation/GetUser){{ target: '_blank' }} and is not directly accessible from the Frontend API.\n */\nexport class User {\n private _raw: UserJSON | null = null;\n\n public get raw(): UserJSON | null {\n return this._raw;\n }\n\n constructor(\n /**\n * The unique identifier for the user.\n */\n readonly id: string,\n /**\n * A boolean indicating whether the user has a password on their account.\n */\n readonly passwordEnabled: boolean,\n /**\n * A boolean indicating whether the user has enabled TOTP by generating a TOTP secret and verifying it via an authenticator app.\n */\n readonly totpEnabled: boolean,\n /**\n * A boolean indicating whether the user has enabled Backup codes.\n */\n readonly backupCodeEnabled: boolean,\n /**\n * A boolean indicating whether the user has enabled two-factor authentication.\n */\n readonly twoFactorEnabled: boolean,\n /**\n * A boolean indicating whether the user is banned or not.\n */\n readonly banned: boolean,\n /**\n * A boolean indicating whether the user is banned or not.\n */\n readonly locked: boolean,\n /**\n * The date when the user was first created.\n */\n readonly createdAt: number,\n /**\n * The date when the user was last updated.\n */\n readonly updatedAt: number,\n /**\n * The URL of the user's profile image.\n */\n readonly imageUrl: string,\n /**\n * A getter boolean to check if the user has uploaded an image or one was copied from OAuth. Returns `false` if Clerk is displaying an avatar for the user.\n */\n readonly hasImage: boolean,\n /**\n * The ID for the `EmailAddress` that the user has set as primary.\n */\n readonly primaryEmailAddressId: string | null,\n /**\n * The ID for the `PhoneNumber` that the user has set as primary.\n */\n readonly primaryPhoneNumberId: string | null,\n /**\n * The ID for the [`Web3Wallet`](https://clerk.com/docs/references/backend/types/backend-web3-wallet) that the user signed up with.\n */\n readonly primaryWeb3WalletId: string | null,\n /**\n * The date when the user last signed in. May be empty if the user has never signed in.\n */\n readonly lastSignInAt: number | null,\n /**\n * The ID of the user as used in your external systems. Must be unique across your instance.\n */\n readonly externalId: string | null,\n /**\n * The user's username.\n */\n readonly username: string | null,\n /**\n * The user's first name.\n */\n readonly firstName: string | null,\n /**\n * The user's last name.\n */\n readonly lastName: string | null,\n /**\n * Metadata that can be read from the Frontend API and [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }} and can be set only from the Backend API.\n */\n readonly publicMetadata: UserPublicMetadata = {},\n /**\n * Metadata that can be read and set only from the [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }}.\n */\n readonly privateMetadata: UserPrivateMetadata = {},\n /**\n * Metadata that can be read and set from the Frontend API. It's considered unsafe because it can be modified from the frontend.\n */\n readonly unsafeMetadata: UserUnsafeMetadata = {},\n /**\n * An array of all the `EmailAddress` objects associated with the user. Includes the primary.\n */\n readonly emailAddresses: EmailAddress[] = [],\n /**\n * An array of all the `PhoneNumber` objects associated with the user. Includes the primary.\n */\n readonly phoneNumbers: PhoneNumber[] = [],\n /**\n * An array of all the `Web3Wallet` objects associated with the user. Includes the primary.\n */\n readonly web3Wallets: Web3Wallet[] = [],\n /**\n * An array of all the `ExternalAccount` objects associated with the user via OAuth. **Note**: This includes both verified & unverified external accounts.\n */\n readonly externalAccounts: ExternalAccount[] = [],\n /**\n * An array of all the `SamlAccount` objects associated with the user via SAML.\n */\n readonly samlAccounts: SamlAccount[] = [],\n /**\n * Date when the user was last active.\n */\n readonly lastActiveAt: number | null,\n /**\n * A boolean indicating whether the organization creation is enabled for the user or not.\n */\n readonly createOrganizationEnabled: boolean,\n /**\n * An integer indicating the number of organizations that can be created by the user. If the value is `0`, then the user can create unlimited organizations. Default is `null`.\n */\n readonly createOrganizationsLimit: number | null = null,\n /**\n * A boolean indicating whether the user can delete their own account.\n */\n readonly deleteSelfEnabled: boolean,\n /**\n * The unix timestamp of when the user accepted the legal requirements. `null` if [**Require express consent to legal documents**](https://clerk.com/docs/authentication/configuration/legal-compliance) is not enabled.\n */\n readonly legalAcceptedAt: number | null,\n ) {}\n\n static fromJSON(data: UserJSON): User {\n const res = new User(\n data.id,\n data.password_enabled,\n data.totp_enabled,\n data.backup_code_enabled,\n data.two_factor_enabled,\n data.banned,\n data.locked,\n data.created_at,\n data.updated_at,\n data.image_url,\n data.has_image,\n data.primary_email_address_id,\n data.primary_phone_number_id,\n data.primary_web3_wallet_id,\n data.last_sign_in_at,\n data.external_id,\n data.username,\n data.first_name,\n data.last_name,\n data.public_metadata,\n data.private_metadata,\n data.unsafe_metadata,\n (data.email_addresses || []).map(x => EmailAddress.fromJSON(x)),\n (data.phone_numbers || []).map(x => PhoneNumber.fromJSON(x)),\n (data.web3_wallets || []).map(x => Web3Wallet.fromJSON(x)),\n (data.external_accounts || []).map((x: ExternalAccountJSON) => ExternalAccount.fromJSON(x)),\n (data.saml_accounts || []).map((x: SamlAccountJSON) => SamlAccount.fromJSON(x)),\n data.last_active_at,\n data.create_organization_enabled,\n data.create_organizations_limit,\n data.delete_self_enabled,\n data.legal_accepted_at,\n );\n res._raw = data;\n return res;\n }\n\n /**\n * The primary email address of the user.\n */\n get primaryEmailAddress() {\n return this.emailAddresses.find(({ id }) => id === this.primaryEmailAddressId) ?? null;\n }\n\n /**\n * The primary phone number of the user.\n */\n get primaryPhoneNumber() {\n return this.phoneNumbers.find(({ id }) => id === this.primaryPhoneNumberId) ?? null;\n }\n\n /**\n * The primary web3 wallet of the user.\n */\n get primaryWeb3Wallet() {\n return this.web3Wallets.find(({ id }) => id === this.primaryWeb3WalletId) ?? null;\n }\n\n /**\n * The full name of the user.\n */\n get fullName() {\n return [this.firstName, this.lastName].join(' ').trim() || null;\n }\n}\n","import type { WaitlistEntryStatus } from './Enums';\nimport { Invitation } from './Invitation';\nimport type { WaitlistEntryJSON } from './JSON';\n\nexport class WaitlistEntry {\n constructor(\n readonly id: string,\n readonly emailAddress: string,\n readonly status: WaitlistEntryStatus,\n readonly invitation: Invitation | null,\n readonly createdAt: number,\n readonly updatedAt: number,\n readonly isLocked?: boolean,\n ) {}\n\n static fromJSON(data: WaitlistEntryJSON): WaitlistEntry {\n return new WaitlistEntry(\n data.id,\n data.email_address,\n data.status,\n data.invitation && Invitation.fromJSON(data.invitation),\n data.created_at,\n data.updated_at,\n data.is_locked,\n );\n }\n}\n","import type { FeatureJSON } from './JSON';\n\n/**\n * The `Feature` object represents a feature of a subscription plan.\n *\n * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes.\n */\nexport class Feature {\n constructor(\n /**\n * The unique identifier for the feature.\n */\n readonly id: string,\n /**\n * The name of the feature.\n */\n readonly name: string,\n /**\n * The description of the feature.\n */\n readonly description: string,\n /**\n * The URL-friendly identifier of the feature.\n */\n readonly slug: string,\n /**\n * The URL of the feature's avatar image.\n */\n readonly avatarUrl: string,\n ) {}\n\n static fromJSON(data: FeatureJSON): Feature {\n return new Feature(data.id, data.name, data.description, data.slug, data.avatar_url);\n }\n}\n","import type { BillingMoneyAmount } from '@clerk/types';\n\nimport { Feature } from './Feature';\nimport type { BillingPlanJSON } from './JSON';\n\n/**\n * The `BillingPlan` object is similar to the [`BillingPlanResource`](/docs/references/javascript/types/billing-plan-resource) object as it holds information about a plan, as well as methods for managing it. However, the `BillingPlan` object is different in that it is used in the [Backend API](https://clerk.com/docs/reference/backend-api/tag/commerce/get/commerce/plans) and is not directly accessible from the Frontend API.\n *\n * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes.\n */\nexport class BillingPlan {\n constructor(\n /**\n * The unique identifier for the plan.\n */\n readonly id: string,\n /**\n * The ID of the product the plan belongs to.\n */\n readonly productId: string,\n /**\n * The name of the plan.\n */\n readonly name: string,\n /**\n * The URL-friendly identifier of the plan.\n */\n readonly slug: string,\n /**\n * The description of the plan.\n */\n readonly description: string | undefined,\n /**\n * Whether the plan is the default plan.\n */\n readonly isDefault: boolean,\n /**\n * Whether the plan is recurring.\n */\n readonly isRecurring: boolean,\n /**\n * Whether the plan has a base fee.\n */\n readonly hasBaseFee: boolean,\n /**\n * Whether the plan is displayed in the `` component.\n */\n readonly publiclyVisible: boolean,\n /**\n * The monthly fee of the plan.\n */\n readonly fee: BillingMoneyAmount,\n /**\n * The annual fee of the plan.\n */\n readonly annualFee: BillingMoneyAmount,\n /**\n * The annual fee of the plan on a monthly basis.\n */\n readonly annualMonthlyFee: BillingMoneyAmount,\n /**\n * The type of payer for the plan.\n */\n readonly forPayerType: 'org' | 'user',\n /**\n * The features the plan offers.\n */\n readonly features: Feature[],\n ) {}\n\n static fromJSON(data: BillingPlanJSON): BillingPlan {\n const formatAmountJSON = (fee: BillingPlanJSON['fee']) => {\n return {\n amount: fee.amount,\n amountFormatted: fee.amount_formatted,\n currency: fee.currency,\n currencySymbol: fee.currency_symbol,\n };\n };\n return new BillingPlan(\n data.id,\n data.product_id,\n data.name,\n data.slug,\n data.description,\n data.is_default,\n data.is_recurring,\n data.has_base_fee,\n data.publicly_visible,\n formatAmountJSON(data.fee),\n formatAmountJSON(data.annual_fee),\n formatAmountJSON(data.annual_monthly_fee),\n data.for_payer_type,\n data.features.map(feature => Feature.fromJSON(feature)),\n );\n }\n}\n","import type { BillingMoneyAmount, BillingMoneyAmountJSON } from '@clerk/types';\n\nimport { BillingPlan } from './CommercePlan';\nimport type { BillingSubscriptionItemJSON } from './JSON';\n\n/**\n * The `BillingSubscriptionItem` object is similar to the [`BillingSubscriptionItemResource`](/docs/references/javascript/types/commerce-subscription-item-resource) object as it holds information about a subscription item, as well as methods for managing it. However, the `BillingSubscriptionItem` object is different in that it is used in the [Backend API](https://clerk.com/docs/reference/backend-api/tag/commerce/get/commerce/subscription_items) and is not directly accessible from the Frontend API.\n *\n * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes.\n */\nexport class BillingSubscriptionItem {\n constructor(\n /**\n * The unique identifier for the subscription item.\n */\n readonly id: string,\n /**\n * The status of the subscription item.\n */\n readonly status: BillingSubscriptionItemJSON['status'],\n /**\n * The plan period for the subscription item.\n */\n readonly planPeriod: 'month' | 'annual',\n /**\n * Unix timestamp (milliseconds) of when the current period starts.\n */\n readonly periodStart: number,\n /**\n * The next payment information.\n */\n readonly nextPayment: {\n /**\n * The amount of the next payment.\n */\n amount: number;\n /**\n * Unix timestamp (milliseconds) of when the next payment is scheduled.\n */\n date: number;\n } | null,\n /**\n * The current amount for the subscription item.\n */\n readonly amount: BillingMoneyAmount | null | undefined,\n /**\n * The plan associated with this subscription item.\n */\n readonly plan: BillingPlan,\n /**\n * The plan ID.\n */\n readonly planId: string,\n /**\n * Unix timestamp (milliseconds) of when the subscription item was created.\n */\n readonly createdAt: number,\n /**\n * Unix timestamp (milliseconds) of when the subscription item was last updated.\n */\n readonly updatedAt: number,\n /**\n * Unix timestamp (milliseconds) of when the current period ends.\n */\n readonly periodEnd: number | null,\n /**\n * Unix timestamp (milliseconds) of when the subscription item was canceled.\n */\n readonly canceledAt: number | null,\n /**\n * Unix timestamp (milliseconds) of when the subscription item became past due.\n */\n readonly pastDueAt: number | null,\n /**\n * Unix timestamp (milliseconds) of when the subscription item ended.\n */\n readonly endedAt: number | null,\n /**\n * The payer ID.\n */\n readonly payerId: string,\n /**\n * Whether this subscription item is currently in a free trial period.\n */\n readonly isFreeTrial?: boolean,\n /**\n * The lifetime amount paid for this subscription item.\n */\n readonly lifetimePaid?: BillingMoneyAmount | null,\n ) {}\n\n static fromJSON(data: BillingSubscriptionItemJSON): BillingSubscriptionItem {\n function formatAmountJSON(\n amount: BillingMoneyAmountJSON | null | undefined,\n ): BillingMoneyAmount | null | undefined {\n if (!amount) {\n return amount;\n }\n\n return {\n amount: amount.amount,\n amountFormatted: amount.amount_formatted,\n currency: amount.currency,\n currencySymbol: amount.currency_symbol,\n };\n }\n\n return new BillingSubscriptionItem(\n data.id,\n data.status,\n data.plan_period,\n data.period_start,\n data.next_payment,\n formatAmountJSON(data.amount),\n BillingPlan.fromJSON(data.plan),\n data.plan_id,\n data.created_at,\n data.updated_at,\n data.period_end,\n data.canceled_at,\n data.past_due_at,\n data.ended_at,\n data.payer_id,\n data.is_free_trial,\n formatAmountJSON(data.lifetime_paid),\n );\n }\n}\n","import type { BillingMoneyAmount } from '@clerk/types';\n\nimport { BillingSubscriptionItem } from './CommerceSubscriptionItem';\nimport type { BillingSubscriptionJSON } from './JSON';\n\n/**\n * The `BillingSubscription` object is similar to the [`BillingSubscriptionResource`](/docs/references/javascript/types/commerce-subscription-resource) object as it holds information about a subscription, as well as methods for managing it. However, the `BillingSubscription` object is different in that it is used in the [Backend API](https://clerk.com/docs/reference/backend-api/tag/billing/get/organizations/%7Borganization_id%7D/billing/subscription) and is not directly accessible from the Frontend API.\n *\n * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes.\n */\nexport class BillingSubscription {\n constructor(\n /**\n * The unique identifier for the billing subscription.\n */\n readonly id: string,\n /**\n * The current status of the subscription.\n */\n readonly status: BillingSubscriptionJSON['status'],\n /**\n * The ID of the payer for this subscription.\n */\n readonly payerId: string,\n /**\n * Unix timestamp (milliseconds) of when the subscription was created.\n */\n readonly createdAt: number,\n /**\n * Unix timestamp (milliseconds) of when the subscription was last updated.\n */\n readonly updatedAt: number,\n /**\n * Unix timestamp (milliseconds) of when the subscription became active.\n */\n readonly activeAt: number | null,\n /**\n * Unix timestamp (milliseconds) of when the subscription became past due.\n */\n readonly pastDueAt: number | null,\n /**\n * Array of subscription items in this subscription.\n */\n readonly subscriptionItems: BillingSubscriptionItem[],\n /**\n * Information about the next scheduled payment.\n */\n readonly nextPayment: { date: number; amount: BillingMoneyAmount } | null,\n /**\n * Whether the payer is eligible for a free trial.\n */\n readonly eligibleForFreeTrial: boolean,\n ) {}\n\n static fromJSON(data: BillingSubscriptionJSON): BillingSubscription {\n const nextPayment = data.next_payment\n ? {\n date: data.next_payment.date,\n amount: {\n amount: data.next_payment.amount.amount,\n amountFormatted: data.next_payment.amount.amount_formatted,\n currency: data.next_payment.amount.currency,\n currencySymbol: data.next_payment.amount.currency_symbol,\n },\n }\n : null;\n\n return new BillingSubscription(\n data.id,\n data.status,\n data.payer_id,\n data.created_at,\n data.updated_at,\n data.active_at ?? null,\n data.past_due_at ?? null,\n data.subscription_items.map(item => BillingSubscriptionItem.fromJSON(item)),\n nextPayment,\n data.eligible_for_free_trial ?? false,\n );\n }\n}\n","import {\n ActorToken,\n AllowlistIdentifier,\n APIKey,\n BlocklistIdentifier,\n Client,\n Cookies,\n DeletedObject,\n Domain,\n Email,\n EmailAddress,\n IdPOAuthAccessToken,\n Instance,\n InstanceRestrictions,\n InstanceSettings,\n Invitation,\n JwtTemplate,\n M2MToken,\n Machine,\n MachineScope,\n MachineSecretKey,\n OauthAccessToken,\n OAuthApplication,\n Organization,\n OrganizationInvitation,\n OrganizationMembership,\n OrganizationSettings,\n PhoneNumber,\n ProxyCheck,\n RedirectUrl,\n SamlConnection,\n Session,\n SignInToken,\n SignUpAttempt,\n SMSMessage,\n Token,\n User,\n} from '.';\nimport { AccountlessApplication } from './AccountlessApplication';\nimport { BillingPlan } from './CommercePlan';\nimport { BillingSubscription } from './CommerceSubscription';\nimport { BillingSubscriptionItem } from './CommerceSubscriptionItem';\nimport { Feature } from './Feature';\nimport type { PaginatedResponseJSON } from './JSON';\nimport { ObjectType } from './JSON';\nimport { WaitlistEntry } from './WaitlistEntry';\n\ntype ResourceResponse = {\n /**\n * An array that contains the fetched data.\n */\n data: T;\n};\n\n/**\n * An interface that describes the response of a method that returns a paginated list of resources.\n *\n * If the promise resolves, you will get back the [properties](#properties) listed below. `data` will be an array of the resource type you requested. You can use the `totalCount` property to determine how many total items exist remotely.\n *\n * Some methods that return this type allow pagination with the `limit` and `offset` parameters, in which case the first 10 items will be returned by default. For methods such as [`getAllowlistIdentifierList()`](https://clerk.com/docs/references/backend/allowlist/get-allowlist-identifier-list), which do not take a `limit` or `offset`, all items will be returned.\n *\n * If the promise is rejected, you will receive a `ClerkAPIResponseError` or network error.\n *\n * @interface\n */\nexport type PaginatedResourceResponse = ResourceResponse & {\n /**\n * The total count of data that exist remotely.\n */\n totalCount: number;\n};\n\nexport function deserialize(payload: unknown): PaginatedResourceResponse | ResourceResponse {\n let data, totalCount: number | undefined;\n\n if (Array.isArray(payload)) {\n const data = payload.map(item => jsonToObject(item)) as U;\n return { data };\n } else if (isPaginated(payload)) {\n data = payload.data.map(item => jsonToObject(item)) as U;\n totalCount = payload.total_count;\n\n return { data, totalCount };\n } else {\n return { data: jsonToObject(payload) };\n }\n}\n\nfunction isPaginated(payload: unknown): payload is PaginatedResponseJSON {\n if (!payload || typeof payload !== 'object' || !('data' in payload)) {\n return false;\n }\n\n return Array.isArray(payload.data) && payload.data !== undefined;\n}\n\nfunction getCount(item: PaginatedResponseJSON) {\n return item.total_count;\n}\n\n// TODO: Revise response deserialization\nfunction jsonToObject(item: any): any {\n // Special case: DeletedObject\n // TODO: Improve this check\n if (typeof item !== 'string' && 'object' in item && 'deleted' in item) {\n return DeletedObject.fromJSON(item);\n }\n\n switch (item.object) {\n case ObjectType.AccountlessApplication:\n return AccountlessApplication.fromJSON(item);\n case ObjectType.ActorToken:\n return ActorToken.fromJSON(item);\n case ObjectType.AllowlistIdentifier:\n return AllowlistIdentifier.fromJSON(item);\n case ObjectType.ApiKey:\n return APIKey.fromJSON(item);\n case ObjectType.BlocklistIdentifier:\n return BlocklistIdentifier.fromJSON(item);\n case ObjectType.Client:\n return Client.fromJSON(item);\n case ObjectType.Cookies:\n return Cookies.fromJSON(item);\n case ObjectType.Domain:\n return Domain.fromJSON(item);\n case ObjectType.EmailAddress:\n return EmailAddress.fromJSON(item);\n case ObjectType.Email:\n return Email.fromJSON(item);\n case ObjectType.IdpOAuthAccessToken:\n return IdPOAuthAccessToken.fromJSON(item);\n case ObjectType.Instance:\n return Instance.fromJSON(item);\n case ObjectType.InstanceRestrictions:\n return InstanceRestrictions.fromJSON(item);\n case ObjectType.InstanceSettings:\n return InstanceSettings.fromJSON(item);\n case ObjectType.Invitation:\n return Invitation.fromJSON(item);\n case ObjectType.JwtTemplate:\n return JwtTemplate.fromJSON(item);\n case ObjectType.Machine:\n return Machine.fromJSON(item);\n case ObjectType.MachineScope:\n return MachineScope.fromJSON(item);\n case ObjectType.MachineSecretKey:\n return MachineSecretKey.fromJSON(item);\n case ObjectType.M2MToken:\n return M2MToken.fromJSON(item);\n case ObjectType.OauthAccessToken:\n return OauthAccessToken.fromJSON(item);\n case ObjectType.OAuthApplication:\n return OAuthApplication.fromJSON(item);\n case ObjectType.Organization:\n return Organization.fromJSON(item);\n case ObjectType.OrganizationInvitation:\n return OrganizationInvitation.fromJSON(item);\n case ObjectType.OrganizationMembership:\n return OrganizationMembership.fromJSON(item);\n case ObjectType.OrganizationSettings:\n return OrganizationSettings.fromJSON(item);\n case ObjectType.PhoneNumber:\n return PhoneNumber.fromJSON(item);\n case ObjectType.ProxyCheck:\n return ProxyCheck.fromJSON(item);\n case ObjectType.RedirectUrl:\n return RedirectUrl.fromJSON(item);\n case ObjectType.SamlConnection:\n return SamlConnection.fromJSON(item);\n case ObjectType.SignInToken:\n return SignInToken.fromJSON(item);\n case ObjectType.SignUpAttempt:\n return SignUpAttempt.fromJSON(item);\n case ObjectType.Session:\n return Session.fromJSON(item);\n case ObjectType.SmsMessage:\n return SMSMessage.fromJSON(item);\n case ObjectType.Token:\n return Token.fromJSON(item);\n case ObjectType.TotalCount:\n return getCount(item);\n case ObjectType.User:\n return User.fromJSON(item);\n case ObjectType.WaitlistEntry:\n return WaitlistEntry.fromJSON(item);\n case ObjectType.BillingPlan:\n return BillingPlan.fromJSON(item);\n case ObjectType.BillingSubscription:\n return BillingSubscription.fromJSON(item);\n case ObjectType.BillingSubscriptionItem:\n return BillingSubscriptionItem.fromJSON(item);\n case ObjectType.Feature:\n return Feature.fromJSON(item);\n default:\n return item;\n }\n}\n","import {\n AccountlessApplicationAPI,\n ActorTokenAPI,\n AllowlistIdentifierAPI,\n APIKeysAPI,\n BetaFeaturesAPI,\n BlocklistIdentifierAPI,\n ClientAPI,\n DomainAPI,\n EmailAddressAPI,\n IdPOAuthAccessTokenApi,\n InstanceAPI,\n InvitationAPI,\n JwksAPI,\n JwtTemplatesApi,\n M2MTokenApi,\n MachineApi,\n OAuthApplicationsApi,\n OrganizationAPI,\n PhoneNumberAPI,\n ProxyCheckAPI,\n RedirectUrlAPI,\n SamlConnectionAPI,\n SessionAPI,\n SignInTokenAPI,\n SignUpAPI,\n TestingTokenAPI,\n UserAPI,\n WaitlistEntryAPI,\n WebhookAPI,\n} from './endpoints';\nimport { BillingAPI } from './endpoints/BillingApi';\nimport { buildRequest } from './request';\n\nexport type CreateBackendApiOptions = Parameters[0];\n\nexport type ApiClient = ReturnType;\n\nexport function createBackendApiClient(options: CreateBackendApiOptions) {\n const request = buildRequest(options);\n\n return {\n __experimental_accountlessApplications: new AccountlessApplicationAPI(\n buildRequest({ ...options, requireSecretKey: false }),\n ),\n actorTokens: new ActorTokenAPI(request),\n allowlistIdentifiers: new AllowlistIdentifierAPI(request),\n apiKeys: new APIKeysAPI(\n buildRequest({\n ...options,\n skipApiVersionInUrl: true,\n }),\n ),\n betaFeatures: new BetaFeaturesAPI(request),\n blocklistIdentifiers: new BlocklistIdentifierAPI(request),\n /**\n * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes.\n */\n billing: new BillingAPI(request),\n clients: new ClientAPI(request),\n domains: new DomainAPI(request),\n emailAddresses: new EmailAddressAPI(request),\n idPOAuthAccessToken: new IdPOAuthAccessTokenApi(\n buildRequest({\n ...options,\n skipApiVersionInUrl: true,\n }),\n ),\n instance: new InstanceAPI(request),\n invitations: new InvitationAPI(request),\n jwks: new JwksAPI(request),\n jwtTemplates: new JwtTemplatesApi(request),\n machines: new MachineApi(request),\n m2m: new M2MTokenApi(\n buildRequest({\n ...options,\n skipApiVersionInUrl: true,\n requireSecretKey: false,\n useMachineSecretKey: true,\n }),\n ),\n oauthApplications: new OAuthApplicationsApi(request),\n organizations: new OrganizationAPI(request),\n phoneNumbers: new PhoneNumberAPI(request),\n proxyChecks: new ProxyCheckAPI(request),\n redirectUrls: new RedirectUrlAPI(request),\n samlConnections: new SamlConnectionAPI(request),\n sessions: new SessionAPI(request),\n signInTokens: new SignInTokenAPI(request),\n signUps: new SignUpAPI(request),\n testingTokens: new TestingTokenAPI(request),\n users: new UserAPI(request),\n waitlistEntries: new WaitlistEntryAPI(request),\n webhooks: new WebhookAPI(request),\n };\n}\n","import type { AuthenticateRequestOptions } from '../tokens/types';\nimport type { MachineTokenType } from './tokenTypes';\nimport { TokenType } from './tokenTypes';\n\nexport const M2M_TOKEN_PREFIX = 'mt_';\nexport const OAUTH_TOKEN_PREFIX = 'oat_';\nexport const API_KEY_PREFIX = 'ak_';\n\nconst MACHINE_TOKEN_PREFIXES = [M2M_TOKEN_PREFIX, OAUTH_TOKEN_PREFIX, API_KEY_PREFIX] as const;\n\n/**\n * Checks if a token is a machine token by looking at its prefix.\n *\n * @remarks\n * In the future, this will support custom prefixes that can be prepended to the base prefixes\n * (e.g. \"org_a_m2m_\", \"org_a_oauth_access_\", \"org_a_api_key_\")\n *\n * @param token - The token string to check\n * @returns true if the token starts with a recognized machine token prefix\n */\nexport function isMachineTokenByPrefix(token: string): boolean {\n return MACHINE_TOKEN_PREFIXES.some(prefix => token.startsWith(prefix));\n}\n\n/**\n * Gets the specific type of machine token based on its prefix.\n *\n * @remarks\n * In the future, this will support custom prefixes that can be prepended to the base prefixes\n * (e.g. \"org_a_m2m_\", \"org_a_oauth_access_\", \"org_a_api_key_\")\n *\n * @param token - The token string to check\n * @returns The specific MachineTokenType\n * @throws Error if the token doesn't match any known machine token prefix\n */\nexport function getMachineTokenType(token: string): MachineTokenType {\n if (token.startsWith(M2M_TOKEN_PREFIX)) {\n return TokenType.M2MToken;\n }\n\n if (token.startsWith(OAUTH_TOKEN_PREFIX)) {\n return TokenType.OAuthToken;\n }\n\n if (token.startsWith(API_KEY_PREFIX)) {\n return TokenType.ApiKey;\n }\n\n throw new Error('Unknown machine token type');\n}\n\n/**\n * Check if a token type is accepted given a requested token type or list of token types.\n *\n * @param tokenType - The token type to check (can be null if the token is invalid)\n * @param acceptsToken - The requested token type or list of token types\n * @returns true if the token type is accepted\n */\nexport const isTokenTypeAccepted = (\n tokenType: TokenType | null,\n acceptsToken: NonNullable,\n): boolean => {\n if (!tokenType) {\n return false;\n }\n\n if (acceptsToken === 'any') {\n return true;\n }\n\n const tokenTypes = Array.isArray(acceptsToken) ? acceptsToken : [acceptsToken];\n return tokenTypes.includes(tokenType);\n};\n\n/**\n * Checks if a token type string is a machine token type (api_key, m2m_token, or oauth_token).\n *\n * @param type - The token type string to check\n * @returns true if the type is a machine token type\n */\nexport function isMachineTokenType(type: string): type is MachineTokenType {\n return type === TokenType.ApiKey || type === TokenType.M2MToken || type === TokenType.OAuthToken;\n}\n","import type { JwtPayload, PendingSessionOptions } from '@clerk/types';\n\nimport { constants } from '../constants';\nimport type { TokenVerificationErrorReason } from '../errors';\nimport type { AuthenticateContext } from './authenticateContext';\nimport type {\n AuthenticatedMachineObject,\n InvalidTokenAuthObject,\n SignedInAuthObject,\n SignedOutAuthObject,\n UnauthenticatedMachineObject,\n} from './authObjects';\nimport {\n authenticatedMachineObject,\n invalidTokenAuthObject,\n signedInAuthObject,\n signedOutAuthObject,\n unauthenticatedMachineObject,\n} from './authObjects';\nimport type { MachineTokenType, SessionTokenType } from './tokenTypes';\nimport { TokenType } from './tokenTypes';\nimport type { MachineAuthType } from './types';\n\nexport const AuthStatus = {\n SignedIn: 'signed-in',\n SignedOut: 'signed-out',\n Handshake: 'handshake',\n} as const;\n\nexport type AuthStatus = (typeof AuthStatus)[keyof typeof AuthStatus];\n\ntype ToAuth = T extends null\n ? () => InvalidTokenAuthObject\n : T extends SessionTokenType\n ? Authenticated extends true\n ? (opts?: PendingSessionOptions) => SignedInAuthObject\n : () => SignedOutAuthObject\n : Authenticated extends true\n ? () => AuthenticatedMachineObject>\n : () => UnauthenticatedMachineObject>;\n\nexport type AuthenticatedState = {\n status: typeof AuthStatus.SignedIn;\n reason: null;\n message: null;\n proxyUrl?: string;\n publishableKey: string;\n isSatellite: boolean;\n domain: string;\n signInUrl: string;\n signUpUrl: string;\n afterSignInUrl: string;\n afterSignUpUrl: string;\n /**\n * @deprecated Use `isAuthenticated` instead.\n */\n isSignedIn: true;\n isAuthenticated: true;\n headers: Headers;\n token: string;\n tokenType: T;\n toAuth: ToAuth;\n};\n\nexport type UnauthenticatedState = {\n status: typeof AuthStatus.SignedOut;\n reason: AuthReason;\n message: string;\n proxyUrl?: string;\n publishableKey: string;\n isSatellite: boolean;\n domain: string;\n signInUrl: string;\n signUpUrl: string;\n afterSignInUrl: string;\n afterSignUpUrl: string;\n /**\n * @deprecated Use `isAuthenticated` instead.\n */\n isSignedIn: false;\n isAuthenticated: false;\n tokenType: T;\n headers: Headers;\n token: null;\n toAuth: ToAuth;\n};\n\nexport type HandshakeState = Omit, 'status' | 'toAuth' | 'tokenType'> & {\n tokenType: SessionTokenType;\n status: typeof AuthStatus.Handshake;\n headers: Headers;\n toAuth: () => null;\n};\n\n/**\n * @deprecated Use AuthenticatedState instead\n */\nexport type SignedInState = AuthenticatedState;\n\n/**\n * @deprecated Use UnauthenticatedState instead\n */\nexport type SignedOutState = UnauthenticatedState;\n\nexport const AuthErrorReason = {\n ClientUATWithoutSessionToken: 'client-uat-but-no-session-token',\n DevBrowserMissing: 'dev-browser-missing',\n DevBrowserSync: 'dev-browser-sync',\n PrimaryRespondsToSyncing: 'primary-responds-to-syncing',\n PrimaryDomainCrossOriginSync: 'primary-domain-cross-origin-sync',\n SatelliteCookieNeedsSyncing: 'satellite-needs-syncing',\n SessionTokenAndUATMissing: 'session-token-and-uat-missing',\n SessionTokenMissing: 'session-token-missing',\n SessionTokenExpired: 'session-token-expired',\n SessionTokenIATBeforeClientUAT: 'session-token-iat-before-client-uat',\n SessionTokenNBF: 'session-token-nbf',\n SessionTokenIatInTheFuture: 'session-token-iat-in-the-future',\n SessionTokenWithoutClientUAT: 'session-token-but-no-client-uat',\n ActiveOrganizationMismatch: 'active-organization-mismatch',\n TokenTypeMismatch: 'token-type-mismatch',\n UnexpectedError: 'unexpected-error',\n} as const;\n\nexport type AuthErrorReason = (typeof AuthErrorReason)[keyof typeof AuthErrorReason];\n\nexport type AuthReason = AuthErrorReason | TokenVerificationErrorReason;\n\nexport type RequestState =\n | AuthenticatedState\n | UnauthenticatedState\n | (T extends SessionTokenType ? HandshakeState : never);\n\ntype BaseSignedInParams = {\n authenticateContext: AuthenticateContext;\n headers?: Headers;\n token: string;\n tokenType: TokenType;\n};\n\ntype SignedInParams =\n | (BaseSignedInParams & { tokenType: SessionTokenType; sessionClaims: JwtPayload })\n | (BaseSignedInParams & { tokenType: MachineTokenType; machineData: MachineAuthType });\n\nexport function signedIn(params: SignedInParams & { tokenType: T }): AuthenticatedState {\n const { authenticateContext, headers = new Headers(), token } = params;\n\n const toAuth = (({ treatPendingAsSignedOut = true } = {}) => {\n if (params.tokenType === TokenType.SessionToken) {\n const { sessionClaims } = params as { sessionClaims: JwtPayload };\n const authObject = signedInAuthObject(authenticateContext, token, sessionClaims);\n\n if (treatPendingAsSignedOut && authObject.sessionStatus === 'pending') {\n return signedOutAuthObject(undefined, authObject.sessionStatus);\n }\n\n return authObject;\n }\n\n const { machineData } = params as { machineData: MachineAuthType };\n return authenticatedMachineObject(params.tokenType, token, machineData, authenticateContext);\n }) as ToAuth;\n\n return {\n status: AuthStatus.SignedIn,\n reason: null,\n message: null,\n proxyUrl: authenticateContext.proxyUrl || '',\n publishableKey: authenticateContext.publishableKey || '',\n isSatellite: authenticateContext.isSatellite || false,\n domain: authenticateContext.domain || '',\n signInUrl: authenticateContext.signInUrl || '',\n signUpUrl: authenticateContext.signUpUrl || '',\n afterSignInUrl: authenticateContext.afterSignInUrl || '',\n afterSignUpUrl: authenticateContext.afterSignUpUrl || '',\n isSignedIn: true,\n isAuthenticated: true,\n tokenType: params.tokenType,\n toAuth,\n headers,\n token,\n };\n}\n\ntype SignedOutParams = Omit & {\n reason: AuthReason;\n message?: string;\n};\n\nexport function signedOut(params: SignedOutParams & { tokenType: T }): UnauthenticatedState {\n const { authenticateContext, headers = new Headers(), reason, message = '', tokenType } = params;\n\n const toAuth = (() => {\n if (tokenType === TokenType.SessionToken) {\n return signedOutAuthObject({ ...authenticateContext, status: AuthStatus.SignedOut, reason, message });\n }\n\n return unauthenticatedMachineObject(tokenType, { reason, message, headers });\n }) as ToAuth;\n\n return withDebugHeaders({\n status: AuthStatus.SignedOut,\n reason,\n message,\n proxyUrl: authenticateContext.proxyUrl || '',\n publishableKey: authenticateContext.publishableKey || '',\n isSatellite: authenticateContext.isSatellite || false,\n domain: authenticateContext.domain || '',\n signInUrl: authenticateContext.signInUrl || '',\n signUpUrl: authenticateContext.signUpUrl || '',\n afterSignInUrl: authenticateContext.afterSignInUrl || '',\n afterSignUpUrl: authenticateContext.afterSignUpUrl || '',\n isSignedIn: false,\n isAuthenticated: false,\n tokenType,\n toAuth,\n headers,\n token: null,\n });\n}\n\nexport function handshake(\n authenticateContext: AuthenticateContext,\n reason: AuthReason,\n message = '',\n headers: Headers,\n): HandshakeState {\n return withDebugHeaders({\n status: AuthStatus.Handshake,\n reason,\n message,\n publishableKey: authenticateContext.publishableKey || '',\n isSatellite: authenticateContext.isSatellite || false,\n domain: authenticateContext.domain || '',\n proxyUrl: authenticateContext.proxyUrl || '',\n signInUrl: authenticateContext.signInUrl || '',\n signUpUrl: authenticateContext.signUpUrl || '',\n afterSignInUrl: authenticateContext.afterSignInUrl || '',\n afterSignUpUrl: authenticateContext.afterSignUpUrl || '',\n isSignedIn: false,\n isAuthenticated: false,\n tokenType: TokenType.SessionToken,\n toAuth: () => null,\n headers,\n token: null,\n });\n}\n\nexport function signedOutInvalidToken(): UnauthenticatedState {\n const authObject = invalidTokenAuthObject();\n return withDebugHeaders({\n status: AuthStatus.SignedOut,\n reason: AuthErrorReason.TokenTypeMismatch,\n message: '',\n proxyUrl: '',\n publishableKey: '',\n isSatellite: false,\n domain: '',\n signInUrl: '',\n signUpUrl: '',\n afterSignInUrl: '',\n afterSignUpUrl: '',\n isSignedIn: false,\n isAuthenticated: false,\n tokenType: null,\n toAuth: () => authObject,\n headers: new Headers(),\n token: null,\n });\n}\n\nconst withDebugHeaders = (\n requestState: T,\n): T => {\n const headers = new Headers(requestState.headers || {});\n\n if (requestState.message) {\n try {\n headers.set(constants.Headers.AuthMessage, requestState.message);\n } catch {\n // headers.set can throw if unicode strings are passed to it. In this case, simply do nothing\n }\n }\n\n if (requestState.reason) {\n try {\n headers.set(constants.Headers.AuthReason, requestState.reason);\n } catch {\n /* empty */\n }\n }\n\n if (requestState.status) {\n try {\n headers.set(constants.Headers.AuthStatus, requestState.status);\n } catch {\n /* empty */\n }\n }\n\n requestState.headers = headers;\n\n return requestState;\n};\n","import { parse } from 'cookie';\n\nimport { constants } from '../constants';\nimport type { ClerkUrl } from './clerkUrl';\nimport { createClerkUrl } from './clerkUrl';\n\n/**\n * A class that extends the native Request class,\n * adds cookies helpers and a normalised clerkUrl that is constructed by using the values found\n * in req.headers so it is able to work reliably when the app is running behind a proxy server.\n */\nclass ClerkRequest extends Request {\n readonly clerkUrl: ClerkUrl;\n readonly cookies: Map;\n\n public constructor(input: ClerkRequest | Request | RequestInfo, init?: RequestInit) {\n // The usual way to duplicate a request object is to\n // pass the original request object to the Request constructor\n // both as the `input` and `init` parameters, eg: super(req, req)\n // However, this fails in certain environments like Vercel Edge Runtime\n // when a framework like Remix polyfills the global Request object.\n // This happens because `undici` performs the following instanceof check\n // which, instead of testing against the global Request object, tests against\n // the Request class defined in the same file (local Request class).\n // For more details, please refer to:\n // https://github.com/nodejs/undici/issues/2155\n // https://github.com/nodejs/undici/blob/7153a1c78d51840bbe16576ce353e481c3934701/lib/fetch/request.js#L854\n const url = typeof input !== 'string' && 'url' in input ? input.url : String(input);\n super(url, init || typeof input === 'string' ? undefined : input);\n this.clerkUrl = this.deriveUrlFromHeaders(this);\n this.cookies = this.parseCookies(this);\n }\n\n public toJSON() {\n return {\n url: this.clerkUrl.href,\n method: this.method,\n headers: JSON.stringify(Object.fromEntries(this.headers)),\n clerkUrl: this.clerkUrl.toString(),\n cookies: JSON.stringify(Object.fromEntries(this.cookies)),\n };\n }\n\n /**\n * Used to fix request.url using the x-forwarded-* headers\n * TODO add detailed description of the issues this solves\n */\n private deriveUrlFromHeaders(req: Request) {\n const initialUrl = new URL(req.url);\n const forwardedProto = req.headers.get(constants.Headers.ForwardedProto);\n const forwardedHost = req.headers.get(constants.Headers.ForwardedHost);\n const host = req.headers.get(constants.Headers.Host);\n const protocol = initialUrl.protocol;\n\n const resolvedHost = this.getFirstValueFromHeader(forwardedHost) ?? host;\n const resolvedProtocol = this.getFirstValueFromHeader(forwardedProto) ?? protocol?.replace(/[:/]/, '');\n const origin = resolvedHost && resolvedProtocol ? `${resolvedProtocol}://${resolvedHost}` : initialUrl.origin;\n\n if (origin === initialUrl.origin) {\n return createClerkUrl(initialUrl);\n }\n return createClerkUrl(initialUrl.pathname + initialUrl.search, origin);\n }\n\n private getFirstValueFromHeader(value?: string | null) {\n return value?.split(',')[0];\n }\n\n private parseCookies(req: Request) {\n const cookiesRecord = parse(this.decodeCookieValue(req.headers.get('cookie') || ''));\n return new Map(Object.entries(cookiesRecord));\n }\n\n private decodeCookieValue(str: string) {\n return str ? str.replace(/(%[0-9A-Z]{2})+/g, decodeURIComponent) : str;\n }\n}\n\nexport const createClerkRequest = (...args: ConstructorParameters): ClerkRequest => {\n return args[0] instanceof ClerkRequest ? args[0] : new ClerkRequest(...args);\n};\n\nexport type { ClerkRequest };\n","class ClerkUrl extends URL {\n public isCrossOrigin(other: URL | string) {\n return this.origin !== new URL(other.toString()).origin;\n }\n}\n\nexport type WithClerkUrl = T & {\n /**\n * When a NextJs app is hosted on a platform different from Vercel\n * or inside a container (Netlify, Fly.io, AWS Amplify, docker etc),\n * req.url is always set to `localhost:3000` instead of the actual host of the app.\n *\n * The `authMiddleware` uses the value of the available req.headers in order to construct\n * and use the correct url internally. This url is then exposed as `experimental_clerkUrl`,\n * intended to be used within `beforeAuth` and `afterAuth` if needed.\n */\n clerkUrl: ClerkUrl;\n};\n\nexport const createClerkUrl = (...args: ConstructorParameters): ClerkUrl => {\n return new ClerkUrl(...args);\n};\n\nexport type { ClerkUrl };\n","export const getCookieName = (cookieDirective: string): string => {\n return cookieDirective.split(';')[0]?.split('=')[0];\n};\n\nexport const getCookieValue = (cookieDirective: string): string => {\n return cookieDirective.split(';')[0]?.split('=')[1];\n};\n","import {\n API_URL,\n API_VERSION,\n MAX_CACHE_LAST_UPDATED_AT_SECONDS,\n SUPPORTED_BAPI_VERSION,\n USER_AGENT,\n} from '../constants';\nimport {\n TokenVerificationError,\n TokenVerificationErrorAction,\n TokenVerificationErrorCode,\n TokenVerificationErrorReason,\n} from '../errors';\nimport { runtime } from '../runtime';\nimport { joinPaths } from '../util/path';\nimport { retry } from '../util/shared';\n\ntype JsonWebKeyWithKid = JsonWebKey & { kid: string };\n\ntype JsonWebKeyCache = Record;\n\nlet cache: JsonWebKeyCache = {};\nlet lastUpdatedAt = 0;\n\nfunction getFromCache(kid: string) {\n return cache[kid];\n}\n\nfunction getCacheValues() {\n return Object.values(cache);\n}\n\nfunction setInCache(jwk: JsonWebKeyWithKid, shouldExpire = true) {\n cache[jwk.kid] = jwk;\n lastUpdatedAt = shouldExpire ? Date.now() : -1;\n}\n\nconst LocalJwkKid = 'local';\nconst PEM_HEADER = '-----BEGIN PUBLIC KEY-----';\nconst PEM_TRAILER = '-----END PUBLIC KEY-----';\nconst RSA_PREFIX = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA';\nconst RSA_SUFFIX = 'IDAQAB';\n\n/**\n *\n * Loads a local PEM key usually from process.env and transform it to JsonWebKey format.\n * The result is also cached on the module level to avoid unnecessary computations in subsequent invocations.\n *\n * @param {string} localKey\n * @returns {JsonWebKey} key\n */\nexport function loadClerkJWKFromLocal(localKey?: string): JsonWebKey {\n if (!getFromCache(LocalJwkKid)) {\n if (!localKey) {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.SetClerkJWTKey,\n message: 'Missing local JWK.',\n reason: TokenVerificationErrorReason.LocalJWKMissing,\n });\n }\n\n const modulus = localKey\n .replace(/\\r\\n|\\n|\\r/g, '')\n .replace(PEM_HEADER, '')\n .replace(PEM_TRAILER, '')\n .replace(RSA_PREFIX, '')\n .replace(RSA_SUFFIX, '')\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_');\n\n // JWK https://datatracker.ietf.org/doc/html/rfc7517\n setInCache(\n {\n kid: 'local',\n kty: 'RSA',\n alg: 'RS256',\n n: modulus,\n e: 'AQAB',\n },\n false, // local key never expires in cache\n );\n }\n\n return getFromCache(LocalJwkKid);\n}\n\n/**\n * @internal\n */\nexport type LoadClerkJWKFromRemoteOptions = {\n /**\n * @internal\n */\n kid: string;\n /**\n * @deprecated This cache TTL will be removed in the next major version. Specifying a cache TTL is a no-op.\n */\n jwksCacheTtlInMs?: number;\n /**\n * A flag to ignore the JWKS cache and always fetch JWKS before each JWT verification.\n */\n skipJwksCache?: boolean;\n /**\n * The Clerk Secret Key from the [**API keys**](https://dashboard.clerk.com/last-active?path=api-keys) page in the Clerk Dashboard.\n */\n secretKey?: string;\n /**\n * The [Clerk Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }} endpoint.\n * @default 'https://api.clerk.com'\n */\n apiUrl?: string;\n /**\n * The version passed to the Clerk API.\n * @default 'v1'\n */\n apiVersion?: string;\n};\n\n/**\n *\n * Loads a key from JWKS retrieved from the well-known Frontend API endpoint of the issuer.\n * The result is also cached on the module level to avoid network requests in subsequent invocations.\n * The cache lasts up to 5 minutes.\n *\n * @param {Object} options\n * @param {string} options.kid - The id of the key that the JWT was signed with\n * @param {string} options.alg - The algorithm of the JWT\n * @returns {JsonWebKey} key\n */\nexport async function loadClerkJWKFromRemote({\n secretKey,\n apiUrl = API_URL,\n apiVersion = API_VERSION,\n kid,\n skipJwksCache,\n}: LoadClerkJWKFromRemoteOptions): Promise {\n if (skipJwksCache || cacheHasExpired() || !getFromCache(kid)) {\n if (!secretKey) {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.ContactSupport,\n message: 'Failed to load JWKS from Clerk Backend or Frontend API.',\n reason: TokenVerificationErrorReason.RemoteJWKFailedToLoad,\n });\n }\n const fetcher = () => fetchJWKSFromBAPI(apiUrl, secretKey, apiVersion) as Promise<{ keys: JsonWebKeyWithKid[] }>;\n const { keys } = await retry(fetcher);\n\n if (!keys || !keys.length) {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.ContactSupport,\n message: 'The JWKS endpoint did not contain any signing keys. Contact support@clerk.com.',\n reason: TokenVerificationErrorReason.RemoteJWKFailedToLoad,\n });\n }\n\n keys.forEach(key => setInCache(key));\n }\n\n const jwk = getFromCache(kid);\n\n if (!jwk) {\n const cacheValues = getCacheValues();\n const jwkKeys = cacheValues\n .map(jwk => jwk.kid)\n .sort()\n .join(', ');\n\n throw new TokenVerificationError({\n action: `Go to your Dashboard and validate your secret and public keys are correct. ${TokenVerificationErrorAction.ContactSupport} if the issue persists.`,\n message: `Unable to find a signing key in JWKS that matches the kid='${kid}' of the provided session token. Please make sure that the __session cookie or the HTTP authorization header contain a Clerk-generated session JWT. The following kid is available: ${jwkKeys}`,\n reason: TokenVerificationErrorReason.JWKKidMismatch,\n });\n }\n\n return jwk;\n}\n\nasync function fetchJWKSFromBAPI(apiUrl: string, key: string, apiVersion: string) {\n if (!key) {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.SetClerkSecretKey,\n message:\n 'Missing Clerk Secret Key or API Key. Go to https://dashboard.clerk.com and get your key for your instance.',\n reason: TokenVerificationErrorReason.RemoteJWKFailedToLoad,\n });\n }\n\n const url = new URL(apiUrl);\n url.pathname = joinPaths(url.pathname, apiVersion, '/jwks');\n\n const response = await runtime.fetch(url.href, {\n headers: {\n Authorization: `Bearer ${key}`,\n 'Clerk-API-Version': SUPPORTED_BAPI_VERSION,\n 'Content-Type': 'application/json',\n 'User-Agent': USER_AGENT,\n },\n });\n\n if (!response.ok) {\n const json = await response.json();\n const invalidSecretKeyError = getErrorObjectByCode(json?.errors, TokenVerificationErrorCode.InvalidSecretKey);\n\n if (invalidSecretKeyError) {\n const reason = TokenVerificationErrorReason.InvalidSecretKey;\n\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.ContactSupport,\n message: invalidSecretKeyError.message,\n reason,\n });\n }\n\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.ContactSupport,\n message: `Error loading Clerk JWKS from ${url.href} with code=${response.status}`,\n reason: TokenVerificationErrorReason.RemoteJWKFailedToLoad,\n });\n }\n\n return response.json();\n}\n\nfunction cacheHasExpired() {\n // If lastUpdatedAt is -1, it means that we're using a local JWKS and it never expires\n if (lastUpdatedAt === -1) {\n return false;\n }\n\n // If the cache has expired, clear the value so we don't attempt to make decisions based on stale data\n const isExpired = Date.now() - lastUpdatedAt >= MAX_CACHE_LAST_UPDATED_AT_SECONDS * 1000;\n\n if (isExpired) {\n cache = {};\n }\n\n return isExpired;\n}\n\ntype ErrorFields = {\n message: string;\n long_message: string;\n code: string;\n};\n\nconst getErrorObjectByCode = (errors: ErrorFields[], code: string) => {\n if (!errors) {\n return null;\n }\n\n return errors.find((err: ErrorFields) => err.code === code);\n};\n","import { isClerkAPIResponseError } from '@clerk/shared/error';\nimport type { JwtPayload } from '@clerk/types';\n\nimport type { APIKey, IdPOAuthAccessToken, M2MToken } from '../api';\nimport { createBackendApiClient } from '../api/factory';\nimport {\n MachineTokenVerificationError,\n MachineTokenVerificationErrorCode,\n TokenVerificationError,\n TokenVerificationErrorAction,\n TokenVerificationErrorReason,\n} from '../errors';\nimport type { VerifyJwtOptions } from '../jwt';\nimport type { JwtReturnType, MachineTokenReturnType } from '../jwt/types';\nimport { decodeJwt, verifyJwt } from '../jwt/verifyJwt';\nimport type { LoadClerkJWKFromRemoteOptions } from './keys';\nimport { loadClerkJWKFromLocal, loadClerkJWKFromRemote } from './keys';\nimport { API_KEY_PREFIX, M2M_TOKEN_PREFIX, OAUTH_TOKEN_PREFIX } from './machine';\nimport type { MachineTokenType } from './tokenTypes';\nimport { TokenType } from './tokenTypes';\n\n/**\n * @interface\n */\nexport type VerifyTokenOptions = Omit &\n Omit & {\n /**\n * Used to verify the session token in a networkless manner. Supply the PEM public key from the **[**API keys**](https://dashboard.clerk.com/last-active?path=api-keys) page -> Show JWT public key -> PEM Public Key** section in the Clerk Dashboard. **It's recommended to use [the environment variable](https://clerk.com/docs/deployments/clerk-environment-variables) instead.** For more information, refer to [Manual JWT verification](https://clerk.com/docs/backend-requests/manual-jwt).\n */\n jwtKey?: string;\n };\n\n/**\n * > [!WARNING]\n * > This is a lower-level method intended for more advanced use-cases. It's recommended to use [`authenticateRequest()`](https://clerk.com/docs/references/backend/authenticate-request), which fully authenticates a token passed from the `request` object.\n *\n * Verifies a Clerk-generated token signature. Networkless if the `jwtKey` is provided. Otherwise, performs a network call to retrieve the JWKS from the [Backend API](https://clerk.com/docs/reference/backend-api/tag/JWKS#operation/GetJWKS){{ target: '_blank' }}.\n *\n * @param token - The token to verify.\n * @param options - Options for verifying the token.\n *\n * @displayFunctionSignature\n *\n * @paramExtension\n *\n * ### `VerifyTokenOptions`\n *\n * It is recommended to set these options as [environment variables](/docs/deployments/clerk-environment-variables#api-and-sdk-configuration) where possible, and then pass them to the function. For example, you can set the `secretKey` option using the `CLERK_SECRET_KEY` environment variable, and then pass it to the function like this: `createClerkClient({ secretKey: process.env.CLERK_SECRET_KEY })`.\n *\n * > [!WARNING]\n * You must provide either `jwtKey` or `secretKey`.\n *\n * \n *\n * @example\n *\n * The following example demonstrates how to use the [JavaScript Backend SDK](https://clerk.com/docs/references/backend/overview) to verify the token signature.\n *\n * In the following example:\n *\n * 1. The **JWKS Public Key** from the Clerk Dashboard is set in the environment variable `CLERK_JWT_KEY`.\n * 1. The session token is retrieved from the `__session` cookie or the Authorization header.\n * 1. The token is verified in a networkless manner by passing the `jwtKey` prop.\n * 1. The `authorizedParties` prop is passed to verify that the session token is generated from the expected frontend application.\n * 1. If the token is valid, the response contains the verified token.\n *\n * ```ts\n * import { verifyToken } from '@clerk/backend'\n * import { cookies } from 'next/headers'\n *\n * export async function GET(request: Request) {\n * const cookieStore = cookies()\n * const sessToken = cookieStore.get('__session')?.value\n * const bearerToken = request.headers.get('Authorization')?.replace('Bearer ', '')\n * const token = sessToken || bearerToken\n *\n * if (!token) {\n * return Response.json({ error: 'Token not found. User must sign in.' }, { status: 401 })\n * }\n *\n * try {\n * const verifiedToken = await verifyToken(token, {\n * jwtKey: process.env.CLERK_JWT_KEY,\n * authorizedParties: ['http://localhost:3001', 'api.example.com'], // Replace with your authorized parties\n * })\n *\n * return Response.json({ verifiedToken })\n * } catch (error) {\n * return Response.json({ error: 'Token not verified.' }, { status: 401 })\n * }\n * }\n * ```\n *\n * If the token is valid, the response will contain a JSON object that looks something like this:\n *\n * ```json\n * {\n * \"verifiedToken\": {\n * \"azp\": \"http://localhost:3000\",\n * \"exp\": 1687906422,\n * \"iat\": 1687906362,\n * \"iss\": \"https://magical-marmoset-51.clerk.accounts.dev\",\n * \"nbf\": 1687906352,\n * \"sid\": \"sess_2Ro7e2IxrffdqBboq8KfB6eGbIy\",\n * \"sub\": \"user_2RfWKJREkjKbHZy0Wqa5qrHeAnb\"\n * }\n * }\n * ```\n */\nexport async function verifyToken(\n token: string,\n options: VerifyTokenOptions,\n): Promise> {\n const { data: decodedResult, errors } = decodeJwt(token);\n if (errors) {\n return { errors };\n }\n\n const { header } = decodedResult;\n const { kid } = header;\n\n try {\n let key;\n\n if (options.jwtKey) {\n key = loadClerkJWKFromLocal(options.jwtKey);\n } else if (options.secretKey) {\n // Fetch JWKS from Backend API using the key\n key = await loadClerkJWKFromRemote({ ...options, kid });\n } else {\n return {\n errors: [\n new TokenVerificationError({\n action: TokenVerificationErrorAction.SetClerkJWTKey,\n message: 'Failed to resolve JWK during verification.',\n reason: TokenVerificationErrorReason.JWKFailedToResolve,\n }),\n ],\n };\n }\n\n return await verifyJwt(token, { ...options, key });\n } catch (error) {\n return { errors: [error as TokenVerificationError] };\n }\n}\n\n/**\n * Handles errors from Clerk API responses for machine tokens\n * @param tokenType - The type of machine token\n * @param err - The error from the Clerk API\n * @param notFoundMessage - Custom message for 404 errors\n */\nfunction handleClerkAPIError(\n tokenType: MachineTokenType,\n err: any,\n notFoundMessage: string,\n): MachineTokenReturnType {\n if (isClerkAPIResponseError(err)) {\n let code: MachineTokenVerificationErrorCode;\n let message: string;\n\n switch (err.status) {\n case 401:\n code = MachineTokenVerificationErrorCode.InvalidSecretKey;\n message = err.errors[0]?.message || 'Invalid secret key';\n break;\n case 404:\n code = MachineTokenVerificationErrorCode.TokenInvalid;\n message = notFoundMessage;\n break;\n default:\n code = MachineTokenVerificationErrorCode.UnexpectedError;\n message = 'Unexpected error';\n }\n\n return {\n data: undefined,\n tokenType,\n errors: [\n new MachineTokenVerificationError({\n message,\n code,\n status: err.status,\n }),\n ],\n };\n }\n\n return {\n data: undefined,\n tokenType,\n errors: [\n new MachineTokenVerificationError({\n message: 'Unexpected error',\n code: MachineTokenVerificationErrorCode.UnexpectedError,\n status: err.status,\n }),\n ],\n };\n}\n\nasync function verifyM2MToken(\n token: string,\n options: VerifyTokenOptions & { machineSecretKey?: string },\n): Promise> {\n try {\n const client = createBackendApiClient(options);\n const verifiedToken = await client.m2m.verifyToken({ token });\n return { data: verifiedToken, tokenType: TokenType.M2MToken, errors: undefined };\n } catch (err: any) {\n return handleClerkAPIError(TokenType.M2MToken, err, 'Machine token not found');\n }\n}\n\nasync function verifyOAuthToken(\n accessToken: string,\n options: VerifyTokenOptions,\n): Promise> {\n try {\n const client = createBackendApiClient(options);\n const verifiedToken = await client.idPOAuthAccessToken.verifyAccessToken(accessToken);\n return { data: verifiedToken, tokenType: TokenType.OAuthToken, errors: undefined };\n } catch (err: any) {\n return handleClerkAPIError(TokenType.OAuthToken, err, 'OAuth token not found');\n }\n}\n\nasync function verifyAPIKey(\n secret: string,\n options: VerifyTokenOptions,\n): Promise> {\n try {\n const client = createBackendApiClient(options);\n const verifiedToken = await client.apiKeys.verifySecret(secret);\n return { data: verifiedToken, tokenType: TokenType.ApiKey, errors: undefined };\n } catch (err: any) {\n return handleClerkAPIError(TokenType.ApiKey, err, 'API key not found');\n }\n}\n\n/**\n * Verifies any type of machine token by detecting its type from the prefix.\n *\n * @param token - The token to verify (e.g. starts with \"m2m_\", \"oauth_\", \"api_key_\", etc.)\n * @param options - Options including secretKey for BAPI authorization\n */\nexport async function verifyMachineAuthToken(token: string, options: VerifyTokenOptions) {\n if (token.startsWith(M2M_TOKEN_PREFIX)) {\n return verifyM2MToken(token, options);\n }\n if (token.startsWith(OAUTH_TOKEN_PREFIX)) {\n return verifyOAuthToken(token, options);\n }\n if (token.startsWith(API_KEY_PREFIX)) {\n return verifyAPIKey(token, options);\n }\n\n throw new Error('Unknown machine token type');\n}\n","import { constants, SUPPORTED_BAPI_VERSION } from '../constants';\nimport { TokenVerificationError, TokenVerificationErrorAction, TokenVerificationErrorReason } from '../errors';\nimport type { VerifyJwtOptions } from '../jwt';\nimport { assertHeaderAlgorithm, assertHeaderType } from '../jwt/assertions';\nimport { decodeJwt, hasValidSignature } from '../jwt/verifyJwt';\nimport type { AuthenticateContext } from './authenticateContext';\nimport type { SignedInState, SignedOutState } from './authStatus';\nimport { AuthErrorReason, signedIn, signedOut } from './authStatus';\nimport { getCookieName, getCookieValue } from './cookie';\nimport { loadClerkJWKFromLocal, loadClerkJWKFromRemote } from './keys';\nimport type { OrganizationMatcher } from './organizationMatcher';\nimport { TokenType } from './tokenTypes';\nimport type { OrganizationSyncOptions, OrganizationSyncTarget } from './types';\nimport type { VerifyTokenOptions } from './verify';\nimport { verifyToken } from './verify';\n\nasync function verifyHandshakeJwt(token: string, { key }: VerifyJwtOptions): Promise<{ handshake: string[] }> {\n const { data: decoded, errors } = decodeJwt(token);\n if (errors) {\n throw errors[0];\n }\n\n const { header, payload } = decoded;\n\n // Header verifications\n const { typ, alg } = header;\n\n assertHeaderType(typ);\n assertHeaderAlgorithm(alg);\n\n const { data: signatureValid, errors: signatureErrors } = await hasValidSignature(decoded, key);\n if (signatureErrors) {\n throw new TokenVerificationError({\n reason: TokenVerificationErrorReason.TokenVerificationFailed,\n message: `Error verifying handshake token. ${signatureErrors[0]}`,\n });\n }\n\n if (!signatureValid) {\n throw new TokenVerificationError({\n reason: TokenVerificationErrorReason.TokenInvalidSignature,\n message: 'Handshake signature is invalid.',\n });\n }\n\n return payload as unknown as { handshake: string[] };\n}\n\n/**\n * Similar to our verifyToken flow for Clerk-issued JWTs, but this verification flow is for our signed handshake payload.\n * The handshake payload requires fewer verification steps.\n */\nexport async function verifyHandshakeToken(\n token: string,\n options: VerifyTokenOptions,\n): Promise<{ handshake: string[] }> {\n const { secretKey, apiUrl, apiVersion, jwksCacheTtlInMs, jwtKey, skipJwksCache } = options;\n\n const { data, errors } = decodeJwt(token);\n if (errors) {\n throw errors[0];\n }\n\n const { kid } = data.header;\n\n let key;\n\n if (jwtKey) {\n key = loadClerkJWKFromLocal(jwtKey);\n } else if (secretKey) {\n // Fetch JWKS from Backend API using the key\n key = await loadClerkJWKFromRemote({ secretKey, apiUrl, apiVersion, kid, jwksCacheTtlInMs, skipJwksCache });\n } else {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.SetClerkJWTKey,\n message: 'Failed to resolve JWK during handshake verification.',\n reason: TokenVerificationErrorReason.JWKFailedToResolve,\n });\n }\n\n return await verifyHandshakeJwt(token, {\n key,\n });\n}\n\nexport class HandshakeService {\n private readonly authenticateContext: AuthenticateContext;\n private readonly organizationMatcher: OrganizationMatcher;\n private readonly options: { organizationSyncOptions?: OrganizationSyncOptions };\n\n constructor(\n authenticateContext: AuthenticateContext,\n options: { organizationSyncOptions?: OrganizationSyncOptions },\n organizationMatcher: OrganizationMatcher,\n ) {\n this.authenticateContext = authenticateContext;\n this.options = options;\n this.organizationMatcher = organizationMatcher;\n }\n\n /**\n * Determines if a request is eligible for handshake based on its headers\n *\n * Currently, a request is only eligible for a handshake if we can say it's *probably* a request for a document, not a fetch or some other exotic request.\n * This heuristic should give us a reliable enough signal for browsers that support `Sec-Fetch-Dest` and for those that don't.\n *\n * @returns boolean indicating if the request is eligible for handshake\n */\n isRequestEligibleForHandshake(): boolean {\n const { accept, secFetchDest } = this.authenticateContext;\n\n // NOTE: we could also check sec-fetch-mode === navigate here, but according to the spec, sec-fetch-dest: document should indicate that the request is the data of a user navigation.\n // Also, we check for 'iframe' because it's the value set when a doc request is made by an iframe.\n if (secFetchDest === 'document' || secFetchDest === 'iframe') {\n return true;\n }\n\n if (!secFetchDest && accept?.startsWith('text/html')) {\n return true;\n }\n\n return false;\n }\n\n /**\n * Builds the redirect headers for a handshake request\n * @param reason - The reason for the handshake (e.g. 'session-token-expired')\n * @returns Headers object containing the Location header for redirect\n * @throws Error if clerkUrl is missing in authenticateContext\n */\n buildRedirectToHandshake(reason: string): Headers {\n if (!this.authenticateContext?.clerkUrl) {\n throw new Error('Missing clerkUrl in authenticateContext');\n }\n\n const redirectUrl = this.removeDevBrowserFromURL(this.authenticateContext.clerkUrl);\n\n let baseUrl = this.authenticateContext.frontendApi.startsWith('http')\n ? this.authenticateContext.frontendApi\n : `https://${this.authenticateContext.frontendApi}`;\n\n baseUrl = baseUrl.replace(/\\/+$/, '') + '/';\n\n const url = new URL('v1/client/handshake', baseUrl);\n url.searchParams.append('redirect_url', redirectUrl?.href || '');\n url.searchParams.append('__clerk_api_version', SUPPORTED_BAPI_VERSION);\n url.searchParams.append(\n constants.QueryParameters.SuffixedCookies,\n this.authenticateContext.usesSuffixedCookies().toString(),\n );\n url.searchParams.append(constants.QueryParameters.HandshakeReason, reason);\n url.searchParams.append(constants.QueryParameters.HandshakeFormat, 'nonce');\n\n if (this.authenticateContext.instanceType === 'development' && this.authenticateContext.devBrowserToken) {\n url.searchParams.append(constants.QueryParameters.DevBrowser, this.authenticateContext.devBrowserToken);\n }\n\n const toActivate = this.getOrganizationSyncTarget(this.authenticateContext.clerkUrl, this.organizationMatcher);\n if (toActivate) {\n const params = this.getOrganizationSyncQueryParams(toActivate);\n params.forEach((value, key) => {\n url.searchParams.append(key, value);\n });\n }\n\n return new Headers({ [constants.Headers.Location]: url.href });\n }\n\n /**\n * Gets cookies from either a handshake nonce or a handshake token\n * @returns Promise resolving to string array of cookie directives\n */\n public async getCookiesFromHandshake(): Promise {\n const cookiesToSet: string[] = [];\n\n if (this.authenticateContext.handshakeNonce) {\n try {\n const handshakePayload = await this.authenticateContext.apiClient?.clients.getHandshakePayload({\n nonce: this.authenticateContext.handshakeNonce,\n });\n if (handshakePayload) {\n cookiesToSet.push(...handshakePayload.directives);\n }\n } catch (error) {\n console.error('Clerk: HandshakeService: error getting handshake payload:', error);\n }\n } else if (this.authenticateContext.handshakeToken) {\n const handshakePayload = await verifyHandshakeToken(\n this.authenticateContext.handshakeToken,\n this.authenticateContext,\n );\n if (handshakePayload && Array.isArray(handshakePayload.handshake)) {\n cookiesToSet.push(...handshakePayload.handshake);\n }\n }\n\n return cookiesToSet;\n }\n\n /**\n * Resolves a handshake request by verifying the handshake token and setting appropriate cookies\n * @returns Promise resolving to either a SignedInState or SignedOutState\n * @throws Error if handshake verification fails or if there are issues with the session token\n */\n async resolveHandshake(): Promise {\n const headers = new Headers({\n 'Access-Control-Allow-Origin': 'null',\n 'Access-Control-Allow-Credentials': 'true',\n });\n\n const cookiesToSet = await this.getCookiesFromHandshake();\n\n let sessionToken = '';\n cookiesToSet.forEach((x: string) => {\n headers.append('Set-Cookie', x);\n if (getCookieName(x).startsWith(constants.Cookies.Session)) {\n sessionToken = getCookieValue(x);\n }\n });\n\n if (this.authenticateContext.instanceType === 'development') {\n const newUrl = new URL(this.authenticateContext.clerkUrl);\n newUrl.searchParams.delete(constants.QueryParameters.Handshake);\n newUrl.searchParams.delete(constants.QueryParameters.HandshakeHelp);\n newUrl.searchParams.delete(constants.QueryParameters.DevBrowser);\n headers.append(constants.Headers.Location, newUrl.toString());\n headers.set(constants.Headers.CacheControl, 'no-store');\n }\n\n if (sessionToken === '') {\n return signedOut({\n tokenType: TokenType.SessionToken,\n authenticateContext: this.authenticateContext,\n reason: AuthErrorReason.SessionTokenMissing,\n message: '',\n headers,\n });\n }\n\n const { data, errors: [error] = [] } = await verifyToken(sessionToken, this.authenticateContext);\n if (data) {\n return signedIn({\n tokenType: TokenType.SessionToken,\n authenticateContext: this.authenticateContext,\n sessionClaims: data,\n headers,\n token: sessionToken,\n });\n }\n\n if (\n this.authenticateContext.instanceType === 'development' &&\n (error?.reason === TokenVerificationErrorReason.TokenExpired ||\n error?.reason === TokenVerificationErrorReason.TokenNotActiveYet ||\n error?.reason === TokenVerificationErrorReason.TokenIatInTheFuture)\n ) {\n // Create a new error object with the same properties\n const developmentError = new TokenVerificationError({\n action: error.action,\n message: error.message,\n reason: error.reason,\n });\n // Set the tokenCarrier after construction\n developmentError.tokenCarrier = 'cookie';\n\n console.error(\n `Clerk: Clock skew detected. This usually means that your system clock is inaccurate. Clerk will attempt to account for the clock skew in development.\n\nTo resolve this issue, make sure your system's clock is set to the correct time (e.g. turn off and on automatic time synchronization).\n\n---\n\n${developmentError.getFullMessage()}`,\n );\n\n const { data: retryResult, errors: [retryError] = [] } = await verifyToken(sessionToken, {\n ...this.authenticateContext,\n clockSkewInMs: 86_400_000,\n });\n if (retryResult) {\n return signedIn({\n tokenType: TokenType.SessionToken,\n authenticateContext: this.authenticateContext,\n sessionClaims: retryResult,\n headers,\n token: sessionToken,\n });\n }\n\n throw new Error(retryError?.message || 'Clerk: Handshake retry failed.');\n }\n\n throw new Error(error?.message || 'Clerk: Handshake failed.');\n }\n\n /**\n * Handles handshake token verification errors in development mode\n * @param error - The TokenVerificationError that occurred\n * @throws Error with a descriptive message about the verification failure\n */\n handleTokenVerificationErrorInDevelopment(error: TokenVerificationError): void {\n // In development, the handshake token is being transferred in the URL as a query parameter, so there is no\n // possibility of collision with a handshake token of another app running on the same local domain\n // (etc one app on localhost:3000 and one on localhost:3001).\n // Therefore, if the handshake token is invalid, it is likely that the user has switched Clerk keys locally.\n // We make sure to throw a descriptive error message and then stop the handshake flow in every case,\n // to avoid the possibility of an infinite loop.\n if (error.reason === TokenVerificationErrorReason.TokenInvalidSignature) {\n const msg = `Clerk: Handshake token verification failed due to an invalid signature. If you have switched Clerk keys locally, clear your cookies and try again.`;\n throw new Error(msg);\n }\n throw new Error(`Clerk: Handshake token verification failed: ${error.getFullMessage()}.`);\n }\n\n /**\n * Checks if a redirect loop is detected and sets headers to track redirect count\n * @param headers - The Headers object to modify\n * @returns boolean indicating if a redirect loop was detected (true) or if the request can proceed (false)\n */\n checkAndTrackRedirectLoop(headers: Headers): boolean {\n if (this.authenticateContext.handshakeRedirectLoopCounter === 3) {\n return true;\n }\n\n const newCounterValue = this.authenticateContext.handshakeRedirectLoopCounter + 1;\n const cookieName = constants.Cookies.RedirectCount;\n headers.append('Set-Cookie', `${cookieName}=${newCounterValue}; SameSite=Lax; HttpOnly; Max-Age=2`);\n return false;\n }\n\n private removeDevBrowserFromURL(url: URL): URL {\n const updatedURL = new URL(url);\n updatedURL.searchParams.delete(constants.QueryParameters.DevBrowser);\n updatedURL.searchParams.delete(constants.QueryParameters.LegacyDevBrowser);\n return updatedURL;\n }\n\n private getOrganizationSyncTarget(url: URL, matchers: OrganizationMatcher): OrganizationSyncTarget | null {\n return matchers.findTarget(url);\n }\n\n private getOrganizationSyncQueryParams(toActivate: OrganizationSyncTarget): Map {\n const ret = new Map();\n if (toActivate.type === 'personalAccount') {\n ret.set('organization_id', '');\n }\n if (toActivate.type === 'organization') {\n if (toActivate.organizationId) {\n ret.set('organization_id', toActivate.organizationId);\n }\n if (toActivate.organizationSlug) {\n ret.set('organization_id', toActivate.organizationSlug);\n }\n }\n return ret;\n }\n}\n","import type { MatchFunction } from '@clerk/shared/pathToRegexp';\nimport { match } from '@clerk/shared/pathToRegexp';\n\nimport type { OrganizationSyncOptions, OrganizationSyncTarget } from './types';\n\nexport class OrganizationMatcher {\n private readonly organizationPattern: MatchFunction | null;\n private readonly personalAccountPattern: MatchFunction | null;\n\n constructor(options?: OrganizationSyncOptions) {\n this.organizationPattern = this.createMatcher(options?.organizationPatterns);\n this.personalAccountPattern = this.createMatcher(options?.personalAccountPatterns);\n }\n\n private createMatcher(pattern?: string[]): MatchFunction | null {\n if (!pattern) {\n return null;\n }\n try {\n return match(pattern);\n } catch (e) {\n throw new Error(`Invalid pattern \"${pattern}\": ${e}`);\n }\n }\n\n findTarget(url: URL): OrganizationSyncTarget | null {\n const orgTarget = this.findOrganizationTarget(url);\n if (orgTarget) {\n return orgTarget;\n }\n\n return this.findPersonalAccountTarget(url);\n }\n\n private findOrganizationTarget(url: URL): OrganizationSyncTarget | null {\n if (!this.organizationPattern) {\n return null;\n }\n\n try {\n const result = this.organizationPattern(url.pathname);\n if (!result || !('params' in result)) {\n return null;\n }\n\n const params = result.params as { id?: string; slug?: string };\n if (params.id) {\n return { type: 'organization', organizationId: params.id };\n }\n if (params.slug) {\n return { type: 'organization', organizationSlug: params.slug };\n }\n\n return null;\n } catch (e) {\n console.error('Failed to match organization pattern:', e);\n return null;\n }\n }\n\n private findPersonalAccountTarget(url: URL): OrganizationSyncTarget | null {\n if (!this.personalAccountPattern) {\n return null;\n }\n\n try {\n const result = this.personalAccountPattern(url.pathname);\n return result ? { type: 'personalAccount' } : null;\n } catch (e) {\n console.error('Failed to match personal account pattern:', e);\n return null;\n }\n }\n}\n","import type { JwtPayload } from '@clerk/types';\n\nimport { constants } from '../constants';\nimport type { TokenCarrier } from '../errors';\nimport { MachineTokenVerificationError, TokenVerificationError, TokenVerificationErrorReason } from '../errors';\nimport { decodeJwt } from '../jwt/verifyJwt';\nimport { assertValidSecretKey } from '../util/optionsAssertions';\nimport { isDevelopmentFromSecretKey } from '../util/shared';\nimport type { AuthenticateContext } from './authenticateContext';\nimport { createAuthenticateContext } from './authenticateContext';\nimport type { SignedInAuthObject } from './authObjects';\nimport type { HandshakeState, RequestState, SignedInState, SignedOutState, UnauthenticatedState } from './authStatus';\nimport { AuthErrorReason, handshake, signedIn, signedOut, signedOutInvalidToken } from './authStatus';\nimport { createClerkRequest } from './clerkRequest';\nimport { getCookieName, getCookieValue } from './cookie';\nimport { HandshakeService } from './handshake';\nimport { getMachineTokenType, isMachineTokenByPrefix, isTokenTypeAccepted } from './machine';\nimport { OrganizationMatcher } from './organizationMatcher';\nimport type { MachineTokenType, SessionTokenType } from './tokenTypes';\nimport { TokenType } from './tokenTypes';\nimport type { AuthenticateRequestOptions } from './types';\nimport { verifyMachineAuthToken, verifyToken } from './verify';\n\nexport const RefreshTokenErrorReason = {\n NonEligibleNoCookie: 'non-eligible-no-refresh-cookie',\n NonEligibleNonGet: 'non-eligible-non-get',\n InvalidSessionToken: 'invalid-session-token',\n MissingApiClient: 'missing-api-client',\n MissingSessionToken: 'missing-session-token',\n MissingRefreshToken: 'missing-refresh-token',\n ExpiredSessionTokenDecodeFailed: 'expired-session-token-decode-failed',\n ExpiredSessionTokenMissingSidClaim: 'expired-session-token-missing-sid-claim',\n FetchError: 'fetch-error',\n UnexpectedSDKError: 'unexpected-sdk-error',\n UnexpectedBAPIError: 'unexpected-bapi-error',\n} as const;\n\nfunction assertSignInUrlExists(signInUrl: string | undefined, key: string): asserts signInUrl is string {\n if (!signInUrl && isDevelopmentFromSecretKey(key)) {\n throw new Error(`Missing signInUrl. Pass a signInUrl for dev instances if an app is satellite`);\n }\n}\n\nfunction assertProxyUrlOrDomain(proxyUrlOrDomain: string | undefined) {\n if (!proxyUrlOrDomain) {\n throw new Error(`Missing domain and proxyUrl. A satellite application needs to specify a domain or a proxyUrl`);\n }\n}\n\nfunction assertSignInUrlFormatAndOrigin(_signInUrl: string, origin: string) {\n let signInUrl: URL;\n try {\n signInUrl = new URL(_signInUrl);\n } catch {\n throw new Error(`The signInUrl needs to have a absolute url format.`);\n }\n\n if (signInUrl.origin === origin) {\n throw new Error(`The signInUrl needs to be on a different origin than your satellite application.`);\n }\n}\n\nfunction assertMachineSecretOrSecretKey(authenticateContext: AuthenticateContext) {\n if (!authenticateContext.machineSecretKey && !authenticateContext.secretKey) {\n throw new Error(\n 'Machine token authentication requires either a Machine secret key or a Clerk secret key. ' +\n 'Ensure a Clerk secret key or Machine secret key is set.',\n );\n }\n}\n\nfunction isRequestEligibleForRefresh(\n err: TokenVerificationError,\n authenticateContext: { refreshTokenInCookie?: string },\n request: Request,\n) {\n return (\n err.reason === TokenVerificationErrorReason.TokenExpired &&\n !!authenticateContext.refreshTokenInCookie &&\n request.method === 'GET'\n );\n}\n\nfunction checkTokenTypeMismatch(\n parsedTokenType: MachineTokenType,\n acceptsToken: NonNullable,\n authenticateContext: AuthenticateContext,\n): UnauthenticatedState | null {\n const mismatch = !isTokenTypeAccepted(parsedTokenType, acceptsToken);\n if (mismatch) {\n const tokenTypeToReturn = (typeof acceptsToken === 'string' ? acceptsToken : parsedTokenType) as MachineTokenType;\n return signedOut({\n tokenType: tokenTypeToReturn,\n authenticateContext,\n reason: AuthErrorReason.TokenTypeMismatch,\n });\n }\n return null;\n}\n\nfunction isTokenTypeInAcceptedArray(acceptsToken: TokenType[], authenticateContext: AuthenticateContext): boolean {\n let parsedTokenType: TokenType | null = null;\n const { tokenInHeader } = authenticateContext;\n if (tokenInHeader) {\n if (isMachineTokenByPrefix(tokenInHeader)) {\n parsedTokenType = getMachineTokenType(tokenInHeader);\n } else {\n parsedTokenType = TokenType.SessionToken;\n }\n }\n const typeToCheck = parsedTokenType ?? TokenType.SessionToken;\n return isTokenTypeAccepted(typeToCheck, acceptsToken);\n}\n\nexport interface AuthenticateRequest {\n /**\n * @example\n * clerkClient.authenticateRequest(request, { acceptsToken: ['session_token', 'api_key'] });\n */\n (\n request: Request,\n options: AuthenticateRequestOptions & { acceptsToken: T },\n ): Promise>;\n\n /**\n * @example\n * clerkClient.authenticateRequest(request, { acceptsToken: 'session_token' });\n */\n (\n request: Request,\n options: AuthenticateRequestOptions & { acceptsToken: T },\n ): Promise>;\n\n /**\n * @example\n * clerkClient.authenticateRequest(request, { acceptsToken: 'any' });\n */\n (request: Request, options: AuthenticateRequestOptions & { acceptsToken: 'any' }): Promise>;\n\n /**\n * @example\n * clerkClient.authenticateRequest(request);\n */\n (request: Request, options?: AuthenticateRequestOptions): Promise>;\n}\n\nexport const authenticateRequest: AuthenticateRequest = (async (\n request: Request,\n options: AuthenticateRequestOptions,\n): Promise | UnauthenticatedState> => {\n const authenticateContext = await createAuthenticateContext(createClerkRequest(request), options);\n\n // Default tokenType is session_token for backwards compatibility.\n const acceptsToken = options.acceptsToken ?? TokenType.SessionToken;\n\n // machine-to-machine tokens can accept a machine secret or a secret key\n if (acceptsToken !== TokenType.M2MToken) {\n assertValidSecretKey(authenticateContext.secretKey);\n\n if (authenticateContext.isSatellite) {\n assertSignInUrlExists(authenticateContext.signInUrl, authenticateContext.secretKey);\n if (authenticateContext.signInUrl && authenticateContext.origin) {\n assertSignInUrlFormatAndOrigin(authenticateContext.signInUrl, authenticateContext.origin);\n }\n assertProxyUrlOrDomain(authenticateContext.proxyUrl || authenticateContext.domain);\n }\n }\n\n // Make sure a machine secret or instance secret key is provided if acceptsToken is m2m_token\n if (acceptsToken === TokenType.M2MToken) {\n assertMachineSecretOrSecretKey(authenticateContext);\n }\n\n const organizationMatcher = new OrganizationMatcher(options.organizationSyncOptions);\n const handshakeService = new HandshakeService(\n authenticateContext,\n { organizationSyncOptions: options.organizationSyncOptions },\n organizationMatcher,\n );\n\n async function refreshToken(\n authenticateContext: AuthenticateContext,\n ): Promise<{ data: string[]; error: null } | { data: null; error: any }> {\n // To perform a token refresh, apiClient must be defined.\n if (!options.apiClient) {\n return {\n data: null,\n error: {\n message: 'An apiClient is needed to perform token refresh.',\n cause: { reason: RefreshTokenErrorReason.MissingApiClient },\n },\n };\n }\n const { sessionToken: expiredSessionToken, refreshTokenInCookie: refreshToken } = authenticateContext;\n if (!expiredSessionToken) {\n return {\n data: null,\n error: {\n message: 'Session token must be provided.',\n cause: { reason: RefreshTokenErrorReason.MissingSessionToken },\n },\n };\n }\n if (!refreshToken) {\n return {\n data: null,\n error: {\n message: 'Refresh token must be provided.',\n cause: { reason: RefreshTokenErrorReason.MissingRefreshToken },\n },\n };\n }\n // The token refresh endpoint requires a sessionId, so we decode that from the expired token.\n const { data: decodeResult, errors: decodedErrors } = decodeJwt(expiredSessionToken);\n if (!decodeResult || decodedErrors) {\n return {\n data: null,\n error: {\n message: 'Unable to decode the expired session token.',\n cause: { reason: RefreshTokenErrorReason.ExpiredSessionTokenDecodeFailed, errors: decodedErrors },\n },\n };\n }\n\n if (!decodeResult?.payload?.sid) {\n return {\n data: null,\n error: {\n message: 'Expired session token is missing the `sid` claim.',\n cause: { reason: RefreshTokenErrorReason.ExpiredSessionTokenMissingSidClaim },\n },\n };\n }\n\n try {\n // Perform the actual token refresh.\n const response = await options.apiClient.sessions.refreshSession(decodeResult.payload.sid, {\n format: 'cookie',\n suffixed_cookies: authenticateContext.usesSuffixedCookies(),\n expired_token: expiredSessionToken || '',\n refresh_token: refreshToken || '',\n request_origin: authenticateContext.clerkUrl.origin,\n // The refresh endpoint expects headers as Record, so we need to transform it.\n request_headers: Object.fromEntries(Array.from(request.headers.entries()).map(([k, v]) => [k, [v]])),\n });\n return { data: response.cookies, error: null };\n } catch (err: any) {\n if (err?.errors?.length) {\n if (err.errors[0].code === 'unexpected_error') {\n return {\n data: null,\n error: {\n message: `Fetch unexpected error`,\n cause: { reason: RefreshTokenErrorReason.FetchError, errors: err.errors },\n },\n };\n }\n return {\n data: null,\n error: {\n message: err.errors[0].code,\n cause: { reason: err.errors[0].code, errors: err.errors },\n },\n };\n } else {\n return {\n data: null,\n error: {\n message: `Unexpected Server/BAPI error`,\n cause: { reason: RefreshTokenErrorReason.UnexpectedBAPIError, errors: [err] },\n },\n };\n }\n }\n }\n\n async function attemptRefresh(\n authenticateContext: AuthenticateContext,\n ): Promise<\n | { data: { jwtPayload: JwtPayload; sessionToken: string; headers: Headers }; error: null }\n | { data: null; error: any }\n > {\n const { data: cookiesToSet, error } = await refreshToken(authenticateContext);\n if (!cookiesToSet || cookiesToSet.length === 0) {\n return { data: null, error };\n }\n\n const headers = new Headers();\n let sessionToken = '';\n cookiesToSet.forEach((x: string) => {\n headers.append('Set-Cookie', x);\n if (getCookieName(x).startsWith(constants.Cookies.Session)) {\n sessionToken = getCookieValue(x);\n }\n });\n\n // Since we're going to return a signedIn response, we need to decode the data from the new sessionToken.\n const { data: jwtPayload, errors } = await verifyToken(sessionToken, authenticateContext);\n if (errors) {\n return {\n data: null,\n error: {\n message: `Clerk: unable to verify refreshed session token.`,\n cause: { reason: RefreshTokenErrorReason.InvalidSessionToken, errors },\n },\n };\n }\n return { data: { jwtPayload, sessionToken, headers }, error: null };\n }\n\n function handleMaybeHandshakeStatus(\n authenticateContext: AuthenticateContext,\n reason: string,\n message: string,\n headers?: Headers,\n ): SignedInState | SignedOutState | HandshakeState {\n if (!handshakeService.isRequestEligibleForHandshake()) {\n return signedOut({\n tokenType: TokenType.SessionToken,\n authenticateContext,\n reason,\n message,\n });\n }\n\n // Right now the only usage of passing in different headers is for multi-domain sync, which redirects somewhere else.\n // In the future if we want to decorate the handshake redirect with additional headers per call we need to tweak this logic.\n const handshakeHeaders = headers ?? handshakeService.buildRedirectToHandshake(reason);\n\n // Chrome aggressively caches inactive tabs. If we don't set the header here,\n // all 307 redirects will be cached and the handshake will end up in an infinite loop.\n if (handshakeHeaders.get(constants.Headers.Location)) {\n handshakeHeaders.set(constants.Headers.CacheControl, 'no-store');\n }\n\n // Introduce the mechanism to protect for infinite handshake redirect loops\n // using a cookie and returning true if it's infinite redirect loop or false if we can\n // proceed with triggering handshake.\n const isRedirectLoop = handshakeService.checkAndTrackRedirectLoop(handshakeHeaders);\n if (isRedirectLoop) {\n const msg = `Clerk: Refreshing the session token resulted in an infinite redirect loop. This usually means that your Clerk instance keys do not match - make sure to copy the correct publishable and secret keys from the Clerk dashboard.`;\n console.log(msg);\n return signedOut({\n tokenType: TokenType.SessionToken,\n authenticateContext,\n reason,\n message,\n });\n }\n\n return handshake(authenticateContext, reason, message, handshakeHeaders);\n }\n\n /**\n * Determines if a handshake must occur to resolve a mismatch between the organization as specified\n * by the URL (according to the options) and the actual active organization on the session.\n *\n * @returns {HandshakeState | SignedOutState | null} - The function can return the following:\n * - {HandshakeState}: If a handshake is needed to resolve the mismatched organization.\n * - {SignedOutState}: If a handshake is required but cannot be performed.\n * - {null}: If no action is required.\n */\n function handleMaybeOrganizationSyncHandshake(\n authenticateContext: AuthenticateContext,\n auth: SignedInAuthObject,\n ): HandshakeState | SignedOutState | null {\n const organizationSyncTarget = organizationMatcher.findTarget(authenticateContext.clerkUrl);\n if (!organizationSyncTarget) {\n return null;\n }\n let mustActivate = false;\n if (organizationSyncTarget.type === 'organization') {\n // Activate an org by slug?\n if (organizationSyncTarget.organizationSlug && organizationSyncTarget.organizationSlug !== auth.orgSlug) {\n mustActivate = true;\n }\n // Activate an org by ID?\n if (organizationSyncTarget.organizationId && organizationSyncTarget.organizationId !== auth.orgId) {\n mustActivate = true;\n }\n }\n // Activate the personal account?\n if (organizationSyncTarget.type === 'personalAccount' && auth.orgId) {\n mustActivate = true;\n }\n if (!mustActivate) {\n return null;\n }\n if (authenticateContext.handshakeRedirectLoopCounter >= 3) {\n // We have an organization that needs to be activated, but this isn't our first time redirecting.\n // This is because we attempted to activate the organization previously, but the organization\n // must not have been valid (either not found, or not valid for this user), and gave us back\n // a null organization. We won't re-try the handshake, and leave it to the server component to handle.\n console.warn(\n 'Clerk: Organization activation handshake loop detected. This is likely due to an invalid organization ID or slug. Skipping organization activation.',\n );\n return null;\n }\n const handshakeState = handleMaybeHandshakeStatus(\n authenticateContext,\n AuthErrorReason.ActiveOrganizationMismatch,\n '',\n );\n if (handshakeState.status !== 'handshake') {\n // Currently, this is only possible if we're in a redirect loop, but the above check should guard against that.\n return null;\n }\n return handshakeState;\n }\n\n async function authenticateRequestWithTokenInHeader() {\n const { tokenInHeader } = authenticateContext;\n\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const { data, errors } = await verifyToken(tokenInHeader!, authenticateContext);\n if (errors) {\n throw errors[0];\n }\n // use `await` to force this try/catch handle the signedIn invocation\n return signedIn({\n tokenType: TokenType.SessionToken,\n authenticateContext,\n sessionClaims: data,\n headers: new Headers(),\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n token: tokenInHeader!,\n });\n } catch (err) {\n return handleSessionTokenError(err, 'header');\n }\n }\n\n async function authenticateRequestWithTokenInCookie() {\n const hasActiveClient = authenticateContext.clientUat;\n const hasSessionToken = !!authenticateContext.sessionTokenInCookie;\n const hasDevBrowserToken = !!authenticateContext.devBrowserToken;\n\n /**\n * If we have a handshakeToken, resolve the handshake and attempt to return a definitive signed in or signed out state.\n */\n if (authenticateContext.handshakeNonce || authenticateContext.handshakeToken) {\n try {\n return await handshakeService.resolveHandshake();\n } catch (error) {\n // In production, the handshake token is being transferred as a cookie, so there is a possibility of collision\n // with a handshake token of another app running on the same etld+1 domain.\n // For example, if one app is running on sub1.clerk.com and another on sub2.clerk.com, the handshake token\n // cookie for both apps will be set on etld+1 (clerk.com) so there's a possibility that one app will accidentally\n // use the handshake token of a different app during the handshake flow.\n // In this scenario, verification will fail with TokenInvalidSignature. In contrast to the development case,\n // we need to allow the flow to continue so the app eventually retries another handshake with the correct token.\n // We need to make sure, however, that we don't allow the flow to continue indefinitely, so we throw an error after X\n // retries to avoid an infinite loop. An infinite loop can happen if the customer switched Clerk keys for their prod app.\n\n // Check the handleTokenVerificationErrorInDevelopment method for the development case.\n if (error instanceof TokenVerificationError && authenticateContext.instanceType === 'development') {\n handshakeService.handleTokenVerificationErrorInDevelopment(error);\n } else {\n console.error('Clerk: unable to resolve handshake:', error);\n }\n }\n }\n /**\n * Otherwise, check for \"known unknown\" auth states that we can resolve with a handshake.\n */\n if (\n authenticateContext.instanceType === 'development' &&\n authenticateContext.clerkUrl.searchParams.has(constants.QueryParameters.DevBrowser)\n ) {\n return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.DevBrowserSync, '');\n }\n\n const isRequestEligibleForMultiDomainSync =\n authenticateContext.isSatellite && authenticateContext.secFetchDest === 'document';\n\n /**\n * Begin multi-domain sync flows\n */\n if (authenticateContext.instanceType === 'production' && isRequestEligibleForMultiDomainSync) {\n return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.SatelliteCookieNeedsSyncing, '');\n }\n\n // Multi-domain development sync flow\n if (\n authenticateContext.instanceType === 'development' &&\n isRequestEligibleForMultiDomainSync &&\n !authenticateContext.clerkUrl.searchParams.has(constants.QueryParameters.ClerkSynced)\n ) {\n // initiate MD sync\n\n // signInUrl exists, checked at the top of `authenticateRequest`\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const redirectURL = new URL(authenticateContext.signInUrl!);\n redirectURL.searchParams.append(\n constants.QueryParameters.ClerkRedirectUrl,\n authenticateContext.clerkUrl.toString(),\n );\n const headers = new Headers({ [constants.Headers.Location]: redirectURL.toString() });\n return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.SatelliteCookieNeedsSyncing, '', headers);\n }\n\n // Multi-domain development sync flow\n const redirectUrl = new URL(authenticateContext.clerkUrl).searchParams.get(\n constants.QueryParameters.ClerkRedirectUrl,\n );\n\n if (authenticateContext.instanceType === 'development' && !authenticateContext.isSatellite && redirectUrl) {\n // Dev MD sync from primary, redirect back to satellite w/ dev browser query param\n const redirectBackToSatelliteUrl = new URL(redirectUrl);\n\n if (authenticateContext.devBrowserToken) {\n redirectBackToSatelliteUrl.searchParams.append(\n constants.QueryParameters.DevBrowser,\n authenticateContext.devBrowserToken,\n );\n }\n redirectBackToSatelliteUrl.searchParams.append(constants.QueryParameters.ClerkSynced, 'true');\n\n const headers = new Headers({ [constants.Headers.Location]: redirectBackToSatelliteUrl.toString() });\n return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.PrimaryRespondsToSyncing, '', headers);\n }\n /**\n * End multi-domain sync flows\n */\n\n if (authenticateContext.instanceType === 'development' && !hasDevBrowserToken) {\n return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.DevBrowserMissing, '');\n }\n\n if (!hasActiveClient && !hasSessionToken) {\n return signedOut({\n tokenType: TokenType.SessionToken,\n authenticateContext,\n reason: AuthErrorReason.SessionTokenAndUATMissing,\n });\n }\n\n // This can eagerly run handshake since client_uat is SameSite=Strict in dev\n if (!hasActiveClient && hasSessionToken) {\n return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.SessionTokenWithoutClientUAT, '');\n }\n\n if (hasActiveClient && !hasSessionToken) {\n return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.ClientUATWithoutSessionToken, '');\n }\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const { data: decodeResult, errors: decodedErrors } = decodeJwt(authenticateContext.sessionTokenInCookie!);\n\n if (decodedErrors) {\n return handleSessionTokenError(decodedErrors[0], 'cookie');\n }\n\n if (decodeResult.payload.iat < authenticateContext.clientUat) {\n return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.SessionTokenIATBeforeClientUAT, '');\n }\n\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const { data, errors } = await verifyToken(authenticateContext.sessionTokenInCookie!, authenticateContext);\n if (errors) {\n throw errors[0];\n }\n\n const signedInRequestState = signedIn({\n tokenType: TokenType.SessionToken,\n authenticateContext,\n sessionClaims: data,\n headers: new Headers(),\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n token: authenticateContext.sessionTokenInCookie!,\n });\n\n // Check for cross-origin requests from satellite domains to primary domain\n const shouldForceHandshakeForCrossDomain =\n !authenticateContext.isSatellite && // We're on primary\n authenticateContext.secFetchDest === 'document' && // Document navigation\n authenticateContext.isCrossOriginReferrer() && // Came from different domain\n !authenticateContext.isKnownClerkReferrer() && // Not from Clerk accounts portal or FAPI\n authenticateContext.handshakeRedirectLoopCounter === 0; // Not in a redirect loop\n\n if (shouldForceHandshakeForCrossDomain) {\n return handleMaybeHandshakeStatus(\n authenticateContext,\n AuthErrorReason.PrimaryDomainCrossOriginSync,\n 'Cross-origin request from satellite domain requires handshake',\n );\n }\n\n const authObject = signedInRequestState.toAuth();\n // Org sync if necessary\n if (authObject.userId) {\n const handshakeRequestState = handleMaybeOrganizationSyncHandshake(authenticateContext, authObject);\n if (handshakeRequestState) {\n return handshakeRequestState;\n }\n }\n\n return signedInRequestState;\n } catch (err) {\n return handleSessionTokenError(err, 'cookie');\n }\n\n // Unreachable\n return signedOut({\n tokenType: TokenType.SessionToken,\n authenticateContext,\n reason: AuthErrorReason.UnexpectedError,\n });\n }\n\n async function handleSessionTokenError(\n err: unknown,\n tokenCarrier: TokenCarrier,\n ): Promise {\n if (!(err instanceof TokenVerificationError)) {\n return signedOut({\n tokenType: TokenType.SessionToken,\n authenticateContext,\n reason: AuthErrorReason.UnexpectedError,\n });\n }\n\n let refreshError: string | null;\n\n if (isRequestEligibleForRefresh(err, authenticateContext, request)) {\n const { data, error } = await attemptRefresh(authenticateContext);\n if (data) {\n return signedIn({\n tokenType: TokenType.SessionToken,\n authenticateContext,\n sessionClaims: data.jwtPayload,\n headers: data.headers,\n token: data.sessionToken,\n });\n }\n\n // If there's any error, simply fallback to the handshake flow including the reason as a query parameter.\n if (error?.cause?.reason) {\n refreshError = error.cause.reason;\n } else {\n refreshError = RefreshTokenErrorReason.UnexpectedSDKError;\n }\n } else {\n if (request.method !== 'GET') {\n refreshError = RefreshTokenErrorReason.NonEligibleNonGet;\n } else if (!authenticateContext.refreshTokenInCookie) {\n refreshError = RefreshTokenErrorReason.NonEligibleNoCookie;\n } else {\n //refresh error is not applicable if token verification error is not 'session-token-expired'\n refreshError = null;\n }\n }\n\n err.tokenCarrier = tokenCarrier;\n\n const reasonToHandshake = [\n TokenVerificationErrorReason.TokenExpired,\n TokenVerificationErrorReason.TokenNotActiveYet,\n TokenVerificationErrorReason.TokenIatInTheFuture,\n ].includes(err.reason);\n\n if (reasonToHandshake) {\n return handleMaybeHandshakeStatus(\n authenticateContext,\n convertTokenVerificationErrorReasonToAuthErrorReason({ tokenError: err.reason, refreshError }),\n err.getFullMessage(),\n );\n }\n\n return signedOut({\n tokenType: TokenType.SessionToken,\n authenticateContext,\n reason: err.reason,\n message: err.getFullMessage(),\n });\n }\n\n function handleMachineError(tokenType: MachineTokenType, err: unknown): UnauthenticatedState {\n if (!(err instanceof MachineTokenVerificationError)) {\n return signedOut({\n tokenType,\n authenticateContext,\n reason: AuthErrorReason.UnexpectedError,\n });\n }\n\n return signedOut({\n tokenType,\n authenticateContext,\n reason: err.code,\n message: err.getFullMessage(),\n });\n }\n\n async function authenticateMachineRequestWithTokenInHeader() {\n const { tokenInHeader } = authenticateContext;\n // Use session token error handling if no token in header (default behavior)\n if (!tokenInHeader) {\n return handleSessionTokenError(new Error('Missing token in header'), 'header');\n }\n\n // Handle case where tokenType is any and the token is not a machine token\n if (!isMachineTokenByPrefix(tokenInHeader)) {\n return signedOut({\n tokenType: acceptsToken as TokenType,\n authenticateContext,\n reason: AuthErrorReason.TokenTypeMismatch,\n message: '',\n });\n }\n\n const parsedTokenType = getMachineTokenType(tokenInHeader);\n const mismatchState = checkTokenTypeMismatch(parsedTokenType, acceptsToken, authenticateContext);\n if (mismatchState) {\n return mismatchState;\n }\n\n const { data, tokenType, errors } = await verifyMachineAuthToken(tokenInHeader, authenticateContext);\n if (errors) {\n return handleMachineError(tokenType, errors[0]);\n }\n return signedIn({\n tokenType,\n authenticateContext,\n machineData: data,\n token: tokenInHeader,\n });\n }\n\n async function authenticateAnyRequestWithTokenInHeader() {\n const { tokenInHeader } = authenticateContext;\n // Use session token error handling if no token in header (default behavior)\n if (!tokenInHeader) {\n return handleSessionTokenError(new Error('Missing token in header'), 'header');\n }\n\n // Handle as a machine token\n if (isMachineTokenByPrefix(tokenInHeader)) {\n const parsedTokenType = getMachineTokenType(tokenInHeader);\n const mismatchState = checkTokenTypeMismatch(parsedTokenType, acceptsToken, authenticateContext);\n if (mismatchState) {\n return mismatchState;\n }\n\n const { data, tokenType, errors } = await verifyMachineAuthToken(tokenInHeader, authenticateContext);\n if (errors) {\n return handleMachineError(tokenType, errors[0]);\n }\n\n return signedIn({\n tokenType,\n authenticateContext,\n machineData: data,\n token: tokenInHeader,\n });\n }\n\n // Handle as a regular session token\n const { data, errors } = await verifyToken(tokenInHeader, authenticateContext);\n if (errors) {\n return handleSessionTokenError(errors[0], 'header');\n }\n\n return signedIn({\n tokenType: TokenType.SessionToken,\n authenticateContext,\n sessionClaims: data,\n token: tokenInHeader,\n });\n }\n\n // If acceptsToken is an array, early check if the token is in the accepted array\n // to avoid unnecessary verification calls\n if (Array.isArray(acceptsToken)) {\n if (!isTokenTypeInAcceptedArray(acceptsToken, authenticateContext)) {\n return signedOutInvalidToken();\n }\n }\n\n if (authenticateContext.tokenInHeader) {\n if (acceptsToken === 'any') {\n return authenticateAnyRequestWithTokenInHeader();\n }\n if (acceptsToken === TokenType.SessionToken) {\n return authenticateRequestWithTokenInHeader();\n }\n return authenticateMachineRequestWithTokenInHeader();\n }\n\n // Machine requests cannot have the token in the cookie, it must be in header.\n if (\n acceptsToken === TokenType.OAuthToken ||\n acceptsToken === TokenType.ApiKey ||\n acceptsToken === TokenType.M2MToken\n ) {\n return signedOut({\n tokenType: acceptsToken,\n authenticateContext,\n reason: 'No token in header',\n });\n }\n\n return authenticateRequestWithTokenInCookie();\n}) as AuthenticateRequest;\n\n/**\n * @internal\n */\nexport const debugRequestState = (params: RequestState) => {\n const { isSignedIn, isAuthenticated, proxyUrl, reason, message, publishableKey, isSatellite, domain } = params;\n return { isSignedIn, isAuthenticated, proxyUrl, reason, message, publishableKey, isSatellite, domain };\n};\n\nconst convertTokenVerificationErrorReasonToAuthErrorReason = ({\n tokenError,\n refreshError,\n}: {\n tokenError: TokenVerificationErrorReason;\n refreshError: string | null;\n}): string => {\n switch (tokenError) {\n case TokenVerificationErrorReason.TokenExpired:\n return `${AuthErrorReason.SessionTokenExpired}-refresh-${refreshError}`;\n case TokenVerificationErrorReason.TokenNotActiveYet:\n return AuthErrorReason.SessionTokenNBF;\n case TokenVerificationErrorReason.TokenIatInTheFuture:\n return AuthErrorReason.SessionTokenIatInTheFuture;\n default:\n return AuthErrorReason.UnexpectedError;\n }\n};\n","import type { ApiClient } from '../api';\nimport { mergePreDefinedOptions } from '../util/mergePreDefinedOptions';\nimport type { AuthenticateRequest } from './request';\nimport { authenticateRequest as authenticateRequestOriginal, debugRequestState } from './request';\nimport type { AuthenticateRequestOptions } from './types';\n\ntype RunTimeOptions = Omit;\ntype BuildTimeOptions = Partial<\n Pick<\n AuthenticateRequestOptions,\n | 'apiUrl'\n | 'apiVersion'\n | 'audience'\n | 'domain'\n | 'isSatellite'\n | 'jwtKey'\n | 'proxyUrl'\n | 'publishableKey'\n | 'secretKey'\n | 'machineSecretKey'\n >\n>;\n\nconst defaultOptions = {\n secretKey: '',\n machineSecretKey: '',\n jwtKey: '',\n apiUrl: undefined,\n apiVersion: undefined,\n proxyUrl: '',\n publishableKey: '',\n isSatellite: false,\n domain: '',\n audience: '',\n} satisfies BuildTimeOptions;\n\n/**\n * @internal\n */\nexport type CreateAuthenticateRequestOptions = {\n options: BuildTimeOptions;\n apiClient: ApiClient;\n};\n\n/**\n * @internal\n */\nexport function createAuthenticateRequest(params: CreateAuthenticateRequestOptions) {\n const buildTimeOptions = mergePreDefinedOptions(defaultOptions, params.options);\n const apiClient = params.apiClient;\n\n const authenticateRequest: AuthenticateRequest = (request: Request, options: RunTimeOptions = {}) => {\n const { apiUrl, apiVersion } = buildTimeOptions;\n const runTimeOptions = mergePreDefinedOptions(buildTimeOptions, options);\n return authenticateRequestOriginal(request, {\n ...options,\n ...runTimeOptions,\n // We should add all the omitted props from options here (eg apiUrl / apiVersion)\n // to avoid runtime options override them.\n apiUrl,\n apiVersion,\n apiClient,\n });\n };\n\n return {\n authenticateRequest,\n debugRequestState,\n };\n}\n","import type { CreateBackendApiOptions, Organization, Session, User } from '../api';\nimport { createBackendApiClient } from '../api';\nimport type { AuthObject, SignedInAuthObject, SignedOutAuthObject } from '../tokens/authObjects';\n\ntype DecorateAuthWithResourcesOptions = {\n loadSession?: boolean;\n loadUser?: boolean;\n loadOrganization?: boolean;\n};\n\ntype WithResources = T & {\n session?: Session | null;\n user?: User | null;\n organization?: Organization | null;\n};\n\n/**\n * @internal\n */\nexport const decorateObjectWithResources = async (\n obj: T,\n authObj: AuthObject,\n opts: CreateBackendApiOptions & DecorateAuthWithResourcesOptions,\n): Promise> => {\n const { loadSession, loadUser, loadOrganization } = opts || {};\n const { userId, sessionId, orgId } = authObj as SignedInAuthObject | SignedOutAuthObject;\n\n const { sessions, users, organizations } = createBackendApiClient({ ...opts });\n\n const [sessionResp, userResp, organizationResp] = await Promise.all([\n loadSession && sessionId ? sessions.getSession(sessionId) : Promise.resolve(undefined),\n loadUser && userId ? users.getUser(userId) : Promise.resolve(undefined),\n loadOrganization && orgId ? organizations.getOrganization({ organizationId: orgId }) : Promise.resolve(undefined),\n ]);\n\n const resources = stripPrivateDataFromObject({\n session: sessionResp,\n user: userResp,\n organization: organizationResp,\n });\n return Object.assign(obj, resources);\n};\n\n/**\n * @internal\n */\nexport function stripPrivateDataFromObject>(authObject: T): T {\n const user = authObject.user ? { ...authObject.user } : authObject.user;\n const organization = authObject.organization ? { ...authObject.organization } : authObject.organization;\n prunePrivateMetadata(user);\n prunePrivateMetadata(organization);\n return { ...authObject, user, organization };\n}\n\nfunction prunePrivateMetadata(resource?: { private_metadata: any } | { privateMetadata: any } | null) {\n // Delete sensitive private metadata from resource before rendering in SSR\n if (resource) {\n if ('privateMetadata' in resource) {\n delete resource['privateMetadata'];\n }\n if ('private_metadata' in resource) {\n delete resource['private_metadata'];\n }\n }\n\n return resource;\n}\n","export { constants } from './constants';\nexport { createRedirect } from './createRedirect';\nexport type { RedirectFun } from './createRedirect';\n\nexport type { CreateAuthenticateRequestOptions } from './tokens/factory';\nexport { createAuthenticateRequest } from './tokens/factory';\n\nexport { debugRequestState } from './tokens/request';\n\nexport type {\n AuthenticateRequestOptions,\n OrganizationSyncOptions,\n InferAuthObjectFromToken,\n InferAuthObjectFromTokenArray,\n GetAuthFn,\n} from './tokens/types';\n\nexport { TokenType } from './tokens/tokenTypes';\nexport type { SessionTokenType, MachineTokenType } from './tokens/tokenTypes';\n\nexport type {\n SignedInAuthObjectOptions,\n SignedInAuthObject,\n SignedOutAuthObject,\n AuthenticatedMachineObject,\n UnauthenticatedMachineObject,\n} from './tokens/authObjects';\nexport {\n makeAuthObjectSerializable,\n signedOutAuthObject,\n signedInAuthObject,\n authenticatedMachineObject,\n unauthenticatedMachineObject,\n invalidTokenAuthObject,\n getAuthObjectFromJwt,\n getAuthObjectForAcceptedToken,\n} from './tokens/authObjects';\n\nexport { AuthStatus } from './tokens/authStatus';\nexport type {\n RequestState,\n SignedInState,\n SignedOutState,\n AuthenticatedState,\n UnauthenticatedState,\n} from './tokens/authStatus';\n\nexport { decorateObjectWithResources, stripPrivateDataFromObject } from './util/decorateObjectWithResources';\n\nexport { createClerkRequest } from './tokens/clerkRequest';\nexport type { ClerkRequest } from './tokens/clerkRequest';\n\nexport { reverificationError, reverificationErrorResponse } from '@clerk/shared/authorization-errors';\n\nexport { verifyMachineAuthToken } from './tokens/verify';\n\nexport { isMachineTokenByPrefix, isMachineTokenType, getMachineTokenType, isTokenTypeAccepted } from './tokens/machine';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAO,IAAM,UAAU;AAChB,IAAM,cAAc;AAEpB,IAAM,aAAa,GAAG,gBAAY,IAAI,QAAe;AACrD,IAAM,oCAAoC,IAAI;AAC9C,IAAM,yBAAyB;AAEtC,IAAM,aAAa;AAAA,EACjB,WAAW;AAAA,EACX,eAAe;AAAA,EACf,YAAY;AAAA,EACZ,YAAY;AAAA,EACZ,aAAa;AAAA,EACb,UAAU;AACZ;AAEA,IAAM,UAAU;AAAA,EACd,SAAS;AAAA,EACT,SAAS;AAAA,EACT,WAAW;AAAA,EACX,WAAW;AAAA,EACX,YAAY;AAAA,EACZ,eAAe;AAAA,EACf,gBAAgB;AAClB;AAEA,IAAM,kBAAkB;AAAA,EACtB,aAAa;AAAA,EACb,iBAAiB;AAAA,EACjB,kBAAkB;AAAA;AAAA,EAElB,YAAY,QAAQ;AAAA,EACpB,WAAW,QAAQ;AAAA,EACnB,eAAe;AAAA,EACf,kBAAkB;AAAA,EAClB,iBAAiB;AAAA,EACjB,gBAAgB,QAAQ;AAAA,EACxB,iBAAiB;AACnB;AAEA,IAAMA,WAAU;AAAA,EACd,QAAQ;AAAA,EACR,aAAa;AAAA,EACb,eAAe;AAAA,EACf,YAAY;AAAA,EACZ,eAAe;AAAA,EACf,YAAY;AAAA,EACZ,WAAW;AAAA,EACX,cAAc;AAAA,EACd,iBAAiB;AAAA,EACjB,kBAAkB;AAAA,EAClB,UAAU;AAAA,EACV,0BAA0B;AAAA,EAC1B,aAAa;AAAA,EACb,uBAAuB;AAAA,EACvB,iCAAiC;AAAA,EACjC,aAAa;AAAA,EACb,eAAe;AAAA,EACf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SAAS,2BAA4D,YAAkB;AAC5F,QAAM,OAAO,WAAW,OAAO,EAAE,GAAG,WAAW,KAAK,IAAI,WAAW;AACnE,QAAM,eAAe,WAAW,eAAe,EAAE,GAAG,WAAW,aAAa,IAAI,WAAW;AAC3F,uBAAqB,IAAI;AACzB,uBAAqB,YAAY;AACjC,SAAO,EAAE,GAAG,YAAY,MAAM,aAAa;AAC7C;AAEA,SAAS,qBAAqB,UAAwE;AAEpG,MAAI,UAAU;AACZ,QAAI,qBAAqB,UAAU;AACjC,aAAO,SAAS,iBAAiB;AAAA,IACnC;AACA,QAAI,sBAAsB,UAAU;AAClC,aAAO,SAAS,kBAAkB;AAAA,IACpC;AAAA,EACF;AAEA,SAAO;AACT;;;ACdA,SAAS,qBAAqB,mCAAmC;","names":["Headers","buildAccountsBaseUrl","buildAccountsBaseUrl","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","match","convertCase","Cookies","data","Cookies","sessionId","jwk","authenticateContext","refreshToken","data","errors","authenticateRequest"]} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/chunk-LWOXHF4E.mjs b/backend/node_modules/@clerk/backend/dist/chunk-LWOXHF4E.mjs new file mode 100644 index 000000000..2d31f5d7c --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/chunk-LWOXHF4E.mjs @@ -0,0 +1,26 @@ +// src/util/shared.ts +import { addClerkPrefix, getScriptUrl, getClerkJsMajorVersionOrTag } from "@clerk/shared/url"; +import { retry } from "@clerk/shared/retry"; +import { + isDevelopmentFromSecretKey, + isProductionFromSecretKey, + parsePublishableKey, + getCookieSuffix, + getSuffixedCookieName +} from "@clerk/shared/keys"; +import { deprecated, deprecatedProperty } from "@clerk/shared/deprecated"; +import { buildErrorThrower } from "@clerk/shared/error"; +import { createDevOrStagingUrlCache } from "@clerk/shared/keys"; +var errorThrower = buildErrorThrower({ packageName: "@clerk/backend" }); +var { isDevOrStagingUrl } = createDevOrStagingUrlCache(); + +export { + errorThrower, + retry, + isDevelopmentFromSecretKey, + parsePublishableKey, + getCookieSuffix, + getSuffixedCookieName, + deprecated +}; +//# sourceMappingURL=chunk-LWOXHF4E.mjs.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/chunk-LWOXHF4E.mjs.map b/backend/node_modules/@clerk/backend/dist/chunk-LWOXHF4E.mjs.map new file mode 100644 index 000000000..7365d561c --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/chunk-LWOXHF4E.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../src/util/shared.ts"],"sourcesContent":["export { addClerkPrefix, getScriptUrl, getClerkJsMajorVersionOrTag } from '@clerk/shared/url';\nexport { retry } from '@clerk/shared/retry';\nexport {\n isDevelopmentFromSecretKey,\n isProductionFromSecretKey,\n parsePublishableKey,\n getCookieSuffix,\n getSuffixedCookieName,\n} from '@clerk/shared/keys';\nexport { deprecated, deprecatedProperty } from '@clerk/shared/deprecated';\n\nimport { buildErrorThrower } from '@clerk/shared/error';\nimport { createDevOrStagingUrlCache } from '@clerk/shared/keys';\n// TODO: replace packageName with `${PACKAGE_NAME}@${PACKAGE_VERSION}` from tsup.config.ts\nexport const errorThrower = buildErrorThrower({ packageName: '@clerk/backend' });\n\nexport const { isDevOrStagingUrl } = createDevOrStagingUrlCache();\n"],"mappings":";AAAA,SAAS,gBAAgB,cAAc,mCAAmC;AAC1E,SAAS,aAAa;AACtB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,YAAY,0BAA0B;AAE/C,SAAS,yBAAyB;AAClC,SAAS,kCAAkC;AAEpC,IAAM,eAAe,kBAAkB,EAAE,aAAa,iBAAiB,CAAC;AAExE,IAAM,EAAE,kBAAkB,IAAI,2BAA2B;","names":[]} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/chunk-P263NW7Z.mjs b/backend/node_modules/@clerk/backend/dist/chunk-P263NW7Z.mjs new file mode 100644 index 000000000..e8f89afcb --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/chunk-P263NW7Z.mjs @@ -0,0 +1,25 @@ +// src/jwt/legacyReturn.ts +function withLegacyReturn(cb) { + return async (...args) => { + const { data, errors } = await cb(...args); + if (errors) { + throw errors[0]; + } + return data; + }; +} +function withLegacySyncReturn(cb) { + return (...args) => { + const { data, errors } = cb(...args); + if (errors) { + throw errors[0]; + } + return data; + }; +} + +export { + withLegacyReturn, + withLegacySyncReturn +}; +//# sourceMappingURL=chunk-P263NW7Z.mjs.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/chunk-P263NW7Z.mjs.map b/backend/node_modules/@clerk/backend/dist/chunk-P263NW7Z.mjs.map new file mode 100644 index 000000000..437d6de0f --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/chunk-P263NW7Z.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../src/jwt/legacyReturn.ts"],"sourcesContent":["import type { JwtReturnType } from './types';\n\n// TODO(dimkl): Will be probably be dropped in next major version\nexport function withLegacyReturn Promise>>(cb: T) {\n return async (...args: Parameters): Promise>['data']>> | never => {\n const { data, errors } = await cb(...args);\n if (errors) {\n throw errors[0];\n }\n return data;\n };\n}\n\n// TODO(dimkl): Will be probably be dropped in next major version\nexport function withLegacySyncReturn JwtReturnType>(cb: T) {\n return (...args: Parameters): NonNullable>['data']> | never => {\n const { data, errors } = cb(...args);\n if (errors) {\n throw errors[0];\n }\n return data;\n };\n}\n"],"mappings":";AAGO,SAAS,iBAAiF,IAAO;AACtG,SAAO,UAAU,SAAsF;AACrG,UAAM,EAAE,MAAM,OAAO,IAAI,MAAM,GAAG,GAAG,IAAI;AACzC,QAAI,QAAQ;AACV,YAAM,OAAO,CAAC;AAAA,IAChB;AACA,WAAO;AAAA,EACT;AACF;AAGO,SAAS,qBAA4E,IAAO;AACjG,SAAO,IAAI,SAA6E;AACtF,UAAM,EAAE,MAAM,OAAO,IAAI,GAAG,GAAG,IAAI;AACnC,QAAI,QAAQ;AACV,YAAM,OAAO,CAAC;AAAA,IAChB;AACA,WAAO;AAAA,EACT;AACF;","names":[]} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/chunk-RPS7XK5K.mjs b/backend/node_modules/@clerk/backend/dist/chunk-RPS7XK5K.mjs new file mode 100644 index 000000000..1df4a05eb --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/chunk-RPS7XK5K.mjs @@ -0,0 +1,12 @@ +var __typeError = (msg) => { + throw TypeError(msg); +}; +var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg); +var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value); +var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method); + +export { + __privateAdd, + __privateMethod +}; +//# sourceMappingURL=chunk-RPS7XK5K.mjs.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/chunk-RPS7XK5K.mjs.map b/backend/node_modules/@clerk/backend/dist/chunk-RPS7XK5K.mjs.map new file mode 100644 index 000000000..84c51b288 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/chunk-RPS7XK5K.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/chunk-XJ4RTXJG.mjs b/backend/node_modules/@clerk/backend/dist/chunk-XJ4RTXJG.mjs new file mode 100644 index 000000000..9a77f8254 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/chunk-XJ4RTXJG.mjs @@ -0,0 +1,393 @@ +import { + TokenVerificationError, + TokenVerificationErrorAction, + TokenVerificationErrorReason +} from "./chunk-YW6OOOXM.mjs"; + +// src/runtime.ts +import { webcrypto as crypto } from "#crypto"; +var globalFetch = fetch.bind(globalThis); +var runtime = { + crypto, + get fetch() { + return process.env.NODE_ENV === "test" ? fetch : globalFetch; + }, + AbortController: globalThis.AbortController, + Blob: globalThis.Blob, + FormData: globalThis.FormData, + Headers: globalThis.Headers, + Request: globalThis.Request, + Response: globalThis.Response +}; + +// src/util/rfc4648.ts +var base64url = { + parse(string, opts) { + return parse(string, base64UrlEncoding, opts); + }, + stringify(data, opts) { + return stringify(data, base64UrlEncoding, opts); + } +}; +var base64UrlEncoding = { + chars: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_", + bits: 6 +}; +function parse(string, encoding, opts = {}) { + if (!encoding.codes) { + encoding.codes = {}; + for (let i = 0; i < encoding.chars.length; ++i) { + encoding.codes[encoding.chars[i]] = i; + } + } + if (!opts.loose && string.length * encoding.bits & 7) { + throw new SyntaxError("Invalid padding"); + } + let end = string.length; + while (string[end - 1] === "=") { + --end; + if (!opts.loose && !((string.length - end) * encoding.bits & 7)) { + throw new SyntaxError("Invalid padding"); + } + } + const out = new (opts.out ?? Uint8Array)(end * encoding.bits / 8 | 0); + let bits = 0; + let buffer = 0; + let written = 0; + for (let i = 0; i < end; ++i) { + const value = encoding.codes[string[i]]; + if (value === void 0) { + throw new SyntaxError("Invalid character " + string[i]); + } + buffer = buffer << encoding.bits | value; + bits += encoding.bits; + if (bits >= 8) { + bits -= 8; + out[written++] = 255 & buffer >> bits; + } + } + if (bits >= encoding.bits || 255 & buffer << 8 - bits) { + throw new SyntaxError("Unexpected end of data"); + } + return out; +} +function stringify(data, encoding, opts = {}) { + const { pad = true } = opts; + const mask = (1 << encoding.bits) - 1; + let out = ""; + let bits = 0; + let buffer = 0; + for (let i = 0; i < data.length; ++i) { + buffer = buffer << 8 | 255 & data[i]; + bits += 8; + while (bits > encoding.bits) { + bits -= encoding.bits; + out += encoding.chars[mask & buffer >> bits]; + } + } + if (bits) { + out += encoding.chars[mask & buffer << encoding.bits - bits]; + } + if (pad) { + while (out.length * encoding.bits & 7) { + out += "="; + } + } + return out; +} + +// src/jwt/algorithms.ts +var algToHash = { + RS256: "SHA-256", + RS384: "SHA-384", + RS512: "SHA-512" +}; +var RSA_ALGORITHM_NAME = "RSASSA-PKCS1-v1_5"; +var jwksAlgToCryptoAlg = { + RS256: RSA_ALGORITHM_NAME, + RS384: RSA_ALGORITHM_NAME, + RS512: RSA_ALGORITHM_NAME +}; +var algs = Object.keys(algToHash); +function getCryptoAlgorithm(algorithmName) { + const hash = algToHash[algorithmName]; + const name = jwksAlgToCryptoAlg[algorithmName]; + if (!hash || !name) { + throw new Error(`Unsupported algorithm ${algorithmName}, expected one of ${algs.join(",")}.`); + } + return { + hash: { name: algToHash[algorithmName] }, + name: jwksAlgToCryptoAlg[algorithmName] + }; +} + +// src/jwt/assertions.ts +var isArrayString = (s) => { + return Array.isArray(s) && s.length > 0 && s.every((a) => typeof a === "string"); +}; +var assertAudienceClaim = (aud, audience) => { + const audienceList = [audience].flat().filter((a) => !!a); + const audList = [aud].flat().filter((a) => !!a); + const shouldVerifyAudience = audienceList.length > 0 && audList.length > 0; + if (!shouldVerifyAudience) { + return; + } + if (typeof aud === "string") { + if (!audienceList.includes(aud)) { + throw new TokenVerificationError({ + action: TokenVerificationErrorAction.EnsureClerkJWT, + reason: TokenVerificationErrorReason.TokenVerificationFailed, + message: `Invalid JWT audience claim (aud) ${JSON.stringify(aud)}. Is not included in "${JSON.stringify( + audienceList + )}".` + }); + } + } else if (isArrayString(aud)) { + if (!aud.some((a) => audienceList.includes(a))) { + throw new TokenVerificationError({ + action: TokenVerificationErrorAction.EnsureClerkJWT, + reason: TokenVerificationErrorReason.TokenVerificationFailed, + message: `Invalid JWT audience claim array (aud) ${JSON.stringify(aud)}. Is not included in "${JSON.stringify( + audienceList + )}".` + }); + } + } +}; +var assertHeaderType = (typ) => { + if (typeof typ === "undefined") { + return; + } + if (typ !== "JWT") { + throw new TokenVerificationError({ + action: TokenVerificationErrorAction.EnsureClerkJWT, + reason: TokenVerificationErrorReason.TokenInvalid, + message: `Invalid JWT type ${JSON.stringify(typ)}. Expected "JWT".` + }); + } +}; +var assertHeaderAlgorithm = (alg) => { + if (!algs.includes(alg)) { + throw new TokenVerificationError({ + action: TokenVerificationErrorAction.EnsureClerkJWT, + reason: TokenVerificationErrorReason.TokenInvalidAlgorithm, + message: `Invalid JWT algorithm ${JSON.stringify(alg)}. Supported: ${algs}.` + }); + } +}; +var assertSubClaim = (sub) => { + if (typeof sub !== "string") { + throw new TokenVerificationError({ + action: TokenVerificationErrorAction.EnsureClerkJWT, + reason: TokenVerificationErrorReason.TokenVerificationFailed, + message: `Subject claim (sub) is required and must be a string. Received ${JSON.stringify(sub)}.` + }); + } +}; +var assertAuthorizedPartiesClaim = (azp, authorizedParties) => { + if (!azp || !authorizedParties || authorizedParties.length === 0) { + return; + } + if (!authorizedParties.includes(azp)) { + throw new TokenVerificationError({ + reason: TokenVerificationErrorReason.TokenInvalidAuthorizedParties, + message: `Invalid JWT Authorized party claim (azp) ${JSON.stringify(azp)}. Expected "${authorizedParties}".` + }); + } +}; +var assertExpirationClaim = (exp, clockSkewInMs) => { + if (typeof exp !== "number") { + throw new TokenVerificationError({ + action: TokenVerificationErrorAction.EnsureClerkJWT, + reason: TokenVerificationErrorReason.TokenVerificationFailed, + message: `Invalid JWT expiry date claim (exp) ${JSON.stringify(exp)}. Expected number.` + }); + } + const currentDate = new Date(Date.now()); + const expiryDate = /* @__PURE__ */ new Date(0); + expiryDate.setUTCSeconds(exp); + const expired = expiryDate.getTime() <= currentDate.getTime() - clockSkewInMs; + if (expired) { + throw new TokenVerificationError({ + reason: TokenVerificationErrorReason.TokenExpired, + message: `JWT is expired. Expiry date: ${expiryDate.toUTCString()}, Current date: ${currentDate.toUTCString()}.` + }); + } +}; +var assertActivationClaim = (nbf, clockSkewInMs) => { + if (typeof nbf === "undefined") { + return; + } + if (typeof nbf !== "number") { + throw new TokenVerificationError({ + action: TokenVerificationErrorAction.EnsureClerkJWT, + reason: TokenVerificationErrorReason.TokenVerificationFailed, + message: `Invalid JWT not before date claim (nbf) ${JSON.stringify(nbf)}. Expected number.` + }); + } + const currentDate = new Date(Date.now()); + const notBeforeDate = /* @__PURE__ */ new Date(0); + notBeforeDate.setUTCSeconds(nbf); + const early = notBeforeDate.getTime() > currentDate.getTime() + clockSkewInMs; + if (early) { + throw new TokenVerificationError({ + reason: TokenVerificationErrorReason.TokenNotActiveYet, + message: `JWT cannot be used prior to not before date claim (nbf). Not before date: ${notBeforeDate.toUTCString()}; Current date: ${currentDate.toUTCString()};` + }); + } +}; +var assertIssuedAtClaim = (iat, clockSkewInMs) => { + if (typeof iat === "undefined") { + return; + } + if (typeof iat !== "number") { + throw new TokenVerificationError({ + action: TokenVerificationErrorAction.EnsureClerkJWT, + reason: TokenVerificationErrorReason.TokenVerificationFailed, + message: `Invalid JWT issued at date claim (iat) ${JSON.stringify(iat)}. Expected number.` + }); + } + const currentDate = new Date(Date.now()); + const issuedAtDate = /* @__PURE__ */ new Date(0); + issuedAtDate.setUTCSeconds(iat); + const postIssued = issuedAtDate.getTime() > currentDate.getTime() + clockSkewInMs; + if (postIssued) { + throw new TokenVerificationError({ + reason: TokenVerificationErrorReason.TokenIatInTheFuture, + message: `JWT issued at date claim (iat) is in the future. Issued at date: ${issuedAtDate.toUTCString()}; Current date: ${currentDate.toUTCString()};` + }); + } +}; + +// src/jwt/cryptoKeys.ts +import { isomorphicAtob } from "@clerk/shared/isomorphicAtob"; +function pemToBuffer(secret) { + const trimmed = secret.replace(/-----BEGIN.*?-----/g, "").replace(/-----END.*?-----/g, "").replace(/\s/g, ""); + const decoded = isomorphicAtob(trimmed); + const buffer = new ArrayBuffer(decoded.length); + const bufView = new Uint8Array(buffer); + for (let i = 0, strLen = decoded.length; i < strLen; i++) { + bufView[i] = decoded.charCodeAt(i); + } + return bufView; +} +function importKey(key, algorithm, keyUsage) { + if (typeof key === "object") { + return runtime.crypto.subtle.importKey("jwk", key, algorithm, false, [keyUsage]); + } + const keyData = pemToBuffer(key); + const format = keyUsage === "sign" ? "pkcs8" : "spki"; + return runtime.crypto.subtle.importKey(format, keyData, algorithm, false, [keyUsage]); +} + +// src/jwt/verifyJwt.ts +var DEFAULT_CLOCK_SKEW_IN_MS = 5 * 1e3; +async function hasValidSignature(jwt, key) { + const { header, signature, raw } = jwt; + const encoder = new TextEncoder(); + const data = encoder.encode([raw.header, raw.payload].join(".")); + const algorithm = getCryptoAlgorithm(header.alg); + try { + const cryptoKey = await importKey(key, algorithm, "verify"); + const verified = await runtime.crypto.subtle.verify(algorithm.name, cryptoKey, signature, data); + return { data: verified }; + } catch (error) { + return { + errors: [ + new TokenVerificationError({ + reason: TokenVerificationErrorReason.TokenInvalidSignature, + message: error?.message + }) + ] + }; + } +} +function decodeJwt(token) { + const tokenParts = (token || "").toString().split("."); + if (tokenParts.length !== 3) { + return { + errors: [ + new TokenVerificationError({ + reason: TokenVerificationErrorReason.TokenInvalid, + message: `Invalid JWT form. A JWT consists of three parts separated by dots.` + }) + ] + }; + } + const [rawHeader, rawPayload, rawSignature] = tokenParts; + const decoder = new TextDecoder(); + const header = JSON.parse(decoder.decode(base64url.parse(rawHeader, { loose: true }))); + const payload = JSON.parse(decoder.decode(base64url.parse(rawPayload, { loose: true }))); + const signature = base64url.parse(rawSignature, { loose: true }); + const data = { + header, + payload, + signature, + raw: { + header: rawHeader, + payload: rawPayload, + signature: rawSignature, + text: token + } + }; + return { data }; +} +async function verifyJwt(token, options) { + const { audience, authorizedParties, clockSkewInMs, key } = options; + const clockSkew = clockSkewInMs || DEFAULT_CLOCK_SKEW_IN_MS; + const { data: decoded, errors } = decodeJwt(token); + if (errors) { + return { errors }; + } + const { header, payload } = decoded; + try { + const { typ, alg } = header; + assertHeaderType(typ); + assertHeaderAlgorithm(alg); + const { azp, sub, aud, iat, exp, nbf } = payload; + assertSubClaim(sub); + assertAudienceClaim([aud], [audience]); + assertAuthorizedPartiesClaim(azp, authorizedParties); + assertExpirationClaim(exp, clockSkew); + assertActivationClaim(nbf, clockSkew); + assertIssuedAtClaim(iat, clockSkew); + } catch (err) { + return { errors: [err] }; + } + const { data: signatureValid, errors: signatureErrors } = await hasValidSignature(decoded, key); + if (signatureErrors) { + return { + errors: [ + new TokenVerificationError({ + action: TokenVerificationErrorAction.EnsureClerkJWT, + reason: TokenVerificationErrorReason.TokenVerificationFailed, + message: `Error verifying JWT signature. ${signatureErrors[0]}` + }) + ] + }; + } + if (!signatureValid) { + return { + errors: [ + new TokenVerificationError({ + reason: TokenVerificationErrorReason.TokenInvalidSignature, + message: "JWT signature is invalid." + }) + ] + }; + } + return { data: payload }; +} + +export { + runtime, + base64url, + getCryptoAlgorithm, + assertHeaderType, + assertHeaderAlgorithm, + importKey, + hasValidSignature, + decodeJwt, + verifyJwt +}; +//# sourceMappingURL=chunk-XJ4RTXJG.mjs.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/chunk-XJ4RTXJG.mjs.map b/backend/node_modules/@clerk/backend/dist/chunk-XJ4RTXJG.mjs.map new file mode 100644 index 000000000..14c1560a4 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/chunk-XJ4RTXJG.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../src/runtime.ts","../src/util/rfc4648.ts","../src/jwt/algorithms.ts","../src/jwt/assertions.ts","../src/jwt/cryptoKeys.ts","../src/jwt/verifyJwt.ts"],"sourcesContent":["/**\n * This file exports APIs that vary across runtimes (i.e. Node & Browser - V8 isolates)\n * as a singleton object.\n *\n * Runtime polyfills are written in VanillaJS for now to avoid TS complication. Moreover,\n * due to this issue https://github.com/microsoft/TypeScript/issues/44848, there is not a good way\n * to tell Typescript which conditional import to use during build type.\n *\n * The Runtime type definition ensures type safety for now.\n * Runtime js modules are copied into dist folder with bash script.\n *\n * TODO: Support TS runtime modules\n */\n\n// @ts-ignore - These are package subpaths\nimport { webcrypto as crypto } from '#crypto';\n\ntype Runtime = {\n crypto: Crypto;\n fetch: typeof globalThis.fetch;\n AbortController: typeof globalThis.AbortController;\n Blob: typeof globalThis.Blob;\n FormData: typeof globalThis.FormData;\n Headers: typeof globalThis.Headers;\n Request: typeof globalThis.Request;\n Response: typeof globalThis.Response;\n};\n\n// Invoking the global.fetch without binding it first to the globalObject fails in\n// Cloudflare Workers with an \"Illegal Invocation\" error.\n//\n// The globalThis object is supported for Node >= 12.0.\n//\n// https://github.com/supabase/supabase/issues/4417\nconst globalFetch = fetch.bind(globalThis);\n\nexport const runtime: Runtime = {\n crypto,\n get fetch() {\n // We need to use the globalFetch for Cloudflare Workers but the fetch for testing\n return process.env.NODE_ENV === 'test' ? fetch : globalFetch;\n },\n AbortController: globalThis.AbortController,\n Blob: globalThis.Blob,\n FormData: globalThis.FormData,\n Headers: globalThis.Headers,\n Request: globalThis.Request,\n Response: globalThis.Response,\n};\n","/**\n * The base64url helper was extracted from the rfc4648 package\n * in order to resolve CSJ/ESM interoperability issues\n *\n * https://github.com/swansontec/rfc4648.js\n *\n * For more context please refer to:\n * - https://github.com/evanw/esbuild/issues/1719\n * - https://github.com/evanw/esbuild/issues/532\n * - https://github.com/swansontec/rollup-plugin-mjs-entry\n */\nexport const base64url = {\n parse(string: string, opts?: ParseOptions): Uint8Array {\n return parse(string, base64UrlEncoding, opts);\n },\n\n stringify(data: ArrayLike, opts?: StringifyOptions): string {\n return stringify(data, base64UrlEncoding, opts);\n },\n};\n\nconst base64UrlEncoding: Encoding = {\n chars: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',\n bits: 6,\n};\n\ninterface Encoding {\n bits: number;\n chars: string;\n codes?: { [char: string]: number };\n}\n\ninterface ParseOptions {\n loose?: boolean;\n out?: new (size: number) => { [index: number]: number };\n}\n\ninterface StringifyOptions {\n pad?: boolean;\n}\n\nfunction parse(string: string, encoding: Encoding, opts: ParseOptions = {}): Uint8Array {\n // Build the character lookup table:\n if (!encoding.codes) {\n encoding.codes = {};\n for (let i = 0; i < encoding.chars.length; ++i) {\n encoding.codes[encoding.chars[i]] = i;\n }\n }\n\n // The string must have a whole number of bytes:\n if (!opts.loose && (string.length * encoding.bits) & 7) {\n throw new SyntaxError('Invalid padding');\n }\n\n // Count the padding bytes:\n let end = string.length;\n while (string[end - 1] === '=') {\n --end;\n\n // If we get a whole number of bytes, there is too much padding:\n if (!opts.loose && !(((string.length - end) * encoding.bits) & 7)) {\n throw new SyntaxError('Invalid padding');\n }\n }\n\n // Allocate the output:\n const out = new (opts.out ?? Uint8Array)(((end * encoding.bits) / 8) | 0) as Uint8Array;\n\n // Parse the data:\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n let written = 0; // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = encoding.codes[string[i]];\n if (value === undefined) {\n throw new SyntaxError('Invalid character ' + string[i]);\n }\n\n // Append the bits to the buffer:\n buffer = (buffer << encoding.bits) | value;\n bits += encoding.bits;\n\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8;\n out[written++] = 0xff & (buffer >> bits);\n }\n }\n\n // Verify that we have received just enough bits:\n if (bits >= encoding.bits || 0xff & (buffer << (8 - bits))) {\n throw new SyntaxError('Unexpected end of data');\n }\n\n return out;\n}\n\nfunction stringify(data: ArrayLike, encoding: Encoding, opts: StringifyOptions = {}): string {\n const { pad = true } = opts;\n const mask = (1 << encoding.bits) - 1;\n let out = '';\n\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | (0xff & data[i]);\n bits += 8;\n\n // Write out as much as we can:\n while (bits > encoding.bits) {\n bits -= encoding.bits;\n out += encoding.chars[mask & (buffer >> bits)];\n }\n }\n\n // Partial character:\n if (bits) {\n out += encoding.chars[mask & (buffer << (encoding.bits - bits))];\n }\n\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while ((out.length * encoding.bits) & 7) {\n out += '=';\n }\n }\n\n return out;\n}\n","const algToHash: Record = {\n RS256: 'SHA-256',\n RS384: 'SHA-384',\n RS512: 'SHA-512',\n};\nconst RSA_ALGORITHM_NAME = 'RSASSA-PKCS1-v1_5';\n\nconst jwksAlgToCryptoAlg: Record = {\n RS256: RSA_ALGORITHM_NAME,\n RS384: RSA_ALGORITHM_NAME,\n RS512: RSA_ALGORITHM_NAME,\n};\n\nexport const algs = Object.keys(algToHash);\n\nexport function getCryptoAlgorithm(algorithmName: string): RsaHashedImportParams {\n const hash = algToHash[algorithmName];\n const name = jwksAlgToCryptoAlg[algorithmName];\n\n if (!hash || !name) {\n throw new Error(`Unsupported algorithm ${algorithmName}, expected one of ${algs.join(',')}.`);\n }\n\n return {\n hash: { name: algToHash[algorithmName] },\n name: jwksAlgToCryptoAlg[algorithmName],\n };\n}\n","import { TokenVerificationError, TokenVerificationErrorAction, TokenVerificationErrorReason } from '../errors';\nimport { algs } from './algorithms';\n\nexport type IssuerResolver = string | ((iss: string) => boolean);\n\nconst isArrayString = (s: unknown): s is string[] => {\n return Array.isArray(s) && s.length > 0 && s.every(a => typeof a === 'string');\n};\n\nexport const assertAudienceClaim = (aud?: unknown, audience?: unknown) => {\n const audienceList = [audience].flat().filter(a => !!a);\n const audList = [aud].flat().filter(a => !!a);\n const shouldVerifyAudience = audienceList.length > 0 && audList.length > 0;\n\n if (!shouldVerifyAudience) {\n // Notice: Clerk JWTs use AZP claim instead of Audience\n //\n // return {\n // valid: false,\n // reason: `Invalid JWT audience claim (aud) ${JSON.stringify(\n // aud,\n // )}. Expected a string or a non-empty array of strings.`,\n // };\n return;\n }\n\n if (typeof aud === 'string') {\n if (!audienceList.includes(aud)) {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.EnsureClerkJWT,\n reason: TokenVerificationErrorReason.TokenVerificationFailed,\n message: `Invalid JWT audience claim (aud) ${JSON.stringify(aud)}. Is not included in \"${JSON.stringify(\n audienceList,\n )}\".`,\n });\n }\n } else if (isArrayString(aud)) {\n if (!aud.some(a => audienceList.includes(a))) {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.EnsureClerkJWT,\n reason: TokenVerificationErrorReason.TokenVerificationFailed,\n message: `Invalid JWT audience claim array (aud) ${JSON.stringify(aud)}. Is not included in \"${JSON.stringify(\n audienceList,\n )}\".`,\n });\n }\n }\n};\n\nexport const assertHeaderType = (typ?: unknown) => {\n if (typeof typ === 'undefined') {\n return;\n }\n\n if (typ !== 'JWT') {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.EnsureClerkJWT,\n reason: TokenVerificationErrorReason.TokenInvalid,\n message: `Invalid JWT type ${JSON.stringify(typ)}. Expected \"JWT\".`,\n });\n }\n};\n\nexport const assertHeaderAlgorithm = (alg: string) => {\n if (!algs.includes(alg)) {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.EnsureClerkJWT,\n reason: TokenVerificationErrorReason.TokenInvalidAlgorithm,\n message: `Invalid JWT algorithm ${JSON.stringify(alg)}. Supported: ${algs}.`,\n });\n }\n};\n\nexport const assertSubClaim = (sub?: string) => {\n if (typeof sub !== 'string') {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.EnsureClerkJWT,\n reason: TokenVerificationErrorReason.TokenVerificationFailed,\n message: `Subject claim (sub) is required and must be a string. Received ${JSON.stringify(sub)}.`,\n });\n }\n};\n\nexport const assertAuthorizedPartiesClaim = (azp?: string, authorizedParties?: string[]) => {\n if (!azp || !authorizedParties || authorizedParties.length === 0) {\n return;\n }\n\n if (!authorizedParties.includes(azp)) {\n throw new TokenVerificationError({\n reason: TokenVerificationErrorReason.TokenInvalidAuthorizedParties,\n message: `Invalid JWT Authorized party claim (azp) ${JSON.stringify(azp)}. Expected \"${authorizedParties}\".`,\n });\n }\n};\n\nexport const assertExpirationClaim = (exp: number, clockSkewInMs: number) => {\n if (typeof exp !== 'number') {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.EnsureClerkJWT,\n reason: TokenVerificationErrorReason.TokenVerificationFailed,\n message: `Invalid JWT expiry date claim (exp) ${JSON.stringify(exp)}. Expected number.`,\n });\n }\n\n const currentDate = new Date(Date.now());\n const expiryDate = new Date(0);\n expiryDate.setUTCSeconds(exp);\n\n const expired = expiryDate.getTime() <= currentDate.getTime() - clockSkewInMs;\n if (expired) {\n throw new TokenVerificationError({\n reason: TokenVerificationErrorReason.TokenExpired,\n message: `JWT is expired. Expiry date: ${expiryDate.toUTCString()}, Current date: ${currentDate.toUTCString()}.`,\n });\n }\n};\n\nexport const assertActivationClaim = (nbf: number | undefined, clockSkewInMs: number) => {\n if (typeof nbf === 'undefined') {\n return;\n }\n\n if (typeof nbf !== 'number') {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.EnsureClerkJWT,\n reason: TokenVerificationErrorReason.TokenVerificationFailed,\n message: `Invalid JWT not before date claim (nbf) ${JSON.stringify(nbf)}. Expected number.`,\n });\n }\n\n const currentDate = new Date(Date.now());\n const notBeforeDate = new Date(0);\n notBeforeDate.setUTCSeconds(nbf);\n\n const early = notBeforeDate.getTime() > currentDate.getTime() + clockSkewInMs;\n if (early) {\n throw new TokenVerificationError({\n reason: TokenVerificationErrorReason.TokenNotActiveYet,\n message: `JWT cannot be used prior to not before date claim (nbf). Not before date: ${notBeforeDate.toUTCString()}; Current date: ${currentDate.toUTCString()};`,\n });\n }\n};\n\nexport const assertIssuedAtClaim = (iat: number | undefined, clockSkewInMs: number) => {\n if (typeof iat === 'undefined') {\n return;\n }\n\n if (typeof iat !== 'number') {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.EnsureClerkJWT,\n reason: TokenVerificationErrorReason.TokenVerificationFailed,\n message: `Invalid JWT issued at date claim (iat) ${JSON.stringify(iat)}. Expected number.`,\n });\n }\n\n const currentDate = new Date(Date.now());\n const issuedAtDate = new Date(0);\n issuedAtDate.setUTCSeconds(iat);\n\n const postIssued = issuedAtDate.getTime() > currentDate.getTime() + clockSkewInMs;\n if (postIssued) {\n throw new TokenVerificationError({\n reason: TokenVerificationErrorReason.TokenIatInTheFuture,\n message: `JWT issued at date claim (iat) is in the future. Issued at date: ${issuedAtDate.toUTCString()}; Current date: ${currentDate.toUTCString()};`,\n });\n }\n};\n","import { isomorphicAtob } from '@clerk/shared/isomorphicAtob';\n\nimport { runtime } from '../runtime';\n\n// https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/importKey#pkcs_8_import\nfunction pemToBuffer(secret: string): ArrayBuffer {\n const trimmed = secret\n .replace(/-----BEGIN.*?-----/g, '')\n .replace(/-----END.*?-----/g, '')\n .replace(/\\s/g, '');\n\n const decoded = isomorphicAtob(trimmed);\n\n const buffer = new ArrayBuffer(decoded.length);\n const bufView = new Uint8Array(buffer);\n\n for (let i = 0, strLen = decoded.length; i < strLen; i++) {\n bufView[i] = decoded.charCodeAt(i);\n }\n\n return bufView;\n}\n\nexport function importKey(\n key: JsonWebKey | string,\n algorithm: RsaHashedImportParams,\n keyUsage: 'verify' | 'sign',\n): Promise {\n if (typeof key === 'object') {\n return runtime.crypto.subtle.importKey('jwk', key, algorithm, false, [keyUsage]);\n }\n\n const keyData = pemToBuffer(key);\n const format = keyUsage === 'sign' ? 'pkcs8' : 'spki';\n\n return runtime.crypto.subtle.importKey(format, keyData, algorithm, false, [keyUsage]);\n}\n","import type { Jwt, JwtPayload } from '@clerk/types';\n\nimport { TokenVerificationError, TokenVerificationErrorAction, TokenVerificationErrorReason } from '../errors';\nimport { runtime } from '../runtime';\nimport { base64url } from '../util/rfc4648';\nimport { getCryptoAlgorithm } from './algorithms';\nimport {\n assertActivationClaim,\n assertAudienceClaim,\n assertAuthorizedPartiesClaim,\n assertExpirationClaim,\n assertHeaderAlgorithm,\n assertHeaderType,\n assertIssuedAtClaim,\n assertSubClaim,\n} from './assertions';\nimport { importKey } from './cryptoKeys';\nimport type { JwtReturnType } from './types';\n\nconst DEFAULT_CLOCK_SKEW_IN_MS = 5 * 1000;\n\nexport async function hasValidSignature(jwt: Jwt, key: JsonWebKey | string): Promise> {\n const { header, signature, raw } = jwt;\n const encoder = new TextEncoder();\n const data = encoder.encode([raw.header, raw.payload].join('.'));\n const algorithm = getCryptoAlgorithm(header.alg);\n\n try {\n const cryptoKey = await importKey(key, algorithm, 'verify');\n\n const verified = await runtime.crypto.subtle.verify(algorithm.name, cryptoKey, signature, data);\n return { data: verified };\n } catch (error) {\n return {\n errors: [\n new TokenVerificationError({\n reason: TokenVerificationErrorReason.TokenInvalidSignature,\n message: (error as Error)?.message,\n }),\n ],\n };\n }\n}\n\nexport function decodeJwt(token: string): JwtReturnType {\n const tokenParts = (token || '').toString().split('.');\n if (tokenParts.length !== 3) {\n return {\n errors: [\n new TokenVerificationError({\n reason: TokenVerificationErrorReason.TokenInvalid,\n message: `Invalid JWT form. A JWT consists of three parts separated by dots.`,\n }),\n ],\n };\n }\n\n const [rawHeader, rawPayload, rawSignature] = tokenParts;\n\n const decoder = new TextDecoder();\n\n // To verify a JWS with SubtleCrypto you need to be careful to encode and decode\n // the data properly between binary and base64url representation. Unfortunately\n // the standard implementation in the V8 of btoa() and atob() are difficult to\n // work with as they use \"a Unicode string containing only characters in the\n // range U+0000 to U+00FF, each representing a binary byte with values 0x00 to\n // 0xFF respectively\" as the representation of binary data.\n\n // A better solution to represent binary data in Javascript is to use ES6 TypedArray\n // and use a Javascript library to convert them to base64url that honors RFC 4648.\n\n // Side note: The difference between base64 and base64url is the characters selected\n // for value 62 and 63 in the standard, base64 encode them to + and / while base64url\n // encode - and _.\n\n // More info at https://stackoverflow.com/questions/54062583/how-to-verify-a-signed-jwt-with-subtlecrypto-of-the-web-crypto-API\n const header = JSON.parse(decoder.decode(base64url.parse(rawHeader, { loose: true })));\n const payload = JSON.parse(decoder.decode(base64url.parse(rawPayload, { loose: true })));\n\n const signature = base64url.parse(rawSignature, { loose: true });\n\n const data = {\n header,\n payload,\n signature,\n raw: {\n header: rawHeader,\n payload: rawPayload,\n signature: rawSignature,\n text: token,\n },\n } satisfies Jwt;\n\n return { data };\n}\n\n/**\n * @inline\n */\nexport type VerifyJwtOptions = {\n /**\n * A string or list of [audiences](https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.3). If passed, it is checked against the `aud` claim in the token.\n */\n audience?: string | string[];\n /**\n * An allowlist of origins to verify against, to protect your application from the subdomain cookie leaking attack.\n * @example\n * ```ts\n * ['http://localhost:3000', 'https://example.com']\n * ```\n */\n authorizedParties?: string[];\n /**\n * Specifies the allowed time difference (in milliseconds) between the Clerk server (which generates the token) and the clock of the user's application server when validating a token.\n * @default 5000\n */\n clockSkewInMs?: number;\n /**\n * @internal\n */\n key: JsonWebKey | string;\n};\n\nexport async function verifyJwt(\n token: string,\n options: VerifyJwtOptions,\n): Promise> {\n const { audience, authorizedParties, clockSkewInMs, key } = options;\n const clockSkew = clockSkewInMs || DEFAULT_CLOCK_SKEW_IN_MS;\n\n const { data: decoded, errors } = decodeJwt(token);\n if (errors) {\n return { errors };\n }\n\n const { header, payload } = decoded;\n try {\n // Header verifications\n const { typ, alg } = header;\n\n assertHeaderType(typ);\n assertHeaderAlgorithm(alg);\n\n // Payload verifications\n const { azp, sub, aud, iat, exp, nbf } = payload;\n\n assertSubClaim(sub);\n assertAudienceClaim([aud], [audience]);\n assertAuthorizedPartiesClaim(azp, authorizedParties);\n assertExpirationClaim(exp, clockSkew);\n assertActivationClaim(nbf, clockSkew);\n assertIssuedAtClaim(iat, clockSkew);\n } catch (err) {\n return { errors: [err as TokenVerificationError] };\n }\n\n const { data: signatureValid, errors: signatureErrors } = await hasValidSignature(decoded, key);\n if (signatureErrors) {\n return {\n errors: [\n new TokenVerificationError({\n action: TokenVerificationErrorAction.EnsureClerkJWT,\n reason: TokenVerificationErrorReason.TokenVerificationFailed,\n message: `Error verifying JWT signature. ${signatureErrors[0]}`,\n }),\n ],\n };\n }\n\n if (!signatureValid) {\n return {\n errors: [\n new TokenVerificationError({\n reason: TokenVerificationErrorReason.TokenInvalidSignature,\n message: 'JWT signature is invalid.',\n }),\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AQ,6BAA6B;AAAA,UACrC,QAAQ,6BAA6B;AAAA,UACrC,SAAS,kCAAkC,gBAAgB,CAAC,CAAC;AAAA,QAC/D,CAAC;AAAA,MACH;AAAA,IACF;AAAA,EACF;AAEA,MAAI,CAAC,gBAAgB;AACnB,WAAO;AAAA,MACL,QAAQ;AAAA,QACN,IAAI,uBAAuB;AAAA,UACzB,QAAQ,6BAA6B;AAAA,UACrC,SAAS;AAAA,QACX,CAAC;AAAA,MACH;AAAA,IACF;AAAA,EACF;AAEA,SAAO,EAAE,MAAM,QAAQ;AACzB;","names":[]} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/chunk-YW6OOOXM.mjs b/backend/node_modules/@clerk/backend/dist/chunk-YW6OOOXM.mjs new file mode 100644 index 000000000..b773599bc --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/chunk-YW6OOOXM.mjs @@ -0,0 +1,73 @@ +// src/errors.ts +var TokenVerificationErrorCode = { + InvalidSecretKey: "clerk_key_invalid" +}; +var TokenVerificationErrorReason = { + TokenExpired: "token-expired", + TokenInvalid: "token-invalid", + TokenInvalidAlgorithm: "token-invalid-algorithm", + TokenInvalidAuthorizedParties: "token-invalid-authorized-parties", + TokenInvalidSignature: "token-invalid-signature", + TokenNotActiveYet: "token-not-active-yet", + TokenIatInTheFuture: "token-iat-in-the-future", + TokenVerificationFailed: "token-verification-failed", + InvalidSecretKey: "secret-key-invalid", + LocalJWKMissing: "jwk-local-missing", + RemoteJWKFailedToLoad: "jwk-remote-failed-to-load", + RemoteJWKInvalid: "jwk-remote-invalid", + RemoteJWKMissing: "jwk-remote-missing", + JWKFailedToResolve: "jwk-failed-to-resolve", + JWKKidMismatch: "jwk-kid-mismatch" +}; +var TokenVerificationErrorAction = { + ContactSupport: "Contact support@clerk.com", + EnsureClerkJWT: "Make sure that this is a valid Clerk generate JWT.", + SetClerkJWTKey: "Set the CLERK_JWT_KEY environment variable.", + SetClerkSecretKey: "Set the CLERK_SECRET_KEY environment variable.", + EnsureClockSync: "Make sure your system clock is in sync (e.g. turn off and on automatic time synchronization)." +}; +var TokenVerificationError = class _TokenVerificationError extends Error { + constructor({ + action, + message, + reason + }) { + super(message); + Object.setPrototypeOf(this, _TokenVerificationError.prototype); + this.reason = reason; + this.message = message; + this.action = action; + } + getFullMessage() { + return `${[this.message, this.action].filter((m) => m).join(" ")} (reason=${this.reason}, token-carrier=${this.tokenCarrier})`; + } +}; +var SignJWTError = class extends Error { +}; +var MachineTokenVerificationErrorCode = { + TokenInvalid: "token-invalid", + InvalidSecretKey: "secret-key-invalid", + UnexpectedError: "unexpected-error" +}; +var MachineTokenVerificationError = class _MachineTokenVerificationError extends Error { + constructor({ message, code, status }) { + super(message); + Object.setPrototypeOf(this, _MachineTokenVerificationError.prototype); + this.code = code; + this.status = status; + } + getFullMessage() { + return `${this.message} (code=${this.code}, status=${this.status})`; + } +}; + +export { + TokenVerificationErrorCode, + TokenVerificationErrorReason, + TokenVerificationErrorAction, + TokenVerificationError, + SignJWTError, + MachineTokenVerificationErrorCode, + MachineTokenVerificationError +}; +//# sourceMappingURL=chunk-YW6OOOXM.mjs.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/chunk-YW6OOOXM.mjs.map b/backend/node_modules/@clerk/backend/dist/chunk-YW6OOOXM.mjs.map new file mode 100644 index 000000000..f5dd5c818 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/chunk-YW6OOOXM.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../src/errors.ts"],"sourcesContent":["export type TokenCarrier = 'header' | 'cookie';\n\nexport const TokenVerificationErrorCode = {\n InvalidSecretKey: 'clerk_key_invalid',\n};\n\nexport type TokenVerificationErrorCode = (typeof TokenVerificationErrorCode)[keyof typeof TokenVerificationErrorCode];\n\nexport const TokenVerificationErrorReason = {\n TokenExpired: 'token-expired',\n TokenInvalid: 'token-invalid',\n TokenInvalidAlgorithm: 'token-invalid-algorithm',\n TokenInvalidAuthorizedParties: 'token-invalid-authorized-parties',\n TokenInvalidSignature: 'token-invalid-signature',\n TokenNotActiveYet: 'token-not-active-yet',\n TokenIatInTheFuture: 'token-iat-in-the-future',\n TokenVerificationFailed: 'token-verification-failed',\n InvalidSecretKey: 'secret-key-invalid',\n LocalJWKMissing: 'jwk-local-missing',\n RemoteJWKFailedToLoad: 'jwk-remote-failed-to-load',\n RemoteJWKInvalid: 'jwk-remote-invalid',\n RemoteJWKMissing: 'jwk-remote-missing',\n JWKFailedToResolve: 'jwk-failed-to-resolve',\n JWKKidMismatch: 'jwk-kid-mismatch',\n};\n\nexport type TokenVerificationErrorReason =\n (typeof TokenVerificationErrorReason)[keyof typeof TokenVerificationErrorReason];\n\nexport const TokenVerificationErrorAction = {\n ContactSupport: 'Contact support@clerk.com',\n EnsureClerkJWT: 'Make sure that this is a valid Clerk generate JWT.',\n SetClerkJWTKey: 'Set the CLERK_JWT_KEY environment variable.',\n SetClerkSecretKey: 'Set the CLERK_SECRET_KEY environment variable.',\n EnsureClockSync: 'Make sure your system clock is in sync (e.g. turn off and on automatic time synchronization).',\n};\n\nexport type TokenVerificationErrorAction =\n (typeof TokenVerificationErrorAction)[keyof typeof TokenVerificationErrorAction];\n\nexport class TokenVerificationError extends Error {\n action?: TokenVerificationErrorAction;\n reason: TokenVerificationErrorReason;\n tokenCarrier?: TokenCarrier;\n\n constructor({\n action,\n message,\n reason,\n }: {\n action?: TokenVerificationErrorAction;\n message: string;\n reason: TokenVerificationErrorReason;\n }) {\n super(message);\n\n Object.setPrototypeOf(this, TokenVerificationError.prototype);\n\n this.reason = reason;\n this.message = message;\n this.action = action;\n }\n\n public getFullMessage() {\n return `${[this.message, this.action].filter(m => m).join(' ')} (reason=${this.reason}, token-carrier=${\n this.tokenCarrier\n })`;\n }\n}\n\nexport class SignJWTError extends Error {}\n\nexport const MachineTokenVerificationErrorCode = {\n TokenInvalid: 'token-invalid',\n InvalidSecretKey: 'secret-key-invalid',\n UnexpectedError: 'unexpected-error',\n} as const;\n\nexport type MachineTokenVerificationErrorCode =\n (typeof MachineTokenVerificationErrorCode)[keyof typeof MachineTokenVerificationErrorCode];\n\nexport class MachineTokenVerificationError extends Error {\n code: MachineTokenVerificationErrorCode;\n long_message?: string;\n status: number;\n\n constructor({ message, code, status }: { message: string; code: MachineTokenVerificationErrorCode; status: number }) {\n super(message);\n Object.setPrototypeOf(this, MachineTokenVerificationError.prototype);\n\n this.code = code;\n this.status = status;\n }\n\n public getFullMessage() {\n return `${this.message} (code=${this.code}, status=${this.status})`;\n }\n}\n"],"mappings":";AAEO,IAAM,6BAA6B;AAAA,EACxC,kBAAkB;AACpB;AAIO,IAAM,+BAA+B;AAAA,EAC1C,cAAc;AAAA,EACd,cAAc;AAAA,EACd,uBAAuB;AAAA,EACvB,+BAA+B;AAAA,EAC/B,uBAAuB;AAAA,EACvB,mBAAmB;AAAA,EACnB,qBAAqB;AAAA,EACrB,yBAAyB;AAAA,EACzB,kBAAkB;AAAA,EAClB,iBAAiB;AAAA,EACjB,uBAAuB;AAAA,EACvB,kBAAkB;AAAA,EAClB,kBAAkB;AAAA,EAClB,oBAAoB;AAAA,EACpB,gBAAgB;AAClB;AAKO,IAAM,+BAA+B;AAAA,EAC1C,gBAAgB;AAAA,EAChB,gBAAgB;AAAA,EAChB,gBAAgB;AAAA,EAChB,mBAAmB;AAAA,EACnB,iBAAiB;AACnB;AAKO,IAAM,yBAAN,MAAM,gCAA+B,MAAM;AAAA,EAKhD,YAAY;AAAA,IACV;AAAA,IACA;AAAA,IACA;AAAA,EACF,GAIG;AACD,UAAM,OAAO;AAEb,WAAO,eAAe,MAAM,wBAAuB,SAAS;AAE5D,SAAK,SAAS;AACd,SAAK,UAAU;AACf,SAAK,SAAS;AAAA,EAChB;AAAA,EAEO,iBAAiB;AACtB,WAAO,GAAG,CAAC,KAAK,SAAS,KAAK,MAAM,EAAE,OAAO,OAAK,CAAC,EAAE,KAAK,GAAG,CAAC,YAAY,KAAK,MAAM,mBACnF,KAAK,YACP;AAAA,EACF;AACF;AAEO,IAAM,eAAN,cAA2B,MAAM;AAAC;AAElC,IAAM,oCAAoC;AAAA,EAC/C,cAAc;AAAA,EACd,kBAAkB;AAAA,EAClB,iBAAiB;AACnB;AAKO,IAAM,gCAAN,MAAM,uCAAsC,MAAM;AAAA,EAKvD,YAAY,EAAE,SAAS,MAAM,OAAO,GAAiF;AACnH,UAAM,OAAO;AACb,WAAO,eAAe,MAAM,+BAA8B,SAAS;AAEnE,SAAK,OAAO;AACZ,SAAK,SAAS;AAAA,EAChB;AAAA,EAEO,iBAAiB;AACtB,WAAO,GAAG,KAAK,OAAO,UAAU,KAAK,IAAI,YAAY,KAAK,MAAM;AAAA,EAClE;AACF;","names":[]} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/constants.d.ts b/backend/node_modules/@clerk/backend/dist/constants.d.ts new file mode 100644 index 000000000..f38bab720 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/constants.d.ts @@ -0,0 +1,74 @@ +export declare const API_URL = "https://api.clerk.com"; +export declare const API_VERSION = "v1"; +export declare const USER_AGENT: string; +export declare const MAX_CACHE_LAST_UPDATED_AT_SECONDS: number; +export declare const SUPPORTED_BAPI_VERSION = "2025-04-10"; +/** + * @internal + */ +export declare const constants: { + readonly Attributes: { + readonly AuthToken: "__clerkAuthToken"; + readonly AuthSignature: "__clerkAuthSignature"; + readonly AuthStatus: "__clerkAuthStatus"; + readonly AuthReason: "__clerkAuthReason"; + readonly AuthMessage: "__clerkAuthMessage"; + readonly ClerkUrl: "__clerkUrl"; + }; + readonly Cookies: { + readonly Session: "__session"; + readonly Refresh: "__refresh"; + readonly ClientUat: "__client_uat"; + readonly Handshake: "__clerk_handshake"; + readonly DevBrowser: "__clerk_db_jwt"; + readonly RedirectCount: "__clerk_redirect_count"; + readonly HandshakeNonce: "__clerk_handshake_nonce"; + }; + readonly Headers: { + readonly Accept: "accept"; + readonly AuthMessage: "x-clerk-auth-message"; + readonly Authorization: "authorization"; + readonly AuthReason: "x-clerk-auth-reason"; + readonly AuthSignature: "x-clerk-auth-signature"; + readonly AuthStatus: "x-clerk-auth-status"; + readonly AuthToken: "x-clerk-auth-token"; + readonly CacheControl: "cache-control"; + readonly ClerkRedirectTo: "x-clerk-redirect-to"; + readonly ClerkRequestData: "x-clerk-request-data"; + readonly ClerkUrl: "x-clerk-clerk-url"; + readonly CloudFrontForwardedProto: "cloudfront-forwarded-proto"; + readonly ContentType: "content-type"; + readonly ContentSecurityPolicy: "content-security-policy"; + readonly ContentSecurityPolicyReportOnly: "content-security-policy-report-only"; + readonly EnableDebug: "x-clerk-debug"; + readonly ForwardedHost: "x-forwarded-host"; + readonly ForwardedPort: "x-forwarded-port"; + readonly ForwardedProto: "x-forwarded-proto"; + readonly Host: "host"; + readonly Location: "location"; + readonly Nonce: "x-nonce"; + readonly Origin: "origin"; + readonly Referrer: "referer"; + readonly SecFetchDest: "sec-fetch-dest"; + readonly SecFetchSite: "sec-fetch-site"; + readonly UserAgent: "user-agent"; + readonly ReportingEndpoints: "reporting-endpoints"; + }; + readonly ContentTypes: { + readonly Json: "application/json"; + }; + readonly QueryParameters: { + readonly ClerkSynced: "__clerk_synced"; + readonly SuffixedCookies: "suffixed_cookies"; + readonly ClerkRedirectUrl: "__clerk_redirect_url"; + readonly DevBrowser: "__clerk_db_jwt"; + readonly Handshake: "__clerk_handshake"; + readonly HandshakeHelp: "__clerk_help"; + readonly LegacyDevBrowser: "__dev_session"; + readonly HandshakeReason: "__clerk_hs_reason"; + readonly HandshakeNonce: "__clerk_handshake_nonce"; + readonly HandshakeFormat: "format"; + }; +}; +export type Constants = typeof constants; +//# sourceMappingURL=constants.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/constants.d.ts.map b/backend/node_modules/@clerk/backend/dist/constants.d.ts.map new file mode 100644 index 000000000..441d0cbbd --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/constants.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,OAAO,0BAA0B,CAAC;AAC/C,eAAO,MAAM,WAAW,OAAO,CAAC;AAEhC,eAAO,MAAM,UAAU,QAAuC,CAAC;AAC/D,eAAO,MAAM,iCAAiC,QAAS,CAAC;AACxD,eAAO,MAAM,sBAAsB,eAAe,CAAC;AAsEnD;;GAEG;AACH,eAAO,MAAM,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAMZ,CAAC;AAEX,MAAM,MAAM,SAAS,GAAG,OAAO,SAAS,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/createRedirect.d.ts b/backend/node_modules/@clerk/backend/dist/createRedirect.d.ts new file mode 100644 index 000000000..ddfe427f8 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/createRedirect.d.ts @@ -0,0 +1,24 @@ +import type { SessionStatusClaim } from '@clerk/types'; +type RedirectAdapter = (url: string) => RedirectReturn; +type RedirectToParams = { + returnBackUrl?: string | URL | null; +}; +export type RedirectFun = (params?: RedirectToParams) => ReturnType; +/** + * @internal + */ +type CreateRedirect = (params: { + publishableKey: string; + devBrowserToken?: string; + redirectAdapter: RedirectAdapter; + baseUrl: URL | string; + signInUrl?: URL | string; + signUpUrl?: URL | string; + sessionStatus?: SessionStatusClaim | null; +}) => { + redirectToSignIn: RedirectFun; + redirectToSignUp: RedirectFun; +}; +export declare const createRedirect: CreateRedirect; +export {}; +//# sourceMappingURL=createRedirect.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/createRedirect.d.ts.map b/backend/node_modules/@clerk/backend/dist/createRedirect.d.ts.map new file mode 100644 index 000000000..6447af855 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/createRedirect.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"createRedirect.d.ts","sourceRoot":"","sources":["../src/createRedirect.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AA+DvD,KAAK,eAAe,CAAC,cAAc,IAAI,CAAC,GAAG,EAAE,MAAM,KAAK,cAAc,CAAC;AACvE,KAAK,gBAAgB,GAAG;IAAE,aAAa,CAAC,EAAE,MAAM,GAAG,GAAG,GAAG,IAAI,CAAA;CAAE,CAAC;AAChE,MAAM,MAAM,WAAW,CAAC,UAAU,IAAI,CAAC,MAAM,CAAC,EAAE,gBAAgB,KAAK,UAAU,CAAC;AAEhF;;GAEG;AACH,KAAK,cAAc,GAAG,CAAC,UAAU,EAAE,MAAM,EAAE;IACzC,cAAc,EAAE,MAAM,CAAC;IACvB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,eAAe,EAAE,eAAe,CAAC,UAAU,CAAC,CAAC;IAC7C,OAAO,EAAE,GAAG,GAAG,MAAM,CAAC;IACtB,SAAS,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC;IACzB,SAAS,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC;IACzB,aAAa,CAAC,EAAE,kBAAkB,GAAG,IAAI,CAAC;CAC3C,KAAK;IACJ,gBAAgB,EAAE,WAAW,CAAC,UAAU,CAAC,CAAC;IAC1C,gBAAgB,EAAE,WAAW,CAAC,UAAU,CAAC,CAAC;CAC3C,CAAC;AAEF,eAAO,MAAM,cAAc,EAAE,cAwD5B,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/errors.d.ts b/backend/node_modules/@clerk/backend/dist/errors.d.ts new file mode 100644 index 000000000..8ad680096 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/errors.d.ts @@ -0,0 +1,62 @@ +export type TokenCarrier = 'header' | 'cookie'; +export declare const TokenVerificationErrorCode: { + InvalidSecretKey: string; +}; +export type TokenVerificationErrorCode = (typeof TokenVerificationErrorCode)[keyof typeof TokenVerificationErrorCode]; +export declare const TokenVerificationErrorReason: { + TokenExpired: string; + TokenInvalid: string; + TokenInvalidAlgorithm: string; + TokenInvalidAuthorizedParties: string; + TokenInvalidSignature: string; + TokenNotActiveYet: string; + TokenIatInTheFuture: string; + TokenVerificationFailed: string; + InvalidSecretKey: string; + LocalJWKMissing: string; + RemoteJWKFailedToLoad: string; + RemoteJWKInvalid: string; + RemoteJWKMissing: string; + JWKFailedToResolve: string; + JWKKidMismatch: string; +}; +export type TokenVerificationErrorReason = (typeof TokenVerificationErrorReason)[keyof typeof TokenVerificationErrorReason]; +export declare const TokenVerificationErrorAction: { + ContactSupport: string; + EnsureClerkJWT: string; + SetClerkJWTKey: string; + SetClerkSecretKey: string; + EnsureClockSync: string; +}; +export type TokenVerificationErrorAction = (typeof TokenVerificationErrorAction)[keyof typeof TokenVerificationErrorAction]; +export declare class TokenVerificationError extends Error { + action?: TokenVerificationErrorAction; + reason: TokenVerificationErrorReason; + tokenCarrier?: TokenCarrier; + constructor({ action, message, reason, }: { + action?: TokenVerificationErrorAction; + message: string; + reason: TokenVerificationErrorReason; + }); + getFullMessage(): string; +} +export declare class SignJWTError extends Error { +} +export declare const MachineTokenVerificationErrorCode: { + readonly TokenInvalid: "token-invalid"; + readonly InvalidSecretKey: "secret-key-invalid"; + readonly UnexpectedError: "unexpected-error"; +}; +export type MachineTokenVerificationErrorCode = (typeof MachineTokenVerificationErrorCode)[keyof typeof MachineTokenVerificationErrorCode]; +export declare class MachineTokenVerificationError extends Error { + code: MachineTokenVerificationErrorCode; + long_message?: string; + status: number; + constructor({ message, code, status }: { + message: string; + code: MachineTokenVerificationErrorCode; + status: number; + }); + getFullMessage(): string; +} +//# sourceMappingURL=errors.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/errors.d.ts.map b/backend/node_modules/@clerk/backend/dist/errors.d.ts.map new file mode 100644 index 000000000..c54346699 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/errors.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"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QAAC,IAAI,EAAE,iCAAiC,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE;IAQ5G,cAAc;CAGtB"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/errors.js b/backend/node_modules/@clerk/backend/dist/errors.js new file mode 100644 index 000000000..739b3a52d --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/errors.js @@ -0,0 +1,103 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/errors.ts +var errors_exports = {}; +__export(errors_exports, { + MachineTokenVerificationError: () => MachineTokenVerificationError, + MachineTokenVerificationErrorCode: () => MachineTokenVerificationErrorCode, + SignJWTError: () => SignJWTError, + TokenVerificationError: () => TokenVerificationError, + TokenVerificationErrorAction: () => TokenVerificationErrorAction, + TokenVerificationErrorCode: () => TokenVerificationErrorCode, + TokenVerificationErrorReason: () => TokenVerificationErrorReason +}); +module.exports = __toCommonJS(errors_exports); +var TokenVerificationErrorCode = { + InvalidSecretKey: "clerk_key_invalid" +}; +var TokenVerificationErrorReason = { + TokenExpired: "token-expired", + TokenInvalid: "token-invalid", + TokenInvalidAlgorithm: "token-invalid-algorithm", + TokenInvalidAuthorizedParties: "token-invalid-authorized-parties", + TokenInvalidSignature: "token-invalid-signature", + TokenNotActiveYet: "token-not-active-yet", + TokenIatInTheFuture: "token-iat-in-the-future", + TokenVerificationFailed: "token-verification-failed", + InvalidSecretKey: "secret-key-invalid", + LocalJWKMissing: "jwk-local-missing", + RemoteJWKFailedToLoad: "jwk-remote-failed-to-load", + RemoteJWKInvalid: "jwk-remote-invalid", + RemoteJWKMissing: "jwk-remote-missing", + JWKFailedToResolve: "jwk-failed-to-resolve", + JWKKidMismatch: "jwk-kid-mismatch" +}; +var TokenVerificationErrorAction = { + ContactSupport: "Contact support@clerk.com", + EnsureClerkJWT: "Make sure that this is a valid Clerk generate JWT.", + SetClerkJWTKey: "Set the CLERK_JWT_KEY environment variable.", + SetClerkSecretKey: "Set the CLERK_SECRET_KEY environment variable.", + EnsureClockSync: "Make sure your system clock is in sync (e.g. turn off and on automatic time synchronization)." +}; +var TokenVerificationError = class _TokenVerificationError extends Error { + constructor({ + action, + message, + reason + }) { + super(message); + Object.setPrototypeOf(this, _TokenVerificationError.prototype); + this.reason = reason; + this.message = message; + this.action = action; + } + getFullMessage() { + return `${[this.message, this.action].filter((m) => m).join(" ")} (reason=${this.reason}, token-carrier=${this.tokenCarrier})`; + } +}; +var SignJWTError = class extends Error { +}; +var MachineTokenVerificationErrorCode = { + TokenInvalid: "token-invalid", + InvalidSecretKey: "secret-key-invalid", + UnexpectedError: "unexpected-error" +}; +var MachineTokenVerificationError = class _MachineTokenVerificationError extends Error { + constructor({ message, code, status }) { + super(message); + Object.setPrototypeOf(this, _MachineTokenVerificationError.prototype); + this.code = code; + this.status = status; + } + getFullMessage() { + return `${this.message} (code=${this.code}, status=${this.status})`; + } +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + MachineTokenVerificationError, + MachineTokenVerificationErrorCode, + SignJWTError, + TokenVerificationError, + TokenVerificationErrorAction, + TokenVerificationErrorCode, + TokenVerificationErrorReason +}); +//# sourceMappingURL=errors.js.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/errors.js.map b/backend/node_modules/@clerk/backend/dist/errors.js.map new file mode 100644 index 000000000..39734e301 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/errors.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../src/errors.ts"],"sourcesContent":["export type TokenCarrier = 'header' | 'cookie';\n\nexport const TokenVerificationErrorCode = {\n InvalidSecretKey: 'clerk_key_invalid',\n};\n\nexport type TokenVerificationErrorCode = (typeof TokenVerificationErrorCode)[keyof typeof TokenVerificationErrorCode];\n\nexport const TokenVerificationErrorReason = {\n TokenExpired: 'token-expired',\n TokenInvalid: 'token-invalid',\n TokenInvalidAlgorithm: 'token-invalid-algorithm',\n TokenInvalidAuthorizedParties: 'token-invalid-authorized-parties',\n TokenInvalidSignature: 'token-invalid-signature',\n TokenNotActiveYet: 'token-not-active-yet',\n TokenIatInTheFuture: 'token-iat-in-the-future',\n TokenVerificationFailed: 'token-verification-failed',\n InvalidSecretKey: 'secret-key-invalid',\n LocalJWKMissing: 'jwk-local-missing',\n RemoteJWKFailedToLoad: 'jwk-remote-failed-to-load',\n RemoteJWKInvalid: 'jwk-remote-invalid',\n RemoteJWKMissing: 'jwk-remote-missing',\n JWKFailedToResolve: 'jwk-failed-to-resolve',\n JWKKidMismatch: 'jwk-kid-mismatch',\n};\n\nexport type TokenVerificationErrorReason =\n (typeof TokenVerificationErrorReason)[keyof typeof TokenVerificationErrorReason];\n\nexport const TokenVerificationErrorAction = {\n ContactSupport: 'Contact support@clerk.com',\n EnsureClerkJWT: 'Make sure that this is a valid Clerk generate JWT.',\n SetClerkJWTKey: 'Set the CLERK_JWT_KEY environment variable.',\n SetClerkSecretKey: 'Set the CLERK_SECRET_KEY environment variable.',\n EnsureClockSync: 'Make sure your system clock is in sync (e.g. turn off and on automatic time synchronization).',\n};\n\nexport type TokenVerificationErrorAction =\n (typeof TokenVerificationErrorAction)[keyof typeof TokenVerificationErrorAction];\n\nexport class TokenVerificationError extends Error {\n action?: TokenVerificationErrorAction;\n reason: TokenVerificationErrorReason;\n tokenCarrier?: TokenCarrier;\n\n constructor({\n action,\n message,\n reason,\n }: {\n action?: TokenVerificationErrorAction;\n message: string;\n reason: TokenVerificationErrorReason;\n }) {\n super(message);\n\n Object.setPrototypeOf(this, TokenVerificationError.prototype);\n\n this.reason = reason;\n this.message = message;\n this.action = action;\n }\n\n public getFullMessage() {\n return `${[this.message, this.action].filter(m => m).join(' ')} (reason=${this.reason}, token-carrier=${\n this.tokenCarrier\n })`;\n }\n}\n\nexport class SignJWTError extends Error {}\n\nexport const MachineTokenVerificationErrorCode = {\n TokenInvalid: 'token-invalid',\n InvalidSecretKey: 'secret-key-invalid',\n UnexpectedError: 'unexpected-error',\n} as const;\n\nexport type MachineTokenVerificationErrorCode =\n (typeof MachineTokenVerificationErrorCode)[keyof typeof MachineTokenVerificationErrorCode];\n\nexport class MachineTokenVerificationError extends Error {\n code: MachineTokenVerificationErrorCode;\n long_message?: string;\n status: number;\n\n constructor({ message, code, status }: { message: string; code: MachineTokenVerificationErrorCode; status: number }) {\n super(message);\n Object.setPrototypeOf(this, MachineTokenVerificationError.prototype);\n\n this.code = code;\n this.status = status;\n }\n\n public getFullMessage() {\n return `${this.message} (code=${this.code}, status=${this.status})`;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAEO,IAAM,6BAA6B;AAAA,EACxC,kBAAkB;AACpB;AAIO,IAAM,+BAA+B;AAAA,EAC1C,cAAc;AAAA,EACd,cAAc;AAAA,EACd,uBAAuB;AAAA,EACvB,+BAA+B;AAAA,EAC/B,uBAAuB;AAAA,EACvB,mBAAmB;AAAA,EACnB,qBAAqB;AAAA,EACrB,yBAAyB;AAAA,EACzB,kBAAkB;AAAA,EAClB,iBAAiB;AAAA,EACjB,uBAAuB;AAAA,EACvB,kBAAkB;AAAA,EAClB,kBAAkB;AAAA,EAClB,oBAAoB;AAAA,EACpB,gBAAgB;AAClB;AAKO,IAAM,+BAA+B;AAAA,EAC1C,gBAAgB;AAAA,EAChB,gBAAgB;AAAA,EAChB,gBAAgB;AAAA,EAChB,mBAAmB;AAAA,EACnB,iBAAiB;AACnB;AAKO,IAAM,yBAAN,MAAM,gCAA+B,MAAM;AAAA,EAKhD,YAAY;AAAA,IACV;AAAA,IACA;AAAA,IACA;AAAA,EACF,GAIG;AACD,UAAM,OAAO;AAEb,WAAO,eAAe,MAAM,wBAAuB,SAAS;AAE5D,SAAK,SAAS;AACd,SAAK,UAAU;AACf,SAAK,SAAS;AAAA,EAChB;AAAA,EAEO,iBAAiB;AACtB,WAAO,GAAG,CAAC,KAAK,SAAS,KAAK,MAAM,EAAE,OAAO,OAAK,CAAC,EAAE,KAAK,GAAG,CAAC,YAAY,KAAK,MAAM,mBACnF,KAAK,YACP;AAAA,EACF;AACF;AAEO,IAAM,eAAN,cAA2B,MAAM;AAAC;AAElC,IAAM,oCAAoC;AAAA,EAC/C,cAAc;AAAA,EACd,kBAAkB;AAAA,EAClB,iBAAiB;AACnB;AAKO,IAAM,gCAAN,MAAM,uCAAsC,MAAM;AAAA,EAKvD,YAAY,EAAE,SAAS,MAAM,OAAO,GAAiF;AACnH,UAAM,OAAO;AACb,WAAO,eAAe,MAAM,+BAA8B,SAAS;AAEnE,SAAK,OAAO;AACZ,SAAK,SAAS;AAAA,EAChB;AAAA,EAEO,iBAAiB;AACtB,WAAO,GAAG,KAAK,OAAO,UAAU,KAAK,IAAI,YAAY,KAAK,MAAM;AAAA,EAClE;AACF;","names":[]} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/errors.mjs b/backend/node_modules/@clerk/backend/dist/errors.mjs new file mode 100644 index 000000000..e273b7947 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/errors.mjs @@ -0,0 +1,20 @@ +import { + MachineTokenVerificationError, + MachineTokenVerificationErrorCode, + SignJWTError, + TokenVerificationError, + TokenVerificationErrorAction, + TokenVerificationErrorCode, + TokenVerificationErrorReason +} from "./chunk-YW6OOOXM.mjs"; +import "./chunk-RPS7XK5K.mjs"; +export { + MachineTokenVerificationError, + MachineTokenVerificationErrorCode, + SignJWTError, + TokenVerificationError, + TokenVerificationErrorAction, + TokenVerificationErrorCode, + TokenVerificationErrorReason +}; +//# sourceMappingURL=errors.mjs.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/errors.mjs.map b/backend/node_modules/@clerk/backend/dist/errors.mjs.map new file mode 100644 index 000000000..84c51b288 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/errors.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/fixtures/index.d.ts b/backend/node_modules/@clerk/backend/dist/fixtures/index.d.ts new file mode 100644 index 000000000..24b25ce66 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/fixtures/index.d.ts @@ -0,0 +1,83 @@ +export declare const mockJwt = "eyJhbGciOiJSUzI1NiIsImtpZCI6Imluc18yR0lvUWhiVXB5MGhYN0IyY1ZrdVRNaW5Yb0QiLCJ0eXAiOiJKV1QifQ.eyJhenAiOiJodHRwczovL2FjY291bnRzLmluc3BpcmVkLnB1bWEtNzQubGNsLmRldiIsImV4cCI6MTY2NjY0ODMxMCwiaWF0IjoxNjY2NjQ4MjUwLCJpc3MiOiJodHRwczovL2NsZXJrLmluc3BpcmVkLnB1bWEtNzQubGNsLmRldiIsIm5iZiI6MTY2NjY0ODI0MCwic2lkIjoic2Vzc18yR2JEQjRlbk5kQ2E1dlMxenBDM1h6Zzl0SzkiLCJzdWIiOiJ1c2VyXzJHSXBYT0VwVnlKdzUxcmtabjlLbW5jNlN4ciJ9.j3rB92k32WqbQDkFB093H4GoQsBVLH4HLGF6ObcwUaVGiHC8SEu6T31FuPf257SL8A5sSGtWWM1fqhQpdLohgZb_hbJswGBuYI-Clxl9BtpIRHbWFZkLBIj8yS9W9aVtD3fWBbF6PHx7BY1udio-rbGWg1YAOZNtVcxF02p-MvX-8XIK92Vwu3Un5zyfCoVIg__qo3Xntzw3tznsZ4XDe212c6kVz1R_L1d5DKjeWXpjUPAS_zFeZSIJEQLf4JNr4JCY38tfdnc3ajfDA3p36saf1XwmTdWXQKCXi75c2TJAXROs3Pgqr5Kw_5clygoFuxN5OEMhFWFSnvIBdi3M6w"; +export declare const mockExpiredJwt = "eyJhbGciOiJSUzI1NiIsImtpZCI6Imluc18yR0lvUWhiVXB5MGhYN0IyY1ZrdVRNaW5Yb0QiLCJ0eXAiOiJKV1QifQ.eyJhenAiOiJodHRwczovL2FjY291bnRzLmluc3BpcmVkLnB1bWEtNzQubGNsLmRldiIsImV4cCI6MTY2NjY0ODIwMCwiaWF0IjoxNjY2NjQ3MjUwLCJpc3MiOiJodHRwczovL2NsZXJrLmluc3BpcmVkLnB1bWEtNzQubGNsLmRldiIsIm5iZiI6MTY2NjY0ODI0MCwic2lkIjoic2Vzc18yR2JEQjRlbk5kQ2E1dlMxenBDM1h6Zzl0SzkiLCJzdWIiOiJ1c2VyXzJHSXBYT0VwVnlKdzUxcmtabjlLbW5jNlN4ciJ9.jLImjg2vGwOJDkK9gtIeJnEJWVOgoCMeC46OFtfzJ1d8OT0KVvwRppC60QIMfHKoOwLTLYlq8SccrkARwlJ_jOvMAYMGZT-R4qHoEfGmet1cSTC67zaafq5gpf9759x1kNMyckry_PJNSx-9hTFbBMWhY7XVLVlrauppqHXOQr1-BC7u-0InzKjCQTCJj-81Yt8xRKweLbO689oYSRAFYK5LNH8BYoLZFWuWLO-6nxUJu0_XAq9xpZPqZOqj3LxFS4hHVGGmTqnPgR8vBetLXxSLAOBsEyIkeQkOBA03YA6enTNIppmy0XTLgAYmUO_JWOGjjjDQoEojuXtuLRdQHQ"; +export declare const mockInvalidSignatureJwt = "eyJhbGciOiJSUzI1NiIsImtpZCI6Imluc18yR0lvUWhiVXB5MGhYN0IyY1ZrdVRNaW5Yb0QiLCJ0eXAiOiJKV1QifQ.eyJhenAiOiJodHRwczovL2FjY291bnRzLnRhbXBlcmVkLWRvbWFpbi5kZXYiLCJle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+export declare const mockJwtHeader: { + alg: string; + kid: string; + typ: string; +}; +export declare const mockJwtPayload: { + azp: string; + exp: number; + iat: number; + iss: string; + nbf: number; + sid: string; + sub: string; +}; +export declare const mockRsaJwkKid = "ins_2GIoQhbUpy0hX7B2cVkuTMinXoD"; +export declare const mockRsaJwk: { + use: string; + kty: string; + kid: string; + alg: string; + n: string; + e: string; +}; +export declare const mockJwks: { + keys: { + use: string; + kty: string; + kid: string; + alg: string; + n: string; + e: string; + }[]; +}; +export declare const mockPEMKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA8Z1oLQbaYkakUSIYRvjmOoeXMDFFjynGP2+gVy0mQJHYgVhgo34RsQgZoz7rSNm/EOL+l/mHTqQAhwaf9Ef8X5vsPX8vP3RNRRm3XYpbIGbOcANJaHihJZwnzG9zIGYF8ki+m55zftO7pkOoXDtIqCt+5nIUQjGJK5axFELrnWaz2qcR03A7rYKQc3F1gut2Ru1xfmiJVUlQe0tLevQO/FzfYpWu7+691q+ZRUGxWvGc0ays4ACa7JXElCIKXRv/yb3Vc1iry77HRAQ28J7Fqpj5Cb+sxfFI+Vhf1GB1bNeOLPR10nkSMJ74HB0heHi/SsM83JiGekv0CpZPCC8jcQIDAQAB"; +export declare const mockPEMJwk: { + kid: string; + kty: string; + alg: string; + n: string; + e: string; +}; +export declare const mockPEMJwtKey: string; +export declare const pemEncodedSignKey = "-----BEGIN PRIVATE KEY-----\nMIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCpjLcxjx86d4TL\nM0O72WnqIZcqQ1QX6791SeuWRp1ljIHfl5/MoUkSv19+2Za/k9SPW5EdNDduHpfV\nxx45iwiPLTTx0dZkmwqEY7GB1ON4r3WuNqSXG3u3IVcSIocg6vUtKArOikKU58Ii\nPEr+g9Q5/fylWHtad6RxIFCZTl+oD4TMoyLqT1XC9vOoqVkzhdCyIXKfbx31W5sl\naNNTyc2i3SfU0T72TpPEzyeCUzhH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Rmpml7hCr\n5GjbYexXl6VjmCzMcoi4qxYr+aIYE6ZSEpzv1xP0wXt7K4i2JjMFYJu9HOe+Jo9H\nlVSTVE/HF5UKRm58EwKliD/gBfAFviIG+pzT0e0CgYBjVfmflnceTDiWGUqZB/6K\nVemEqCD+L3Pf6FIGI0h2RfFcLowvyOC3qwINTrYXdNUHtLI1BDUkMYBv6YJdI4E/\nEJa5L6umCqdlL4+iL3FKgnsVSkb7io8+n1XLF+qrbRjWpEDuSn8ICC+k/fea/mvj\n5gTPwKCFpNesz5MP8D2kRg==\n-----END PRIVATE KEY-----"; +export declare const pemEncodedPublicKey = "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqYy3MY8fOneEyzNDu9lp\n6iGXKkNUF+u/dUnrlkadZYyB35efzKFJEr9fftmWv5PUj1uRHTQ3bh6X1cceOYsI\njy008dHWZJsKhGOxgdTjeK91rjaklxt7tyFXEiKHIOr1LSgKzopClOfCIjxK/oPU\nOf38pVh7WnekcSBQmU5fqA+EzKMi6k9VwvbzqKlZM4XQsiFyn28d9VubJWjTU8nN\not0n1NE+9k6TxM8nglM4RwkBH4Ni4B0LhKKOOV+AG8tBNiZVil415dpBldmJ/j0w\nk7Ad4VFi9en3Z17oCKr+K+zuT7vKMKSb1548dk0vnmi0vj2QGXSo+61wM5yQWpk6\nsQIDAQAB\n-----END PUBLIC KEY-----"; +export declare const someOtherPublicKey = "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA5wdNEDm/HUAO6xarLs6e\ncS0/J8GencMs5I6rYS825knb8jsNbfoukYfBiK81vQy1/eK5gdWrEprpXQrmIcwG\nakdeUhybYlK68UhHNA5+TAmZ+ReLTJ2QDk5YU4I1NlRRq/bqtEhWsBDOCCkpVsC4\nOLnUpsZKGUwpCrE/8stMSJ6Xx+TzBlDe21cV1j0gn5CWswrrXo7m8OIZ9xkRnNn4\nfTNypMSCbx6BS7fgmer6Efx9HOu9UIKgXD/29q3pEpFXiHRdQRbVoAc9vEZl0QIw\nPSNjILVJLKvb6MhKoQMyaP5k0c1rEkVJr9jQk5Z/6WPklCNK3oT5+gh2lgi7ZxBd\noQIDAQAB\n-----END PUBLIC KEY-----"; +export declare const signingJwks: { + key_ops: string[]; + ext: boolean; + kty: string; + n: string; + e: string; + d: string; + p: string; + q: string; + dp: string; + dq: string; + qi: string; + alg: string; +}; +export declare const publicJwks: { + key_ops: string[]; + ext: boolean; + kty: string; + n: string; + e: string; + alg: string; +}; +export declare const signedJwt = "eyJhbGciOiJSUzI1NiIsImtpZCI6Imluc18yR0lvUWhiVXB5MGhYN0IyY1ZrdVRNaW5Yb0QiLCJ0eXAiOiJKV1QifQ.eyJhenAiOiJodHRwczovL2FjY291bnRzLmluc3BpcmVkLnB1bWEtNzQubGNsLmRldiIsImV4cCI6MTY2NjY0ODMxMCwiaWF0IjoxNjY2NjQ4MjUwLCJpc3MiOiJodHRwczovL2NsZXJrLmluc3BpcmVkLnB1bWEtNzQubGNsLmRldiIsIm5iZiI6MTY2NjY0ODI0MCwic2lkIjoic2Vzc18yR2JEQjRlbk5kQ2E1dlMxenBDM1h6Zzl0SzkiLCJzdWIiOiJ1c2VyXzJHSXBYT0VwVnlKdzUxcmtabjlLbW5jNlN4ciJ9.j3rB92k32WqbQDkFB093H4GoQsBVLH4HLGF6ObcwUaVGiHC8SEu6T31FuPf257SL8A5sSGtWWM1fqhQpdLohgZb_hbJswGBuYI-Clxl9BtpIRHbWFZkLBIj8yS9W9aVtD3fWBbF6PHx7BY1udio-rbGWg1YAOZNtVcxF02p-MvX-8XIK92Vwu3Un5zyfCoVIg__qo3Xntzw3tznsZ4XDe212c6kVz1R_L1d5DKjeWXpjUPAS_zFeZSIJEQLf4JNr4JCY38tfdnc3ajfDA3p36saf1XwmTdWXQKCXi75c2TJAXROs3Pgqr5Kw_5clygoFuxN5OEMhFWFSnvIBdi3M6w"; +export declare const pkTest = "pk_test_Y2xlcmsuaW5zcGlyZWQucHVtYS03NC5sY2wuZGV2JA"; +export declare const pkLive = "pk_live_Y2xlcmsuaW5zcGlyZWQucHVtYS03NC5sY2wuZGV2JA"; +type CreateJwt = (opts?: { + header?: any; + payload?: any; + signature?: string; +}) => string; +export declare const createJwt: CreateJwt; +export declare function createCookieHeader(cookies: Record): string; +export {}; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/fixtures/index.d.ts.map b/backend/node_modules/@clerk/backend/dist/fixtures/index.d.ts.map new file mode 100644 index 000000000..de8bfe2d2 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/fixtures/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/fixtures/index.ts"],"names":[],"mappings":"AAGA,eAAO,MAAM,OAAO,2uBACstB,CAAC;AAG3uB,eAAO,MAAM,cAAc,2uBAC+sB,CAAC;AAE3uB,eAAO,MAAM,uBAAuB,quBACgsB,CAAC;AAEruB,eAAO,MAAM,gBAAgB,+cACib,CAAC;AAK/c,eAAO,MAAM,aAAa;;;;CAIzB,CAAC;AAEF,eAAO,MAAM,cAAc;;;;;;;;CAQ1B,CAAC;AAEF,eAAO,MAAM,aAAa,oCAAoC,CAAC;AAE/D,eAAO,MAAM,UAAU;;;;;;;CAOtB,CAAC;AAEF,eAAO,MAAM,QAAQ;;;;;;;;;CAEpB,CAAC;AAEF,eAAO,MAAM,UAAU,6YACqX,CAAC;AAE7Y,eAAO,MAAM,UAAU;;;;;;CAMtB,CAAC;AAEF,eAAO,MAAM,aAAa,QASE,CAAC;AAE7B,eAAO,MAAM,iBAAiB,usDA2BJ,CAAC;AAE3B,eAAO,MAAM,mBAAmB,+cAQP,CAAC;AAE1B,eAAO,MAAM,kBAAkB,+cAQN,CAAC;AAG1B,eAAO,MAAM,WAAW;;;;;;;;;;;;;CAavB,CAAC;AAEF,eAAO,MAAM,UAAU;;;;;;;CAOtB,CAAC;AAGF,eAAO,MAAM,SAAS,2uBACotB,CAAC;AAE3uB,eAAO,MAAM,MAAM,uDAAuD,CAAC;AAC3E,eAAO,MAAM,MAAM,uDAAuD,CAAC;AAE3E,KAAK,SAAS,GAAG,CAAC,IAAI,CAAC,EAAE;IAAE,MAAM,CAAC,EAAE,GAAG,CAAC;IAAC,OAAO,CAAC,EAAE,GAAG,CAAC;IAAC,SAAS,CAAC,EAAE,MAAM,CAAA;CAAE,KAAK,MAAM,CAAC;AACxF,eAAO,MAAM,SAAS,EAAE,SAWvB,CAAC;AAEF,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,MAAM,CAM1E"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/fixtures/machine.d.ts b/backend/node_modules/@clerk/backend/dist/fixtures/machine.d.ts new file mode 100644 index 000000000..abd98892c --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/fixtures/machine.d.ts @@ -0,0 +1,70 @@ +export declare const mockTokens: { + readonly api_key: "ak_LCWGdaM8mv8K4PC/57IICZQXAeWfCgF30DZaFXHoGn9="; + readonly oauth_token: "oat_8XOIucKvqHVr5tYP123456789abcdefghij"; + readonly m2m_token: "mt_8XOIucKvqHVr5tYP123456789abcdefghij"; +}; +export declare const mockVerificationResults: { + api_key: { + id: string; + type: string; + name: string; + subject: string; + claims: { + foo: string; + }; + scopes: string[]; + revoked: boolean; + revocationReason: null; + expired: boolean; + expiration: null; + createdBy: null; + creationReason: null; + secondsUntilExpiration: null; + createdAt: number; + updatedAt: number; + }; + oauth_token: { + id: string; + clientId: string; + type: string; + name: string; + subject: string; + scopes: string[]; + revoked: boolean; + revocationReason: null; + expired: boolean; + expiration: null; + createdAt: number; + updatedAt: number; + }; + m2m_token: { + id: string; + subject: string; + scopes: string[]; + claims: { + foo: string; + }; + revoked: boolean; + revocationReason: null; + expired: boolean; + expiration: null; + creationReason: null; + createdAt: number; + updatedAt: number; + }; +}; +export declare const mockMachineAuthResponses: { + readonly api_key: { + readonly endpoint: "https://api.clerk.test/api_keys/verify"; + readonly errorMessage: "API key not found"; + }; + readonly oauth_token: { + readonly endpoint: "https://api.clerk.test/oauth_applications/access_tokens/verify"; + readonly errorMessage: "OAuth token not found"; + }; + readonly m2m_token: { + readonly endpoint: "https://api.clerk.test/m2m_tokens/verify"; + readonly errorMessage: "Machine token not found"; + }; +}; +//# sourceMappingURL=machine.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/fixtures/machine.d.ts.map b/backend/node_modules/@clerk/backend/dist/fixtures/machine.d.ts.map new file mode 100644 index 000000000..63335a2c0 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/fixtures/machine.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"machine.d.ts","sourceRoot":"","sources":["../../src/fixtures/machine.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,UAAU;;;;CAIb,CAAC;AAEX,eAAO,MAAM,uBAAuB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA6CnC,CAAC;AAEF,eAAO,MAAM,wBAAwB;;;;;;;;;;;;;CAa3B,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/index.d.ts b/backend/node_modules/@clerk/backend/dist/index.d.ts new file mode 100644 index 000000000..1cc7a5ec4 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/index.d.ts @@ -0,0 +1,38 @@ +import type { TelemetryCollectorOptions } from '@clerk/shared/telemetry'; +import { TelemetryCollector } from '@clerk/shared/telemetry'; +import type { SDKMetadata } from '@clerk/types'; +import type { ApiClient, CreateBackendApiOptions } from './api'; +import type { CreateAuthenticateRequestOptions } from './tokens/factory'; +import { createAuthenticateRequest } from './tokens/factory'; +export declare const verifyToken: (token: string, options: import("./tokens/verify").VerifyTokenOptions) => Promise>; +export type ClerkOptions = Omit & Partial> & { + sdkMetadata?: SDKMetadata; + telemetry?: Pick; +}; +export type ClerkClient = { + telemetry: TelemetryCollector; +} & ApiClient & ReturnType; +export declare function createClerkClient(options: ClerkOptions): ClerkClient; +/** + * General Types + */ +export type { OrganizationMembershipRole } from './api/resources'; +export type { VerifyTokenOptions } from './tokens/verify'; +/** + * JSON types + */ +export type { ActorTokenJSON, AccountlessApplicationJSON, ClerkResourceJSON, TokenJSON, AllowlistIdentifierJSON, BlocklistIdentifierJSON, ClientJSON, CnameTargetJSON, DomainJSON, EmailJSON, EmailAddressJSON, ExternalAccountJSON, IdentificationLinkJSON, InstanceJSON, InstanceRestrictionsJSON, InstanceSettingsJSON, InvitationJSON, JwtTemplateJSON, OauthAccessTokenJSON, OAuthApplicationJSON, OrganizationJSON, OrganizationDomainJSON, OrganizationDomainVerificationJSON, OrganizationInvitationJSON, OrganizationSettingsJSON, PublicOrganizationDataJSON, OrganizationMembershipJSON, OrganizationMembershipPublicUserDataJSON, PhoneNumberJSON, ProxyCheckJSON, RedirectUrlJSON, SessionJSON, SignInJSON, SignInTokenJSON, SignUpJSON, SignUpVerificationJSON, SignUpVerificationsJSON, SMSMessageJSON, UserJSON, VerificationJSON, WaitlistEntryJSON, Web3WalletJSON, DeletedObjectJSON, PaginatedResponseJSON, TestingTokenJSON, WebhooksSvixJSON, BillingPlanJSON, BillingSubscriptionJSON, BillingSubscriptionItemJSON, } from './api/resources/JSON'; +/** + * Resources + */ +export type { APIKey, ActorToken, AccountlessApplication, AllowlistIdentifier, BlocklistIdentifier, Client, CnameTarget, Domain, EmailAddress, ExternalAccount, Feature, Instance, InstanceRestrictions, InstanceSettings, Invitation, JwtTemplate, Machine, M2MToken, OauthAccessToken, OAuthApplication, Organization, OrganizationDomain, OrganizationDomainVerification, OrganizationInvitation, OrganizationMembership, OrganizationMembershipPublicUserData, OrganizationSettings, PhoneNumber, SamlConnection, Session, SignInToken, SignUpAttempt, SMSMessage, Token, User, TestingToken, BillingPlan, BillingSubscription, BillingSubscriptionItem, } from './api/resources'; +/** + * Webhooks event types + */ +export type { EmailWebhookEvent, OrganizationWebhookEvent, OrganizationDomainWebhookEvent, OrganizationInvitationWebhookEvent, OrganizationMembershipWebhookEvent, RoleWebhookEvent, PermissionWebhookEvent, SessionWebhookEvent, SMSWebhookEvent, UserWebhookEvent, WaitlistEntryWebhookEvent, WebhookEvent, WebhookEventType, BillingPaymentAttemptWebhookEvent, BillingSubscriptionWebhookEvent, BillingSubscriptionItemWebhookEvent, } from './api/resources/Webhooks'; +/** + * Auth objects + */ +export type { AuthObject, InvalidTokenAuthObject } from './tokens/authObjects'; +export type { SessionAuthObject, MachineAuthObject } from './tokens/types'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/index.d.ts.map b/backend/node_modules/@clerk/backend/dist/index.d.ts.map new file mode 100644 index 000000000..b6fff34a6 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,yBAAyB,CAAC;AACzE,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAC7D,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAEhD,OAAO,KAAK,EAAE,SAAS,EAAE,uBAAuB,EAAE,MAAM,OAAO,CAAC;AAGhE,OAAO,KAAK,EAAE,gCAAgC,EAAE,MAAM,kBAAkB,CAAC;AACzE,OAAO,EAAE,yBAAyB,EAAE,MAAM,kBAAkB,CAAC;AAG7D,eAAO,MAAM,WAAW,+IAAiC,CAAC;AAE1D,MAAM,MAAM,YAAY,GAAG,IAAI,CAAC,uBAAuB,EAAE,qBAAqB,GAAG,qBAAqB,CAAC,GACrG,OAAO,CACL,IAAI,CACF,gCAAgC,CAAC,SAAS,CAAC,EAC3C,UAAU,GAAG,QAAQ,GAAG,UAAU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AACH,YAAY,EACV,MAAM,EACN,UAAU,EACV,sBAAsB,EACtB,mBAAmB,EACnB,mBAAmB,EACnB,MAAM,EACN,WAAW,EACX,MAAM,EACN,YAAY,EACZ,eAAe,EACf,OAAO,EACP,QAAQ,EACR,oBAAoB,EACpB,gBAAgB,EAChB,UAAU,EACV,WAAW,EACX,OAAO,EACP,QAAQ,EACR,gBAAgB,EAChB,gBAAgB,EAChB,YAAY,EACZ,kBAAkB,EAClB,8BAA8B,EAC9B,sBAAsB,EACtB,sBAAsB,EACtB,oCAAoC,EACpC,oBAAoB,EACpB,WAAW,EACX,cAAc,EACd,OAAO,EACP,WAAW,EACX,aAAa,EACb,UAAU,EACV,KAAK,EACL,IAAI,EACJ,YAAY,EACZ,WAAW,EACX,mBAAmB,EACnB,uBAAuB,GACxB,MAAM,iBAAiB,CAAC;AAEzB;;GAEG;AACH,YAAY,EACV,iBAAiB,EACjB,wBAAwB,EACxB,8BAA8B,EAC9B,kCAAkC,EAClC,kCAAkC,EAClC,gBAAgB,EAChB,sBAAsB,EACtB,mBAAmB,EACnB,eAAe,EACf,gBAAgB,EAChB,yBAAyB,EACzB,YAAY,EACZ,gBAAgB,EAChB,iCAAiC,EACjC,+BAA+B,EAC/B,mCAAmC,GACpC,MAAM,0BAA0B,CAAC;AAElC;;GAEG;AACH,YAAY,EAAE,UAAU,EAAE,sBAAsB,EAAE,MAAM,sBAAsB,CAAC;AAC/E,YAAY,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/index.js b/backend/node_modules/@clerk/backend/dist/index.js new file mode 100644 index 000000000..c00ffdc0c --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/index.js @@ -0,0 +1,5890 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __typeError = (msg) => { + throw TypeError(msg); +}; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg); +var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value); +var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method); + +// src/index.ts +var index_exports = {}; +__export(index_exports, { + createClerkClient: () => createClerkClient, + verifyToken: () => verifyToken2 +}); +module.exports = __toCommonJS(index_exports); +var import_telemetry = require("@clerk/shared/telemetry"); + +// src/util/path.ts +var SEPARATOR = "/"; +var MULTIPLE_SEPARATOR_REGEX = new RegExp("(? p).join(SEPARATOR).replace(MULTIPLE_SEPARATOR_REGEX, SEPARATOR); +} + +// src/api/endpoints/AbstractApi.ts +var AbstractAPI = class { + constructor(request) { + this.request = request; + } + requireId(id) { + if (!id) { + throw new Error("A valid resource ID is required."); + } + } +}; + +// src/api/endpoints/ActorTokenApi.ts +var basePath = "/actor_tokens"; +var ActorTokenAPI = class extends AbstractAPI { + async create(params) { + return this.request({ + method: "POST", + path: basePath, + bodyParams: params + }); + } + async revoke(actorTokenId) { + this.requireId(actorTokenId); + return this.request({ + method: "POST", + path: joinPaths(basePath, actorTokenId, "revoke") + }); + } +}; + +// src/api/endpoints/AccountlessApplicationsAPI.ts +var basePath2 = "/accountless_applications"; +var AccountlessApplicationAPI = class extends AbstractAPI { + async createAccountlessApplication(params) { + const headerParams = params?.requestHeaders ? Object.fromEntries(params.requestHeaders.entries()) : void 0; + return this.request({ + method: "POST", + path: basePath2, + headerParams + }); + } + async completeAccountlessApplicationOnboarding(params) { + const headerParams = params?.requestHeaders ? Object.fromEntries(params.requestHeaders.entries()) : void 0; + return this.request({ + method: "POST", + path: joinPaths(basePath2, "complete"), + headerParams + }); + } +}; + +// src/api/endpoints/AllowlistIdentifierApi.ts +var basePath3 = "/allowlist_identifiers"; +var AllowlistIdentifierAPI = class extends AbstractAPI { + async getAllowlistIdentifierList(params = {}) { + return this.request({ + method: "GET", + path: basePath3, + queryParams: { ...params, paginated: true } + }); + } + async createAllowlistIdentifier(params) { + return this.request({ + method: "POST", + path: basePath3, + bodyParams: params + }); + } + async deleteAllowlistIdentifier(allowlistIdentifierId) { + this.requireId(allowlistIdentifierId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath3, allowlistIdentifierId) + }); + } +}; + +// src/api/endpoints/APIKeysApi.ts +var basePath4 = "/api_keys"; +var APIKeysAPI = class extends AbstractAPI { + async create(params) { + return this.request({ + method: "POST", + path: basePath4, + bodyParams: params + }); + } + async revoke(params) { + const { apiKeyId, ...bodyParams } = params; + this.requireId(apiKeyId); + return this.request({ + method: "POST", + path: joinPaths(basePath4, apiKeyId, "revoke"), + bodyParams + }); + } + async getSecret(apiKeyId) { + this.requireId(apiKeyId); + return this.request({ + method: "GET", + path: joinPaths(basePath4, apiKeyId, "secret") + }); + } + async verifySecret(secret) { + return this.request({ + method: "POST", + path: joinPaths(basePath4, "verify"), + bodyParams: { secret } + }); + } +}; + +// src/api/endpoints/BetaFeaturesApi.ts +var basePath5 = "/beta_features"; +var BetaFeaturesAPI = class extends AbstractAPI { + /** + * Change the domain of a production instance. + * + * Changing the domain requires updating the DNS records accordingly, deploying new SSL certificates, + * updating your Social Connection's redirect URLs and setting the new keys in your code. + * + * @remarks + * WARNING: Changing your domain will invalidate all current user sessions (i.e. users will be logged out). + * Also, while your application is being deployed, a small downtime is expected to occur. + */ + async changeDomain(params) { + return this.request({ + method: "POST", + path: joinPaths(basePath5, "change_domain"), + bodyParams: params + }); + } +}; + +// src/api/endpoints/BlocklistIdentifierApi.ts +var basePath6 = "/blocklist_identifiers"; +var BlocklistIdentifierAPI = class extends AbstractAPI { + async getBlocklistIdentifierList(params = {}) { + return this.request({ + method: "GET", + path: basePath6, + queryParams: params + }); + } + async createBlocklistIdentifier(params) { + return this.request({ + method: "POST", + path: basePath6, + bodyParams: params + }); + } + async deleteBlocklistIdentifier(blocklistIdentifierId) { + this.requireId(blocklistIdentifierId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath6, blocklistIdentifierId) + }); + } +}; + +// src/api/endpoints/ClientApi.ts +var basePath7 = "/clients"; +var ClientAPI = class extends AbstractAPI { + async getClientList(params = {}) { + return this.request({ + method: "GET", + path: basePath7, + queryParams: { ...params, paginated: true } + }); + } + async getClient(clientId) { + this.requireId(clientId); + return this.request({ + method: "GET", + path: joinPaths(basePath7, clientId) + }); + } + verifyClient(token) { + return this.request({ + method: "POST", + path: joinPaths(basePath7, "verify"), + bodyParams: { token } + }); + } + async getHandshakePayload(queryParams) { + return this.request({ + method: "GET", + path: joinPaths(basePath7, "handshake_payload"), + queryParams + }); + } +}; + +// src/api/endpoints/DomainApi.ts +var basePath8 = "/domains"; +var DomainAPI = class extends AbstractAPI { + async list() { + return this.request({ + method: "GET", + path: basePath8 + }); + } + async add(params) { + return this.request({ + method: "POST", + path: basePath8, + bodyParams: params + }); + } + async update(params) { + const { domainId, ...bodyParams } = params; + this.requireId(domainId); + return this.request({ + method: "PATCH", + path: joinPaths(basePath8, domainId), + bodyParams + }); + } + /** + * Deletes a satellite domain for the instance. + * It is currently not possible to delete the instance's primary domain. + */ + async delete(satelliteDomainId) { + return this.deleteDomain(satelliteDomainId); + } + /** + * @deprecated Use `delete` instead + */ + async deleteDomain(satelliteDomainId) { + this.requireId(satelliteDomainId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath8, satelliteDomainId) + }); + } +}; + +// src/api/endpoints/EmailAddressApi.ts +var basePath9 = "/email_addresses"; +var EmailAddressAPI = class extends AbstractAPI { + async getEmailAddress(emailAddressId) { + this.requireId(emailAddressId); + return this.request({ + method: "GET", + path: joinPaths(basePath9, emailAddressId) + }); + } + async createEmailAddress(params) { + return this.request({ + method: "POST", + path: basePath9, + bodyParams: params + }); + } + async updateEmailAddress(emailAddressId, params = {}) { + this.requireId(emailAddressId); + return this.request({ + method: "PATCH", + path: joinPaths(basePath9, emailAddressId), + bodyParams: params + }); + } + async deleteEmailAddress(emailAddressId) { + this.requireId(emailAddressId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath9, emailAddressId) + }); + } +}; + +// src/api/endpoints/IdPOAuthAccessTokenApi.ts +var basePath10 = "/oauth_applications/access_tokens"; +var IdPOAuthAccessTokenApi = class extends AbstractAPI { + async verifyAccessToken(accessToken) { + return this.request({ + method: "POST", + path: joinPaths(basePath10, "verify"), + bodyParams: { access_token: accessToken } + }); + } +}; + +// src/api/endpoints/InstanceApi.ts +var basePath11 = "/instance"; +var InstanceAPI = class extends AbstractAPI { + async get() { + return this.request({ + method: "GET", + path: basePath11 + }); + } + async update(params) { + return this.request({ + method: "PATCH", + path: basePath11, + bodyParams: params + }); + } + async updateRestrictions(params) { + return this.request({ + method: "PATCH", + path: joinPaths(basePath11, "restrictions"), + bodyParams: params + }); + } + async updateOrganizationSettings(params) { + return this.request({ + method: "PATCH", + path: joinPaths(basePath11, "organization_settings"), + bodyParams: params + }); + } +}; + +// src/api/endpoints/InvitationApi.ts +var basePath12 = "/invitations"; +var InvitationAPI = class extends AbstractAPI { + async getInvitationList(params = {}) { + return this.request({ + method: "GET", + path: basePath12, + queryParams: { ...params, paginated: true } + }); + } + async createInvitation(params) { + return this.request({ + method: "POST", + path: basePath12, + bodyParams: params + }); + } + async createInvitationBulk(params) { + return this.request({ + method: "POST", + path: joinPaths(basePath12, "bulk"), + bodyParams: params + }); + } + async revokeInvitation(invitationId) { + this.requireId(invitationId); + return this.request({ + method: "POST", + path: joinPaths(basePath12, invitationId, "revoke") + }); + } +}; + +// src/api/endpoints/MachineApi.ts +var basePath13 = "/machines"; +var MachineApi = class extends AbstractAPI { + async get(machineId) { + this.requireId(machineId); + return this.request({ + method: "GET", + path: joinPaths(basePath13, machineId) + }); + } + async list(queryParams = {}) { + return this.request({ + method: "GET", + path: basePath13, + queryParams + }); + } + async create(bodyParams) { + return this.request({ + method: "POST", + path: basePath13, + bodyParams + }); + } + async update(params) { + const { machineId, ...bodyParams } = params; + this.requireId(machineId); + return this.request({ + method: "PATCH", + path: joinPaths(basePath13, machineId), + bodyParams + }); + } + async delete(machineId) { + this.requireId(machineId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath13, machineId) + }); + } + async getSecretKey(machineId) { + this.requireId(machineId); + return this.request({ + method: "GET", + path: joinPaths(basePath13, machineId, "secret_key") + }); + } + async rotateSecretKey(params) { + const { machineId, previousTokenTtl } = params; + this.requireId(machineId); + return this.request({ + method: "POST", + path: joinPaths(basePath13, machineId, "secret_key", "rotate"), + bodyParams: { + previousTokenTtl + } + }); + } + /** + * Creates a new machine scope, allowing the specified machine to access another machine. + * + * @param machineId - The ID of the machine that will have access to another machine. + * @param toMachineId - The ID of the machine that will be scoped to the current machine. + */ + async createScope(machineId, toMachineId) { + this.requireId(machineId); + return this.request({ + method: "POST", + path: joinPaths(basePath13, machineId, "scopes"), + bodyParams: { + toMachineId + } + }); + } + /** + * Deletes a machine scope, removing access from one machine to another. + * + * @param machineId - The ID of the machine that has access to another machine. + * @param otherMachineId - The ID of the machine that is being accessed. + */ + async deleteScope(machineId, otherMachineId) { + this.requireId(machineId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath13, machineId, "scopes", otherMachineId) + }); + } +}; + +// src/api/endpoints/M2MTokenApi.ts +var basePath14 = "/m2m_tokens"; +var _M2MTokenApi_instances, createRequestOptions_fn; +var M2MTokenApi = class extends AbstractAPI { + constructor() { + super(...arguments); + __privateAdd(this, _M2MTokenApi_instances); + } + async createToken(params) { + const { claims = null, machineSecretKey, secondsUntilExpiration = null } = params || {}; + const requestOptions = __privateMethod(this, _M2MTokenApi_instances, createRequestOptions_fn).call(this, { + method: "POST", + path: basePath14, + bodyParams: { + secondsUntilExpiration, + claims + } + }, machineSecretKey); + return this.request(requestOptions); + } + async revokeToken(params) { + const { m2mTokenId, revocationReason = null, machineSecretKey } = params; + this.requireId(m2mTokenId); + const requestOptions = __privateMethod(this, _M2MTokenApi_instances, createRequestOptions_fn).call(this, { + method: "POST", + path: joinPaths(basePath14, m2mTokenId, "revoke"), + bodyParams: { + revocationReason + } + }, machineSecretKey); + return this.request(requestOptions); + } + async verifyToken(params) { + const { token, machineSecretKey } = params; + const requestOptions = __privateMethod(this, _M2MTokenApi_instances, createRequestOptions_fn).call(this, { + method: "POST", + path: joinPaths(basePath14, "verify"), + bodyParams: { token } + }, machineSecretKey); + return this.request(requestOptions); + } +}; +_M2MTokenApi_instances = new WeakSet(); +createRequestOptions_fn = function(options, machineSecretKey) { + if (machineSecretKey) { + return { + ...options, + headerParams: { + ...options.headerParams, + Authorization: `Bearer ${machineSecretKey}` + } + }; + } + return options; +}; + +// src/api/endpoints/JwksApi.ts +var basePath15 = "/jwks"; +var JwksAPI = class extends AbstractAPI { + async getJwks() { + return this.request({ + method: "GET", + path: basePath15 + }); + } +}; + +// src/api/endpoints/JwtTemplatesApi.ts +var basePath16 = "/jwt_templates"; +var JwtTemplatesApi = class extends AbstractAPI { + async list(params = {}) { + return this.request({ + method: "GET", + path: basePath16, + queryParams: { ...params, paginated: true } + }); + } + async get(templateId) { + this.requireId(templateId); + return this.request({ + method: "GET", + path: joinPaths(basePath16, templateId) + }); + } + async create(params) { + return this.request({ + method: "POST", + path: basePath16, + bodyParams: params + }); + } + async update(params) { + const { templateId, ...bodyParams } = params; + this.requireId(templateId); + return this.request({ + method: "PATCH", + path: joinPaths(basePath16, templateId), + bodyParams + }); + } + async delete(templateId) { + this.requireId(templateId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath16, templateId) + }); + } +}; + +// src/runtime.ts +var import_crypto = require("#crypto"); +var globalFetch = fetch.bind(globalThis); +var runtime = { + crypto: import_crypto.webcrypto, + get fetch() { + return process.env.NODE_ENV === "test" ? fetch : globalFetch; + }, + AbortController: globalThis.AbortController, + Blob: globalThis.Blob, + FormData: globalThis.FormData, + Headers: globalThis.Headers, + Request: globalThis.Request, + Response: globalThis.Response +}; + +// src/api/endpoints/OrganizationApi.ts +var basePath17 = "/organizations"; +var OrganizationAPI = class extends AbstractAPI { + async getOrganizationList(params) { + return this.request({ + method: "GET", + path: basePath17, + queryParams: params + }); + } + async createOrganization(params) { + return this.request({ + method: "POST", + path: basePath17, + bodyParams: params + }); + } + async getOrganization(params) { + const { includeMembersCount } = params; + const organizationIdOrSlug = "organizationId" in params ? params.organizationId : params.slug; + this.requireId(organizationIdOrSlug); + return this.request({ + method: "GET", + path: joinPaths(basePath17, organizationIdOrSlug), + queryParams: { + includeMembersCount + } + }); + } + async updateOrganization(organizationId, params) { + this.requireId(organizationId); + return this.request({ + method: "PATCH", + path: joinPaths(basePath17, organizationId), + bodyParams: params + }); + } + async updateOrganizationLogo(organizationId, params) { + this.requireId(organizationId); + const formData = new runtime.FormData(); + formData.append("file", params?.file); + if (params?.uploaderUserId) { + formData.append("uploader_user_id", params?.uploaderUserId); + } + return this.request({ + method: "PUT", + path: joinPaths(basePath17, organizationId, "logo"), + formData + }); + } + async deleteOrganizationLogo(organizationId) { + this.requireId(organizationId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath17, organizationId, "logo") + }); + } + async updateOrganizationMetadata(organizationId, params) { + this.requireId(organizationId); + return this.request({ + method: "PATCH", + path: joinPaths(basePath17, organizationId, "metadata"), + bodyParams: params + }); + } + async deleteOrganization(organizationId) { + return this.request({ + method: "DELETE", + path: joinPaths(basePath17, organizationId) + }); + } + async getOrganizationMembershipList(params) { + const { organizationId, ...queryParams } = params; + this.requireId(organizationId); + return this.request({ + method: "GET", + path: joinPaths(basePath17, organizationId, "memberships"), + queryParams + }); + } + async getInstanceOrganizationMembershipList(params) { + return this.request({ + method: "GET", + path: "/organization_memberships", + queryParams: params + }); + } + async createOrganizationMembership(params) { + const { organizationId, ...bodyParams } = params; + this.requireId(organizationId); + return this.request({ + method: "POST", + path: joinPaths(basePath17, organizationId, "memberships"), + bodyParams + }); + } + async updateOrganizationMembership(params) { + const { organizationId, userId, ...bodyParams } = params; + this.requireId(organizationId); + return this.request({ + method: "PATCH", + path: joinPaths(basePath17, organizationId, "memberships", userId), + bodyParams + }); + } + async updateOrganizationMembershipMetadata(params) { + const { organizationId, userId, ...bodyParams } = params; + return this.request({ + method: "PATCH", + path: joinPaths(basePath17, organizationId, "memberships", userId, "metadata"), + bodyParams + }); + } + async deleteOrganizationMembership(params) { + const { organizationId, userId } = params; + this.requireId(organizationId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath17, organizationId, "memberships", userId) + }); + } + async getOrganizationInvitationList(params) { + const { organizationId, ...queryParams } = params; + this.requireId(organizationId); + return this.request({ + method: "GET", + path: joinPaths(basePath17, organizationId, "invitations"), + queryParams + }); + } + async createOrganizationInvitation(params) { + const { organizationId, ...bodyParams } = params; + this.requireId(organizationId); + return this.request({ + method: "POST", + path: joinPaths(basePath17, organizationId, "invitations"), + bodyParams + }); + } + async createOrganizationInvitationBulk(organizationId, params) { + this.requireId(organizationId); + return this.request({ + method: "POST", + path: joinPaths(basePath17, organizationId, "invitations", "bulk"), + bodyParams: params + }); + } + async getOrganizationInvitation(params) { + const { organizationId, invitationId } = params; + this.requireId(organizationId); + this.requireId(invitationId); + return this.request({ + method: "GET", + path: joinPaths(basePath17, organizationId, "invitations", invitationId) + }); + } + async revokeOrganizationInvitation(params) { + const { organizationId, invitationId, ...bodyParams } = params; + this.requireId(organizationId); + return this.request({ + method: "POST", + path: joinPaths(basePath17, organizationId, "invitations", invitationId, "revoke"), + bodyParams + }); + } + async getOrganizationDomainList(params) { + const { organizationId, ...queryParams } = params; + this.requireId(organizationId); + return this.request({ + method: "GET", + path: joinPaths(basePath17, organizationId, "domains"), + queryParams + }); + } + async createOrganizationDomain(params) { + const { organizationId, ...bodyParams } = params; + this.requireId(organizationId); + return this.request({ + method: "POST", + path: joinPaths(basePath17, organizationId, "domains"), + bodyParams: { + ...bodyParams, + verified: bodyParams.verified ?? true + } + }); + } + async updateOrganizationDomain(params) { + const { organizationId, domainId, ...bodyParams } = params; + this.requireId(organizationId); + this.requireId(domainId); + return this.request({ + method: "PATCH", + path: joinPaths(basePath17, organizationId, "domains", domainId), + bodyParams + }); + } + async deleteOrganizationDomain(params) { + const { organizationId, domainId } = params; + this.requireId(organizationId); + this.requireId(domainId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath17, organizationId, "domains", domainId) + }); + } +}; + +// src/api/endpoints/OAuthApplicationsApi.ts +var basePath18 = "/oauth_applications"; +var OAuthApplicationsApi = class extends AbstractAPI { + async list(params = {}) { + return this.request({ + method: "GET", + path: basePath18, + queryParams: params + }); + } + async get(oauthApplicationId) { + this.requireId(oauthApplicationId); + return this.request({ + method: "GET", + path: joinPaths(basePath18, oauthApplicationId) + }); + } + async create(params) { + return this.request({ + method: "POST", + path: basePath18, + bodyParams: params + }); + } + async update(params) { + const { oauthApplicationId, ...bodyParams } = params; + this.requireId(oauthApplicationId); + return this.request({ + method: "PATCH", + path: joinPaths(basePath18, oauthApplicationId), + bodyParams + }); + } + async delete(oauthApplicationId) { + this.requireId(oauthApplicationId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath18, oauthApplicationId) + }); + } + async rotateSecret(oauthApplicationId) { + this.requireId(oauthApplicationId); + return this.request({ + method: "POST", + path: joinPaths(basePath18, oauthApplicationId, "rotate_secret") + }); + } +}; + +// src/api/endpoints/PhoneNumberApi.ts +var basePath19 = "/phone_numbers"; +var PhoneNumberAPI = class extends AbstractAPI { + async getPhoneNumber(phoneNumberId) { + this.requireId(phoneNumberId); + return this.request({ + method: "GET", + path: joinPaths(basePath19, phoneNumberId) + }); + } + async createPhoneNumber(params) { + return this.request({ + method: "POST", + path: basePath19, + bodyParams: params + }); + } + async updatePhoneNumber(phoneNumberId, params = {}) { + this.requireId(phoneNumberId); + return this.request({ + method: "PATCH", + path: joinPaths(basePath19, phoneNumberId), + bodyParams: params + }); + } + async deletePhoneNumber(phoneNumberId) { + this.requireId(phoneNumberId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath19, phoneNumberId) + }); + } +}; + +// src/api/endpoints/ProxyCheckApi.ts +var basePath20 = "/proxy_checks"; +var ProxyCheckAPI = class extends AbstractAPI { + async verify(params) { + return this.request({ + method: "POST", + path: basePath20, + bodyParams: params + }); + } +}; + +// src/api/endpoints/RedirectUrlApi.ts +var basePath21 = "/redirect_urls"; +var RedirectUrlAPI = class extends AbstractAPI { + async getRedirectUrlList() { + return this.request({ + method: "GET", + path: basePath21, + queryParams: { paginated: true } + }); + } + async getRedirectUrl(redirectUrlId) { + this.requireId(redirectUrlId); + return this.request({ + method: "GET", + path: joinPaths(basePath21, redirectUrlId) + }); + } + async createRedirectUrl(params) { + return this.request({ + method: "POST", + path: basePath21, + bodyParams: params + }); + } + async deleteRedirectUrl(redirectUrlId) { + this.requireId(redirectUrlId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath21, redirectUrlId) + }); + } +}; + +// src/api/endpoints/SamlConnectionApi.ts +var basePath22 = "/saml_connections"; +var SamlConnectionAPI = class extends AbstractAPI { + async getSamlConnectionList(params = {}) { + return this.request({ + method: "GET", + path: basePath22, + queryParams: params + }); + } + async createSamlConnection(params) { + return this.request({ + method: "POST", + path: basePath22, + bodyParams: params, + options: { + deepSnakecaseBodyParamKeys: true + } + }); + } + async getSamlConnection(samlConnectionId) { + this.requireId(samlConnectionId); + return this.request({ + method: "GET", + path: joinPaths(basePath22, samlConnectionId) + }); + } + async updateSamlConnection(samlConnectionId, params = {}) { + this.requireId(samlConnectionId); + return this.request({ + method: "PATCH", + path: joinPaths(basePath22, samlConnectionId), + bodyParams: params, + options: { + deepSnakecaseBodyParamKeys: true + } + }); + } + async deleteSamlConnection(samlConnectionId) { + this.requireId(samlConnectionId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath22, samlConnectionId) + }); + } +}; + +// src/api/endpoints/SessionApi.ts +var basePath23 = "/sessions"; +var SessionAPI = class extends AbstractAPI { + async getSessionList(params = {}) { + return this.request({ + method: "GET", + path: basePath23, + queryParams: { ...params, paginated: true } + }); + } + async getSession(sessionId) { + this.requireId(sessionId); + return this.request({ + method: "GET", + path: joinPaths(basePath23, sessionId) + }); + } + async createSession(params) { + return this.request({ + method: "POST", + path: basePath23, + bodyParams: params + }); + } + async revokeSession(sessionId) { + this.requireId(sessionId); + return this.request({ + method: "POST", + path: joinPaths(basePath23, sessionId, "revoke") + }); + } + async verifySession(sessionId, token) { + this.requireId(sessionId); + return this.request({ + method: "POST", + path: joinPaths(basePath23, sessionId, "verify"), + bodyParams: { token } + }); + } + /** + * Retrieves a session token or generates a JWT using a specified template. + * + * @param sessionId - The ID of the session for which to generate the token + * @param template - Optional name of the JWT template configured in the Clerk Dashboard. + * @param expiresInSeconds - Optional expiration time for the token in seconds. + * If not provided, uses the default expiration. + * + * @returns A promise that resolves to the generated token + * + * @throws {Error} When sessionId is invalid or empty + */ + async getToken(sessionId, template, expiresInSeconds) { + this.requireId(sessionId); + const path = template ? joinPaths(basePath23, sessionId, "tokens", template) : joinPaths(basePath23, sessionId, "tokens"); + const requestOptions = { + method: "POST", + path + }; + if (expiresInSeconds !== void 0) { + requestOptions.bodyParams = { expires_in_seconds: expiresInSeconds }; + } + return this.request(requestOptions); + } + async refreshSession(sessionId, params) { + this.requireId(sessionId); + const { suffixed_cookies, ...restParams } = params; + return this.request({ + method: "POST", + path: joinPaths(basePath23, sessionId, "refresh"), + bodyParams: restParams, + queryParams: { suffixed_cookies } + }); + } +}; + +// src/api/endpoints/SignInTokenApi.ts +var basePath24 = "/sign_in_tokens"; +var SignInTokenAPI = class extends AbstractAPI { + async createSignInToken(params) { + return this.request({ + method: "POST", + path: basePath24, + bodyParams: params + }); + } + async revokeSignInToken(signInTokenId) { + this.requireId(signInTokenId); + return this.request({ + method: "POST", + path: joinPaths(basePath24, signInTokenId, "revoke") + }); + } +}; + +// src/api/endpoints/SignUpApi.ts +var basePath25 = "/sign_ups"; +var SignUpAPI = class extends AbstractAPI { + async get(signUpAttemptId) { + this.requireId(signUpAttemptId); + return this.request({ + method: "GET", + path: joinPaths(basePath25, signUpAttemptId) + }); + } + async update(params) { + const { signUpAttemptId, ...bodyParams } = params; + return this.request({ + method: "PATCH", + path: joinPaths(basePath25, signUpAttemptId), + bodyParams + }); + } +}; + +// src/api/endpoints/TestingTokenApi.ts +var basePath26 = "/testing_tokens"; +var TestingTokenAPI = class extends AbstractAPI { + async createTestingToken() { + return this.request({ + method: "POST", + path: basePath26 + }); + } +}; + +// src/util/shared.ts +var import_url = require("@clerk/shared/url"); +var import_retry = require("@clerk/shared/retry"); +var import_keys = require("@clerk/shared/keys"); +var import_deprecated = require("@clerk/shared/deprecated"); +var import_error = require("@clerk/shared/error"); +var import_keys2 = require("@clerk/shared/keys"); +var errorThrower = (0, import_error.buildErrorThrower)({ packageName: "@clerk/backend" }); +var { isDevOrStagingUrl } = (0, import_keys2.createDevOrStagingUrlCache)(); + +// src/api/endpoints/UserApi.ts +var basePath27 = "/users"; +var UserAPI = class extends AbstractAPI { + async getUserList(params = {}) { + const { limit, offset, orderBy, ...userCountParams } = params; + const [data, totalCount] = await Promise.all([ + this.request({ + method: "GET", + path: basePath27, + queryParams: params + }), + this.getCount(userCountParams) + ]); + return { data, totalCount }; + } + async getUser(userId) { + this.requireId(userId); + return this.request({ + method: "GET", + path: joinPaths(basePath27, userId) + }); + } + async createUser(params) { + return this.request({ + method: "POST", + path: basePath27, + bodyParams: params + }); + } + async updateUser(userId, params = {}) { + this.requireId(userId); + return this.request({ + method: "PATCH", + path: joinPaths(basePath27, userId), + bodyParams: params + }); + } + async updateUserProfileImage(userId, params) { + this.requireId(userId); + const formData = new runtime.FormData(); + formData.append("file", params?.file); + return this.request({ + method: "POST", + path: joinPaths(basePath27, userId, "profile_image"), + formData + }); + } + async updateUserMetadata(userId, params) { + this.requireId(userId); + return this.request({ + method: "PATCH", + path: joinPaths(basePath27, userId, "metadata"), + bodyParams: params + }); + } + async deleteUser(userId) { + this.requireId(userId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath27, userId) + }); + } + async getCount(params = {}) { + return this.request({ + method: "GET", + path: joinPaths(basePath27, "count"), + queryParams: params + }); + } + async getUserOauthAccessToken(userId, provider) { + this.requireId(userId); + const hasPrefix = provider.startsWith("oauth_"); + const _provider = hasPrefix ? provider : `oauth_${provider}`; + if (hasPrefix) { + (0, import_deprecated.deprecated)( + "getUserOauthAccessToken(userId, provider)", + "Remove the `oauth_` prefix from the `provider` argument." + ); + } + return this.request({ + method: "GET", + path: joinPaths(basePath27, userId, "oauth_access_tokens", _provider), + queryParams: { paginated: true } + }); + } + async disableUserMFA(userId) { + this.requireId(userId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath27, userId, "mfa") + }); + } + async getOrganizationMembershipList(params) { + const { userId, limit, offset } = params; + this.requireId(userId); + return this.request({ + method: "GET", + path: joinPaths(basePath27, userId, "organization_memberships"), + queryParams: { limit, offset } + }); + } + async getOrganizationInvitationList(params) { + const { userId, ...queryParams } = params; + this.requireId(userId); + return this.request({ + method: "GET", + path: joinPaths(basePath27, userId, "organization_invitations"), + queryParams + }); + } + async verifyPassword(params) { + const { userId, password } = params; + this.requireId(userId); + return this.request({ + method: "POST", + path: joinPaths(basePath27, userId, "verify_password"), + bodyParams: { password } + }); + } + async verifyTOTP(params) { + const { userId, code } = params; + this.requireId(userId); + return this.request({ + method: "POST", + path: joinPaths(basePath27, userId, "verify_totp"), + bodyParams: { code } + }); + } + async banUser(userId) { + this.requireId(userId); + return this.request({ + method: "POST", + path: joinPaths(basePath27, userId, "ban") + }); + } + async unbanUser(userId) { + this.requireId(userId); + return this.request({ + method: "POST", + path: joinPaths(basePath27, userId, "unban") + }); + } + async lockUser(userId) { + this.requireId(userId); + return this.request({ + method: "POST", + path: joinPaths(basePath27, userId, "lock") + }); + } + async unlockUser(userId) { + this.requireId(userId); + return this.request({ + method: "POST", + path: joinPaths(basePath27, userId, "unlock") + }); + } + async deleteUserProfileImage(userId) { + this.requireId(userId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath27, userId, "profile_image") + }); + } + async deleteUserPasskey(params) { + this.requireId(params.userId); + this.requireId(params.passkeyIdentificationId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath27, params.userId, "passkeys", params.passkeyIdentificationId) + }); + } + async deleteUserWeb3Wallet(params) { + this.requireId(params.userId); + this.requireId(params.web3WalletIdentificationId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath27, params.userId, "web3_wallets", params.web3WalletIdentificationId) + }); + } + async deleteUserExternalAccount(params) { + this.requireId(params.userId); + this.requireId(params.externalAccountId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath27, params.userId, "external_accounts", params.externalAccountId) + }); + } + async deleteUserBackupCodes(userId) { + this.requireId(userId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath27, userId, "backup_code") + }); + } + async deleteUserTOTP(userId) { + this.requireId(userId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath27, userId, "totp") + }); + } +}; + +// src/api/endpoints/WaitlistEntryApi.ts +var basePath28 = "/waitlist_entries"; +var WaitlistEntryAPI = class extends AbstractAPI { + /** + * List waitlist entries. + * @param params Optional parameters (e.g., `query`, `status`, `orderBy`). + */ + async list(params = {}) { + return this.request({ + method: "GET", + path: basePath28, + queryParams: params + }); + } + /** + * Create a waitlist entry. + * @param params The parameters for creating a waitlist entry. + */ + async create(params) { + return this.request({ + method: "POST", + path: basePath28, + bodyParams: params + }); + } + /** + * Invite a waitlist entry. + * @param id The waitlist entry ID. + * @param params Optional parameters (e.g., `ignoreExisting`). + */ + async invite(id, params = {}) { + this.requireId(id); + return this.request({ + method: "POST", + path: joinPaths(basePath28, id, "invite"), + bodyParams: params + }); + } + /** + * Reject a waitlist entry. + * @param id The waitlist entry ID. + */ + async reject(id) { + this.requireId(id); + return this.request({ + method: "POST", + path: joinPaths(basePath28, id, "reject") + }); + } + /** + * Delete a waitlist entry. + * @param id The waitlist entry ID. + */ + async delete(id) { + this.requireId(id); + return this.request({ + method: "DELETE", + path: joinPaths(basePath28, id) + }); + } +}; + +// src/api/endpoints/WebhookApi.ts +var basePath29 = "/webhooks"; +var WebhookAPI = class extends AbstractAPI { + async createSvixApp() { + return this.request({ + method: "POST", + path: joinPaths(basePath29, "svix") + }); + } + async generateSvixAuthURL() { + return this.request({ + method: "POST", + path: joinPaths(basePath29, "svix_url") + }); + } + async deleteSvixApp() { + return this.request({ + method: "DELETE", + path: joinPaths(basePath29, "svix") + }); + } +}; + +// src/api/endpoints/BillingApi.ts +var basePath30 = "/commerce"; +var organizationBasePath = "/organizations"; +var userBasePath = "/users"; +var BillingAPI = class extends AbstractAPI { + /** + * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. + */ + async getPlanList(params) { + return this.request({ + method: "GET", + path: joinPaths(basePath30, "plans"), + queryParams: params + }); + } + /** + * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. + */ + async cancelSubscriptionItem(subscriptionItemId, params) { + this.requireId(subscriptionItemId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath30, "subscription_items", subscriptionItemId), + queryParams: params + }); + } + /** + * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. + */ + async extendSubscriptionItemFreeTrial(subscriptionItemId, params) { + this.requireId(subscriptionItemId); + return this.request({ + method: "POST", + path: joinPaths("/billing", "subscription_items", subscriptionItemId, "extend_free_trial"), + bodyParams: params + }); + } + /** + * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. + */ + async getOrganizationBillingSubscription(organizationId) { + this.requireId(organizationId); + return this.request({ + method: "GET", + path: joinPaths(organizationBasePath, organizationId, "billing", "subscription") + }); + } + /** + * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. + */ + async getUserBillingSubscription(userId) { + this.requireId(userId); + return this.request({ + method: "GET", + path: joinPaths(userBasePath, userId, "billing", "subscription") + }); + } +}; + +// src/api/request.ts +var import_error2 = require("@clerk/shared/error"); + +// ../../node_modules/.pnpm/map-obj@5.0.2/node_modules/map-obj/index.js +var isObject = (value) => typeof value === "object" && value !== null; +var isObjectCustom = (value) => isObject(value) && !(value instanceof RegExp) && !(value instanceof Error) && !(value instanceof Date) && !(globalThis.Blob && value instanceof globalThis.Blob); +var mapObjectSkip = Symbol("mapObjectSkip"); +var _mapObject = (object, mapper, options, isSeen = /* @__PURE__ */ new WeakMap()) => { + options = { + deep: false, + target: {}, + ...options + }; + if (isSeen.has(object)) { + return isSeen.get(object); + } + isSeen.set(object, options.target); + const { target } = options; + delete options.target; + const mapArray = (array) => array.map((element) => isObjectCustom(element) ? _mapObject(element, mapper, options, isSeen) : element); + if (Array.isArray(object)) { + return mapArray(object); + } + for (const [key, value] of Object.entries(object)) { + const mapResult = mapper(key, value, object); + if (mapResult === mapObjectSkip) { + continue; + } + let [newKey, newValue, { shouldRecurse = true } = {}] = mapResult; + if (newKey === "__proto__") { + continue; + } + if (options.deep && shouldRecurse && isObjectCustom(newValue)) { + newValue = Array.isArray(newValue) ? mapArray(newValue) : _mapObject(newValue, mapper, options, isSeen); + } + target[newKey] = newValue; + } + return target; +}; +function mapObject(object, mapper, options) { + if (!isObject(object)) { + throw new TypeError(`Expected an object, got \`${object}\` (${typeof object})`); + } + if (Array.isArray(object)) { + throw new TypeError("Expected an object, got an array"); + } + return _mapObject(object, mapper, options); +} + +// ../../node_modules/.pnpm/change-case@5.4.4/node_modules/change-case/dist/index.js +var SPLIT_LOWER_UPPER_RE = /([\p{Ll}\d])(\p{Lu})/gu; +var SPLIT_UPPER_UPPER_RE = /(\p{Lu})([\p{Lu}][\p{Ll}])/gu; +var SPLIT_SEPARATE_NUMBER_RE = /(\d)\p{Ll}|(\p{L})\d/u; +var DEFAULT_STRIP_REGEXP = /[^\p{L}\d]+/giu; +var SPLIT_REPLACE_VALUE = "$1\0$2"; +var DEFAULT_PREFIX_SUFFIX_CHARACTERS = ""; +function split(value) { + let result = value.trim(); + result = result.replace(SPLIT_LOWER_UPPER_RE, SPLIT_REPLACE_VALUE).replace(SPLIT_UPPER_UPPER_RE, SPLIT_REPLACE_VALUE); + result = result.replace(DEFAULT_STRIP_REGEXP, "\0"); + let start = 0; + let end = result.length; + while (result.charAt(start) === "\0") + start++; + if (start === end) + return []; + while (result.charAt(end - 1) === "\0") + end--; + return result.slice(start, end).split(/\0/g); +} +function splitSeparateNumbers(value) { + const words = split(value); + for (let i = 0; i < words.length; i++) { + const word = words[i]; + const match2 = SPLIT_SEPARATE_NUMBER_RE.exec(word); + if (match2) { + const offset = match2.index + (match2[1] ?? match2[2]).length; + words.splice(i, 1, word.slice(0, offset), word.slice(offset)); + } + } + return words; +} +function noCase(input, options) { + const [prefix, words, suffix] = splitPrefixSuffix(input, options); + return prefix + words.map(lowerFactory(options?.locale)).join(options?.delimiter ?? " ") + suffix; +} +function snakeCase(input, options) { + return noCase(input, { delimiter: "_", ...options }); +} +function lowerFactory(locale) { + return locale === false ? (input) => input.toLowerCase() : (input) => input.toLocaleLowerCase(locale); +} +function splitPrefixSuffix(input, options = {}) { + const splitFn = options.split ?? (options.separateNumbers ? splitSeparateNumbers : split); + const prefixCharacters = options.prefixCharacters ?? DEFAULT_PREFIX_SUFFIX_CHARACTERS; + const suffixCharacters = options.suffixCharacters ?? DEFAULT_PREFIX_SUFFIX_CHARACTERS; + let prefixIndex = 0; + let suffixIndex = input.length; + while (prefixIndex < input.length) { + const char = input.charAt(prefixIndex); + if (!prefixCharacters.includes(char)) + break; + prefixIndex++; + } + while (suffixIndex > prefixIndex) { + const index = suffixIndex - 1; + const char = input.charAt(index); + if (!suffixCharacters.includes(char)) + break; + suffixIndex = index; + } + return [ + input.slice(0, prefixIndex), + splitFn(input.slice(prefixIndex, suffixIndex)), + input.slice(suffixIndex) + ]; +} + +// ../../node_modules/.pnpm/snakecase-keys@9.0.2/node_modules/snakecase-keys/index.js +var PlainObjectConstructor = {}.constructor; +function snakecaseKeys(obj, options) { + if (Array.isArray(obj)) { + if (obj.some((item) => item.constructor !== PlainObjectConstructor)) { + throw new Error("obj must be array of plain objects"); + } + options = { deep: true, exclude: [], parsingOptions: {}, ...options }; + const convertCase2 = options.snakeCase || ((key) => snakeCase(key, options.parsingOptions)); + return obj.map((item) => { + return mapObject(item, (key, val) => { + return [ + matches(options.exclude, key) ? key : convertCase2(key), + val, + mapperOptions(key, val, options) + ]; + }, options); + }); + } else { + if (obj.constructor !== PlainObjectConstructor) { + throw new Error("obj must be an plain object"); + } + } + options = { deep: true, exclude: [], parsingOptions: {}, ...options }; + const convertCase = options.snakeCase || ((key) => snakeCase(key, options.parsingOptions)); + return mapObject(obj, (key, val) => { + return [ + matches(options.exclude, key) ? key : convertCase(key), + val, + mapperOptions(key, val, options) + ]; + }, options); +} +function matches(patterns, value) { + return patterns.some((pattern) => { + return typeof pattern === "string" ? pattern === value : pattern.test(value); + }); +} +function mapperOptions(key, val, options) { + return options.shouldRecurse ? { shouldRecurse: options.shouldRecurse(key, val) } : void 0; +} +var snakecase_keys_default = snakecaseKeys; + +// src/constants.ts +var API_URL = "https://api.clerk.com"; +var API_VERSION = "v1"; +var USER_AGENT = `${"@clerk/backend"}@${"2.15.0"}`; +var MAX_CACHE_LAST_UPDATED_AT_SECONDS = 5 * 60; +var SUPPORTED_BAPI_VERSION = "2025-04-10"; +var Attributes = { + AuthToken: "__clerkAuthToken", + AuthSignature: "__clerkAuthSignature", + AuthStatus: "__clerkAuthStatus", + AuthReason: "__clerkAuthReason", + AuthMessage: "__clerkAuthMessage", + ClerkUrl: "__clerkUrl" +}; +var Cookies = { + Session: "__session", + Refresh: "__refresh", + ClientUat: "__client_uat", + Handshake: "__clerk_handshake", + DevBrowser: "__clerk_db_jwt", + RedirectCount: "__clerk_redirect_count", + HandshakeNonce: "__clerk_handshake_nonce" +}; +var QueryParameters = { + ClerkSynced: "__clerk_synced", + SuffixedCookies: "suffixed_cookies", + ClerkRedirectUrl: "__clerk_redirect_url", + // use the reference to Cookies to indicate that it's the same value + DevBrowser: Cookies.DevBrowser, + Handshake: Cookies.Handshake, + HandshakeHelp: "__clerk_help", + LegacyDevBrowser: "__dev_session", + HandshakeReason: "__clerk_hs_reason", + HandshakeNonce: Cookies.HandshakeNonce, + HandshakeFormat: "format" +}; +var Headers2 = { + Accept: "accept", + AuthMessage: "x-clerk-auth-message", + Authorization: "authorization", + AuthReason: "x-clerk-auth-reason", + AuthSignature: "x-clerk-auth-signature", + AuthStatus: "x-clerk-auth-status", + AuthToken: "x-clerk-auth-token", + CacheControl: "cache-control", + ClerkRedirectTo: "x-clerk-redirect-to", + ClerkRequestData: "x-clerk-request-data", + ClerkUrl: "x-clerk-clerk-url", + CloudFrontForwardedProto: "cloudfront-forwarded-proto", + ContentType: "content-type", + ContentSecurityPolicy: "content-security-policy", + ContentSecurityPolicyReportOnly: "content-security-policy-report-only", + EnableDebug: "x-clerk-debug", + ForwardedHost: "x-forwarded-host", + ForwardedPort: "x-forwarded-port", + ForwardedProto: "x-forwarded-proto", + Host: "host", + Location: "location", + Nonce: "x-nonce", + Origin: "origin", + Referrer: "referer", + SecFetchDest: "sec-fetch-dest", + SecFetchSite: "sec-fetch-site", + UserAgent: "user-agent", + ReportingEndpoints: "reporting-endpoints" +}; +var ContentTypes = { + Json: "application/json" +}; +var constants = { + Attributes, + Cookies, + Headers: Headers2, + ContentTypes, + QueryParameters +}; + +// src/util/optionsAssertions.ts +function assertValidSecretKey(val) { + if (!val || typeof val !== "string") { + throw Error("Missing Clerk Secret Key. Go to https://dashboard.clerk.com and get your key for your instance."); + } +} +function assertValidPublishableKey(val) { + (0, import_keys.parsePublishableKey)(val, { fatal: true }); +} + +// src/api/resources/AccountlessApplication.ts +var AccountlessApplication = class _AccountlessApplication { + constructor(publishableKey, secretKey, claimUrl, apiKeysUrl) { + this.publishableKey = publishableKey; + this.secretKey = secretKey; + this.claimUrl = claimUrl; + this.apiKeysUrl = apiKeysUrl; + } + static fromJSON(data) { + return new _AccountlessApplication(data.publishable_key, data.secret_key, data.claim_url, data.api_keys_url); + } +}; + +// src/api/resources/ActorToken.ts +var ActorToken = class _ActorToken { + constructor(id, status, userId, actor, token, url, createdAt, updatedAt) { + this.id = id; + this.status = status; + this.userId = userId; + this.actor = actor; + this.token = token; + this.url = url; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + } + static fromJSON(data) { + return new _ActorToken( + data.id, + data.status, + data.user_id, + data.actor, + data.token, + data.url, + data.created_at, + data.updated_at + ); + } +}; + +// src/api/resources/AllowlistIdentifier.ts +var AllowlistIdentifier = class _AllowlistIdentifier { + constructor(id, identifier, identifierType, createdAt, updatedAt, instanceId, invitationId) { + this.id = id; + this.identifier = identifier; + this.identifierType = identifierType; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + this.instanceId = instanceId; + this.invitationId = invitationId; + } + static fromJSON(data) { + return new _AllowlistIdentifier( + data.id, + data.identifier, + data.identifier_type, + data.created_at, + data.updated_at, + data.instance_id, + data.invitation_id + ); + } +}; + +// src/api/resources/APIKey.ts +var APIKey = class _APIKey { + constructor(id, type, name, subject, scopes, claims, revoked, revocationReason, expired, expiration, createdBy, description, lastUsedAt, createdAt, updatedAt, secret) { + this.id = id; + this.type = type; + this.name = name; + this.subject = subject; + this.scopes = scopes; + this.claims = claims; + this.revoked = revoked; + this.revocationReason = revocationReason; + this.expired = expired; + this.expiration = expiration; + this.createdBy = createdBy; + this.description = description; + this.lastUsedAt = lastUsedAt; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + this.secret = secret; + } + static fromJSON(data) { + return new _APIKey( + data.id, + data.type, + data.name, + data.subject, + data.scopes, + data.claims, + data.revoked, + data.revocation_reason, + data.expired, + data.expiration, + data.created_by, + data.description, + data.last_used_at, + data.created_at, + data.updated_at, + data.secret + ); + } +}; + +// src/api/resources/BlocklistIdentifier.ts +var BlocklistIdentifier = class _BlocklistIdentifier { + constructor(id, identifier, identifierType, createdAt, updatedAt, instanceId) { + this.id = id; + this.identifier = identifier; + this.identifierType = identifierType; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + this.instanceId = instanceId; + } + static fromJSON(data) { + return new _BlocklistIdentifier( + data.id, + data.identifier, + data.identifier_type, + data.created_at, + data.updated_at, + data.instance_id + ); + } +}; + +// src/api/resources/Session.ts +var SessionActivity = class _SessionActivity { + constructor(id, isMobile, ipAddress, city, country, browserVersion, browserName, deviceType) { + this.id = id; + this.isMobile = isMobile; + this.ipAddress = ipAddress; + this.city = city; + this.country = country; + this.browserVersion = browserVersion; + this.browserName = browserName; + this.deviceType = deviceType; + } + static fromJSON(data) { + return new _SessionActivity( + data.id, + data.is_mobile, + data.ip_address, + data.city, + data.country, + data.browser_version, + data.browser_name, + data.device_type + ); + } +}; +var Session = class _Session { + constructor(id, clientId, userId, status, lastActiveAt, expireAt, abandonAt, createdAt, updatedAt, lastActiveOrganizationId, latestActivity, actor = null) { + this.id = id; + this.clientId = clientId; + this.userId = userId; + this.status = status; + this.lastActiveAt = lastActiveAt; + this.expireAt = expireAt; + this.abandonAt = abandonAt; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + this.lastActiveOrganizationId = lastActiveOrganizationId; + this.latestActivity = latestActivity; + this.actor = actor; + } + static fromJSON(data) { + return new _Session( + data.id, + data.client_id, + data.user_id, + data.status, + data.last_active_at, + data.expire_at, + data.abandon_at, + data.created_at, + data.updated_at, + data.last_active_organization_id, + data.latest_activity && SessionActivity.fromJSON(data.latest_activity), + data.actor + ); + } +}; + +// src/api/resources/Client.ts +var Client = class _Client { + constructor(id, sessionIds, sessions, signInId, signUpId, lastActiveSessionId, lastAuthenticationStrategy, createdAt, updatedAt) { + this.id = id; + this.sessionIds = sessionIds; + this.sessions = sessions; + this.signInId = signInId; + this.signUpId = signUpId; + this.lastActiveSessionId = lastActiveSessionId; + this.lastAuthenticationStrategy = lastAuthenticationStrategy; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + } + static fromJSON(data) { + return new _Client( + data.id, + data.session_ids, + data.sessions.map((x) => Session.fromJSON(x)), + data.sign_in_id, + data.sign_up_id, + data.last_active_session_id, + data.last_authentication_strategy, + data.created_at, + data.updated_at + ); + } +}; + +// src/api/resources/CnameTarget.ts +var CnameTarget = class _CnameTarget { + constructor(host, value, required) { + this.host = host; + this.value = value; + this.required = required; + } + static fromJSON(data) { + return new _CnameTarget(data.host, data.value, data.required); + } +}; + +// src/api/resources/Cookies.ts +var Cookies2 = class _Cookies { + constructor(cookies) { + this.cookies = cookies; + } + static fromJSON(data) { + return new _Cookies(data.cookies); + } +}; + +// src/api/resources/DeletedObject.ts +var DeletedObject = class _DeletedObject { + constructor(object, id, slug, deleted) { + this.object = object; + this.id = id; + this.slug = slug; + this.deleted = deleted; + } + static fromJSON(data) { + return new _DeletedObject(data.object, data.id || null, data.slug || null, data.deleted); + } +}; + +// src/api/resources/Domain.ts +var Domain = class _Domain { + constructor(id, name, isSatellite, frontendApiUrl, developmentOrigin, cnameTargets, accountsPortalUrl, proxyUrl) { + this.id = id; + this.name = name; + this.isSatellite = isSatellite; + this.frontendApiUrl = frontendApiUrl; + this.developmentOrigin = developmentOrigin; + this.cnameTargets = cnameTargets; + this.accountsPortalUrl = accountsPortalUrl; + this.proxyUrl = proxyUrl; + } + static fromJSON(data) { + return new _Domain( + data.id, + data.name, + data.is_satellite, + data.frontend_api_url, + data.development_origin, + data.cname_targets && data.cname_targets.map((x) => CnameTarget.fromJSON(x)), + data.accounts_portal_url, + data.proxy_url + ); + } +}; + +// src/api/resources/Email.ts +var Email = class _Email { + constructor(id, fromEmailName, emailAddressId, toEmailAddress, subject, body, bodyPlain, status, slug, data, deliveredByClerk) { + this.id = id; + this.fromEmailName = fromEmailName; + this.emailAddressId = emailAddressId; + this.toEmailAddress = toEmailAddress; + this.subject = subject; + this.body = body; + this.bodyPlain = bodyPlain; + this.status = status; + this.slug = slug; + this.data = data; + this.deliveredByClerk = deliveredByClerk; + } + static fromJSON(data) { + return new _Email( + data.id, + data.from_email_name, + data.email_address_id, + data.to_email_address, + data.subject, + data.body, + data.body_plain, + data.status, + data.slug, + data.data, + data.delivered_by_clerk + ); + } +}; + +// src/api/resources/IdentificationLink.ts +var IdentificationLink = class _IdentificationLink { + constructor(id, type) { + this.id = id; + this.type = type; + } + static fromJSON(data) { + return new _IdentificationLink(data.id, data.type); + } +}; + +// src/api/resources/Verification.ts +var Verification = class _Verification { + constructor(status, strategy, externalVerificationRedirectURL = null, attempts = null, expireAt = null, nonce = null, message = null) { + this.status = status; + this.strategy = strategy; + this.externalVerificationRedirectURL = externalVerificationRedirectURL; + this.attempts = attempts; + this.expireAt = expireAt; + this.nonce = nonce; + this.message = message; + } + static fromJSON(data) { + return new _Verification( + data.status, + data.strategy, + data.external_verification_redirect_url ? new URL(data.external_verification_redirect_url) : null, + data.attempts, + data.expire_at, + data.nonce + ); + } +}; + +// src/api/resources/EmailAddress.ts +var EmailAddress = class _EmailAddress { + constructor(id, emailAddress, verification, linkedTo) { + this.id = id; + this.emailAddress = emailAddress; + this.verification = verification; + this.linkedTo = linkedTo; + } + static fromJSON(data) { + return new _EmailAddress( + data.id, + data.email_address, + data.verification && Verification.fromJSON(data.verification), + data.linked_to.map((link) => IdentificationLink.fromJSON(link)) + ); + } +}; + +// src/api/resources/ExternalAccount.ts +var ExternalAccount = class _ExternalAccount { + constructor(id, provider, identificationId, externalId, approvedScopes, emailAddress, firstName, lastName, imageUrl, username, phoneNumber, publicMetadata = {}, label, verification) { + this.id = id; + this.provider = provider; + this.identificationId = identificationId; + this.externalId = externalId; + this.approvedScopes = approvedScopes; + this.emailAddress = emailAddress; + this.firstName = firstName; + this.lastName = lastName; + this.imageUrl = imageUrl; + this.username = username; + this.phoneNumber = phoneNumber; + this.publicMetadata = publicMetadata; + this.label = label; + this.verification = verification; + } + static fromJSON(data) { + return new _ExternalAccount( + data.id, + data.provider, + data.identification_id, + data.provider_user_id, + data.approved_scopes, + data.email_address, + data.first_name, + data.last_name, + data.image_url || "", + data.username, + data.phone_number, + data.public_metadata, + data.label, + data.verification && Verification.fromJSON(data.verification) + ); + } +}; + +// src/api/resources/IdPOAuthAccessToken.ts +var IdPOAuthAccessToken = class _IdPOAuthAccessToken { + constructor(id, clientId, type, subject, scopes, revoked, revocationReason, expired, expiration, createdAt, updatedAt) { + this.id = id; + this.clientId = clientId; + this.type = type; + this.subject = subject; + this.scopes = scopes; + this.revoked = revoked; + this.revocationReason = revocationReason; + this.expired = expired; + this.expiration = expiration; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + } + static fromJSON(data) { + return new _IdPOAuthAccessToken( + data.id, + data.client_id, + data.type, + data.subject, + data.scopes, + data.revoked, + data.revocation_reason, + data.expired, + data.expiration, + data.created_at, + data.updated_at + ); + } +}; + +// src/api/resources/Instance.ts +var Instance = class _Instance { + constructor(id, environmentType, allowedOrigins) { + this.id = id; + this.environmentType = environmentType; + this.allowedOrigins = allowedOrigins; + } + static fromJSON(data) { + return new _Instance(data.id, data.environment_type, data.allowed_origins); + } +}; + +// src/api/resources/InstanceRestrictions.ts +var InstanceRestrictions = class _InstanceRestrictions { + constructor(allowlist, blocklist, blockEmailSubaddresses, blockDisposableEmailDomains, ignoreDotsForGmailAddresses) { + this.allowlist = allowlist; + this.blocklist = blocklist; + this.blockEmailSubaddresses = blockEmailSubaddresses; + this.blockDisposableEmailDomains = blockDisposableEmailDomains; + this.ignoreDotsForGmailAddresses = ignoreDotsForGmailAddresses; + } + static fromJSON(data) { + return new _InstanceRestrictions( + data.allowlist, + data.blocklist, + data.block_email_subaddresses, + data.block_disposable_email_domains, + data.ignore_dots_for_gmail_addresses + ); + } +}; + +// src/api/resources/InstanceSettings.ts +var InstanceSettings = class _InstanceSettings { + constructor(id, restrictedToAllowlist, fromEmailAddress, progressiveSignUp, enhancedEmailDeliverability) { + this.id = id; + this.restrictedToAllowlist = restrictedToAllowlist; + this.fromEmailAddress = fromEmailAddress; + this.progressiveSignUp = progressiveSignUp; + this.enhancedEmailDeliverability = enhancedEmailDeliverability; + } + static fromJSON(data) { + return new _InstanceSettings( + data.id, + data.restricted_to_allowlist, + data.from_email_address, + data.progressive_sign_up, + data.enhanced_email_deliverability + ); + } +}; + +// src/api/resources/Invitation.ts +var Invitation = class _Invitation { + constructor(id, emailAddress, publicMetadata, createdAt, updatedAt, status, url, revoked) { + this.id = id; + this.emailAddress = emailAddress; + this.publicMetadata = publicMetadata; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + this.status = status; + this.url = url; + this.revoked = revoked; + this._raw = null; + } + get raw() { + return this._raw; + } + static fromJSON(data) { + const res = new _Invitation( + data.id, + data.email_address, + data.public_metadata, + data.created_at, + data.updated_at, + data.status, + data.url, + data.revoked + ); + res._raw = data; + return res; + } +}; + +// src/api/resources/JSON.ts +var ObjectType = { + AccountlessApplication: "accountless_application", + ActorToken: "actor_token", + AllowlistIdentifier: "allowlist_identifier", + ApiKey: "api_key", + BlocklistIdentifier: "blocklist_identifier", + Client: "client", + Cookies: "cookies", + Domain: "domain", + Email: "email", + EmailAddress: "email_address", + ExternalAccount: "external_account", + FacebookAccount: "facebook_account", + GoogleAccount: "google_account", + Instance: "instance", + InstanceRestrictions: "instance_restrictions", + InstanceSettings: "instance_settings", + Invitation: "invitation", + Machine: "machine", + MachineScope: "machine_scope", + MachineSecretKey: "machine_secret_key", + M2MToken: "machine_to_machine_token", + JwtTemplate: "jwt_template", + OauthAccessToken: "oauth_access_token", + IdpOAuthAccessToken: "clerk_idp_oauth_access_token", + OAuthApplication: "oauth_application", + Organization: "organization", + OrganizationDomain: "organization_domain", + OrganizationInvitation: "organization_invitation", + OrganizationMembership: "organization_membership", + OrganizationSettings: "organization_settings", + PhoneNumber: "phone_number", + ProxyCheck: "proxy_check", + RedirectUrl: "redirect_url", + SamlAccount: "saml_account", + SamlConnection: "saml_connection", + Session: "session", + SignInAttempt: "sign_in_attempt", + SignInToken: "sign_in_token", + SignUpAttempt: "sign_up_attempt", + SmsMessage: "sms_message", + User: "user", + WaitlistEntry: "waitlist_entry", + Web3Wallet: "web3_wallet", + Token: "token", + TotalCount: "total_count", + TestingToken: "testing_token", + Role: "role", + Permission: "permission", + BillingPayer: "commerce_payer", + BillingPaymentAttempt: "commerce_payment_attempt", + BillingSubscription: "commerce_subscription", + BillingSubscriptionItem: "commerce_subscription_item", + BillingPlan: "commerce_plan", + Feature: "feature" +}; + +// src/api/resources/Machine.ts +var Machine = class _Machine { + constructor(id, name, instanceId, createdAt, updatedAt, scopedMachines, defaultTokenTtl, secretKey) { + this.id = id; + this.name = name; + this.instanceId = instanceId; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + this.scopedMachines = scopedMachines; + this.defaultTokenTtl = defaultTokenTtl; + this.secretKey = secretKey; + } + static fromJSON(data) { + return new _Machine( + data.id, + data.name, + data.instance_id, + data.created_at, + data.updated_at, + data.scoped_machines.map( + (m) => new _Machine( + m.id, + m.name, + m.instance_id, + m.created_at, + m.updated_at, + [], + // Nested machines don't have scoped_machines + m.default_token_ttl + ) + ), + data.default_token_ttl, + data.secret_key + ); + } +}; + +// src/api/resources/MachineScope.ts +var MachineScope = class _MachineScope { + constructor(fromMachineId, toMachineId, createdAt, deleted) { + this.fromMachineId = fromMachineId; + this.toMachineId = toMachineId; + this.createdAt = createdAt; + this.deleted = deleted; + } + static fromJSON(data) { + return new _MachineScope(data.from_machine_id, data.to_machine_id, data.created_at, data.deleted); + } +}; + +// src/api/resources/MachineSecretKey.ts +var MachineSecretKey = class _MachineSecretKey { + constructor(secret) { + this.secret = secret; + } + static fromJSON(data) { + return new _MachineSecretKey(data.secret); + } +}; + +// src/api/resources/M2MToken.ts +var M2MToken = class _M2MToken { + constructor(id, subject, scopes, claims, revoked, revocationReason, expired, expiration, createdAt, updatedAt, token) { + this.id = id; + this.subject = subject; + this.scopes = scopes; + this.claims = claims; + this.revoked = revoked; + this.revocationReason = revocationReason; + this.expired = expired; + this.expiration = expiration; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + this.token = token; + } + static fromJSON(data) { + return new _M2MToken( + data.id, + data.subject, + data.scopes, + data.claims, + data.revoked, + data.revocation_reason, + data.expired, + data.expiration, + data.created_at, + data.updated_at, + data.token + ); + } +}; + +// src/api/resources/JwtTemplate.ts +var JwtTemplate = class _JwtTemplate { + constructor(id, name, claims, lifetime, allowedClockSkew, customSigningKey, signingAlgorithm, createdAt, updatedAt) { + this.id = id; + this.name = name; + this.claims = claims; + this.lifetime = lifetime; + this.allowedClockSkew = allowedClockSkew; + this.customSigningKey = customSigningKey; + this.signingAlgorithm = signingAlgorithm; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + } + static fromJSON(data) { + return new _JwtTemplate( + data.id, + data.name, + data.claims, + data.lifetime, + data.allowed_clock_skew, + data.custom_signing_key, + data.signing_algorithm, + data.created_at, + data.updated_at + ); + } +}; + +// src/api/resources/OauthAccessToken.ts +var OauthAccessToken = class _OauthAccessToken { + constructor(externalAccountId, provider, token, publicMetadata = {}, label, scopes, tokenSecret, expiresAt) { + this.externalAccountId = externalAccountId; + this.provider = provider; + this.token = token; + this.publicMetadata = publicMetadata; + this.label = label; + this.scopes = scopes; + this.tokenSecret = tokenSecret; + this.expiresAt = expiresAt; + } + static fromJSON(data) { + return new _OauthAccessToken( + data.external_account_id, + data.provider, + data.token, + data.public_metadata, + data.label || "", + data.scopes, + data.token_secret, + data.expires_at + ); + } +}; + +// src/api/resources/OAuthApplication.ts +var OAuthApplication = class _OAuthApplication { + constructor(id, instanceId, name, clientId, clientUri, clientImageUrl, dynamicallyRegistered, consentScreenEnabled, pkceRequired, isPublic, scopes, redirectUris, authorizeUrl, tokenFetchUrl, userInfoUrl, discoveryUrl, tokenIntrospectionUrl, createdAt, updatedAt, clientSecret) { + this.id = id; + this.instanceId = instanceId; + this.name = name; + this.clientId = clientId; + this.clientUri = clientUri; + this.clientImageUrl = clientImageUrl; + this.dynamicallyRegistered = dynamicallyRegistered; + this.consentScreenEnabled = consentScreenEnabled; + this.pkceRequired = pkceRequired; + this.isPublic = isPublic; + this.scopes = scopes; + this.redirectUris = redirectUris; + this.authorizeUrl = authorizeUrl; + this.tokenFetchUrl = tokenFetchUrl; + this.userInfoUrl = userInfoUrl; + this.discoveryUrl = discoveryUrl; + this.tokenIntrospectionUrl = tokenIntrospectionUrl; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + this.clientSecret = clientSecret; + } + static fromJSON(data) { + return new _OAuthApplication( + data.id, + data.instance_id, + data.name, + data.client_id, + data.client_uri, + data.client_image_url, + data.dynamically_registered, + data.consent_screen_enabled, + data.pkce_required, + data.public, + data.scopes, + data.redirect_uris, + data.authorize_url, + data.token_fetch_url, + data.user_info_url, + data.discovery_url, + data.token_introspection_url, + data.created_at, + data.updated_at, + data.client_secret + ); + } +}; + +// src/api/resources/Organization.ts +var Organization = class _Organization { + constructor(id, name, slug, imageUrl, hasImage, createdAt, updatedAt, publicMetadata = {}, privateMetadata = {}, maxAllowedMemberships, adminDeleteEnabled, membersCount, createdBy) { + this.id = id; + this.name = name; + this.slug = slug; + this.imageUrl = imageUrl; + this.hasImage = hasImage; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + this.publicMetadata = publicMetadata; + this.privateMetadata = privateMetadata; + this.maxAllowedMemberships = maxAllowedMemberships; + this.adminDeleteEnabled = adminDeleteEnabled; + this.membersCount = membersCount; + this.createdBy = createdBy; + this._raw = null; + } + get raw() { + return this._raw; + } + static fromJSON(data) { + const res = new _Organization( + data.id, + data.name, + data.slug, + data.image_url || "", + data.has_image, + data.created_at, + data.updated_at, + data.public_metadata, + data.private_metadata, + data.max_allowed_memberships, + data.admin_delete_enabled, + data.members_count, + data.created_by + ); + res._raw = data; + return res; + } +}; + +// src/api/resources/OrganizationInvitation.ts +var OrganizationInvitation = class _OrganizationInvitation { + constructor(id, emailAddress, role, roleName, organizationId, createdAt, updatedAt, expiresAt, url, status, publicMetadata = {}, privateMetadata = {}, publicOrganizationData) { + this.id = id; + this.emailAddress = emailAddress; + this.role = role; + this.roleName = roleName; + this.organizationId = organizationId; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + this.expiresAt = expiresAt; + this.url = url; + this.status = status; + this.publicMetadata = publicMetadata; + this.privateMetadata = privateMetadata; + this.publicOrganizationData = publicOrganizationData; + this._raw = null; + } + get raw() { + return this._raw; + } + static fromJSON(data) { + const res = new _OrganizationInvitation( + data.id, + data.email_address, + data.role, + data.role_name, + data.organization_id, + data.created_at, + data.updated_at, + data.expires_at, + data.url, + data.status, + data.public_metadata, + data.private_metadata, + data.public_organization_data + ); + res._raw = data; + return res; + } +}; + +// src/api/resources/OrganizationMembership.ts +var OrganizationMembership = class _OrganizationMembership { + constructor(id, role, permissions, publicMetadata = {}, privateMetadata = {}, createdAt, updatedAt, organization, publicUserData) { + this.id = id; + this.role = role; + this.permissions = permissions; + this.publicMetadata = publicMetadata; + this.privateMetadata = privateMetadata; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + this.organization = organization; + this.publicUserData = publicUserData; + this._raw = null; + } + get raw() { + return this._raw; + } + static fromJSON(data) { + const res = new _OrganizationMembership( + data.id, + data.role, + data.permissions, + data.public_metadata, + data.private_metadata, + data.created_at, + data.updated_at, + Organization.fromJSON(data.organization), + OrganizationMembershipPublicUserData.fromJSON(data.public_user_data) + ); + res._raw = data; + return res; + } +}; +var OrganizationMembershipPublicUserData = class _OrganizationMembershipPublicUserData { + constructor(identifier, firstName, lastName, imageUrl, hasImage, userId) { + this.identifier = identifier; + this.firstName = firstName; + this.lastName = lastName; + this.imageUrl = imageUrl; + this.hasImage = hasImage; + this.userId = userId; + } + static fromJSON(data) { + return new _OrganizationMembershipPublicUserData( + data.identifier, + data.first_name, + data.last_name, + data.image_url, + data.has_image, + data.user_id + ); + } +}; + +// src/api/resources/OrganizationSettings.ts +var OrganizationSettings = class _OrganizationSettings { + constructor(enabled, maxAllowedMemberships, maxAllowedRoles, maxAllowedPermissions, creatorRole, adminDeleteEnabled, domainsEnabled, domainsEnrollmentModes, domainsDefaultRole) { + this.enabled = enabled; + this.maxAllowedMemberships = maxAllowedMemberships; + this.maxAllowedRoles = maxAllowedRoles; + this.maxAllowedPermissions = maxAllowedPermissions; + this.creatorRole = creatorRole; + this.adminDeleteEnabled = adminDeleteEnabled; + this.domainsEnabled = domainsEnabled; + this.domainsEnrollmentModes = domainsEnrollmentModes; + this.domainsDefaultRole = domainsDefaultRole; + } + static fromJSON(data) { + return new _OrganizationSettings( + data.enabled, + data.max_allowed_memberships, + data.max_allowed_roles, + data.max_allowed_permissions, + data.creator_role, + data.admin_delete_enabled, + data.domains_enabled, + data.domains_enrollment_modes, + data.domains_default_role + ); + } +}; + +// src/api/resources/PhoneNumber.ts +var PhoneNumber = class _PhoneNumber { + constructor(id, phoneNumber, reservedForSecondFactor, defaultSecondFactor, verification, linkedTo) { + this.id = id; + this.phoneNumber = phoneNumber; + this.reservedForSecondFactor = reservedForSecondFactor; + this.defaultSecondFactor = defaultSecondFactor; + this.verification = verification; + this.linkedTo = linkedTo; + } + static fromJSON(data) { + return new _PhoneNumber( + data.id, + data.phone_number, + data.reserved_for_second_factor, + data.default_second_factor, + data.verification && Verification.fromJSON(data.verification), + data.linked_to.map((link) => IdentificationLink.fromJSON(link)) + ); + } +}; + +// src/api/resources/ProxyCheck.ts +var ProxyCheck = class _ProxyCheck { + constructor(id, domainId, lastRunAt, proxyUrl, successful, createdAt, updatedAt) { + this.id = id; + this.domainId = domainId; + this.lastRunAt = lastRunAt; + this.proxyUrl = proxyUrl; + this.successful = successful; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + } + static fromJSON(data) { + return new _ProxyCheck( + data.id, + data.domain_id, + data.last_run_at, + data.proxy_url, + data.successful, + data.created_at, + data.updated_at + ); + } +}; + +// src/api/resources/RedirectUrl.ts +var RedirectUrl = class _RedirectUrl { + constructor(id, url, createdAt, updatedAt) { + this.id = id; + this.url = url; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + } + static fromJSON(data) { + return new _RedirectUrl(data.id, data.url, data.created_at, data.updated_at); + } +}; + +// src/api/resources/SamlConnection.ts +var SamlConnection = class _SamlConnection { + constructor(id, name, domain, organizationId, idpEntityId, idpSsoUrl, idpCertificate, idpMetadataUrl, idpMetadata, acsUrl, spEntityId, spMetadataUrl, active, provider, userCount, syncUserAttributes, allowSubdomains, allowIdpInitiated, createdAt, updatedAt, attributeMapping) { + this.id = id; + this.name = name; + this.domain = domain; + this.organizationId = organizationId; + this.idpEntityId = idpEntityId; + this.idpSsoUrl = idpSsoUrl; + this.idpCertificate = idpCertificate; + this.idpMetadataUrl = idpMetadataUrl; + this.idpMetadata = idpMetadata; + this.acsUrl = acsUrl; + this.spEntityId = spEntityId; + this.spMetadataUrl = spMetadataUrl; + this.active = active; + this.provider = provider; + this.userCount = userCount; + this.syncUserAttributes = syncUserAttributes; + this.allowSubdomains = allowSubdomains; + this.allowIdpInitiated = allowIdpInitiated; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + this.attributeMapping = attributeMapping; + } + static fromJSON(data) { + return new _SamlConnection( + data.id, + data.name, + data.domain, + data.organization_id, + data.idp_entity_id, + data.idp_sso_url, + data.idp_certificate, + data.idp_metadata_url, + data.idp_metadata, + data.acs_url, + data.sp_entity_id, + data.sp_metadata_url, + data.active, + data.provider, + data.user_count, + data.sync_user_attributes, + data.allow_subdomains, + data.allow_idp_initiated, + data.created_at, + data.updated_at, + data.attribute_mapping && AttributeMapping.fromJSON(data.attribute_mapping) + ); + } +}; +var SamlAccountConnection = class _SamlAccountConnection { + constructor(id, name, domain, active, provider, syncUserAttributes, allowSubdomains, allowIdpInitiated, createdAt, updatedAt) { + this.id = id; + this.name = name; + this.domain = domain; + this.active = active; + this.provider = provider; + this.syncUserAttributes = syncUserAttributes; + this.allowSubdomains = allowSubdomains; + this.allowIdpInitiated = allowIdpInitiated; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + } + static fromJSON(data) { + return new _SamlAccountConnection( + data.id, + data.name, + data.domain, + data.active, + data.provider, + data.sync_user_attributes, + data.allow_subdomains, + data.allow_idp_initiated, + data.created_at, + data.updated_at + ); + } +}; +var AttributeMapping = class _AttributeMapping { + constructor(userId, emailAddress, firstName, lastName) { + this.userId = userId; + this.emailAddress = emailAddress; + this.firstName = firstName; + this.lastName = lastName; + } + static fromJSON(data) { + return new _AttributeMapping(data.user_id, data.email_address, data.first_name, data.last_name); + } +}; + +// src/api/resources/SamlAccount.ts +var SamlAccount = class _SamlAccount { + constructor(id, provider, providerUserId, active, emailAddress, firstName, lastName, verification, samlConnection) { + this.id = id; + this.provider = provider; + this.providerUserId = providerUserId; + this.active = active; + this.emailAddress = emailAddress; + this.firstName = firstName; + this.lastName = lastName; + this.verification = verification; + this.samlConnection = samlConnection; + } + static fromJSON(data) { + return new _SamlAccount( + data.id, + data.provider, + data.provider_user_id, + data.active, + data.email_address, + data.first_name, + data.last_name, + data.verification && Verification.fromJSON(data.verification), + data.saml_connection && SamlAccountConnection.fromJSON(data.saml_connection) + ); + } +}; + +// src/api/resources/SignInTokens.ts +var SignInToken = class _SignInToken { + constructor(id, userId, token, status, url, createdAt, updatedAt) { + this.id = id; + this.userId = userId; + this.token = token; + this.status = status; + this.url = url; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + } + static fromJSON(data) { + return new _SignInToken(data.id, data.user_id, data.token, data.status, data.url, data.created_at, data.updated_at); + } +}; + +// src/api/resources/SignUpAttempt.ts +var SignUpAttemptVerification = class _SignUpAttemptVerification { + constructor(nextAction, supportedStrategies) { + this.nextAction = nextAction; + this.supportedStrategies = supportedStrategies; + } + static fromJSON(data) { + return new _SignUpAttemptVerification(data.next_action, data.supported_strategies); + } +}; +var SignUpAttemptVerifications = class _SignUpAttemptVerifications { + constructor(emailAddress, phoneNumber, web3Wallet, externalAccount) { + this.emailAddress = emailAddress; + this.phoneNumber = phoneNumber; + this.web3Wallet = web3Wallet; + this.externalAccount = externalAccount; + } + static fromJSON(data) { + return new _SignUpAttemptVerifications( + data.email_address && SignUpAttemptVerification.fromJSON(data.email_address), + data.phone_number && SignUpAttemptVerification.fromJSON(data.phone_number), + data.web3_wallet && SignUpAttemptVerification.fromJSON(data.web3_wallet), + data.external_account + ); + } +}; +var SignUpAttempt = class _SignUpAttempt { + constructor(id, status, requiredFields, optionalFields, missingFields, unverifiedFields, verifications, username, emailAddress, phoneNumber, web3Wallet, passwordEnabled, firstName, lastName, customAction, externalId, createdSessionId, createdUserId, abandonAt, legalAcceptedAt, publicMetadata, unsafeMetadata) { + this.id = id; + this.status = status; + this.requiredFields = requiredFields; + this.optionalFields = optionalFields; + this.missingFields = missingFields; + this.unverifiedFields = unverifiedFields; + this.verifications = verifications; + this.username = username; + this.emailAddress = emailAddress; + this.phoneNumber = phoneNumber; + this.web3Wallet = web3Wallet; + this.passwordEnabled = passwordEnabled; + this.firstName = firstName; + this.lastName = lastName; + this.customAction = customAction; + this.externalId = externalId; + this.createdSessionId = createdSessionId; + this.createdUserId = createdUserId; + this.abandonAt = abandonAt; + this.legalAcceptedAt = legalAcceptedAt; + this.publicMetadata = publicMetadata; + this.unsafeMetadata = unsafeMetadata; + } + static fromJSON(data) { + return new _SignUpAttempt( + data.id, + data.status, + data.required_fields, + data.optional_fields, + data.missing_fields, + data.unverified_fields, + data.verifications ? SignUpAttemptVerifications.fromJSON(data.verifications) : null, + data.username, + data.email_address, + data.phone_number, + data.web3_wallet, + data.password_enabled, + data.first_name, + data.last_name, + data.custom_action, + data.external_id, + data.created_session_id, + data.created_user_id, + data.abandon_at, + data.legal_accepted_at, + data.public_metadata, + data.unsafe_metadata + ); + } +}; + +// src/api/resources/SMSMessage.ts +var SMSMessage = class _SMSMessage { + constructor(id, fromPhoneNumber, toPhoneNumber, message, status, phoneNumberId, data) { + this.id = id; + this.fromPhoneNumber = fromPhoneNumber; + this.toPhoneNumber = toPhoneNumber; + this.message = message; + this.status = status; + this.phoneNumberId = phoneNumberId; + this.data = data; + } + static fromJSON(data) { + return new _SMSMessage( + data.id, + data.from_phone_number, + data.to_phone_number, + data.message, + data.status, + data.phone_number_id, + data.data + ); + } +}; + +// src/api/resources/Token.ts +var Token = class _Token { + constructor(jwt) { + this.jwt = jwt; + } + static fromJSON(data) { + return new _Token(data.jwt); + } +}; + +// src/api/resources/Web3Wallet.ts +var Web3Wallet = class _Web3Wallet { + constructor(id, web3Wallet, verification) { + this.id = id; + this.web3Wallet = web3Wallet; + this.verification = verification; + } + static fromJSON(data) { + return new _Web3Wallet(data.id, data.web3_wallet, data.verification && Verification.fromJSON(data.verification)); + } +}; + +// src/api/resources/User.ts +var User = class _User { + constructor(id, passwordEnabled, totpEnabled, backupCodeEnabled, twoFactorEnabled, banned, locked, createdAt, updatedAt, imageUrl, hasImage, primaryEmailAddressId, primaryPhoneNumberId, primaryWeb3WalletId, lastSignInAt, externalId, username, firstName, lastName, publicMetadata = {}, privateMetadata = {}, unsafeMetadata = {}, emailAddresses = [], phoneNumbers = [], web3Wallets = [], externalAccounts = [], samlAccounts = [], lastActiveAt, createOrganizationEnabled, createOrganizationsLimit = null, deleteSelfEnabled, legalAcceptedAt) { + this.id = id; + this.passwordEnabled = passwordEnabled; + this.totpEnabled = totpEnabled; + this.backupCodeEnabled = backupCodeEnabled; + this.twoFactorEnabled = twoFactorEnabled; + this.banned = banned; + this.locked = locked; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + this.imageUrl = imageUrl; + this.hasImage = hasImage; + this.primaryEmailAddressId = primaryEmailAddressId; + this.primaryPhoneNumberId = primaryPhoneNumberId; + this.primaryWeb3WalletId = primaryWeb3WalletId; + this.lastSignInAt = lastSignInAt; + this.externalId = externalId; + this.username = username; + this.firstName = firstName; + this.lastName = lastName; + this.publicMetadata = publicMetadata; + this.privateMetadata = privateMetadata; + this.unsafeMetadata = unsafeMetadata; + this.emailAddresses = emailAddresses; + this.phoneNumbers = phoneNumbers; + this.web3Wallets = web3Wallets; + this.externalAccounts = externalAccounts; + this.samlAccounts = samlAccounts; + this.lastActiveAt = lastActiveAt; + this.createOrganizationEnabled = createOrganizationEnabled; + this.createOrganizationsLimit = createOrganizationsLimit; + this.deleteSelfEnabled = deleteSelfEnabled; + this.legalAcceptedAt = legalAcceptedAt; + this._raw = null; + } + get raw() { + return this._raw; + } + static fromJSON(data) { + const res = new _User( + data.id, + data.password_enabled, + data.totp_enabled, + data.backup_code_enabled, + data.two_factor_enabled, + data.banned, + data.locked, + data.created_at, + data.updated_at, + data.image_url, + data.has_image, + data.primary_email_address_id, + data.primary_phone_number_id, + data.primary_web3_wallet_id, + data.last_sign_in_at, + data.external_id, + data.username, + data.first_name, + data.last_name, + data.public_metadata, + data.private_metadata, + data.unsafe_metadata, + (data.email_addresses || []).map((x) => EmailAddress.fromJSON(x)), + (data.phone_numbers || []).map((x) => PhoneNumber.fromJSON(x)), + (data.web3_wallets || []).map((x) => Web3Wallet.fromJSON(x)), + (data.external_accounts || []).map((x) => ExternalAccount.fromJSON(x)), + (data.saml_accounts || []).map((x) => SamlAccount.fromJSON(x)), + data.last_active_at, + data.create_organization_enabled, + data.create_organizations_limit, + data.delete_self_enabled, + data.legal_accepted_at + ); + res._raw = data; + return res; + } + /** + * The primary email address of the user. + */ + get primaryEmailAddress() { + return this.emailAddresses.find(({ id }) => id === this.primaryEmailAddressId) ?? null; + } + /** + * The primary phone number of the user. + */ + get primaryPhoneNumber() { + return this.phoneNumbers.find(({ id }) => id === this.primaryPhoneNumberId) ?? null; + } + /** + * The primary web3 wallet of the user. + */ + get primaryWeb3Wallet() { + return this.web3Wallets.find(({ id }) => id === this.primaryWeb3WalletId) ?? null; + } + /** + * The full name of the user. + */ + get fullName() { + return [this.firstName, this.lastName].join(" ").trim() || null; + } +}; + +// src/api/resources/WaitlistEntry.ts +var WaitlistEntry = class _WaitlistEntry { + constructor(id, emailAddress, status, invitation, createdAt, updatedAt, isLocked) { + this.id = id; + this.emailAddress = emailAddress; + this.status = status; + this.invitation = invitation; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + this.isLocked = isLocked; + } + static fromJSON(data) { + return new _WaitlistEntry( + data.id, + data.email_address, + data.status, + data.invitation && Invitation.fromJSON(data.invitation), + data.created_at, + data.updated_at, + data.is_locked + ); + } +}; + +// src/api/resources/Feature.ts +var Feature = class _Feature { + constructor(id, name, description, slug, avatarUrl) { + this.id = id; + this.name = name; + this.description = description; + this.slug = slug; + this.avatarUrl = avatarUrl; + } + static fromJSON(data) { + return new _Feature(data.id, data.name, data.description, data.slug, data.avatar_url); + } +}; + +// src/api/resources/CommercePlan.ts +var BillingPlan = class _BillingPlan { + constructor(id, productId, name, slug, description, isDefault, isRecurring, hasBaseFee, publiclyVisible, fee, annualFee, annualMonthlyFee, forPayerType, features) { + this.id = id; + this.productId = productId; + this.name = name; + this.slug = slug; + this.description = description; + this.isDefault = isDefault; + this.isRecurring = isRecurring; + this.hasBaseFee = hasBaseFee; + this.publiclyVisible = publiclyVisible; + this.fee = fee; + this.annualFee = annualFee; + this.annualMonthlyFee = annualMonthlyFee; + this.forPayerType = forPayerType; + this.features = features; + } + static fromJSON(data) { + const formatAmountJSON = (fee) => { + return { + amount: fee.amount, + amountFormatted: fee.amount_formatted, + currency: fee.currency, + currencySymbol: fee.currency_symbol + }; + }; + return new _BillingPlan( + data.id, + data.product_id, + data.name, + data.slug, + data.description, + data.is_default, + data.is_recurring, + data.has_base_fee, + data.publicly_visible, + formatAmountJSON(data.fee), + formatAmountJSON(data.annual_fee), + formatAmountJSON(data.annual_monthly_fee), + data.for_payer_type, + data.features.map((feature) => Feature.fromJSON(feature)) + ); + } +}; + +// src/api/resources/CommerceSubscriptionItem.ts +var BillingSubscriptionItem = class _BillingSubscriptionItem { + constructor(id, status, planPeriod, periodStart, nextPayment, amount, plan, planId, createdAt, updatedAt, periodEnd, canceledAt, pastDueAt, endedAt, payerId, isFreeTrial, lifetimePaid) { + this.id = id; + this.status = status; + this.planPeriod = planPeriod; + this.periodStart = periodStart; + this.nextPayment = nextPayment; + this.amount = amount; + this.plan = plan; + this.planId = planId; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + this.periodEnd = periodEnd; + this.canceledAt = canceledAt; + this.pastDueAt = pastDueAt; + this.endedAt = endedAt; + this.payerId = payerId; + this.isFreeTrial = isFreeTrial; + this.lifetimePaid = lifetimePaid; + } + static fromJSON(data) { + function formatAmountJSON(amount) { + if (!amount) { + return amount; + } + return { + amount: amount.amount, + amountFormatted: amount.amount_formatted, + currency: amount.currency, + currencySymbol: amount.currency_symbol + }; + } + return new _BillingSubscriptionItem( + data.id, + data.status, + data.plan_period, + data.period_start, + data.next_payment, + formatAmountJSON(data.amount), + BillingPlan.fromJSON(data.plan), + data.plan_id, + data.created_at, + data.updated_at, + data.period_end, + data.canceled_at, + data.past_due_at, + data.ended_at, + data.payer_id, + data.is_free_trial, + formatAmountJSON(data.lifetime_paid) + ); + } +}; + +// src/api/resources/CommerceSubscription.ts +var BillingSubscription = class _BillingSubscription { + constructor(id, status, payerId, createdAt, updatedAt, activeAt, pastDueAt, subscriptionItems, nextPayment, eligibleForFreeTrial) { + this.id = id; + this.status = status; + this.payerId = payerId; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + this.activeAt = activeAt; + this.pastDueAt = pastDueAt; + this.subscriptionItems = subscriptionItems; + this.nextPayment = nextPayment; + this.eligibleForFreeTrial = eligibleForFreeTrial; + } + static fromJSON(data) { + const nextPayment = data.next_payment ? { + date: data.next_payment.date, + amount: { + amount: data.next_payment.amount.amount, + amountFormatted: data.next_payment.amount.amount_formatted, + currency: data.next_payment.amount.currency, + currencySymbol: data.next_payment.amount.currency_symbol + } + } : null; + return new _BillingSubscription( + data.id, + data.status, + data.payer_id, + data.created_at, + data.updated_at, + data.active_at ?? null, + data.past_due_at ?? null, + data.subscription_items.map((item) => BillingSubscriptionItem.fromJSON(item)), + nextPayment, + data.eligible_for_free_trial ?? false + ); + } +}; + +// src/api/resources/Deserializer.ts +function deserialize(payload) { + let data, totalCount; + if (Array.isArray(payload)) { + const data2 = payload.map((item) => jsonToObject(item)); + return { data: data2 }; + } else if (isPaginated(payload)) { + data = payload.data.map((item) => jsonToObject(item)); + totalCount = payload.total_count; + return { data, totalCount }; + } else { + return { data: jsonToObject(payload) }; + } +} +function isPaginated(payload) { + if (!payload || typeof payload !== "object" || !("data" in payload)) { + return false; + } + return Array.isArray(payload.data) && payload.data !== void 0; +} +function getCount(item) { + return item.total_count; +} +function jsonToObject(item) { + if (typeof item !== "string" && "object" in item && "deleted" in item) { + return DeletedObject.fromJSON(item); + } + switch (item.object) { + case ObjectType.AccountlessApplication: + return AccountlessApplication.fromJSON(item); + case ObjectType.ActorToken: + return ActorToken.fromJSON(item); + case ObjectType.AllowlistIdentifier: + return AllowlistIdentifier.fromJSON(item); + case ObjectType.ApiKey: + return APIKey.fromJSON(item); + case ObjectType.BlocklistIdentifier: + return BlocklistIdentifier.fromJSON(item); + case ObjectType.Client: + return Client.fromJSON(item); + case ObjectType.Cookies: + return Cookies2.fromJSON(item); + case ObjectType.Domain: + return Domain.fromJSON(item); + case ObjectType.EmailAddress: + return EmailAddress.fromJSON(item); + case ObjectType.Email: + return Email.fromJSON(item); + case ObjectType.IdpOAuthAccessToken: + return IdPOAuthAccessToken.fromJSON(item); + case ObjectType.Instance: + return Instance.fromJSON(item); + case ObjectType.InstanceRestrictions: + return InstanceRestrictions.fromJSON(item); + case ObjectType.InstanceSettings: + return InstanceSettings.fromJSON(item); + case ObjectType.Invitation: + return Invitation.fromJSON(item); + case ObjectType.JwtTemplate: + return JwtTemplate.fromJSON(item); + case ObjectType.Machine: + return Machine.fromJSON(item); + case ObjectType.MachineScope: + return MachineScope.fromJSON(item); + case ObjectType.MachineSecretKey: + return MachineSecretKey.fromJSON(item); + case ObjectType.M2MToken: + return M2MToken.fromJSON(item); + case ObjectType.OauthAccessToken: + return OauthAccessToken.fromJSON(item); + case ObjectType.OAuthApplication: + return OAuthApplication.fromJSON(item); + case ObjectType.Organization: + return Organization.fromJSON(item); + case ObjectType.OrganizationInvitation: + return OrganizationInvitation.fromJSON(item); + case ObjectType.OrganizationMembership: + return OrganizationMembership.fromJSON(item); + case ObjectType.OrganizationSettings: + return OrganizationSettings.fromJSON(item); + case ObjectType.PhoneNumber: + return PhoneNumber.fromJSON(item); + case ObjectType.ProxyCheck: + return ProxyCheck.fromJSON(item); + case ObjectType.RedirectUrl: + return RedirectUrl.fromJSON(item); + case ObjectType.SamlConnection: + return SamlConnection.fromJSON(item); + case ObjectType.SignInToken: + return SignInToken.fromJSON(item); + case ObjectType.SignUpAttempt: + return SignUpAttempt.fromJSON(item); + case ObjectType.Session: + return Session.fromJSON(item); + case ObjectType.SmsMessage: + return SMSMessage.fromJSON(item); + case ObjectType.Token: + return Token.fromJSON(item); + case ObjectType.TotalCount: + return getCount(item); + case ObjectType.User: + return User.fromJSON(item); + case ObjectType.WaitlistEntry: + return WaitlistEntry.fromJSON(item); + case ObjectType.BillingPlan: + return BillingPlan.fromJSON(item); + case ObjectType.BillingSubscription: + return BillingSubscription.fromJSON(item); + case ObjectType.BillingSubscriptionItem: + return BillingSubscriptionItem.fromJSON(item); + case ObjectType.Feature: + return Feature.fromJSON(item); + default: + return item; + } +} + +// src/api/request.ts +function buildRequest(options) { + const requestFn = async (requestOptions) => { + const { + secretKey, + machineSecretKey, + useMachineSecretKey = false, + requireSecretKey = true, + apiUrl = API_URL, + apiVersion = API_VERSION, + userAgent = USER_AGENT, + skipApiVersionInUrl = false + } = options; + const { path, method, queryParams, headerParams, bodyParams, formData, options: opts } = requestOptions; + const { deepSnakecaseBodyParamKeys = false } = opts || {}; + if (requireSecretKey) { + assertValidSecretKey(secretKey); + } + const url = skipApiVersionInUrl ? joinPaths(apiUrl, path) : joinPaths(apiUrl, apiVersion, path); + const finalUrl = new URL(url); + if (queryParams) { + const snakecasedQueryParams = snakecase_keys_default({ ...queryParams }); + for (const [key, val] of Object.entries(snakecasedQueryParams)) { + if (val) { + [val].flat().forEach((v) => finalUrl.searchParams.append(key, v)); + } + } + } + const headers = new Headers({ + "Clerk-API-Version": SUPPORTED_BAPI_VERSION, + [constants.Headers.UserAgent]: userAgent, + ...headerParams + }); + const authorizationHeader = constants.Headers.Authorization; + if (!headers.has(authorizationHeader)) { + if (useMachineSecretKey && machineSecretKey) { + headers.set(authorizationHeader, `Bearer ${machineSecretKey}`); + } else if (secretKey) { + headers.set(authorizationHeader, `Bearer ${secretKey}`); + } + } + let res; + try { + if (formData) { + res = await runtime.fetch(finalUrl.href, { + method, + headers, + body: formData + }); + } else { + headers.set("Content-Type", "application/json"); + const buildBody = () => { + const hasBody = method !== "GET" && bodyParams && Object.keys(bodyParams).length > 0; + if (!hasBody) { + return null; + } + const formatKeys = (object) => snakecase_keys_default(object, { deep: deepSnakecaseBodyParamKeys }); + return { + body: JSON.stringify(Array.isArray(bodyParams) ? bodyParams.map(formatKeys) : formatKeys(bodyParams)) + }; + }; + res = await runtime.fetch(finalUrl.href, { + method, + headers, + ...buildBody() + }); + } + const isJSONResponse = res?.headers && res.headers?.get(constants.Headers.ContentType) === constants.ContentTypes.Json; + const responseBody = await (isJSONResponse ? res.json() : res.text()); + if (!res.ok) { + return { + data: null, + errors: parseErrors(responseBody), + status: res?.status, + statusText: res?.statusText, + clerkTraceId: getTraceId(responseBody, res?.headers), + retryAfter: getRetryAfter(res?.headers) + }; + } + return { + ...deserialize(responseBody), + errors: null + }; + } catch (err) { + if (err instanceof Error) { + return { + data: null, + errors: [ + { + code: "unexpected_error", + message: err.message || "Unexpected error" + } + ], + clerkTraceId: getTraceId(err, res?.headers) + }; + } + return { + data: null, + errors: parseErrors(err), + status: res?.status, + statusText: res?.statusText, + clerkTraceId: getTraceId(err, res?.headers), + retryAfter: getRetryAfter(res?.headers) + }; + } + }; + return withLegacyRequestReturn(requestFn); +} +function getTraceId(data, headers) { + if (data && typeof data === "object" && "clerk_trace_id" in data && typeof data.clerk_trace_id === "string") { + return data.clerk_trace_id; + } + const cfRay = headers?.get("cf-ray"); + return cfRay || ""; +} +function getRetryAfter(headers) { + const retryAfter = headers?.get("Retry-After"); + if (!retryAfter) { + return; + } + const value = parseInt(retryAfter, 10); + if (isNaN(value)) { + return; + } + return value; +} +function parseErrors(data) { + if (!!data && typeof data === "object" && "errors" in data) { + const errors = data.errors; + return errors.length > 0 ? errors.map(import_error2.parseError) : []; + } + return []; +} +function withLegacyRequestReturn(cb) { + return async (...args) => { + const { data, errors, totalCount, status, statusText, clerkTraceId, retryAfter } = await cb(...args); + if (errors) { + const error = new import_error2.ClerkAPIResponseError(statusText || "", { + data: [], + status, + clerkTraceId, + retryAfter + }); + error.errors = errors; + throw error; + } + if (typeof totalCount !== "undefined") { + return { data, totalCount }; + } + return data; + }; +} + +// src/api/factory.ts +function createBackendApiClient(options) { + const request = buildRequest(options); + return { + __experimental_accountlessApplications: new AccountlessApplicationAPI( + buildRequest({ ...options, requireSecretKey: false }) + ), + actorTokens: new ActorTokenAPI(request), + allowlistIdentifiers: new AllowlistIdentifierAPI(request), + apiKeys: new APIKeysAPI( + buildRequest({ + ...options, + skipApiVersionInUrl: true + }) + ), + betaFeatures: new BetaFeaturesAPI(request), + blocklistIdentifiers: new BlocklistIdentifierAPI(request), + /** + * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. + */ + billing: new BillingAPI(request), + clients: new ClientAPI(request), + domains: new DomainAPI(request), + emailAddresses: new EmailAddressAPI(request), + idPOAuthAccessToken: new IdPOAuthAccessTokenApi( + buildRequest({ + ...options, + skipApiVersionInUrl: true + }) + ), + instance: new InstanceAPI(request), + invitations: new InvitationAPI(request), + jwks: new JwksAPI(request), + jwtTemplates: new JwtTemplatesApi(request), + machines: new MachineApi(request), + m2m: new M2MTokenApi( + buildRequest({ + ...options, + skipApiVersionInUrl: true, + requireSecretKey: false, + useMachineSecretKey: true + }) + ), + oauthApplications: new OAuthApplicationsApi(request), + organizations: new OrganizationAPI(request), + phoneNumbers: new PhoneNumberAPI(request), + proxyChecks: new ProxyCheckAPI(request), + redirectUrls: new RedirectUrlAPI(request), + samlConnections: new SamlConnectionAPI(request), + sessions: new SessionAPI(request), + signInTokens: new SignInTokenAPI(request), + signUps: new SignUpAPI(request), + testingTokens: new TestingTokenAPI(request), + users: new UserAPI(request), + waitlistEntries: new WaitlistEntryAPI(request), + webhooks: new WebhookAPI(request) + }; +} + +// src/jwt/legacyReturn.ts +function withLegacyReturn(cb) { + return async (...args) => { + const { data, errors } = await cb(...args); + if (errors) { + throw errors[0]; + } + return data; + }; +} + +// src/util/mergePreDefinedOptions.ts +function mergePreDefinedOptions(preDefinedOptions, options) { + return Object.keys(preDefinedOptions).reduce( + (obj, key) => { + return { ...obj, [key]: options[key] || obj[key] }; + }, + { ...preDefinedOptions } + ); +} + +// src/errors.ts +var TokenVerificationErrorCode = { + InvalidSecretKey: "clerk_key_invalid" +}; +var TokenVerificationErrorReason = { + TokenExpired: "token-expired", + TokenInvalid: "token-invalid", + TokenInvalidAlgorithm: "token-invalid-algorithm", + TokenInvalidAuthorizedParties: "token-invalid-authorized-parties", + TokenInvalidSignature: "token-invalid-signature", + TokenNotActiveYet: "token-not-active-yet", + TokenIatInTheFuture: "token-iat-in-the-future", + TokenVerificationFailed: "token-verification-failed", + InvalidSecretKey: "secret-key-invalid", + LocalJWKMissing: "jwk-local-missing", + RemoteJWKFailedToLoad: "jwk-remote-failed-to-load", + RemoteJWKInvalid: "jwk-remote-invalid", + RemoteJWKMissing: "jwk-remote-missing", + JWKFailedToResolve: "jwk-failed-to-resolve", + JWKKidMismatch: "jwk-kid-mismatch" +}; +var TokenVerificationErrorAction = { + ContactSupport: "Contact support@clerk.com", + EnsureClerkJWT: "Make sure that this is a valid Clerk generate JWT.", + SetClerkJWTKey: "Set the CLERK_JWT_KEY environment variable.", + SetClerkSecretKey: "Set the CLERK_SECRET_KEY environment variable.", + EnsureClockSync: "Make sure your system clock is in sync (e.g. turn off and on automatic time synchronization)." +}; +var TokenVerificationError = class _TokenVerificationError extends Error { + constructor({ + action, + message, + reason + }) { + super(message); + Object.setPrototypeOf(this, _TokenVerificationError.prototype); + this.reason = reason; + this.message = message; + this.action = action; + } + getFullMessage() { + return `${[this.message, this.action].filter((m) => m).join(" ")} (reason=${this.reason}, token-carrier=${this.tokenCarrier})`; + } +}; +var MachineTokenVerificationErrorCode = { + TokenInvalid: "token-invalid", + InvalidSecretKey: "secret-key-invalid", + UnexpectedError: "unexpected-error" +}; +var MachineTokenVerificationError = class _MachineTokenVerificationError extends Error { + constructor({ message, code, status }) { + super(message); + Object.setPrototypeOf(this, _MachineTokenVerificationError.prototype); + this.code = code; + this.status = status; + } + getFullMessage() { + return `${this.message} (code=${this.code}, status=${this.status})`; + } +}; + +// src/util/rfc4648.ts +var base64url = { + parse(string, opts) { + return parse(string, base64UrlEncoding, opts); + }, + stringify(data, opts) { + return stringify(data, base64UrlEncoding, opts); + } +}; +var base64UrlEncoding = { + chars: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_", + bits: 6 +}; +function parse(string, encoding, opts = {}) { + if (!encoding.codes) { + encoding.codes = {}; + for (let i = 0; i < encoding.chars.length; ++i) { + encoding.codes[encoding.chars[i]] = i; + } + } + if (!opts.loose && string.length * encoding.bits & 7) { + throw new SyntaxError("Invalid padding"); + } + let end = string.length; + while (string[end - 1] === "=") { + --end; + if (!opts.loose && !((string.length - end) * encoding.bits & 7)) { + throw new SyntaxError("Invalid padding"); + } + } + const out = new (opts.out ?? Uint8Array)(end * encoding.bits / 8 | 0); + let bits = 0; + let buffer = 0; + let written = 0; + for (let i = 0; i < end; ++i) { + const value = encoding.codes[string[i]]; + if (value === void 0) { + throw new SyntaxError("Invalid character " + string[i]); + } + buffer = buffer << encoding.bits | value; + bits += encoding.bits; + if (bits >= 8) { + bits -= 8; + out[written++] = 255 & buffer >> bits; + } + } + if (bits >= encoding.bits || 255 & buffer << 8 - bits) { + throw new SyntaxError("Unexpected end of data"); + } + return out; +} +function stringify(data, encoding, opts = {}) { + const { pad = true } = opts; + const mask = (1 << encoding.bits) - 1; + let out = ""; + let bits = 0; + let buffer = 0; + for (let i = 0; i < data.length; ++i) { + buffer = buffer << 8 | 255 & data[i]; + bits += 8; + while (bits > encoding.bits) { + bits -= encoding.bits; + out += encoding.chars[mask & buffer >> bits]; + } + } + if (bits) { + out += encoding.chars[mask & buffer << encoding.bits - bits]; + } + if (pad) { + while (out.length * encoding.bits & 7) { + out += "="; + } + } + return out; +} + +// src/jwt/algorithms.ts +var algToHash = { + RS256: "SHA-256", + RS384: "SHA-384", + RS512: "SHA-512" +}; +var RSA_ALGORITHM_NAME = "RSASSA-PKCS1-v1_5"; +var jwksAlgToCryptoAlg = { + RS256: RSA_ALGORITHM_NAME, + RS384: RSA_ALGORITHM_NAME, + RS512: RSA_ALGORITHM_NAME +}; +var algs = Object.keys(algToHash); +function getCryptoAlgorithm(algorithmName) { + const hash = algToHash[algorithmName]; + const name = jwksAlgToCryptoAlg[algorithmName]; + if (!hash || !name) { + throw new Error(`Unsupported algorithm ${algorithmName}, expected one of ${algs.join(",")}.`); + } + return { + hash: { name: algToHash[algorithmName] }, + name: jwksAlgToCryptoAlg[algorithmName] + }; +} + +// src/jwt/assertions.ts +var isArrayString = (s) => { + return Array.isArray(s) && s.length > 0 && s.every((a) => typeof a === "string"); +}; +var assertAudienceClaim = (aud, audience) => { + const audienceList = [audience].flat().filter((a) => !!a); + const audList = [aud].flat().filter((a) => !!a); + const shouldVerifyAudience = audienceList.length > 0 && audList.length > 0; + if (!shouldVerifyAudience) { + return; + } + if (typeof aud === "string") { + if (!audienceList.includes(aud)) { + throw new TokenVerificationError({ + action: TokenVerificationErrorAction.EnsureClerkJWT, + reason: TokenVerificationErrorReason.TokenVerificationFailed, + message: `Invalid JWT audience claim (aud) ${JSON.stringify(aud)}. Is not included in "${JSON.stringify( + audienceList + )}".` + }); + } + } else if (isArrayString(aud)) { + if (!aud.some((a) => audienceList.includes(a))) { + throw new TokenVerificationError({ + action: TokenVerificationErrorAction.EnsureClerkJWT, + reason: TokenVerificationErrorReason.TokenVerificationFailed, + message: `Invalid JWT audience claim array (aud) ${JSON.stringify(aud)}. Is not included in "${JSON.stringify( + audienceList + )}".` + }); + } + } +}; +var assertHeaderType = (typ) => { + if (typeof typ === "undefined") { + return; + } + if (typ !== "JWT") { + throw new TokenVerificationError({ + action: TokenVerificationErrorAction.EnsureClerkJWT, + reason: TokenVerificationErrorReason.TokenInvalid, + message: `Invalid JWT type ${JSON.stringify(typ)}. Expected "JWT".` + }); + } +}; +var assertHeaderAlgorithm = (alg) => { + if (!algs.includes(alg)) { + throw new TokenVerificationError({ + action: TokenVerificationErrorAction.EnsureClerkJWT, + reason: TokenVerificationErrorReason.TokenInvalidAlgorithm, + message: `Invalid JWT algorithm ${JSON.stringify(alg)}. Supported: ${algs}.` + }); + } +}; +var assertSubClaim = (sub) => { + if (typeof sub !== "string") { + throw new TokenVerificationError({ + action: TokenVerificationErrorAction.EnsureClerkJWT, + reason: TokenVerificationErrorReason.TokenVerificationFailed, + message: `Subject claim (sub) is required and must be a string. Received ${JSON.stringify(sub)}.` + }); + } +}; +var assertAuthorizedPartiesClaim = (azp, authorizedParties) => { + if (!azp || !authorizedParties || authorizedParties.length === 0) { + return; + } + if (!authorizedParties.includes(azp)) { + throw new TokenVerificationError({ + reason: TokenVerificationErrorReason.TokenInvalidAuthorizedParties, + message: `Invalid JWT Authorized party claim (azp) ${JSON.stringify(azp)}. Expected "${authorizedParties}".` + }); + } +}; +var assertExpirationClaim = (exp, clockSkewInMs) => { + if (typeof exp !== "number") { + throw new TokenVerificationError({ + action: TokenVerificationErrorAction.EnsureClerkJWT, + reason: TokenVerificationErrorReason.TokenVerificationFailed, + message: `Invalid JWT expiry date claim (exp) ${JSON.stringify(exp)}. Expected number.` + }); + } + const currentDate = new Date(Date.now()); + const expiryDate = /* @__PURE__ */ new Date(0); + expiryDate.setUTCSeconds(exp); + const expired = expiryDate.getTime() <= currentDate.getTime() - clockSkewInMs; + if (expired) { + throw new TokenVerificationError({ + reason: TokenVerificationErrorReason.TokenExpired, + message: `JWT is expired. Expiry date: ${expiryDate.toUTCString()}, Current date: ${currentDate.toUTCString()}.` + }); + } +}; +var assertActivationClaim = (nbf, clockSkewInMs) => { + if (typeof nbf === "undefined") { + return; + } + if (typeof nbf !== "number") { + throw new TokenVerificationError({ + action: TokenVerificationErrorAction.EnsureClerkJWT, + reason: TokenVerificationErrorReason.TokenVerificationFailed, + message: `Invalid JWT not before date claim (nbf) ${JSON.stringify(nbf)}. Expected number.` + }); + } + const currentDate = new Date(Date.now()); + const notBeforeDate = /* @__PURE__ */ new Date(0); + notBeforeDate.setUTCSeconds(nbf); + const early = notBeforeDate.getTime() > currentDate.getTime() + clockSkewInMs; + if (early) { + throw new TokenVerificationError({ + reason: TokenVerificationErrorReason.TokenNotActiveYet, + message: `JWT cannot be used prior to not before date claim (nbf). Not before date: ${notBeforeDate.toUTCString()}; Current date: ${currentDate.toUTCString()};` + }); + } +}; +var assertIssuedAtClaim = (iat, clockSkewInMs) => { + if (typeof iat === "undefined") { + return; + } + if (typeof iat !== "number") { + throw new TokenVerificationError({ + action: TokenVerificationErrorAction.EnsureClerkJWT, + reason: TokenVerificationErrorReason.TokenVerificationFailed, + message: `Invalid JWT issued at date claim (iat) ${JSON.stringify(iat)}. Expected number.` + }); + } + const currentDate = new Date(Date.now()); + const issuedAtDate = /* @__PURE__ */ new Date(0); + issuedAtDate.setUTCSeconds(iat); + const postIssued = issuedAtDate.getTime() > currentDate.getTime() + clockSkewInMs; + if (postIssued) { + throw new TokenVerificationError({ + reason: TokenVerificationErrorReason.TokenIatInTheFuture, + message: `JWT issued at date claim (iat) is in the future. Issued at date: ${issuedAtDate.toUTCString()}; Current date: ${currentDate.toUTCString()};` + }); + } +}; + +// src/jwt/cryptoKeys.ts +var import_isomorphicAtob = require("@clerk/shared/isomorphicAtob"); +function pemToBuffer(secret) { + const trimmed = secret.replace(/-----BEGIN.*?-----/g, "").replace(/-----END.*?-----/g, "").replace(/\s/g, ""); + const decoded = (0, import_isomorphicAtob.isomorphicAtob)(trimmed); + const buffer = new ArrayBuffer(decoded.length); + const bufView = new Uint8Array(buffer); + for (let i = 0, strLen = decoded.length; i < strLen; i++) { + bufView[i] = decoded.charCodeAt(i); + } + return bufView; +} +function importKey(key, algorithm, keyUsage) { + if (typeof key === "object") { + return runtime.crypto.subtle.importKey("jwk", key, algorithm, false, [keyUsage]); + } + const keyData = pemToBuffer(key); + const format = keyUsage === "sign" ? "pkcs8" : "spki"; + return runtime.crypto.subtle.importKey(format, keyData, algorithm, false, [keyUsage]); +} + +// src/jwt/verifyJwt.ts +var DEFAULT_CLOCK_SKEW_IN_MS = 5 * 1e3; +async function hasValidSignature(jwt, key) { + const { header, signature, raw } = jwt; + const encoder = new TextEncoder(); + const data = encoder.encode([raw.header, raw.payload].join(".")); + const algorithm = getCryptoAlgorithm(header.alg); + try { + const cryptoKey = await importKey(key, algorithm, "verify"); + const verified = await runtime.crypto.subtle.verify(algorithm.name, cryptoKey, signature, data); + return { data: verified }; + } catch (error) { + return { + errors: [ + new TokenVerificationError({ + reason: TokenVerificationErrorReason.TokenInvalidSignature, + message: error?.message + }) + ] + }; + } +} +function decodeJwt(token) { + const tokenParts = (token || "").toString().split("."); + if (tokenParts.length !== 3) { + return { + errors: [ + new TokenVerificationError({ + reason: TokenVerificationErrorReason.TokenInvalid, + message: `Invalid JWT form. A JWT consists of three parts separated by dots.` + }) + ] + }; + } + const [rawHeader, rawPayload, rawSignature] = tokenParts; + const decoder = new TextDecoder(); + const header = JSON.parse(decoder.decode(base64url.parse(rawHeader, { loose: true }))); + const payload = JSON.parse(decoder.decode(base64url.parse(rawPayload, { loose: true }))); + const signature = base64url.parse(rawSignature, { loose: true }); + const data = { + header, + payload, + signature, + raw: { + header: rawHeader, + payload: rawPayload, + signature: rawSignature, + text: token + } + }; + return { data }; +} +async function verifyJwt(token, options) { + const { audience, authorizedParties, clockSkewInMs, key } = options; + const clockSkew = clockSkewInMs || DEFAULT_CLOCK_SKEW_IN_MS; + const { data: decoded, errors } = decodeJwt(token); + if (errors) { + return { errors }; + } + const { header, payload } = decoded; + try { + const { typ, alg } = header; + assertHeaderType(typ); + assertHeaderAlgorithm(alg); + const { azp, sub, aud, iat, exp, nbf } = payload; + assertSubClaim(sub); + assertAudienceClaim([aud], [audience]); + assertAuthorizedPartiesClaim(azp, authorizedParties); + assertExpirationClaim(exp, clockSkew); + assertActivationClaim(nbf, clockSkew); + assertIssuedAtClaim(iat, clockSkew); + } catch (err) { + return { errors: [err] }; + } + const { data: signatureValid, errors: signatureErrors } = await hasValidSignature(decoded, key); + if (signatureErrors) { + return { + errors: [ + new TokenVerificationError({ + action: TokenVerificationErrorAction.EnsureClerkJWT, + reason: TokenVerificationErrorReason.TokenVerificationFailed, + message: `Error verifying JWT signature. ${signatureErrors[0]}` + }) + ] + }; + } + if (!signatureValid) { + return { + errors: [ + new TokenVerificationError({ + reason: TokenVerificationErrorReason.TokenInvalidSignature, + message: "JWT signature is invalid." + }) + ] + }; + } + return { data: payload }; +} + +// src/tokens/authenticateContext.ts +var import_buildAccountsBaseUrl = require("@clerk/shared/buildAccountsBaseUrl"); +var import_url2 = require("@clerk/shared/url"); + +// src/tokens/tokenTypes.ts +var TokenType = { + SessionToken: "session_token", + ApiKey: "api_key", + M2MToken: "m2m_token", + OAuthToken: "oauth_token" +}; + +// src/tokens/authenticateContext.ts +var AuthenticateContext = class { + constructor(cookieSuffix, clerkRequest, options) { + this.cookieSuffix = cookieSuffix; + this.clerkRequest = clerkRequest; + /** + * The original Clerk frontend API URL, extracted from publishable key before proxy URL override. + * Used for backend operations like token validation and issuer checking. + */ + this.originalFrontendApi = ""; + if (options.acceptsToken === TokenType.M2MToken || options.acceptsToken === TokenType.ApiKey) { + this.initHeaderValues(); + } else { + this.initPublishableKeyValues(options); + this.initHeaderValues(); + this.initCookieValues(); + this.initHandshakeValues(); + } + Object.assign(this, options); + this.clerkUrl = this.clerkRequest.clerkUrl; + } + /** + * Retrieves the session token from either the cookie or the header. + * + * @returns {string | undefined} The session token if available, otherwise undefined. + */ + get sessionToken() { + return this.sessionTokenInCookie || this.tokenInHeader; + } + usesSuffixedCookies() { + const suffixedClientUat = this.getSuffixedCookie(constants.Cookies.ClientUat); + const clientUat = this.getCookie(constants.Cookies.ClientUat); + const suffixedSession = this.getSuffixedCookie(constants.Cookies.Session) || ""; + const session = this.getCookie(constants.Cookies.Session) || ""; + if (session && !this.tokenHasIssuer(session)) { + return false; + } + if (session && !this.tokenBelongsToInstance(session)) { + return true; + } + if (!suffixedClientUat && !suffixedSession) { + return false; + } + const { data: sessionData } = decodeJwt(session); + const sessionIat = sessionData?.payload.iat || 0; + const { data: suffixedSessionData } = decodeJwt(suffixedSession); + const suffixedSessionIat = suffixedSessionData?.payload.iat || 0; + if (suffixedClientUat !== "0" && clientUat !== "0" && sessionIat > suffixedSessionIat) { + return false; + } + if (suffixedClientUat === "0" && clientUat !== "0") { + return false; + } + if (this.instanceType !== "production") { + const isSuffixedSessionExpired = this.sessionExpired(suffixedSessionData); + if (suffixedClientUat !== "0" && clientUat === "0" && isSuffixedSessionExpired) { + return false; + } + } + if (!suffixedClientUat && suffixedSession) { + return false; + } + return true; + } + /** + * Determines if the request came from a different origin based on the referrer header. + * Used for cross-origin detection in multi-domain authentication flows. + * + * @returns {boolean} True if referrer exists and is from a different origin, false otherwise. + */ + isCrossOriginReferrer() { + if (!this.referrer || !this.clerkUrl.origin) { + return false; + } + try { + const referrerOrigin = new URL(this.referrer).origin; + return referrerOrigin !== this.clerkUrl.origin; + } catch { + return false; + } + } + /** + * Determines if the referrer URL is from a Clerk domain (accounts portal or FAPI). + * This includes both development and production account portal domains, as well as FAPI domains + * used for redirect-based authentication flows. + * + * @returns {boolean} True if the referrer is from a Clerk accounts portal or FAPI domain, false otherwise + */ + isKnownClerkReferrer() { + if (!this.referrer) { + return false; + } + try { + const referrerOrigin = new URL(this.referrer); + const referrerHost = referrerOrigin.hostname; + if (this.frontendApi) { + const fapiHost = this.frontendApi.startsWith("http") ? new URL(this.frontendApi).hostname : this.frontendApi; + if (referrerHost === fapiHost) { + return true; + } + } + if ((0, import_url2.isLegacyDevAccountPortalOrigin)(referrerHost) || (0, import_url2.isCurrentDevAccountPortalOrigin)(referrerHost)) { + return true; + } + const expectedAccountsUrl = (0, import_buildAccountsBaseUrl.buildAccountsBaseUrl)(this.frontendApi); + if (expectedAccountsUrl) { + const expectedAccountsOrigin = new URL(expectedAccountsUrl).origin; + if (referrerOrigin.origin === expectedAccountsOrigin) { + return true; + } + } + if (referrerHost.startsWith("accounts.")) { + return true; + } + return false; + } catch { + return false; + } + } + initPublishableKeyValues(options) { + assertValidPublishableKey(options.publishableKey); + this.publishableKey = options.publishableKey; + const originalPk = (0, import_keys.parsePublishableKey)(this.publishableKey, { + fatal: true, + domain: options.domain, + isSatellite: options.isSatellite + }); + this.originalFrontendApi = originalPk.frontendApi; + const pk = (0, import_keys.parsePublishableKey)(this.publishableKey, { + fatal: true, + proxyUrl: options.proxyUrl, + domain: options.domain, + isSatellite: options.isSatellite + }); + this.instanceType = pk.instanceType; + this.frontendApi = pk.frontendApi; + } + initHeaderValues() { + this.tokenInHeader = this.parseAuthorizationHeader(this.getHeader(constants.Headers.Authorization)); + this.origin = this.getHeader(constants.Headers.Origin); + this.host = this.getHeader(constants.Headers.Host); + this.forwardedHost = this.getHeader(constants.Headers.ForwardedHost); + this.forwardedProto = this.getHeader(constants.Headers.CloudFrontForwardedProto) || this.getHeader(constants.Headers.ForwardedProto); + this.referrer = this.getHeader(constants.Headers.Referrer); + this.userAgent = this.getHeader(constants.Headers.UserAgent); + this.secFetchDest = this.getHeader(constants.Headers.SecFetchDest); + this.accept = this.getHeader(constants.Headers.Accept); + } + initCookieValues() { + this.sessionTokenInCookie = this.getSuffixedOrUnSuffixedCookie(constants.Cookies.Session); + this.refreshTokenInCookie = this.getSuffixedCookie(constants.Cookies.Refresh); + this.clientUat = Number.parseInt(this.getSuffixedOrUnSuffixedCookie(constants.Cookies.ClientUat) || "") || 0; + } + initHandshakeValues() { + this.devBrowserToken = this.getQueryParam(constants.QueryParameters.DevBrowser) || this.getSuffixedOrUnSuffixedCookie(constants.Cookies.DevBrowser); + this.handshakeToken = this.getQueryParam(constants.QueryParameters.Handshake) || this.getCookie(constants.Cookies.Handshake); + this.handshakeRedirectLoopCounter = Number(this.getCookie(constants.Cookies.RedirectCount)) || 0; + this.handshakeNonce = this.getQueryParam(constants.QueryParameters.HandshakeNonce) || this.getCookie(constants.Cookies.HandshakeNonce); + } + getQueryParam(name) { + return this.clerkRequest.clerkUrl.searchParams.get(name); + } + getHeader(name) { + return this.clerkRequest.headers.get(name) || void 0; + } + getCookie(name) { + return this.clerkRequest.cookies.get(name) || void 0; + } + getSuffixedCookie(name) { + return this.getCookie((0, import_keys.getSuffixedCookieName)(name, this.cookieSuffix)) || void 0; + } + getSuffixedOrUnSuffixedCookie(cookieName) { + if (this.usesSuffixedCookies()) { + return this.getSuffixedCookie(cookieName); + } + return this.getCookie(cookieName); + } + parseAuthorizationHeader(authorizationHeader) { + if (!authorizationHeader) { + return void 0; + } + const [scheme, token] = authorizationHeader.split(" ", 2); + if (!token) { + return scheme; + } + if (scheme === "Bearer") { + return token; + } + return void 0; + } + tokenHasIssuer(token) { + const { data, errors } = decodeJwt(token); + if (errors) { + return false; + } + return !!data.payload.iss; + } + tokenBelongsToInstance(token) { + if (!token) { + return false; + } + const { data, errors } = decodeJwt(token); + if (errors) { + return false; + } + const tokenIssuer = data.payload.iss.replace(/https?:\/\//gi, ""); + return this.originalFrontendApi === tokenIssuer; + } + sessionExpired(jwt) { + return !!jwt && jwt?.payload.exp <= Date.now() / 1e3 >> 0; + } +}; +var createAuthenticateContext = async (clerkRequest, options) => { + const cookieSuffix = options.publishableKey ? await (0, import_keys.getCookieSuffix)(options.publishableKey, runtime.crypto.subtle) : ""; + return new AuthenticateContext(cookieSuffix, clerkRequest, options); +}; + +// src/tokens/authObjects.ts +var import_authorization = require("@clerk/shared/authorization"); +var import_jwtPayloadParser = require("@clerk/shared/jwtPayloadParser"); + +// src/createRedirect.ts +var import_buildAccountsBaseUrl2 = require("@clerk/shared/buildAccountsBaseUrl"); + +// src/tokens/clerkRequest.ts +var import_cookie = require("cookie"); + +// src/tokens/clerkUrl.ts +var ClerkUrl = class extends URL { + isCrossOrigin(other) { + return this.origin !== new URL(other.toString()).origin; + } +}; +var createClerkUrl = (...args) => { + return new ClerkUrl(...args); +}; + +// src/tokens/clerkRequest.ts +var ClerkRequest = class extends Request { + constructor(input, init) { + const url = typeof input !== "string" && "url" in input ? input.url : String(input); + super(url, init || typeof input === "string" ? void 0 : input); + this.clerkUrl = this.deriveUrlFromHeaders(this); + this.cookies = this.parseCookies(this); + } + toJSON() { + return { + url: this.clerkUrl.href, + method: this.method, + headers: JSON.stringify(Object.fromEntries(this.headers)), + clerkUrl: this.clerkUrl.toString(), + cookies: JSON.stringify(Object.fromEntries(this.cookies)) + }; + } + /** + * Used to fix request.url using the x-forwarded-* headers + * TODO add detailed description of the issues this solves + */ + deriveUrlFromHeaders(req) { + const initialUrl = new URL(req.url); + const forwardedProto = req.headers.get(constants.Headers.ForwardedProto); + const forwardedHost = req.headers.get(constants.Headers.ForwardedHost); + const host = req.headers.get(constants.Headers.Host); + const protocol = initialUrl.protocol; + const resolvedHost = this.getFirstValueFromHeader(forwardedHost) ?? host; + const resolvedProtocol = this.getFirstValueFromHeader(forwardedProto) ?? protocol?.replace(/[:/]/, ""); + const origin = resolvedHost && resolvedProtocol ? `${resolvedProtocol}://${resolvedHost}` : initialUrl.origin; + if (origin === initialUrl.origin) { + return createClerkUrl(initialUrl); + } + return createClerkUrl(initialUrl.pathname + initialUrl.search, origin); + } + getFirstValueFromHeader(value) { + return value?.split(",")[0]; + } + parseCookies(req) { + const cookiesRecord = (0, import_cookie.parse)(this.decodeCookieValue(req.headers.get("cookie") || "")); + return new Map(Object.entries(cookiesRecord)); + } + decodeCookieValue(str) { + return str ? str.replace(/(%[0-9A-Z]{2})+/g, decodeURIComponent) : str; + } +}; +var createClerkRequest = (...args) => { + return args[0] instanceof ClerkRequest ? args[0] : new ClerkRequest(...args); +}; + +// src/internal.ts +var import_authorization_errors = require("@clerk/shared/authorization-errors"); + +// src/tokens/verify.ts +var import_error3 = require("@clerk/shared/error"); + +// src/tokens/keys.ts +var cache = {}; +var lastUpdatedAt = 0; +function getFromCache(kid) { + return cache[kid]; +} +function getCacheValues() { + return Object.values(cache); +} +function setInCache(jwk, shouldExpire = true) { + cache[jwk.kid] = jwk; + lastUpdatedAt = shouldExpire ? Date.now() : -1; +} +var LocalJwkKid = "local"; +var PEM_HEADER = "-----BEGIN PUBLIC KEY-----"; +var PEM_TRAILER = "-----END PUBLIC KEY-----"; +var RSA_PREFIX = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA"; +var RSA_SUFFIX = "IDAQAB"; +function loadClerkJWKFromLocal(localKey) { + if (!getFromCache(LocalJwkKid)) { + if (!localKey) { + throw new TokenVerificationError({ + action: TokenVerificationErrorAction.SetClerkJWTKey, + message: "Missing local JWK.", + reason: TokenVerificationErrorReason.LocalJWKMissing + }); + } + const modulus = localKey.replace(/\r\n|\n|\r/g, "").replace(PEM_HEADER, "").replace(PEM_TRAILER, "").replace(RSA_PREFIX, "").replace(RSA_SUFFIX, "").replace(/\+/g, "-").replace(/\//g, "_"); + setInCache( + { + kid: "local", + kty: "RSA", + alg: "RS256", + n: modulus, + e: "AQAB" + }, + false + // local key never expires in cache + ); + } + return getFromCache(LocalJwkKid); +} +async function loadClerkJWKFromRemote({ + secretKey, + apiUrl = API_URL, + apiVersion = API_VERSION, + kid, + skipJwksCache +}) { + if (skipJwksCache || cacheHasExpired() || !getFromCache(kid)) { + if (!secretKey) { + throw new TokenVerificationError({ + action: TokenVerificationErrorAction.ContactSupport, + message: "Failed to load JWKS from Clerk Backend or Frontend API.", + reason: TokenVerificationErrorReason.RemoteJWKFailedToLoad + }); + } + const fetcher = () => fetchJWKSFromBAPI(apiUrl, secretKey, apiVersion); + const { keys } = await (0, import_retry.retry)(fetcher); + if (!keys || !keys.length) { + throw new TokenVerificationError({ + action: TokenVerificationErrorAction.ContactSupport, + message: "The JWKS endpoint did not contain any signing keys. Contact support@clerk.com.", + reason: TokenVerificationErrorReason.RemoteJWKFailedToLoad + }); + } + keys.forEach((key) => setInCache(key)); + } + const jwk = getFromCache(kid); + if (!jwk) { + const cacheValues = getCacheValues(); + const jwkKeys = cacheValues.map((jwk2) => jwk2.kid).sort().join(", "); + throw new TokenVerificationError({ + action: `Go to your Dashboard and validate your secret and public keys are correct. ${TokenVerificationErrorAction.ContactSupport} if the issue persists.`, + message: `Unable to find a signing key in JWKS that matches the kid='${kid}' of the provided session token. Please make sure that the __session cookie or the HTTP authorization header contain a Clerk-generated session JWT. The following kid is available: ${jwkKeys}`, + reason: TokenVerificationErrorReason.JWKKidMismatch + }); + } + return jwk; +} +async function fetchJWKSFromBAPI(apiUrl, key, apiVersion) { + if (!key) { + throw new TokenVerificationError({ + action: TokenVerificationErrorAction.SetClerkSecretKey, + message: "Missing Clerk Secret Key or API Key. Go to https://dashboard.clerk.com and get your key for your instance.", + reason: TokenVerificationErrorReason.RemoteJWKFailedToLoad + }); + } + const url = new URL(apiUrl); + url.pathname = joinPaths(url.pathname, apiVersion, "/jwks"); + const response = await runtime.fetch(url.href, { + headers: { + Authorization: `Bearer ${key}`, + "Clerk-API-Version": SUPPORTED_BAPI_VERSION, + "Content-Type": "application/json", + "User-Agent": USER_AGENT + } + }); + if (!response.ok) { + const json = await response.json(); + const invalidSecretKeyError = getErrorObjectByCode(json?.errors, TokenVerificationErrorCode.InvalidSecretKey); + if (invalidSecretKeyError) { + const reason = TokenVerificationErrorReason.InvalidSecretKey; + throw new TokenVerificationError({ + action: TokenVerificationErrorAction.ContactSupport, + message: invalidSecretKeyError.message, + reason + }); + } + throw new TokenVerificationError({ + action: TokenVerificationErrorAction.ContactSupport, + message: `Error loading Clerk JWKS from ${url.href} with code=${response.status}`, + reason: TokenVerificationErrorReason.RemoteJWKFailedToLoad + }); + } + return response.json(); +} +function cacheHasExpired() { + if (lastUpdatedAt === -1) { + return false; + } + const isExpired = Date.now() - lastUpdatedAt >= MAX_CACHE_LAST_UPDATED_AT_SECONDS * 1e3; + if (isExpired) { + cache = {}; + } + return isExpired; +} +var getErrorObjectByCode = (errors, code) => { + if (!errors) { + return null; + } + return errors.find((err) => err.code === code); +}; + +// src/tokens/machine.ts +var M2M_TOKEN_PREFIX = "mt_"; +var OAUTH_TOKEN_PREFIX = "oat_"; +var API_KEY_PREFIX = "ak_"; +var MACHINE_TOKEN_PREFIXES = [M2M_TOKEN_PREFIX, OAUTH_TOKEN_PREFIX, API_KEY_PREFIX]; +function isMachineTokenByPrefix(token) { + return MACHINE_TOKEN_PREFIXES.some((prefix) => token.startsWith(prefix)); +} +function getMachineTokenType(token) { + if (token.startsWith(M2M_TOKEN_PREFIX)) { + return TokenType.M2MToken; + } + if (token.startsWith(OAUTH_TOKEN_PREFIX)) { + return TokenType.OAuthToken; + } + if (token.startsWith(API_KEY_PREFIX)) { + return TokenType.ApiKey; + } + throw new Error("Unknown machine token type"); +} +var isTokenTypeAccepted = (tokenType, acceptsToken) => { + if (!tokenType) { + return false; + } + if (acceptsToken === "any") { + return true; + } + const tokenTypes = Array.isArray(acceptsToken) ? acceptsToken : [acceptsToken]; + return tokenTypes.includes(tokenType); +}; + +// src/tokens/verify.ts +async function verifyToken(token, options) { + const { data: decodedResult, errors } = decodeJwt(token); + if (errors) { + return { errors }; + } + const { header } = decodedResult; + const { kid } = header; + try { + let key; + if (options.jwtKey) { + key = loadClerkJWKFromLocal(options.jwtKey); + } else if (options.secretKey) { + key = await loadClerkJWKFromRemote({ ...options, kid }); + } else { + return { + errors: [ + new TokenVerificationError({ + action: TokenVerificationErrorAction.SetClerkJWTKey, + message: "Failed to resolve JWK during verification.", + reason: TokenVerificationErrorReason.JWKFailedToResolve + }) + ] + }; + } + return await verifyJwt(token, { ...options, key }); + } catch (error) { + return { errors: [error] }; + } +} +function handleClerkAPIError(tokenType, err, notFoundMessage) { + if ((0, import_error3.isClerkAPIResponseError)(err)) { + let code; + let message; + switch (err.status) { + case 401: + code = MachineTokenVerificationErrorCode.InvalidSecretKey; + message = err.errors[0]?.message || "Invalid secret key"; + break; + case 404: + code = MachineTokenVerificationErrorCode.TokenInvalid; + message = notFoundMessage; + break; + default: + code = MachineTokenVerificationErrorCode.UnexpectedError; + message = "Unexpected error"; + } + return { + data: void 0, + tokenType, + errors: [ + new MachineTokenVerificationError({ + message, + code, + status: err.status + }) + ] + }; + } + return { + data: void 0, + tokenType, + errors: [ + new MachineTokenVerificationError({ + message: "Unexpected error", + code: MachineTokenVerificationErrorCode.UnexpectedError, + status: err.status + }) + ] + }; +} +async function verifyM2MToken(token, options) { + try { + const client = createBackendApiClient(options); + const verifiedToken = await client.m2m.verifyToken({ token }); + return { data: verifiedToken, tokenType: TokenType.M2MToken, errors: void 0 }; + } catch (err) { + return handleClerkAPIError(TokenType.M2MToken, err, "Machine token not found"); + } +} +async function verifyOAuthToken(accessToken, options) { + try { + const client = createBackendApiClient(options); + const verifiedToken = await client.idPOAuthAccessToken.verifyAccessToken(accessToken); + return { data: verifiedToken, tokenType: TokenType.OAuthToken, errors: void 0 }; + } catch (err) { + return handleClerkAPIError(TokenType.OAuthToken, err, "OAuth token not found"); + } +} +async function verifyAPIKey(secret, options) { + try { + const client = createBackendApiClient(options); + const verifiedToken = await client.apiKeys.verifySecret(secret); + return { data: verifiedToken, tokenType: TokenType.ApiKey, errors: void 0 }; + } catch (err) { + return handleClerkAPIError(TokenType.ApiKey, err, "API key not found"); + } +} +async function verifyMachineAuthToken(token, options) { + if (token.startsWith(M2M_TOKEN_PREFIX)) { + return verifyM2MToken(token, options); + } + if (token.startsWith(OAUTH_TOKEN_PREFIX)) { + return verifyOAuthToken(token, options); + } + if (token.startsWith(API_KEY_PREFIX)) { + return verifyAPIKey(token, options); + } + throw new Error("Unknown machine token type"); +} + +// src/tokens/authObjects.ts +var createDebug = (data) => { + return () => { + const res = { ...data }; + res.secretKey = (res.secretKey || "").substring(0, 7); + res.jwtKey = (res.jwtKey || "").substring(0, 7); + return { ...res }; + }; +}; +function signedInAuthObject(authenticateContext, sessionToken, sessionClaims) { + const { actor, sessionId, sessionStatus, userId, orgId, orgRole, orgSlug, orgPermissions, factorVerificationAge } = (0, import_jwtPayloadParser.__experimental_JWTPayloadToAuthObjectProperties)(sessionClaims); + const apiClient = createBackendApiClient(authenticateContext); + const getToken = createGetToken({ + sessionId, + sessionToken, + fetcher: async (sessionId2, template, expiresInSeconds) => (await apiClient.sessions.getToken(sessionId2, template || "", expiresInSeconds)).jwt + }); + return { + tokenType: TokenType.SessionToken, + actor, + sessionClaims, + sessionId, + sessionStatus, + userId, + orgId, + orgRole, + orgSlug, + orgPermissions, + factorVerificationAge, + getToken, + has: (0, import_authorization.createCheckAuthorization)({ + orgId, + orgRole, + orgPermissions, + userId, + factorVerificationAge, + features: sessionClaims.fea || "", + plans: sessionClaims.pla || "" + }), + debug: createDebug({ ...authenticateContext, sessionToken }), + isAuthenticated: true + }; +} +function signedOutAuthObject(debugData, initialSessionStatus) { + return { + tokenType: TokenType.SessionToken, + sessionClaims: null, + sessionId: null, + sessionStatus: initialSessionStatus ?? null, + userId: null, + actor: null, + orgId: null, + orgRole: null, + orgSlug: null, + orgPermissions: null, + factorVerificationAge: null, + getToken: () => Promise.resolve(null), + has: () => false, + debug: createDebug(debugData), + isAuthenticated: false + }; +} +function authenticatedMachineObject(tokenType, token, verificationResult, debugData) { + const baseObject = { + id: verificationResult.id, + subject: verificationResult.subject, + getToken: () => Promise.resolve(token), + has: () => false, + debug: createDebug(debugData), + isAuthenticated: true + }; + switch (tokenType) { + case TokenType.ApiKey: { + const result = verificationResult; + return { + ...baseObject, + tokenType, + name: result.name, + claims: result.claims, + scopes: result.scopes, + userId: result.subject.startsWith("user_") ? result.subject : null, + orgId: result.subject.startsWith("org_") ? result.subject : null + }; + } + case TokenType.M2MToken: { + const result = verificationResult; + return { + ...baseObject, + tokenType, + claims: result.claims, + scopes: result.scopes, + machineId: result.subject + }; + } + case TokenType.OAuthToken: { + const result = verificationResult; + return { + ...baseObject, + tokenType, + scopes: result.scopes, + userId: result.subject, + clientId: result.clientId + }; + } + default: + throw new Error(`Invalid token type: ${tokenType}`); + } +} +function unauthenticatedMachineObject(tokenType, debugData) { + const baseObject = { + id: null, + subject: null, + scopes: null, + has: () => false, + getToken: () => Promise.resolve(null), + debug: createDebug(debugData), + isAuthenticated: false + }; + switch (tokenType) { + case TokenType.ApiKey: { + return { + ...baseObject, + tokenType, + name: null, + claims: null, + scopes: null, + userId: null, + orgId: null + }; + } + case TokenType.M2MToken: { + return { + ...baseObject, + tokenType, + claims: null, + scopes: null, + machineId: null + }; + } + case TokenType.OAuthToken: { + return { + ...baseObject, + tokenType, + scopes: null, + userId: null, + clientId: null + }; + } + default: + throw new Error(`Invalid token type: ${tokenType}`); + } +} +function invalidTokenAuthObject() { + return { + isAuthenticated: false, + tokenType: null, + getToken: () => Promise.resolve(null), + has: () => false, + debug: () => ({}) + }; +} +var createGetToken = (params) => { + const { fetcher, sessionToken, sessionId } = params || {}; + return async (options = {}) => { + if (!sessionId) { + return null; + } + if (options.template || options.expiresInSeconds !== void 0) { + return fetcher(sessionId, options.template, options.expiresInSeconds); + } + return sessionToken; + }; +}; + +// src/tokens/authStatus.ts +var AuthStatus = { + SignedIn: "signed-in", + SignedOut: "signed-out", + Handshake: "handshake" +}; +var AuthErrorReason = { + ClientUATWithoutSessionToken: "client-uat-but-no-session-token", + DevBrowserMissing: "dev-browser-missing", + DevBrowserSync: "dev-browser-sync", + PrimaryRespondsToSyncing: "primary-responds-to-syncing", + PrimaryDomainCrossOriginSync: "primary-domain-cross-origin-sync", + SatelliteCookieNeedsSyncing: "satellite-needs-syncing", + SessionTokenAndUATMissing: "session-token-and-uat-missing", + SessionTokenMissing: "session-token-missing", + SessionTokenExpired: "session-token-expired", + SessionTokenIATBeforeClientUAT: "session-token-iat-before-client-uat", + SessionTokenNBF: "session-token-nbf", + SessionTokenIatInTheFuture: "session-token-iat-in-the-future", + SessionTokenWithoutClientUAT: "session-token-but-no-client-uat", + ActiveOrganizationMismatch: "active-organization-mismatch", + TokenTypeMismatch: "token-type-mismatch", + UnexpectedError: "unexpected-error" +}; +function signedIn(params) { + const { authenticateContext, headers = new Headers(), token } = params; + const toAuth = ({ treatPendingAsSignedOut = true } = {}) => { + if (params.tokenType === TokenType.SessionToken) { + const { sessionClaims } = params; + const authObject = signedInAuthObject(authenticateContext, token, sessionClaims); + if (treatPendingAsSignedOut && authObject.sessionStatus === "pending") { + return signedOutAuthObject(void 0, authObject.sessionStatus); + } + return authObject; + } + const { machineData } = params; + return authenticatedMachineObject(params.tokenType, token, machineData, authenticateContext); + }; + return { + status: AuthStatus.SignedIn, + reason: null, + message: null, + proxyUrl: authenticateContext.proxyUrl || "", + publishableKey: authenticateContext.publishableKey || "", + isSatellite: authenticateContext.isSatellite || false, + domain: authenticateContext.domain || "", + signInUrl: authenticateContext.signInUrl || "", + signUpUrl: authenticateContext.signUpUrl || "", + afterSignInUrl: authenticateContext.afterSignInUrl || "", + afterSignUpUrl: authenticateContext.afterSignUpUrl || "", + isSignedIn: true, + isAuthenticated: true, + tokenType: params.tokenType, + toAuth, + headers, + token + }; +} +function signedOut(params) { + const { authenticateContext, headers = new Headers(), reason, message = "", tokenType } = params; + const toAuth = () => { + if (tokenType === TokenType.SessionToken) { + return signedOutAuthObject({ ...authenticateContext, status: AuthStatus.SignedOut, reason, message }); + } + return unauthenticatedMachineObject(tokenType, { reason, message, headers }); + }; + return withDebugHeaders({ + status: AuthStatus.SignedOut, + reason, + message, + proxyUrl: authenticateContext.proxyUrl || "", + publishableKey: authenticateContext.publishableKey || "", + isSatellite: authenticateContext.isSatellite || false, + domain: authenticateContext.domain || "", + signInUrl: authenticateContext.signInUrl || "", + signUpUrl: authenticateContext.signUpUrl || "", + afterSignInUrl: authenticateContext.afterSignInUrl || "", + afterSignUpUrl: authenticateContext.afterSignUpUrl || "", + isSignedIn: false, + isAuthenticated: false, + tokenType, + toAuth, + headers, + token: null + }); +} +function handshake(authenticateContext, reason, message = "", headers) { + return withDebugHeaders({ + status: AuthStatus.Handshake, + reason, + message, + publishableKey: authenticateContext.publishableKey || "", + isSatellite: authenticateContext.isSatellite || false, + domain: authenticateContext.domain || "", + proxyUrl: authenticateContext.proxyUrl || "", + signInUrl: authenticateContext.signInUrl || "", + signUpUrl: authenticateContext.signUpUrl || "", + afterSignInUrl: authenticateContext.afterSignInUrl || "", + afterSignUpUrl: authenticateContext.afterSignUpUrl || "", + isSignedIn: false, + isAuthenticated: false, + tokenType: TokenType.SessionToken, + toAuth: () => null, + headers, + token: null + }); +} +function signedOutInvalidToken() { + const authObject = invalidTokenAuthObject(); + return withDebugHeaders({ + status: AuthStatus.SignedOut, + reason: AuthErrorReason.TokenTypeMismatch, + message: "", + proxyUrl: "", + publishableKey: "", + isSatellite: false, + domain: "", + signInUrl: "", + signUpUrl: "", + afterSignInUrl: "", + afterSignUpUrl: "", + isSignedIn: false, + isAuthenticated: false, + tokenType: null, + toAuth: () => authObject, + headers: new Headers(), + token: null + }); +} +var withDebugHeaders = (requestState) => { + const headers = new Headers(requestState.headers || {}); + if (requestState.message) { + try { + headers.set(constants.Headers.AuthMessage, requestState.message); + } catch { + } + } + if (requestState.reason) { + try { + headers.set(constants.Headers.AuthReason, requestState.reason); + } catch { + } + } + if (requestState.status) { + try { + headers.set(constants.Headers.AuthStatus, requestState.status); + } catch { + } + } + requestState.headers = headers; + return requestState; +}; + +// src/tokens/cookie.ts +var getCookieName = (cookieDirective) => { + return cookieDirective.split(";")[0]?.split("=")[0]; +}; +var getCookieValue = (cookieDirective) => { + return cookieDirective.split(";")[0]?.split("=")[1]; +}; + +// src/tokens/handshake.ts +async function verifyHandshakeJwt(token, { key }) { + const { data: decoded, errors } = decodeJwt(token); + if (errors) { + throw errors[0]; + } + const { header, payload } = decoded; + const { typ, alg } = header; + assertHeaderType(typ); + assertHeaderAlgorithm(alg); + const { data: signatureValid, errors: signatureErrors } = await hasValidSignature(decoded, key); + if (signatureErrors) { + throw new TokenVerificationError({ + reason: TokenVerificationErrorReason.TokenVerificationFailed, + message: `Error verifying handshake token. ${signatureErrors[0]}` + }); + } + if (!signatureValid) { + throw new TokenVerificationError({ + reason: TokenVerificationErrorReason.TokenInvalidSignature, + message: "Handshake signature is invalid." + }); + } + return payload; +} +async function verifyHandshakeToken(token, options) { + const { secretKey, apiUrl, apiVersion, jwksCacheTtlInMs, jwtKey, skipJwksCache } = options; + const { data, errors } = decodeJwt(token); + if (errors) { + throw errors[0]; + } + const { kid } = data.header; + let key; + if (jwtKey) { + key = loadClerkJWKFromLocal(jwtKey); + } else if (secretKey) { + key = await loadClerkJWKFromRemote({ secretKey, apiUrl, apiVersion, kid, jwksCacheTtlInMs, skipJwksCache }); + } else { + throw new TokenVerificationError({ + action: TokenVerificationErrorAction.SetClerkJWTKey, + message: "Failed to resolve JWK during handshake verification.", + reason: TokenVerificationErrorReason.JWKFailedToResolve + }); + } + return await verifyHandshakeJwt(token, { + key + }); +} +var HandshakeService = class { + constructor(authenticateContext, options, organizationMatcher) { + this.authenticateContext = authenticateContext; + this.options = options; + this.organizationMatcher = organizationMatcher; + } + /** + * Determines if a request is eligible for handshake based on its headers + * + * Currently, a request is only eligible for a handshake if we can say it's *probably* a request for a document, not a fetch or some other exotic request. + * This heuristic should give us a reliable enough signal for browsers that support `Sec-Fetch-Dest` and for those that don't. + * + * @returns boolean indicating if the request is eligible for handshake + */ + isRequestEligibleForHandshake() { + const { accept, secFetchDest } = this.authenticateContext; + if (secFetchDest === "document" || secFetchDest === "iframe") { + return true; + } + if (!secFetchDest && accept?.startsWith("text/html")) { + return true; + } + return false; + } + /** + * Builds the redirect headers for a handshake request + * @param reason - The reason for the handshake (e.g. 'session-token-expired') + * @returns Headers object containing the Location header for redirect + * @throws Error if clerkUrl is missing in authenticateContext + */ + buildRedirectToHandshake(reason) { + if (!this.authenticateContext?.clerkUrl) { + throw new Error("Missing clerkUrl in authenticateContext"); + } + const redirectUrl = this.removeDevBrowserFromURL(this.authenticateContext.clerkUrl); + let baseUrl = this.authenticateContext.frontendApi.startsWith("http") ? this.authenticateContext.frontendApi : `https://${this.authenticateContext.frontendApi}`; + baseUrl = baseUrl.replace(/\/+$/, "") + "/"; + const url = new URL("v1/client/handshake", baseUrl); + url.searchParams.append("redirect_url", redirectUrl?.href || ""); + url.searchParams.append("__clerk_api_version", SUPPORTED_BAPI_VERSION); + url.searchParams.append( + constants.QueryParameters.SuffixedCookies, + this.authenticateContext.usesSuffixedCookies().toString() + ); + url.searchParams.append(constants.QueryParameters.HandshakeReason, reason); + url.searchParams.append(constants.QueryParameters.HandshakeFormat, "nonce"); + if (this.authenticateContext.instanceType === "development" && this.authenticateContext.devBrowserToken) { + url.searchParams.append(constants.QueryParameters.DevBrowser, this.authenticateContext.devBrowserToken); + } + const toActivate = this.getOrganizationSyncTarget(this.authenticateContext.clerkUrl, this.organizationMatcher); + if (toActivate) { + const params = this.getOrganizationSyncQueryParams(toActivate); + params.forEach((value, key) => { + url.searchParams.append(key, value); + }); + } + return new Headers({ [constants.Headers.Location]: url.href }); + } + /** + * Gets cookies from either a handshake nonce or a handshake token + * @returns Promise resolving to string array of cookie directives + */ + async getCookiesFromHandshake() { + const cookiesToSet = []; + if (this.authenticateContext.handshakeNonce) { + try { + const handshakePayload = await this.authenticateContext.apiClient?.clients.getHandshakePayload({ + nonce: this.authenticateContext.handshakeNonce + }); + if (handshakePayload) { + cookiesToSet.push(...handshakePayload.directives); + } + } catch (error) { + console.error("Clerk: HandshakeService: error getting handshake payload:", error); + } + } else if (this.authenticateContext.handshakeToken) { + const handshakePayload = await verifyHandshakeToken( + this.authenticateContext.handshakeToken, + this.authenticateContext + ); + if (handshakePayload && Array.isArray(handshakePayload.handshake)) { + cookiesToSet.push(...handshakePayload.handshake); + } + } + return cookiesToSet; + } + /** + * Resolves a handshake request by verifying the handshake token and setting appropriate cookies + * @returns Promise resolving to either a SignedInState or SignedOutState + * @throws Error if handshake verification fails or if there are issues with the session token + */ + async resolveHandshake() { + const headers = new Headers({ + "Access-Control-Allow-Origin": "null", + "Access-Control-Allow-Credentials": "true" + }); + const cookiesToSet = await this.getCookiesFromHandshake(); + let sessionToken = ""; + cookiesToSet.forEach((x) => { + headers.append("Set-Cookie", x); + if (getCookieName(x).startsWith(constants.Cookies.Session)) { + sessionToken = getCookieValue(x); + } + }); + if (this.authenticateContext.instanceType === "development") { + const newUrl = new URL(this.authenticateContext.clerkUrl); + newUrl.searchParams.delete(constants.QueryParameters.Handshake); + newUrl.searchParams.delete(constants.QueryParameters.HandshakeHelp); + newUrl.searchParams.delete(constants.QueryParameters.DevBrowser); + headers.append(constants.Headers.Location, newUrl.toString()); + headers.set(constants.Headers.CacheControl, "no-store"); + } + if (sessionToken === "") { + return signedOut({ + tokenType: TokenType.SessionToken, + authenticateContext: this.authenticateContext, + reason: AuthErrorReason.SessionTokenMissing, + message: "", + headers + }); + } + const { data, errors: [error] = [] } = await verifyToken(sessionToken, this.authenticateContext); + if (data) { + return signedIn({ + tokenType: TokenType.SessionToken, + authenticateContext: this.authenticateContext, + sessionClaims: data, + headers, + token: sessionToken + }); + } + if (this.authenticateContext.instanceType === "development" && (error?.reason === TokenVerificationErrorReason.TokenExpired || error?.reason === TokenVerificationErrorReason.TokenNotActiveYet || error?.reason === TokenVerificationErrorReason.TokenIatInTheFuture)) { + const developmentError = new TokenVerificationError({ + action: error.action, + message: error.message, + reason: error.reason + }); + developmentError.tokenCarrier = "cookie"; + console.error( + `Clerk: Clock skew detected. This usually means that your system clock is inaccurate. Clerk will attempt to account for the clock skew in development. + +To resolve this issue, make sure your system's clock is set to the correct time (e.g. turn off and on automatic time synchronization). + +--- + +${developmentError.getFullMessage()}` + ); + const { data: retryResult, errors: [retryError] = [] } = await verifyToken(sessionToken, { + ...this.authenticateContext, + clockSkewInMs: 864e5 + }); + if (retryResult) { + return signedIn({ + tokenType: TokenType.SessionToken, + authenticateContext: this.authenticateContext, + sessionClaims: retryResult, + headers, + token: sessionToken + }); + } + throw new Error(retryError?.message || "Clerk: Handshake retry failed."); + } + throw new Error(error?.message || "Clerk: Handshake failed."); + } + /** + * Handles handshake token verification errors in development mode + * @param error - The TokenVerificationError that occurred + * @throws Error with a descriptive message about the verification failure + */ + handleTokenVerificationErrorInDevelopment(error) { + if (error.reason === TokenVerificationErrorReason.TokenInvalidSignature) { + const msg = `Clerk: Handshake token verification failed due to an invalid signature. If you have switched Clerk keys locally, clear your cookies and try again.`; + throw new Error(msg); + } + throw new Error(`Clerk: Handshake token verification failed: ${error.getFullMessage()}.`); + } + /** + * Checks if a redirect loop is detected and sets headers to track redirect count + * @param headers - The Headers object to modify + * @returns boolean indicating if a redirect loop was detected (true) or if the request can proceed (false) + */ + checkAndTrackRedirectLoop(headers) { + if (this.authenticateContext.handshakeRedirectLoopCounter === 3) { + return true; + } + const newCounterValue = this.authenticateContext.handshakeRedirectLoopCounter + 1; + const cookieName = constants.Cookies.RedirectCount; + headers.append("Set-Cookie", `${cookieName}=${newCounterValue}; SameSite=Lax; HttpOnly; Max-Age=2`); + return false; + } + removeDevBrowserFromURL(url) { + const updatedURL = new URL(url); + updatedURL.searchParams.delete(constants.QueryParameters.DevBrowser); + updatedURL.searchParams.delete(constants.QueryParameters.LegacyDevBrowser); + return updatedURL; + } + getOrganizationSyncTarget(url, matchers) { + return matchers.findTarget(url); + } + getOrganizationSyncQueryParams(toActivate) { + const ret = /* @__PURE__ */ new Map(); + if (toActivate.type === "personalAccount") { + ret.set("organization_id", ""); + } + if (toActivate.type === "organization") { + if (toActivate.organizationId) { + ret.set("organization_id", toActivate.organizationId); + } + if (toActivate.organizationSlug) { + ret.set("organization_id", toActivate.organizationSlug); + } + } + return ret; + } +}; + +// src/tokens/organizationMatcher.ts +var import_pathToRegexp = require("@clerk/shared/pathToRegexp"); +var OrganizationMatcher = class { + constructor(options) { + this.organizationPattern = this.createMatcher(options?.organizationPatterns); + this.personalAccountPattern = this.createMatcher(options?.personalAccountPatterns); + } + createMatcher(pattern) { + if (!pattern) { + return null; + } + try { + return (0, import_pathToRegexp.match)(pattern); + } catch (e) { + throw new Error(`Invalid pattern "${pattern}": ${e}`); + } + } + findTarget(url) { + const orgTarget = this.findOrganizationTarget(url); + if (orgTarget) { + return orgTarget; + } + return this.findPersonalAccountTarget(url); + } + findOrganizationTarget(url) { + if (!this.organizationPattern) { + return null; + } + try { + const result = this.organizationPattern(url.pathname); + if (!result || !("params" in result)) { + return null; + } + const params = result.params; + if (params.id) { + return { type: "organization", organizationId: params.id }; + } + if (params.slug) { + return { type: "organization", organizationSlug: params.slug }; + } + return null; + } catch (e) { + console.error("Failed to match organization pattern:", e); + return null; + } + } + findPersonalAccountTarget(url) { + if (!this.personalAccountPattern) { + return null; + } + try { + const result = this.personalAccountPattern(url.pathname); + return result ? { type: "personalAccount" } : null; + } catch (e) { + console.error("Failed to match personal account pattern:", e); + return null; + } + } +}; + +// src/tokens/request.ts +var RefreshTokenErrorReason = { + NonEligibleNoCookie: "non-eligible-no-refresh-cookie", + NonEligibleNonGet: "non-eligible-non-get", + InvalidSessionToken: "invalid-session-token", + MissingApiClient: "missing-api-client", + MissingSessionToken: "missing-session-token", + MissingRefreshToken: "missing-refresh-token", + ExpiredSessionTokenDecodeFailed: "expired-session-token-decode-failed", + ExpiredSessionTokenMissingSidClaim: "expired-session-token-missing-sid-claim", + FetchError: "fetch-error", + UnexpectedSDKError: "unexpected-sdk-error", + UnexpectedBAPIError: "unexpected-bapi-error" +}; +function assertSignInUrlExists(signInUrl, key) { + if (!signInUrl && (0, import_keys.isDevelopmentFromSecretKey)(key)) { + throw new Error(`Missing signInUrl. Pass a signInUrl for dev instances if an app is satellite`); + } +} +function assertProxyUrlOrDomain(proxyUrlOrDomain) { + if (!proxyUrlOrDomain) { + throw new Error(`Missing domain and proxyUrl. A satellite application needs to specify a domain or a proxyUrl`); + } +} +function assertSignInUrlFormatAndOrigin(_signInUrl, origin) { + let signInUrl; + try { + signInUrl = new URL(_signInUrl); + } catch { + throw new Error(`The signInUrl needs to have a absolute url format.`); + } + if (signInUrl.origin === origin) { + throw new Error(`The signInUrl needs to be on a different origin than your satellite application.`); + } +} +function assertMachineSecretOrSecretKey(authenticateContext) { + if (!authenticateContext.machineSecretKey && !authenticateContext.secretKey) { + throw new Error( + "Machine token authentication requires either a Machine secret key or a Clerk secret key. Ensure a Clerk secret key or Machine secret key is set." + ); + } +} +function isRequestEligibleForRefresh(err, authenticateContext, request) { + return err.reason === TokenVerificationErrorReason.TokenExpired && !!authenticateContext.refreshTokenInCookie && request.method === "GET"; +} +function checkTokenTypeMismatch(parsedTokenType, acceptsToken, authenticateContext) { + const mismatch = !isTokenTypeAccepted(parsedTokenType, acceptsToken); + if (mismatch) { + const tokenTypeToReturn = typeof acceptsToken === "string" ? acceptsToken : parsedTokenType; + return signedOut({ + tokenType: tokenTypeToReturn, + authenticateContext, + reason: AuthErrorReason.TokenTypeMismatch + }); + } + return null; +} +function isTokenTypeInAcceptedArray(acceptsToken, authenticateContext) { + let parsedTokenType = null; + const { tokenInHeader } = authenticateContext; + if (tokenInHeader) { + if (isMachineTokenByPrefix(tokenInHeader)) { + parsedTokenType = getMachineTokenType(tokenInHeader); + } else { + parsedTokenType = TokenType.SessionToken; + } + } + const typeToCheck = parsedTokenType ?? TokenType.SessionToken; + return isTokenTypeAccepted(typeToCheck, acceptsToken); +} +var authenticateRequest = async (request, options) => { + const authenticateContext = await createAuthenticateContext(createClerkRequest(request), options); + const acceptsToken = options.acceptsToken ?? TokenType.SessionToken; + if (acceptsToken !== TokenType.M2MToken) { + assertValidSecretKey(authenticateContext.secretKey); + if (authenticateContext.isSatellite) { + assertSignInUrlExists(authenticateContext.signInUrl, authenticateContext.secretKey); + if (authenticateContext.signInUrl && authenticateContext.origin) { + assertSignInUrlFormatAndOrigin(authenticateContext.signInUrl, authenticateContext.origin); + } + assertProxyUrlOrDomain(authenticateContext.proxyUrl || authenticateContext.domain); + } + } + if (acceptsToken === TokenType.M2MToken) { + assertMachineSecretOrSecretKey(authenticateContext); + } + const organizationMatcher = new OrganizationMatcher(options.organizationSyncOptions); + const handshakeService = new HandshakeService( + authenticateContext, + { organizationSyncOptions: options.organizationSyncOptions }, + organizationMatcher + ); + async function refreshToken(authenticateContext2) { + if (!options.apiClient) { + return { + data: null, + error: { + message: "An apiClient is needed to perform token refresh.", + cause: { reason: RefreshTokenErrorReason.MissingApiClient } + } + }; + } + const { sessionToken: expiredSessionToken, refreshTokenInCookie: refreshToken2 } = authenticateContext2; + if (!expiredSessionToken) { + return { + data: null, + error: { + message: "Session token must be provided.", + cause: { reason: RefreshTokenErrorReason.MissingSessionToken } + } + }; + } + if (!refreshToken2) { + return { + data: null, + error: { + message: "Refresh token must be provided.", + cause: { reason: RefreshTokenErrorReason.MissingRefreshToken } + } + }; + } + const { data: decodeResult, errors: decodedErrors } = decodeJwt(expiredSessionToken); + if (!decodeResult || decodedErrors) { + return { + data: null, + error: { + message: "Unable to decode the expired session token.", + cause: { reason: RefreshTokenErrorReason.ExpiredSessionTokenDecodeFailed, errors: decodedErrors } + } + }; + } + if (!decodeResult?.payload?.sid) { + return { + data: null, + error: { + message: "Expired session token is missing the `sid` claim.", + cause: { reason: RefreshTokenErrorReason.ExpiredSessionTokenMissingSidClaim } + } + }; + } + try { + const response = await options.apiClient.sessions.refreshSession(decodeResult.payload.sid, { + format: "cookie", + suffixed_cookies: authenticateContext2.usesSuffixedCookies(), + expired_token: expiredSessionToken || "", + refresh_token: refreshToken2 || "", + request_origin: authenticateContext2.clerkUrl.origin, + // The refresh endpoint expects headers as Record, so we need to transform it. + request_headers: Object.fromEntries(Array.from(request.headers.entries()).map(([k, v]) => [k, [v]])) + }); + return { data: response.cookies, error: null }; + } catch (err) { + if (err?.errors?.length) { + if (err.errors[0].code === "unexpected_error") { + return { + data: null, + error: { + message: `Fetch unexpected error`, + cause: { reason: RefreshTokenErrorReason.FetchError, errors: err.errors } + } + }; + } + return { + data: null, + error: { + message: err.errors[0].code, + cause: { reason: err.errors[0].code, errors: err.errors } + } + }; + } else { + return { + data: null, + error: { + message: `Unexpected Server/BAPI error`, + cause: { reason: RefreshTokenErrorReason.UnexpectedBAPIError, errors: [err] } + } + }; + } + } + } + async function attemptRefresh(authenticateContext2) { + const { data: cookiesToSet, error } = await refreshToken(authenticateContext2); + if (!cookiesToSet || cookiesToSet.length === 0) { + return { data: null, error }; + } + const headers = new Headers(); + let sessionToken = ""; + cookiesToSet.forEach((x) => { + headers.append("Set-Cookie", x); + if (getCookieName(x).startsWith(constants.Cookies.Session)) { + sessionToken = getCookieValue(x); + } + }); + const { data: jwtPayload, errors } = await verifyToken(sessionToken, authenticateContext2); + if (errors) { + return { + data: null, + error: { + message: `Clerk: unable to verify refreshed session token.`, + cause: { reason: RefreshTokenErrorReason.InvalidSessionToken, errors } + } + }; + } + return { data: { jwtPayload, sessionToken, headers }, error: null }; + } + function handleMaybeHandshakeStatus(authenticateContext2, reason, message, headers) { + if (!handshakeService.isRequestEligibleForHandshake()) { + return signedOut({ + tokenType: TokenType.SessionToken, + authenticateContext: authenticateContext2, + reason, + message + }); + } + const handshakeHeaders = headers ?? handshakeService.buildRedirectToHandshake(reason); + if (handshakeHeaders.get(constants.Headers.Location)) { + handshakeHeaders.set(constants.Headers.CacheControl, "no-store"); + } + const isRedirectLoop = handshakeService.checkAndTrackRedirectLoop(handshakeHeaders); + if (isRedirectLoop) { + const msg = `Clerk: Refreshing the session token resulted in an infinite redirect loop. This usually means that your Clerk instance keys do not match - make sure to copy the correct publishable and secret keys from the Clerk dashboard.`; + console.log(msg); + return signedOut({ + tokenType: TokenType.SessionToken, + authenticateContext: authenticateContext2, + reason, + message + }); + } + return handshake(authenticateContext2, reason, message, handshakeHeaders); + } + function handleMaybeOrganizationSyncHandshake(authenticateContext2, auth) { + const organizationSyncTarget = organizationMatcher.findTarget(authenticateContext2.clerkUrl); + if (!organizationSyncTarget) { + return null; + } + let mustActivate = false; + if (organizationSyncTarget.type === "organization") { + if (organizationSyncTarget.organizationSlug && organizationSyncTarget.organizationSlug !== auth.orgSlug) { + mustActivate = true; + } + if (organizationSyncTarget.organizationId && organizationSyncTarget.organizationId !== auth.orgId) { + mustActivate = true; + } + } + if (organizationSyncTarget.type === "personalAccount" && auth.orgId) { + mustActivate = true; + } + if (!mustActivate) { + return null; + } + if (authenticateContext2.handshakeRedirectLoopCounter >= 3) { + console.warn( + "Clerk: Organization activation handshake loop detected. This is likely due to an invalid organization ID or slug. Skipping organization activation." + ); + return null; + } + const handshakeState = handleMaybeHandshakeStatus( + authenticateContext2, + AuthErrorReason.ActiveOrganizationMismatch, + "" + ); + if (handshakeState.status !== "handshake") { + return null; + } + return handshakeState; + } + async function authenticateRequestWithTokenInHeader() { + const { tokenInHeader } = authenticateContext; + try { + const { data, errors } = await verifyToken(tokenInHeader, authenticateContext); + if (errors) { + throw errors[0]; + } + return signedIn({ + tokenType: TokenType.SessionToken, + authenticateContext, + sessionClaims: data, + headers: new Headers(), + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + token: tokenInHeader + }); + } catch (err) { + return handleSessionTokenError(err, "header"); + } + } + async function authenticateRequestWithTokenInCookie() { + const hasActiveClient = authenticateContext.clientUat; + const hasSessionToken = !!authenticateContext.sessionTokenInCookie; + const hasDevBrowserToken = !!authenticateContext.devBrowserToken; + if (authenticateContext.handshakeNonce || authenticateContext.handshakeToken) { + try { + return await handshakeService.resolveHandshake(); + } catch (error) { + if (error instanceof TokenVerificationError && authenticateContext.instanceType === "development") { + handshakeService.handleTokenVerificationErrorInDevelopment(error); + } else { + console.error("Clerk: unable to resolve handshake:", error); + } + } + } + if (authenticateContext.instanceType === "development" && authenticateContext.clerkUrl.searchParams.has(constants.QueryParameters.DevBrowser)) { + return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.DevBrowserSync, ""); + } + const isRequestEligibleForMultiDomainSync = authenticateContext.isSatellite && authenticateContext.secFetchDest === "document"; + if (authenticateContext.instanceType === "production" && isRequestEligibleForMultiDomainSync) { + return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.SatelliteCookieNeedsSyncing, ""); + } + if (authenticateContext.instanceType === "development" && isRequestEligibleForMultiDomainSync && !authenticateContext.clerkUrl.searchParams.has(constants.QueryParameters.ClerkSynced)) { + const redirectURL = new URL(authenticateContext.signInUrl); + redirectURL.searchParams.append( + constants.QueryParameters.ClerkRedirectUrl, + authenticateContext.clerkUrl.toString() + ); + const headers = new Headers({ [constants.Headers.Location]: redirectURL.toString() }); + return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.SatelliteCookieNeedsSyncing, "", headers); + } + const redirectUrl = new URL(authenticateContext.clerkUrl).searchParams.get( + constants.QueryParameters.ClerkRedirectUrl + ); + if (authenticateContext.instanceType === "development" && !authenticateContext.isSatellite && redirectUrl) { + const redirectBackToSatelliteUrl = new URL(redirectUrl); + if (authenticateContext.devBrowserToken) { + redirectBackToSatelliteUrl.searchParams.append( + constants.QueryParameters.DevBrowser, + authenticateContext.devBrowserToken + ); + } + redirectBackToSatelliteUrl.searchParams.append(constants.QueryParameters.ClerkSynced, "true"); + const headers = new Headers({ [constants.Headers.Location]: redirectBackToSatelliteUrl.toString() }); + return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.PrimaryRespondsToSyncing, "", headers); + } + if (authenticateContext.instanceType === "development" && !hasDevBrowserToken) { + return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.DevBrowserMissing, ""); + } + if (!hasActiveClient && !hasSessionToken) { + return signedOut({ + tokenType: TokenType.SessionToken, + authenticateContext, + reason: AuthErrorReason.SessionTokenAndUATMissing + }); + } + if (!hasActiveClient && hasSessionToken) { + return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.SessionTokenWithoutClientUAT, ""); + } + if (hasActiveClient && !hasSessionToken) { + return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.ClientUATWithoutSessionToken, ""); + } + const { data: decodeResult, errors: decodedErrors } = decodeJwt(authenticateContext.sessionTokenInCookie); + if (decodedErrors) { + return handleSessionTokenError(decodedErrors[0], "cookie"); + } + if (decodeResult.payload.iat < authenticateContext.clientUat) { + return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.SessionTokenIATBeforeClientUAT, ""); + } + try { + const { data, errors } = await verifyToken(authenticateContext.sessionTokenInCookie, authenticateContext); + if (errors) { + throw errors[0]; + } + const signedInRequestState = signedIn({ + tokenType: TokenType.SessionToken, + authenticateContext, + sessionClaims: data, + headers: new Headers(), + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + token: authenticateContext.sessionTokenInCookie + }); + const shouldForceHandshakeForCrossDomain = !authenticateContext.isSatellite && // We're on primary + authenticateContext.secFetchDest === "document" && // Document navigation + authenticateContext.isCrossOriginReferrer() && // Came from different domain + !authenticateContext.isKnownClerkReferrer() && // Not from Clerk accounts portal or FAPI + authenticateContext.handshakeRedirectLoopCounter === 0; + if (shouldForceHandshakeForCrossDomain) { + return handleMaybeHandshakeStatus( + authenticateContext, + AuthErrorReason.PrimaryDomainCrossOriginSync, + "Cross-origin request from satellite domain requires handshake" + ); + } + const authObject = signedInRequestState.toAuth(); + if (authObject.userId) { + const handshakeRequestState = handleMaybeOrganizationSyncHandshake(authenticateContext, authObject); + if (handshakeRequestState) { + return handshakeRequestState; + } + } + return signedInRequestState; + } catch (err) { + return handleSessionTokenError(err, "cookie"); + } + return signedOut({ + tokenType: TokenType.SessionToken, + authenticateContext, + reason: AuthErrorReason.UnexpectedError + }); + } + async function handleSessionTokenError(err, tokenCarrier) { + if (!(err instanceof TokenVerificationError)) { + return signedOut({ + tokenType: TokenType.SessionToken, + authenticateContext, + reason: AuthErrorReason.UnexpectedError + }); + } + let refreshError; + if (isRequestEligibleForRefresh(err, authenticateContext, request)) { + const { data, error } = await attemptRefresh(authenticateContext); + if (data) { + return signedIn({ + tokenType: TokenType.SessionToken, + authenticateContext, + sessionClaims: data.jwtPayload, + headers: data.headers, + token: data.sessionToken + }); + } + if (error?.cause?.reason) { + refreshError = error.cause.reason; + } else { + refreshError = RefreshTokenErrorReason.UnexpectedSDKError; + } + } else { + if (request.method !== "GET") { + refreshError = RefreshTokenErrorReason.NonEligibleNonGet; + } else if (!authenticateContext.refreshTokenInCookie) { + refreshError = RefreshTokenErrorReason.NonEligibleNoCookie; + } else { + refreshError = null; + } + } + err.tokenCarrier = tokenCarrier; + const reasonToHandshake = [ + TokenVerificationErrorReason.TokenExpired, + TokenVerificationErrorReason.TokenNotActiveYet, + TokenVerificationErrorReason.TokenIatInTheFuture + ].includes(err.reason); + if (reasonToHandshake) { + return handleMaybeHandshakeStatus( + authenticateContext, + convertTokenVerificationErrorReasonToAuthErrorReason({ tokenError: err.reason, refreshError }), + err.getFullMessage() + ); + } + return signedOut({ + tokenType: TokenType.SessionToken, + authenticateContext, + reason: err.reason, + message: err.getFullMessage() + }); + } + function handleMachineError(tokenType, err) { + if (!(err instanceof MachineTokenVerificationError)) { + return signedOut({ + tokenType, + authenticateContext, + reason: AuthErrorReason.UnexpectedError + }); + } + return signedOut({ + tokenType, + authenticateContext, + reason: err.code, + message: err.getFullMessage() + }); + } + async function authenticateMachineRequestWithTokenInHeader() { + const { tokenInHeader } = authenticateContext; + if (!tokenInHeader) { + return handleSessionTokenError(new Error("Missing token in header"), "header"); + } + if (!isMachineTokenByPrefix(tokenInHeader)) { + return signedOut({ + tokenType: acceptsToken, + authenticateContext, + reason: AuthErrorReason.TokenTypeMismatch, + message: "" + }); + } + const parsedTokenType = getMachineTokenType(tokenInHeader); + const mismatchState = checkTokenTypeMismatch(parsedTokenType, acceptsToken, authenticateContext); + if (mismatchState) { + return mismatchState; + } + const { data, tokenType, errors } = await verifyMachineAuthToken(tokenInHeader, authenticateContext); + if (errors) { + return handleMachineError(tokenType, errors[0]); + } + return signedIn({ + tokenType, + authenticateContext, + machineData: data, + token: tokenInHeader + }); + } + async function authenticateAnyRequestWithTokenInHeader() { + const { tokenInHeader } = authenticateContext; + if (!tokenInHeader) { + return handleSessionTokenError(new Error("Missing token in header"), "header"); + } + if (isMachineTokenByPrefix(tokenInHeader)) { + const parsedTokenType = getMachineTokenType(tokenInHeader); + const mismatchState = checkTokenTypeMismatch(parsedTokenType, acceptsToken, authenticateContext); + if (mismatchState) { + return mismatchState; + } + const { data: data2, tokenType, errors: errors2 } = await verifyMachineAuthToken(tokenInHeader, authenticateContext); + if (errors2) { + return handleMachineError(tokenType, errors2[0]); + } + return signedIn({ + tokenType, + authenticateContext, + machineData: data2, + token: tokenInHeader + }); + } + const { data, errors } = await verifyToken(tokenInHeader, authenticateContext); + if (errors) { + return handleSessionTokenError(errors[0], "header"); + } + return signedIn({ + tokenType: TokenType.SessionToken, + authenticateContext, + sessionClaims: data, + token: tokenInHeader + }); + } + if (Array.isArray(acceptsToken)) { + if (!isTokenTypeInAcceptedArray(acceptsToken, authenticateContext)) { + return signedOutInvalidToken(); + } + } + if (authenticateContext.tokenInHeader) { + if (acceptsToken === "any") { + return authenticateAnyRequestWithTokenInHeader(); + } + if (acceptsToken === TokenType.SessionToken) { + return authenticateRequestWithTokenInHeader(); + } + return authenticateMachineRequestWithTokenInHeader(); + } + if (acceptsToken === TokenType.OAuthToken || acceptsToken === TokenType.ApiKey || acceptsToken === TokenType.M2MToken) { + return signedOut({ + tokenType: acceptsToken, + authenticateContext, + reason: "No token in header" + }); + } + return authenticateRequestWithTokenInCookie(); +}; +var debugRequestState = (params) => { + const { isSignedIn, isAuthenticated, proxyUrl, reason, message, publishableKey, isSatellite, domain } = params; + return { isSignedIn, isAuthenticated, proxyUrl, reason, message, publishableKey, isSatellite, domain }; +}; +var convertTokenVerificationErrorReasonToAuthErrorReason = ({ + tokenError, + refreshError +}) => { + switch (tokenError) { + case TokenVerificationErrorReason.TokenExpired: + return `${AuthErrorReason.SessionTokenExpired}-refresh-${refreshError}`; + case TokenVerificationErrorReason.TokenNotActiveYet: + return AuthErrorReason.SessionTokenNBF; + case TokenVerificationErrorReason.TokenIatInTheFuture: + return AuthErrorReason.SessionTokenIatInTheFuture; + default: + return AuthErrorReason.UnexpectedError; + } +}; + +// src/tokens/factory.ts +var defaultOptions = { + secretKey: "", + machineSecretKey: "", + jwtKey: "", + apiUrl: void 0, + apiVersion: void 0, + proxyUrl: "", + publishableKey: "", + isSatellite: false, + domain: "", + audience: "" +}; +function createAuthenticateRequest(params) { + const buildTimeOptions = mergePreDefinedOptions(defaultOptions, params.options); + const apiClient = params.apiClient; + const authenticateRequest2 = (request, options = {}) => { + const { apiUrl, apiVersion } = buildTimeOptions; + const runTimeOptions = mergePreDefinedOptions(buildTimeOptions, options); + return authenticateRequest(request, { + ...options, + ...runTimeOptions, + // We should add all the omitted props from options here (eg apiUrl / apiVersion) + // to avoid runtime options override them. + apiUrl, + apiVersion, + apiClient + }); + }; + return { + authenticateRequest: authenticateRequest2, + debugRequestState + }; +} + +// src/index.ts +var verifyToken2 = withLegacyReturn(verifyToken); +function createClerkClient(options) { + const opts = { ...options }; + const apiClient = createBackendApiClient(opts); + const requestState = createAuthenticateRequest({ options: opts, apiClient }); + const telemetry = new import_telemetry.TelemetryCollector({ + publishableKey: opts.publishableKey, + secretKey: opts.secretKey, + samplingRate: 0.1, + ...opts.sdkMetadata ? { sdk: opts.sdkMetadata.name, sdkVersion: opts.sdkMetadata.version } : {}, + ...opts.telemetry || {} + }); + return { + ...apiClient, + ...requestState, + telemetry + }; +} +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + createClerkClient, + verifyToken +}); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/index.js.map b/backend/node_modules/@clerk/backend/dist/index.js.map new file mode 100644 index 000000000..07bb4ae5c --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/index.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../src/index.ts","../src/util/path.ts","../src/api/endpoints/AbstractApi.ts","../src/api/endpoints/ActorTokenApi.ts","../src/api/endpoints/AccountlessApplicationsAPI.ts","../src/api/endpoints/AllowlistIdentifierApi.ts","../src/api/endpoints/APIKeysApi.ts","../src/api/endpoints/BetaFeaturesApi.ts","../src/api/endpoints/BlocklistIdentifierApi.ts","../src/api/endpoints/ClientApi.ts","../src/api/endpoints/DomainApi.ts","../src/api/endpoints/EmailAddressApi.ts","../src/api/endpoints/IdPOAuthAccessTokenApi.ts","../src/api/endpoints/InstanceApi.ts","../src/api/endpoints/InvitationApi.ts","../src/api/endpoints/MachineApi.ts","../src/api/endpoints/M2MTokenApi.ts","../src/api/endpoints/JwksApi.ts","../src/api/endpoints/JwtTemplatesApi.ts","../src/runtime.ts","../src/api/endpoints/OrganizationApi.ts","../src/api/endpoints/OAuthApplicationsApi.ts","../src/api/endpoints/PhoneNumberApi.ts","../src/api/endpoints/ProxyCheckApi.ts","../src/api/endpoints/RedirectUrlApi.ts","../src/api/endpoints/SamlConnectionApi.ts","../src/api/endpoints/SessionApi.ts","../src/api/endpoints/SignInTokenApi.ts","../src/api/endpoints/SignUpApi.ts","../src/api/endpoints/TestingTokenApi.ts","../src/util/shared.ts","../src/api/endpoints/UserApi.ts","../src/api/endpoints/WaitlistEntryApi.ts","../src/api/endpoints/WebhookApi.ts","../src/api/endpoints/BillingApi.ts","../src/api/request.ts","../../../node_modules/.pnpm/map-obj@5.0.2/node_modules/map-obj/index.js","../../../node_modules/.pnpm/change-case@5.4.4/node_modules/change-case/src/index.ts","../../../node_modules/.pnpm/snakecase-keys@9.0.2/node_modules/snakecase-keys/index.js","../src/constants.ts","../src/util/optionsAssertions.ts","../src/api/resources/AccountlessApplication.ts","../src/api/resources/ActorToken.ts","../src/api/resources/AllowlistIdentifier.ts","../src/api/resources/APIKey.ts","../src/api/resources/BlocklistIdentifier.ts","../src/api/resources/Session.ts","../src/api/resources/Client.ts","../src/api/resources/CnameTarget.ts","../src/api/resources/Cookies.ts","../src/api/resources/DeletedObject.ts","../src/api/resources/Domain.ts","../src/api/resources/Email.ts","../src/api/resources/IdentificationLink.ts","../src/api/resources/Verification.ts","../src/api/resources/EmailAddress.ts","../src/api/resources/ExternalAccount.ts","../src/api/resources/IdPOAuthAccessToken.ts","../src/api/resources/Instance.ts","../src/api/resources/InstanceRestrictions.ts","../src/api/resources/InstanceSettings.ts","../src/api/resources/Invitation.ts","../src/api/resources/JSON.ts","../src/api/resources/Machine.ts","../src/api/resources/MachineScope.ts","../src/api/resources/MachineSecretKey.ts","../src/api/resources/M2MToken.ts","../src/api/resources/JwtTemplate.ts","../src/api/resources/OauthAccessToken.ts","../src/api/resources/OAuthApplication.ts","../src/api/resources/Organization.ts","../src/api/resources/OrganizationInvitation.ts","../src/api/resources/OrganizationMembership.ts","../src/api/resources/OrganizationSettings.ts","../src/api/resources/PhoneNumber.ts","../src/api/resources/ProxyCheck.ts","../src/api/resources/RedirectUrl.ts","../src/api/resources/SamlConnection.ts","../src/api/resources/SamlAccount.ts","../src/api/resources/SignInTokens.ts","../src/api/resources/SignUpAttempt.ts","../src/api/resources/SMSMessage.ts","../src/api/resources/Token.ts","../src/api/resources/Web3Wallet.ts","../src/api/resources/User.ts","../src/api/resources/WaitlistEntry.ts","../src/api/resources/Feature.ts","../src/api/resources/CommercePlan.ts","../src/api/resources/CommerceSubscriptionItem.ts","../src/api/resources/CommerceSubscription.ts","../src/api/resources/Deserializer.ts","../src/api/factory.ts","../src/jwt/legacyReturn.ts","../src/util/mergePreDefinedOptions.ts","../src/errors.ts","../src/util/rfc4648.ts","../src/jwt/algorithms.ts","../src/jwt/assertions.ts","../src/jwt/cryptoKeys.ts","../src/jwt/verifyJwt.ts","../src/tokens/authenticateContext.ts","../src/tokens/tokenTypes.ts","../src/tokens/authObjects.ts","../src/createRedirect.ts","../src/tokens/clerkRequest.ts","../src/tokens/clerkUrl.ts","../src/internal.ts","../src/tokens/verify.ts","../src/tokens/keys.ts","../src/tokens/machine.ts","../src/tokens/authStatus.ts","../src/tokens/cookie.ts","../src/tokens/handshake.ts","../src/tokens/organizationMatcher.ts","../src/tokens/request.ts","../src/tokens/factory.ts"],"sourcesContent":["import type { TelemetryCollectorOptions } from '@clerk/shared/telemetry';\nimport { TelemetryCollector } from '@clerk/shared/telemetry';\nimport type { SDKMetadata } from '@clerk/types';\n\nimport type { ApiClient, CreateBackendApiOptions } from './api';\nimport { createBackendApiClient } from './api';\nimport { withLegacyReturn } from './jwt/legacyReturn';\nimport type { CreateAuthenticateRequestOptions } from './tokens/factory';\nimport { createAuthenticateRequest } from './tokens/factory';\nimport { verifyToken as _verifyToken } from './tokens/verify';\n\nexport const verifyToken = withLegacyReturn(_verifyToken);\n\nexport type ClerkOptions = Omit &\n Partial<\n Pick<\n CreateAuthenticateRequestOptions['options'],\n 'audience' | 'jwtKey' | 'proxyUrl' | 'secretKey' | 'publishableKey' | 'domain' | 'isSatellite'\n >\n > & { sdkMetadata?: SDKMetadata; telemetry?: Pick };\n\n// The current exported type resolves the following issue in packages importing createClerkClient\n// TS4023: Exported variable 'clerkClient' has or is using name 'AuthErrorReason' from external module \"/packages/backend/dist/index\" but cannot be named.\nexport type ClerkClient = {\n telemetry: TelemetryCollector;\n} & ApiClient &\n ReturnType;\n\nexport function createClerkClient(options: ClerkOptions): ClerkClient {\n const opts = { ...options };\n const apiClient = createBackendApiClient(opts);\n const requestState = createAuthenticateRequest({ options: opts, apiClient });\n const telemetry = new TelemetryCollector({\n publishableKey: opts.publishableKey,\n secretKey: opts.secretKey,\n samplingRate: 0.1,\n ...(opts.sdkMetadata ? { sdk: opts.sdkMetadata.name, sdkVersion: opts.sdkMetadata.version } : {}),\n ...(opts.telemetry || {}),\n });\n\n return {\n ...apiClient,\n ...requestState,\n telemetry,\n };\n}\n\n/**\n * General Types\n */\nexport type { OrganizationMembershipRole } from './api/resources';\nexport type { VerifyTokenOptions } from './tokens/verify';\n/**\n * JSON types\n */\nexport type {\n ActorTokenJSON,\n AccountlessApplicationJSON,\n ClerkResourceJSON,\n TokenJSON,\n AllowlistIdentifierJSON,\n BlocklistIdentifierJSON,\n ClientJSON,\n CnameTargetJSON,\n DomainJSON,\n EmailJSON,\n EmailAddressJSON,\n ExternalAccountJSON,\n IdentificationLinkJSON,\n InstanceJSON,\n InstanceRestrictionsJSON,\n InstanceSettingsJSON,\n InvitationJSON,\n JwtTemplateJSON,\n OauthAccessTokenJSON,\n OAuthApplicationJSON,\n OrganizationJSON,\n OrganizationDomainJSON,\n OrganizationDomainVerificationJSON,\n OrganizationInvitationJSON,\n OrganizationSettingsJSON,\n PublicOrganizationDataJSON,\n OrganizationMembershipJSON,\n OrganizationMembershipPublicUserDataJSON,\n PhoneNumberJSON,\n ProxyCheckJSON,\n RedirectUrlJSON,\n SessionJSON,\n SignInJSON,\n SignInTokenJSON,\n SignUpJSON,\n SignUpVerificationJSON,\n SignUpVerificationsJSON,\n SMSMessageJSON,\n UserJSON,\n VerificationJSON,\n WaitlistEntryJSON,\n Web3WalletJSON,\n DeletedObjectJSON,\n PaginatedResponseJSON,\n TestingTokenJSON,\n WebhooksSvixJSON,\n BillingPlanJSON,\n BillingSubscriptionJSON,\n BillingSubscriptionItemJSON,\n} from './api/resources/JSON';\n\n/**\n * Resources\n */\nexport type {\n APIKey,\n ActorToken,\n AccountlessApplication,\n AllowlistIdentifier,\n BlocklistIdentifier,\n Client,\n CnameTarget,\n Domain,\n EmailAddress,\n ExternalAccount,\n Feature,\n Instance,\n InstanceRestrictions,\n InstanceSettings,\n Invitation,\n JwtTemplate,\n Machine,\n M2MToken,\n OauthAccessToken,\n OAuthApplication,\n Organization,\n OrganizationDomain,\n OrganizationDomainVerification,\n OrganizationInvitation,\n OrganizationMembership,\n OrganizationMembershipPublicUserData,\n OrganizationSettings,\n PhoneNumber,\n SamlConnection,\n Session,\n SignInToken,\n SignUpAttempt,\n SMSMessage,\n Token,\n User,\n TestingToken,\n BillingPlan,\n BillingSubscription,\n BillingSubscriptionItem,\n} from './api/resources';\n\n/**\n * Webhooks event types\n */\nexport type {\n EmailWebhookEvent,\n OrganizationWebhookEvent,\n OrganizationDomainWebhookEvent,\n OrganizationInvitationWebhookEvent,\n OrganizationMembershipWebhookEvent,\n RoleWebhookEvent,\n PermissionWebhookEvent,\n SessionWebhookEvent,\n SMSWebhookEvent,\n UserWebhookEvent,\n WaitlistEntryWebhookEvent,\n WebhookEvent,\n WebhookEventType,\n BillingPaymentAttemptWebhookEvent,\n BillingSubscriptionWebhookEvent,\n BillingSubscriptionItemWebhookEvent,\n} from './api/resources/Webhooks';\n\n/**\n * Auth objects\n */\nexport type { AuthObject, InvalidTokenAuthObject } from './tokens/authObjects';\nexport type { SessionAuthObject, MachineAuthObject } from './tokens/types';\n","const SEPARATOR = '/';\nconst MULTIPLE_SEPARATOR_REGEX = new RegExp('(? p)\n .join(SEPARATOR)\n .replace(MULTIPLE_SEPARATOR_REGEX, SEPARATOR);\n}\n","import type { RequestFunction } from '../request';\n\nexport abstract class AbstractAPI {\n constructor(protected request: RequestFunction) {}\n\n protected requireId(id: string) {\n if (!id) {\n throw new Error('A valid resource ID is required.');\n }\n }\n}\n","import { joinPaths } from '../../util/path';\nimport type { ActorToken } from '../resources/ActorToken';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/actor_tokens';\n\ntype ActorTokenActorCreateParams = {\n /**\n * The ID of the actor.\n */\n sub: string;\n /**\n * Additional properties of the actor.\n */\n additionalProperties?: { [k: string]: any };\n};\n\ntype ActorTokenCreateParams = {\n /**\n * The ID of the user being impersonated.\n */\n userId: string;\n /**\n * The actor payload. It needs to include a sub property which should contain the ID of the actor.\n *\n * @remarks\n * This whole payload will be also included in the JWT session token.\n */\n actor: ActorTokenActorCreateParams;\n /**\n * Optional parameter to specify the life duration of the actor token in seconds.\n *\n * @remarks\n * By default, the duration is 1 hour.\n */\n expiresInSeconds?: number | undefined;\n /**\n * The maximum duration that the session which will be created by the generated actor token should last.\n *\n * @remarks\n * By default, the duration of a session created via an actor token, lasts 30 minutes.\n */\n sessionMaxDurationInSeconds?: number | undefined;\n};\n\nexport class ActorTokenAPI extends AbstractAPI {\n public async create(params: ActorTokenCreateParams) {\n return this.request({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async revoke(actorTokenId: string) {\n this.requireId(actorTokenId);\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, actorTokenId, 'revoke'),\n });\n }\n}\n","import { joinPaths } from '../../util/path';\nimport type { AccountlessApplication } from '../resources/AccountlessApplication';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/accountless_applications';\n\nexport class AccountlessApplicationAPI extends AbstractAPI {\n public async createAccountlessApplication(params?: { requestHeaders?: Headers }) {\n const headerParams = params?.requestHeaders ? Object.fromEntries(params.requestHeaders.entries()) : undefined;\n return this.request({\n method: 'POST',\n path: basePath,\n headerParams,\n });\n }\n\n public async completeAccountlessApplicationOnboarding(params?: { requestHeaders?: Headers }) {\n const headerParams = params?.requestHeaders ? Object.fromEntries(params.requestHeaders.entries()) : undefined;\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, 'complete'),\n headerParams,\n });\n }\n}\n","import type { ClerkPaginationRequest } from '@clerk/types';\n\nimport { joinPaths } from '../../util/path';\nimport type { AllowlistIdentifier } from '../resources/AllowlistIdentifier';\nimport type { DeletedObject } from '../resources/DeletedObject';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/allowlist_identifiers';\n\ntype AllowlistIdentifierCreateParams = {\n identifier: string;\n notify: boolean;\n};\n\nexport class AllowlistIdentifierAPI extends AbstractAPI {\n public async getAllowlistIdentifierList(params: ClerkPaginationRequest = {}) {\n return this.request>({\n method: 'GET',\n path: basePath,\n queryParams: { ...params, paginated: true },\n });\n }\n\n public async createAllowlistIdentifier(params: AllowlistIdentifierCreateParams) {\n return this.request({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async deleteAllowlistIdentifier(allowlistIdentifierId: string) {\n this.requireId(allowlistIdentifierId);\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, allowlistIdentifierId),\n });\n }\n}\n","import { joinPaths } from '../../util/path';\nimport type { APIKey } from '../resources/APIKey';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/api_keys';\n\ntype CreateAPIKeyParams = {\n type?: 'api_key';\n /**\n * API key name\n */\n name: string;\n /**\n * user or organization ID the API key is associated with\n */\n subject: string;\n /**\n * API key description\n */\n description?: string | null;\n claims?: Record | null;\n scopes?: string[];\n createdBy?: string | null;\n secondsUntilExpiration?: number | null;\n};\n\ntype RevokeAPIKeyParams = {\n /**\n * API key ID\n */\n apiKeyId: string;\n /**\n * Reason for revocation\n */\n revocationReason?: string | null;\n};\n\nexport class APIKeysAPI extends AbstractAPI {\n async create(params: CreateAPIKeyParams) {\n return this.request({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n async revoke(params: RevokeAPIKeyParams) {\n const { apiKeyId, ...bodyParams } = params;\n\n this.requireId(apiKeyId);\n\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, apiKeyId, 'revoke'),\n bodyParams,\n });\n }\n\n async getSecret(apiKeyId: string) {\n this.requireId(apiKeyId);\n\n return this.request<{ secret: string }>({\n method: 'GET',\n path: joinPaths(basePath, apiKeyId, 'secret'),\n });\n }\n\n async verifySecret(secret: string) {\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, 'verify'),\n bodyParams: { secret },\n });\n }\n}\n","import { joinPaths } from '../../util/path';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/beta_features';\n\ntype ChangeDomainParams = {\n /**\n * The new home URL of the production instance e.g. https://www.example.com\n */\n homeUrl?: string;\n /**\n * Whether this is a domain for a secondary app, meaning that any subdomain\n * provided is significant and will be stored as part of the domain. This is\n * useful for supporting multiple apps (one primary and multiple secondaries)\n * on the same root domain (eTLD+1).\n */\n isSecondary?: boolean;\n};\n\nexport class BetaFeaturesAPI extends AbstractAPI {\n /**\n * Change the domain of a production instance.\n *\n * Changing the domain requires updating the DNS records accordingly, deploying new SSL certificates,\n * updating your Social Connection's redirect URLs and setting the new keys in your code.\n *\n * @remarks\n * WARNING: Changing your domain will invalidate all current user sessions (i.e. users will be logged out).\n * Also, while your application is being deployed, a small downtime is expected to occur.\n */\n public async changeDomain(params: ChangeDomainParams) {\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, 'change_domain'),\n bodyParams: params,\n });\n }\n}\n","import type { ClerkPaginationRequest } from '@clerk/types';\n\nimport { joinPaths } from '../../util/path';\nimport type { BlocklistIdentifier } from '../resources/BlocklistIdentifier';\nimport type { DeletedObject } from '../resources/DeletedObject';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/blocklist_identifiers';\n\ntype BlocklistIdentifierCreateParams = {\n identifier: string;\n};\n\nexport class BlocklistIdentifierAPI extends AbstractAPI {\n public async getBlocklistIdentifierList(params: ClerkPaginationRequest = {}) {\n return this.request>({\n method: 'GET',\n path: basePath,\n queryParams: params,\n });\n }\n\n public async createBlocklistIdentifier(params: BlocklistIdentifierCreateParams) {\n return this.request({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async deleteBlocklistIdentifier(blocklistIdentifierId: string) {\n this.requireId(blocklistIdentifierId);\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, blocklistIdentifierId),\n });\n }\n}\n","import type { ClerkPaginationRequest } from '@clerk/types';\n\nimport { joinPaths } from '../../util/path';\nimport type { Client } from '../resources/Client';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport type { HandshakePayload } from '../resources/HandshakePayload';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/clients';\n\ntype GetHandshakePayloadParams = {\n nonce: string;\n};\n\nexport class ClientAPI extends AbstractAPI {\n public async getClientList(params: ClerkPaginationRequest = {}) {\n return this.request>({\n method: 'GET',\n path: basePath,\n queryParams: { ...params, paginated: true },\n });\n }\n\n public async getClient(clientId: string) {\n this.requireId(clientId);\n return this.request({\n method: 'GET',\n path: joinPaths(basePath, clientId),\n });\n }\n\n public verifyClient(token: string) {\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, 'verify'),\n bodyParams: { token },\n });\n }\n\n public async getHandshakePayload(queryParams: GetHandshakePayloadParams) {\n return this.request({\n method: 'GET',\n path: joinPaths(basePath, 'handshake_payload'),\n queryParams,\n });\n }\n}\n","import { joinPaths } from '../../util/path';\nimport type { DeletedObject } from '../resources/DeletedObject';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport type { Domain } from '../resources/Domain';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/domains';\n\ntype AddDomainParams = {\n /**\n * The new domain name. For development instances, can contain the port, i.e myhostname:3000. For production instances, must be a valid FQDN, i.e mysite.com. Cannot contain protocol scheme.\n */\n name: string;\n /**\n * Marks the new domain as satellite. Only true is accepted at the moment.\n */\n is_satellite: boolean;\n /**\n * The full URL of the proxy which will forward requests to the Clerk Frontend API for this domain. Applicable only to production instances.\n */\n proxy_url?: string | null;\n};\n\ntype UpdateDomainParams = Partial> & {\n /**\n * The ID of the domain that will be updated.\n */\n domainId: string;\n /**\n * Whether this is a domain for a secondary app, meaning that any subdomain provided is significant\n * and will be stored as part of the domain. This is useful for supporting multiple apps\n * (one primary and multiple secondaries) on the same root domain (eTLD+1).\n */\n is_secondary?: boolean | null;\n};\n\nexport class DomainAPI extends AbstractAPI {\n public async list() {\n return this.request>({\n method: 'GET',\n path: basePath,\n });\n }\n\n public async add(params: AddDomainParams) {\n return this.request({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async update(params: UpdateDomainParams) {\n const { domainId, ...bodyParams } = params;\n\n this.requireId(domainId);\n\n return this.request({\n method: 'PATCH',\n path: joinPaths(basePath, domainId),\n bodyParams: bodyParams,\n });\n }\n\n /**\n * Deletes a satellite domain for the instance.\n * It is currently not possible to delete the instance's primary domain.\n */\n public async delete(satelliteDomainId: string) {\n return this.deleteDomain(satelliteDomainId);\n }\n\n /**\n * @deprecated Use `delete` instead\n */\n public async deleteDomain(satelliteDomainId: string) {\n this.requireId(satelliteDomainId);\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, satelliteDomainId),\n });\n }\n}\n","import { joinPaths } from '../../util/path';\nimport type { DeletedObject, EmailAddress } from '../resources';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/email_addresses';\n\ntype CreateEmailAddressParams = {\n userId: string;\n emailAddress: string;\n verified?: boolean;\n primary?: boolean;\n};\n\ntype UpdateEmailAddressParams = {\n verified?: boolean;\n primary?: boolean;\n};\n\nexport class EmailAddressAPI extends AbstractAPI {\n public async getEmailAddress(emailAddressId: string) {\n this.requireId(emailAddressId);\n\n return this.request({\n method: 'GET',\n path: joinPaths(basePath, emailAddressId),\n });\n }\n\n public async createEmailAddress(params: CreateEmailAddressParams) {\n return this.request({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async updateEmailAddress(emailAddressId: string, params: UpdateEmailAddressParams = {}) {\n this.requireId(emailAddressId);\n\n return this.request({\n method: 'PATCH',\n path: joinPaths(basePath, emailAddressId),\n bodyParams: params,\n });\n }\n\n public async deleteEmailAddress(emailAddressId: string) {\n this.requireId(emailAddressId);\n\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, emailAddressId),\n });\n }\n}\n","import { joinPaths } from '../../util/path';\nimport type { IdPOAuthAccessToken } from '../resources';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/oauth_applications/access_tokens';\n\nexport class IdPOAuthAccessTokenApi extends AbstractAPI {\n async verifyAccessToken(accessToken: string) {\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, 'verify'),\n bodyParams: { access_token: accessToken },\n });\n }\n}\n","import { joinPaths } from '../../util/path';\nimport type { Instance } from '../resources/Instance';\nimport type { InstanceRestrictions } from '../resources/InstanceRestrictions';\nimport type { OrganizationSettings } from '../resources/OrganizationSettings';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/instance';\n\ntype UpdateParams = {\n /**\n * Toggles test mode for this instance, allowing the use of test email addresses and phone numbers.\n *\n * @remarks Defaults to true for development instances.\n */\n testMode?: boolean | null | undefined;\n /**\n * Whether the instance should be using the HIBP service to check passwords for breaches\n */\n hibp?: boolean | null | undefined;\n /**\n * The \"enhanced_email_deliverability\" feature will send emails from \"verifications@clerk.dev\" instead of your domain.\n *\n * @remarks This can be helpful if you do not have a high domain reputation.\n */\n enhancedEmailDeliverability?: boolean | null | undefined;\n supportEmail?: string | null | undefined;\n clerkJsVersion?: string | null | undefined;\n developmentOrigin?: string | null | undefined;\n /**\n * For browser-like stacks such as browser extensions, Electron, or Capacitor.js the instance allowed origins need to be updated with the request origin value.\n *\n * @remarks For Chrome extensions popup, background, or service worker pages the origin is chrome-extension://extension_uiid. For Electron apps the default origin is http://localhost:3000. For Capacitor, the origin is capacitor://localhost.\n */\n allowedOrigins?: Array | undefined;\n /**\n * Whether the instance should use URL-based session syncing in development mode (i.e. without third-party cookies).\n */\n urlBasedSessionSyncing?: boolean | null | undefined;\n};\n\ntype UpdateRestrictionsParams = {\n allowlist?: boolean | null | undefined;\n blocklist?: boolean | null | undefined;\n blockEmailSubaddresses?: boolean | null | undefined;\n blockDisposableEmailDomains?: boolean | null | undefined;\n ignoreDotsForGmailAddresses?: boolean | null | undefined;\n};\n\ntype UpdateOrganizationSettingsParams = {\n enabled?: boolean | null | undefined;\n maxAllowedMemberships?: number | null | undefined;\n adminDeleteEnabled?: boolean | null | undefined;\n domainsEnabled?: boolean | null | undefined;\n /**\n * Specifies which [enrollment modes](https://clerk.com/docs/organizations/verified-domains#enrollment-mode) to enable for your Organization Domains.\n *\n * @remarks Supported modes are 'automatic_invitation' & 'automatic_suggestion'.\n */\n domainsEnrollmentModes?: Array | undefined;\n /**\n * Specifies what the default organization role is for an organization creator.\n */\n creatorRoleId?: string | null | undefined;\n /**\n * Specifies what the default organization role is for the organization domains.\n */\n domainsDefaultRoleId?: string | null | undefined;\n};\n\nexport class InstanceAPI extends AbstractAPI {\n public async get() {\n return this.request({\n method: 'GET',\n path: basePath,\n });\n }\n\n public async update(params: UpdateParams) {\n return this.request({\n method: 'PATCH',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async updateRestrictions(params: UpdateRestrictionsParams) {\n return this.request({\n method: 'PATCH',\n path: joinPaths(basePath, 'restrictions'),\n bodyParams: params,\n });\n }\n\n public async updateOrganizationSettings(params: UpdateOrganizationSettingsParams) {\n return this.request({\n method: 'PATCH',\n path: joinPaths(basePath, 'organization_settings'),\n bodyParams: params,\n });\n }\n}\n","import type { ClerkPaginationRequest } from '@clerk/types';\n\nimport { joinPaths } from '../../util/path';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport type { InvitationStatus } from '../resources/Enums';\nimport type { Invitation } from '../resources/Invitation';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/invitations';\n\ntype TemplateSlug = 'invitation' | 'waitlist_invitation';\n\ntype CreateParams = {\n emailAddress: string;\n expiresInDays?: number;\n ignoreExisting?: boolean;\n notify?: boolean;\n publicMetadata?: UserPublicMetadata;\n redirectUrl?: string;\n templateSlug?: TemplateSlug;\n};\n\ntype CreateBulkParams = Array;\n\ntype GetInvitationListParams = ClerkPaginationRequest<{\n /**\n * Filters invitations based on their status.\n *\n * @example\n * Get all revoked invitations\n * ```ts\n * import { createClerkClient } from '@clerk/backend';\n * const clerkClient = createClerkClient(...)\n * await clerkClient.invitations.getInvitationList({ status: 'revoked' })\n * ```\n */\n status?: InvitationStatus;\n /**\n * Filters invitations based on `email_address` or `id`.\n *\n * @example\n * Get all invitations for a specific email address\n * ```ts\n * import { createClerkClient } from '@clerk/backend';\n * const clerkClient = createClerkClient(...)\n * await clerkClient.invitations.getInvitationList({ query: 'user@example.com' })\n * ```\n */\n query?: string;\n}>;\n\nexport class InvitationAPI extends AbstractAPI {\n public async getInvitationList(params: GetInvitationListParams = {}) {\n return this.request>({\n method: 'GET',\n path: basePath,\n queryParams: { ...params, paginated: true },\n });\n }\n\n public async createInvitation(params: CreateParams) {\n return this.request({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async createInvitationBulk(params: CreateBulkParams) {\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, 'bulk'),\n bodyParams: params,\n });\n }\n\n public async revokeInvitation(invitationId: string) {\n this.requireId(invitationId);\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, invitationId, 'revoke'),\n });\n }\n}\n","import type { ClerkPaginationRequest } from '@clerk/types';\n\nimport { joinPaths } from '../../util/path';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport type { Machine } from '../resources/Machine';\nimport type { MachineScope } from '../resources/MachineScope';\nimport type { MachineSecretKey } from '../resources/MachineSecretKey';\nimport { AbstractAPI } from './AbstractApi';\nimport type { WithSign } from './util-types';\n\nconst basePath = '/machines';\n\ntype CreateMachineParams = {\n /**\n * The name of the machine.\n */\n name: string;\n /**\n * Array of machine IDs that this machine will have access to.\n */\n scopedMachines?: string[];\n /**\n * The default time-to-live (TTL) in seconds for tokens created by this machine.\n */\n defaultTokenTtl?: number;\n};\n\ntype UpdateMachineParams = {\n /**\n * The ID of the machine to update.\n */\n machineId: string;\n /**\n * The name of the machine.\n */\n name?: string;\n /**\n * The default time-to-live (TTL) in seconds for tokens created by this machine.\n */\n defaultTokenTtl?: number;\n};\n\ntype GetMachineListParams = ClerkPaginationRequest<{\n /**\n * Sorts machines by name or created_at.\n * By prepending one of those values with + or -, we can choose to sort in ascending (ASC) or descending (DESC) order.\n */\n orderBy?: WithSign<'name' | 'created_at'>;\n /**\n * Returns machines that have a ID or name that matches the given query.\n */\n query?: string;\n}>;\n\ntype RotateMachineSecretKeyParams = {\n /**\n * The ID of the machine to rotate the secret key for.\n */\n machineId: string;\n /**\n * The time in seconds that the previous secret key will remain valid after rotation.\n */\n previousTokenTtl: number;\n};\n\nexport class MachineApi extends AbstractAPI {\n async get(machineId: string) {\n this.requireId(machineId);\n return this.request({\n method: 'GET',\n path: joinPaths(basePath, machineId),\n });\n }\n\n async list(queryParams: GetMachineListParams = {}) {\n return this.request>({\n method: 'GET',\n path: basePath,\n queryParams,\n });\n }\n\n async create(bodyParams: CreateMachineParams) {\n return this.request({\n method: 'POST',\n path: basePath,\n bodyParams,\n });\n }\n\n async update(params: UpdateMachineParams) {\n const { machineId, ...bodyParams } = params;\n this.requireId(machineId);\n return this.request({\n method: 'PATCH',\n path: joinPaths(basePath, machineId),\n bodyParams,\n });\n }\n\n async delete(machineId: string) {\n this.requireId(machineId);\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, machineId),\n });\n }\n\n async getSecretKey(machineId: string) {\n this.requireId(machineId);\n return this.request({\n method: 'GET',\n path: joinPaths(basePath, machineId, 'secret_key'),\n });\n }\n\n async rotateSecretKey(params: RotateMachineSecretKeyParams) {\n const { machineId, previousTokenTtl } = params;\n this.requireId(machineId);\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, machineId, 'secret_key', 'rotate'),\n bodyParams: {\n previousTokenTtl,\n },\n });\n }\n\n /**\n * Creates a new machine scope, allowing the specified machine to access another machine.\n *\n * @param machineId - The ID of the machine that will have access to another machine.\n * @param toMachineId - The ID of the machine that will be scoped to the current machine.\n */\n async createScope(machineId: string, toMachineId: string) {\n this.requireId(machineId);\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, machineId, 'scopes'),\n bodyParams: {\n toMachineId,\n },\n });\n }\n\n /**\n * Deletes a machine scope, removing access from one machine to another.\n *\n * @param machineId - The ID of the machine that has access to another machine.\n * @param otherMachineId - The ID of the machine that is being accessed.\n */\n async deleteScope(machineId: string, otherMachineId: string) {\n this.requireId(machineId);\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, machineId, 'scopes', otherMachineId),\n });\n }\n}\n","import { joinPaths } from '../../util/path';\nimport type { ClerkBackendApiRequestOptions } from '../request';\nimport type { M2MToken } from '../resources/M2MToken';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/m2m_tokens';\n\ntype CreateM2MTokenParams = {\n /**\n * Custom machine secret key for authentication.\n */\n machineSecretKey?: string;\n /**\n * Number of seconds until the token expires.\n *\n * @default null - Token does not expire\n */\n secondsUntilExpiration?: number | null;\n claims?: Record | null;\n};\n\ntype RevokeM2MTokenParams = {\n /**\n * Custom machine secret key for authentication.\n */\n machineSecretKey?: string;\n /**\n * Machine-to-machine token ID to revoke.\n */\n m2mTokenId: string;\n revocationReason?: string | null;\n};\n\ntype VerifyM2MTokenParams = {\n /**\n * Custom machine secret key for authentication.\n */\n machineSecretKey?: string;\n /**\n * Machine-to-machine token to verify.\n */\n token: string;\n};\n\nexport class M2MTokenApi extends AbstractAPI {\n #createRequestOptions(options: ClerkBackendApiRequestOptions, machineSecretKey?: string) {\n if (machineSecretKey) {\n return {\n ...options,\n headerParams: {\n ...options.headerParams,\n Authorization: `Bearer ${machineSecretKey}`,\n },\n };\n }\n\n return options;\n }\n\n async createToken(params?: CreateM2MTokenParams) {\n const { claims = null, machineSecretKey, secondsUntilExpiration = null } = params || {};\n\n const requestOptions = this.#createRequestOptions(\n {\n method: 'POST',\n path: basePath,\n bodyParams: {\n secondsUntilExpiration,\n claims,\n },\n },\n machineSecretKey,\n );\n\n return this.request(requestOptions);\n }\n\n async revokeToken(params: RevokeM2MTokenParams) {\n const { m2mTokenId, revocationReason = null, machineSecretKey } = params;\n\n this.requireId(m2mTokenId);\n\n const requestOptions = this.#createRequestOptions(\n {\n method: 'POST',\n path: joinPaths(basePath, m2mTokenId, 'revoke'),\n bodyParams: {\n revocationReason,\n },\n },\n machineSecretKey,\n );\n\n return this.request(requestOptions);\n }\n\n async verifyToken(params: VerifyM2MTokenParams) {\n const { token, machineSecretKey } = params;\n\n const requestOptions = this.#createRequestOptions(\n {\n method: 'POST',\n path: joinPaths(basePath, 'verify'),\n bodyParams: { token },\n },\n machineSecretKey,\n );\n\n return this.request(requestOptions);\n }\n}\n","import type { JwksJSON } from '../resources/JSON';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/jwks';\n\nexport class JwksAPI extends AbstractAPI {\n public async getJwks() {\n return this.request({\n method: 'GET',\n path: basePath,\n });\n }\n}\n","import type { ClerkPaginationRequest } from '@clerk/types';\nimport { joinPaths } from 'src/util/path';\n\nimport type { DeletedObject, JwtTemplate } from '../resources';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/jwt_templates';\n\ntype Claims = object;\n\ntype CreateJWTTemplateParams = {\n /**\n * JWT template name\n */\n name: string;\n /**\n * JWT template claims in JSON format\n */\n claims: Claims;\n /**\n * JWT token lifetime\n */\n lifetime?: number | null | undefined;\n /**\n * JWT token allowed clock skew\n */\n allowedClockSkew?: number | null | undefined;\n /**\n * Whether a custom signing key/algorithm is also provided for this template\n */\n customSigningKey?: boolean | undefined;\n /**\n * The custom signing algorithm to use when minting JWTs. Required if `custom_signing_key` is `true`.\n */\n signingAlgorithm?: string | null | undefined;\n /**\n * The custom signing private key to use when minting JWTs. Required if `custom_signing_key` is `true`.\n */\n signingKey?: string | null | undefined;\n};\n\ntype UpdateJWTTemplateParams = CreateJWTTemplateParams & {\n /**\n * JWT template ID\n */\n templateId: string;\n};\n\nexport class JwtTemplatesApi extends AbstractAPI {\n public async list(params: ClerkPaginationRequest = {}) {\n return this.request({\n method: 'GET',\n path: basePath,\n queryParams: { ...params, paginated: true },\n });\n }\n\n public async get(templateId: string) {\n this.requireId(templateId);\n\n return this.request({\n method: 'GET',\n path: joinPaths(basePath, templateId),\n });\n }\n\n public async create(params: CreateJWTTemplateParams) {\n return this.request({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async update(params: UpdateJWTTemplateParams) {\n const { templateId, ...bodyParams } = params;\n\n this.requireId(templateId);\n return this.request({\n method: 'PATCH',\n path: joinPaths(basePath, templateId),\n bodyParams,\n });\n }\n\n public async delete(templateId: string) {\n this.requireId(templateId);\n\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, templateId),\n });\n }\n}\n","/**\n * This file exports APIs that vary across runtimes (i.e. Node & Browser - V8 isolates)\n * as a singleton object.\n *\n * Runtime polyfills are written in VanillaJS for now to avoid TS complication. Moreover,\n * due to this issue https://github.com/microsoft/TypeScript/issues/44848, there is not a good way\n * to tell Typescript which conditional import to use during build type.\n *\n * The Runtime type definition ensures type safety for now.\n * Runtime js modules are copied into dist folder with bash script.\n *\n * TODO: Support TS runtime modules\n */\n\n// @ts-ignore - These are package subpaths\nimport { webcrypto as crypto } from '#crypto';\n\ntype Runtime = {\n crypto: Crypto;\n fetch: typeof globalThis.fetch;\n AbortController: typeof globalThis.AbortController;\n Blob: typeof globalThis.Blob;\n FormData: typeof globalThis.FormData;\n Headers: typeof globalThis.Headers;\n Request: typeof globalThis.Request;\n Response: typeof globalThis.Response;\n};\n\n// Invoking the global.fetch without binding it first to the globalObject fails in\n// Cloudflare Workers with an \"Illegal Invocation\" error.\n//\n// The globalThis object is supported for Node >= 12.0.\n//\n// https://github.com/supabase/supabase/issues/4417\nconst globalFetch = fetch.bind(globalThis);\n\nexport const runtime: Runtime = {\n crypto,\n get fetch() {\n // We need to use the globalFetch for Cloudflare Workers but the fetch for testing\n return process.env.NODE_ENV === 'test' ? fetch : globalFetch;\n },\n AbortController: globalThis.AbortController,\n Blob: globalThis.Blob,\n FormData: globalThis.FormData,\n Headers: globalThis.Headers,\n Request: globalThis.Request,\n Response: globalThis.Response,\n};\n","import type { ClerkPaginationRequest, OrganizationEnrollmentMode } from '@clerk/types';\n\nimport { runtime } from '../../runtime';\nimport { joinPaths } from '../../util/path';\nimport type {\n Organization,\n OrganizationDomain,\n OrganizationInvitation,\n OrganizationInvitationStatus,\n OrganizationMembership,\n} from '../resources';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport type { OrganizationMembershipRole } from '../resources/Enums';\nimport { AbstractAPI } from './AbstractApi';\nimport type { WithSign } from './util-types';\n\nconst basePath = '/organizations';\n\ntype MetadataParams = {\n publicMetadata?: TPublic;\n privateMetadata?: TPrivate;\n};\n\ntype GetOrganizationListParams = ClerkPaginationRequest<{\n includeMembersCount?: boolean;\n query?: string;\n orderBy?: WithSign<'name' | 'created_at' | 'members_count'>;\n organizationId?: string[];\n}>;\n\ntype CreateParams = {\n name: string;\n slug?: string;\n /* The User id for the user creating the organization. The user will become an administrator for the organization. */\n createdBy?: string;\n maxAllowedMemberships?: number;\n} & MetadataParams;\n\ntype GetOrganizationParams = ({ organizationId: string } | { slug: string }) & {\n includeMembersCount?: boolean;\n};\n\ntype UpdateParams = {\n name?: string;\n slug?: string;\n maxAllowedMemberships?: number;\n} & MetadataParams;\n\ntype UpdateLogoParams = {\n file: Blob | File;\n uploaderUserId?: string;\n};\n\ntype UpdateMetadataParams = MetadataParams;\n\ntype GetOrganizationMembershipListParams = ClerkPaginationRequest<{\n organizationId: string;\n\n /**\n * Sorts organizations memberships by phone_number, email_address, created_at, first_name, last_name or username.\n * By prepending one of those values with + or -, we can choose to sort in ascending (ASC) or descending (DESC) order.\n */\n orderBy?: WithSign<'phone_number' | 'email_address' | 'created_at' | 'first_name' | 'last_name' | 'username'>;\n\n /**\n * Returns users with the user ids specified. For each user id, the `+` and `-` can be\n * prepended to the id, which denote whether the respective user id should be included or\n * excluded from the result set. Accepts up to 100 user ids. Any user ids not found are ignored.\n */\n userId?: string[];\n\n /* Returns users with the specified email addresses. Accepts up to 100 email addresses. Any email addresses not found are ignored. */\n emailAddress?: string[];\n\n /* Returns users with the specified phone numbers. Accepts up to 100 phone numbers. Any phone numbers not found are ignored. */\n phoneNumber?: string[];\n\n /* Returns users with the specified usernames. Accepts up to 100 usernames. Any usernames not found are ignored. */\n username?: string[];\n\n /* Returns users with the specified web3 wallet addresses. Accepts up to 100 web3 wallet addresses. Any web3 wallet addressed not found are ignored. */\n web3Wallet?: string[];\n\n /* Returns users with the specified roles. Accepts up to 100 roles. Any roles not found are ignored. */\n role?: OrganizationMembershipRole[];\n\n /**\n * Returns users that match the given query.\n * For possible matches, we check the email addresses, phone numbers, usernames, web3 wallets, user ids, first and last names.\n * The query value doesn't need to match the exact value you are looking for, it is capable of partial matches as well.\n */\n query?: string;\n\n /**\n * Returns users with emails that match the given query, via case-insensitive partial match.\n * For example, `email_address_query=ello` will match a user with the email `HELLO@example.com`.\n */\n emailAddressQuery?: string;\n\n /**\n * Returns users with phone numbers that match the given query, via case-insensitive partial match.\n * For example, `phone_number_query=555` will match a user with the phone number `+1555xxxxxxx`.\n */\n phoneNumberQuery?: string;\n\n /**\n * Returns users with usernames that match the given query, via case-insensitive partial match.\n * For example, `username_query=CoolUser` will match a user with the username `SomeCoolUser`.\n */\n usernameQuery?: string;\n\n /* Returns users with names that match the given query, via case-insensitive partial match. */\n nameQuery?: string;\n\n /**\n * Returns users whose last session activity was before the given date (with millisecond precision).\n * Example: use 1700690400000 to retrieve users whose last session activity was before 2023-11-23.\n */\n lastActiveAtBefore?: number;\n /**\n * Returns users whose last session activity was after the given date (with millisecond precision).\n * Example: use 1700690400000 to retrieve users whose last session activity was after 2023-11-23.\n */\n lastActiveAtAfter?: number;\n\n /**\n * Returns users who have been created before the given date (with millisecond precision).\n * Example: use 1730160000000 to retrieve users who have been created before 2024-10-29.\n */\n createdAtBefore?: number;\n\n /**\n * Returns users who have been created after the given date (with millisecond precision).\n * Example: use 1730160000000 to retrieve users who have been created after 2024-10-29.\n */\n createdAtAfter?: number;\n}>;\n\ntype GetInstanceOrganizationMembershipListParams = ClerkPaginationRequest<{\n /**\n * Sorts organizations memberships by phone_number, email_address, created_at, first_name, last_name or username.\n * By prepending one of those values with + or -, we can choose to sort in ascending (ASC) or descending (DESC) order.\n */\n orderBy?: WithSign<'phone_number' | 'email_address' | 'created_at' | 'first_name' | 'last_name' | 'username'>;\n}>;\n\ntype CreateOrganizationMembershipParams = {\n organizationId: string;\n userId: string;\n role: OrganizationMembershipRole;\n};\n\ntype UpdateOrganizationMembershipParams = CreateOrganizationMembershipParams;\n\ntype UpdateOrganizationMembershipMetadataParams = {\n organizationId: string;\n userId: string;\n} & MetadataParams;\n\ntype DeleteOrganizationMembershipParams = {\n organizationId: string;\n userId: string;\n};\n\ntype CreateOrganizationInvitationParams = {\n organizationId: string;\n emailAddress: string;\n role: OrganizationMembershipRole;\n expiresInDays?: number;\n inviterUserId?: string;\n privateMetadata?: OrganizationInvitationPrivateMetadata;\n publicMetadata?: OrganizationInvitationPublicMetadata;\n redirectUrl?: string;\n};\n\ntype CreateBulkOrganizationInvitationParams = Array<{\n emailAddress: string;\n role: OrganizationMembershipRole;\n expiresInDays?: number;\n inviterUserId?: string;\n privateMetadata?: OrganizationInvitationPrivateMetadata;\n publicMetadata?: OrganizationInvitationPublicMetadata;\n redirectUrl?: string;\n}>;\n\ntype GetOrganizationInvitationListParams = ClerkPaginationRequest<{\n organizationId: string;\n status?: OrganizationInvitationStatus[];\n}>;\n\ntype GetOrganizationInvitationParams = {\n organizationId: string;\n invitationId: string;\n};\n\ntype RevokeOrganizationInvitationParams = {\n organizationId: string;\n invitationId: string;\n requestingUserId?: string;\n};\n\ntype GetOrganizationDomainListParams = {\n organizationId: string;\n limit?: number;\n offset?: number;\n};\n\ntype CreateOrganizationDomainParams = {\n organizationId: string;\n name: string;\n enrollmentMode: OrganizationEnrollmentMode;\n verified?: boolean;\n};\n\ntype UpdateOrganizationDomainParams = {\n organizationId: string;\n domainId: string;\n} & Partial;\n\ntype DeleteOrganizationDomainParams = {\n organizationId: string;\n domainId: string;\n};\n\nexport class OrganizationAPI extends AbstractAPI {\n public async getOrganizationList(params?: GetOrganizationListParams) {\n return this.request>({\n method: 'GET',\n path: basePath,\n queryParams: params,\n });\n }\n\n public async createOrganization(params: CreateParams) {\n return this.request({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async getOrganization(params: GetOrganizationParams) {\n const { includeMembersCount } = params;\n const organizationIdOrSlug = 'organizationId' in params ? params.organizationId : params.slug;\n this.requireId(organizationIdOrSlug);\n\n return this.request({\n method: 'GET',\n path: joinPaths(basePath, organizationIdOrSlug),\n queryParams: {\n includeMembersCount,\n },\n });\n }\n\n public async updateOrganization(organizationId: string, params: UpdateParams) {\n this.requireId(organizationId);\n return this.request({\n method: 'PATCH',\n path: joinPaths(basePath, organizationId),\n bodyParams: params,\n });\n }\n\n public async updateOrganizationLogo(organizationId: string, params: UpdateLogoParams) {\n this.requireId(organizationId);\n\n const formData = new runtime.FormData();\n formData.append('file', params?.file);\n if (params?.uploaderUserId) {\n formData.append('uploader_user_id', params?.uploaderUserId);\n }\n\n return this.request({\n method: 'PUT',\n path: joinPaths(basePath, organizationId, 'logo'),\n formData,\n });\n }\n\n public async deleteOrganizationLogo(organizationId: string) {\n this.requireId(organizationId);\n\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, organizationId, 'logo'),\n });\n }\n\n public async updateOrganizationMetadata(organizationId: string, params: UpdateMetadataParams) {\n this.requireId(organizationId);\n\n return this.request({\n method: 'PATCH',\n path: joinPaths(basePath, organizationId, 'metadata'),\n bodyParams: params,\n });\n }\n\n public async deleteOrganization(organizationId: string) {\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, organizationId),\n });\n }\n\n public async getOrganizationMembershipList(params: GetOrganizationMembershipListParams) {\n const { organizationId, ...queryParams } = params;\n this.requireId(organizationId);\n\n return this.request>({\n method: 'GET',\n path: joinPaths(basePath, organizationId, 'memberships'),\n queryParams,\n });\n }\n\n public async getInstanceOrganizationMembershipList(params: GetInstanceOrganizationMembershipListParams) {\n return this.request>({\n method: 'GET',\n path: '/organization_memberships',\n queryParams: params,\n });\n }\n\n public async createOrganizationMembership(params: CreateOrganizationMembershipParams) {\n const { organizationId, ...bodyParams } = params;\n this.requireId(organizationId);\n\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, organizationId, 'memberships'),\n bodyParams,\n });\n }\n\n public async updateOrganizationMembership(params: UpdateOrganizationMembershipParams) {\n const { organizationId, userId, ...bodyParams } = params;\n this.requireId(organizationId);\n\n return this.request({\n method: 'PATCH',\n path: joinPaths(basePath, organizationId, 'memberships', userId),\n bodyParams,\n });\n }\n\n public async updateOrganizationMembershipMetadata(params: UpdateOrganizationMembershipMetadataParams) {\n const { organizationId, userId, ...bodyParams } = params;\n\n return this.request({\n method: 'PATCH',\n path: joinPaths(basePath, organizationId, 'memberships', userId, 'metadata'),\n bodyParams,\n });\n }\n\n public async deleteOrganizationMembership(params: DeleteOrganizationMembershipParams) {\n const { organizationId, userId } = params;\n this.requireId(organizationId);\n\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, organizationId, 'memberships', userId),\n });\n }\n\n public async getOrganizationInvitationList(params: GetOrganizationInvitationListParams) {\n const { organizationId, ...queryParams } = params;\n this.requireId(organizationId);\n\n return this.request>({\n method: 'GET',\n path: joinPaths(basePath, organizationId, 'invitations'),\n queryParams,\n });\n }\n\n public async createOrganizationInvitation(params: CreateOrganizationInvitationParams) {\n const { organizationId, ...bodyParams } = params;\n this.requireId(organizationId);\n\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, organizationId, 'invitations'),\n bodyParams,\n });\n }\n\n public async createOrganizationInvitationBulk(\n organizationId: string,\n params: CreateBulkOrganizationInvitationParams,\n ) {\n this.requireId(organizationId);\n\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, organizationId, 'invitations', 'bulk'),\n bodyParams: params,\n });\n }\n\n public async getOrganizationInvitation(params: GetOrganizationInvitationParams) {\n const { organizationId, invitationId } = params;\n this.requireId(organizationId);\n this.requireId(invitationId);\n\n return this.request({\n method: 'GET',\n path: joinPaths(basePath, organizationId, 'invitations', invitationId),\n });\n }\n\n public async revokeOrganizationInvitation(params: RevokeOrganizationInvitationParams) {\n const { organizationId, invitationId, ...bodyParams } = params;\n this.requireId(organizationId);\n\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, organizationId, 'invitations', invitationId, 'revoke'),\n bodyParams,\n });\n }\n\n public async getOrganizationDomainList(params: GetOrganizationDomainListParams) {\n const { organizationId, ...queryParams } = params;\n this.requireId(organizationId);\n\n return this.request>({\n method: 'GET',\n path: joinPaths(basePath, organizationId, 'domains'),\n queryParams,\n });\n }\n\n public async createOrganizationDomain(params: CreateOrganizationDomainParams) {\n const { organizationId, ...bodyParams } = params;\n this.requireId(organizationId);\n\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, organizationId, 'domains'),\n bodyParams: {\n ...bodyParams,\n verified: bodyParams.verified ?? true,\n },\n });\n }\n\n public async updateOrganizationDomain(params: UpdateOrganizationDomainParams) {\n const { organizationId, domainId, ...bodyParams } = params;\n this.requireId(organizationId);\n this.requireId(domainId);\n\n return this.request({\n method: 'PATCH',\n path: joinPaths(basePath, organizationId, 'domains', domainId),\n bodyParams,\n });\n }\n\n public async deleteOrganizationDomain(params: DeleteOrganizationDomainParams) {\n const { organizationId, domainId } = params;\n this.requireId(organizationId);\n this.requireId(domainId);\n\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, organizationId, 'domains', domainId),\n });\n }\n}\n","import type { ClerkPaginationRequest } from '@clerk/types';\n\nimport { joinPaths } from '../../util/path';\nimport type { DeletedObject } from '../resources';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport type { OAuthApplication } from '../resources/OAuthApplication';\nimport { AbstractAPI } from './AbstractApi';\nimport type { WithSign } from './util-types';\n\nconst basePath = '/oauth_applications';\n\ntype CreateOAuthApplicationParams = {\n /**\n * The name of the new OAuth application.\n *\n * @remarks Max length: 256\n */\n name: string;\n /**\n * An array of redirect URIs of the new OAuth application\n */\n redirectUris?: Array | null | undefined;\n /**\n * Define the allowed scopes for the new OAuth applications that dictate the user payload of the OAuth user info endpoint. Available scopes are `profile`, `email`, `public_metadata`, `private_metadata`. Provide the requested scopes as a string, separated by spaces.\n */\n scopes?: string | null | undefined;\n /**\n * If true, this client is public and you can use the Proof Key of Code Exchange (PKCE) flow.\n */\n public?: boolean | null | undefined;\n};\n\ntype UpdateOAuthApplicationParams = CreateOAuthApplicationParams & {\n /**\n * The ID of the OAuth application to update\n */\n oauthApplicationId: string;\n};\n\ntype GetOAuthApplicationListParams = ClerkPaginationRequest<{\n /**\n * Sorts OAuth applications by name or created_at.\n * By prepending one of those values with + or -, we can choose to sort in ascending (ASC) or descending (DESC) order.\n */\n orderBy?: WithSign<'name' | 'created_at'>;\n}>;\n\nexport class OAuthApplicationsApi extends AbstractAPI {\n public async list(params: GetOAuthApplicationListParams = {}) {\n return this.request>({\n method: 'GET',\n path: basePath,\n queryParams: params,\n });\n }\n\n public async get(oauthApplicationId: string) {\n this.requireId(oauthApplicationId);\n\n return this.request({\n method: 'GET',\n path: joinPaths(basePath, oauthApplicationId),\n });\n }\n\n public async create(params: CreateOAuthApplicationParams) {\n return this.request({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async update(params: UpdateOAuthApplicationParams) {\n const { oauthApplicationId, ...bodyParams } = params;\n\n this.requireId(oauthApplicationId);\n\n return this.request({\n method: 'PATCH',\n path: joinPaths(basePath, oauthApplicationId),\n bodyParams,\n });\n }\n\n public async delete(oauthApplicationId: string) {\n this.requireId(oauthApplicationId);\n\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, oauthApplicationId),\n });\n }\n\n public async rotateSecret(oauthApplicationId: string) {\n this.requireId(oauthApplicationId);\n\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, oauthApplicationId, 'rotate_secret'),\n });\n }\n}\n","import { joinPaths } from '../../util/path';\nimport type { DeletedObject, PhoneNumber } from '../resources';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/phone_numbers';\n\ntype CreatePhoneNumberParams = {\n userId: string;\n phoneNumber: string;\n verified?: boolean;\n primary?: boolean;\n reservedForSecondFactor?: boolean;\n};\n\ntype UpdatePhoneNumberParams = {\n verified?: boolean;\n primary?: boolean;\n reservedForSecondFactor?: boolean;\n};\n\nexport class PhoneNumberAPI extends AbstractAPI {\n public async getPhoneNumber(phoneNumberId: string) {\n this.requireId(phoneNumberId);\n\n return this.request({\n method: 'GET',\n path: joinPaths(basePath, phoneNumberId),\n });\n }\n\n public async createPhoneNumber(params: CreatePhoneNumberParams) {\n return this.request({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async updatePhoneNumber(phoneNumberId: string, params: UpdatePhoneNumberParams = {}) {\n this.requireId(phoneNumberId);\n\n return this.request({\n method: 'PATCH',\n path: joinPaths(basePath, phoneNumberId),\n bodyParams: params,\n });\n }\n\n public async deletePhoneNumber(phoneNumberId: string) {\n this.requireId(phoneNumberId);\n\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, phoneNumberId),\n });\n }\n}\n","import type { ProxyCheck } from '../resources';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/proxy_checks';\n\ntype VerifyParams = {\n domainId: string;\n proxyUrl: string;\n};\n\nexport class ProxyCheckAPI extends AbstractAPI {\n public async verify(params: VerifyParams) {\n return this.request({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n}\n","import { joinPaths } from '../../util/path';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport type { RedirectUrl } from '../resources/RedirectUrl';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/redirect_urls';\n\ntype CreateRedirectUrlParams = {\n url: string;\n};\n\nexport class RedirectUrlAPI extends AbstractAPI {\n public async getRedirectUrlList() {\n return this.request>({\n method: 'GET',\n path: basePath,\n queryParams: { paginated: true },\n });\n }\n\n public async getRedirectUrl(redirectUrlId: string) {\n this.requireId(redirectUrlId);\n return this.request({\n method: 'GET',\n path: joinPaths(basePath, redirectUrlId),\n });\n }\n\n public async createRedirectUrl(params: CreateRedirectUrlParams) {\n return this.request({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async deleteRedirectUrl(redirectUrlId: string) {\n this.requireId(redirectUrlId);\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, redirectUrlId),\n });\n }\n}\n","import type { ClerkPaginationRequest, SamlIdpSlug } from '@clerk/types';\n\nimport { joinPaths } from '../../util/path';\nimport type { SamlConnection } from '../resources';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport { AbstractAPI } from './AbstractApi';\nimport type { WithSign } from './util-types';\n\nconst basePath = '/saml_connections';\n\ntype SamlConnectionListParams = ClerkPaginationRequest<{\n /**\n * Returns SAML connections that have a name that matches the given query, via case-insensitive partial match.\n */\n query?: string;\n\n /**\n * Sorts SAML connections by phone_number, email_address, created_at, first_name, last_name or username.\n * By prepending one of those values with + or -, we can choose to sort in ascending (ASC) or descending (DESC) order.\n */\n orderBy?: WithSign<'phone_number' | 'email_address' | 'created_at' | 'first_name' | 'last_name' | 'username'>;\n\n /**\n * Returns SAML connections that have an associated organization ID to the given organizations.\n * For each organization id, the + and - can be prepended to the id, which denote whether the\n * respective organization should be included or excluded from the result set. Accepts up to 100 organization ids.\n */\n organizationId?: WithSign[];\n}>;\n\ntype CreateSamlConnectionParams = {\n name: string;\n provider: SamlIdpSlug;\n domain: string;\n organizationId?: string;\n idpEntityId?: string;\n idpSsoUrl?: string;\n idpCertificate?: string;\n idpMetadataUrl?: string;\n idpMetadata?: string;\n attributeMapping?: {\n emailAddress?: string;\n firstName?: string;\n lastName?: string;\n userId?: string;\n };\n};\n\ntype UpdateSamlConnectionParams = {\n name?: string;\n provider?: SamlIdpSlug;\n domain?: string;\n organizationId?: string;\n idpEntityId?: string;\n idpSsoUrl?: string;\n idpCertificate?: string;\n idpMetadataUrl?: string;\n idpMetadata?: string;\n attributeMapping?: {\n emailAddress?: string;\n firstName?: string;\n lastName?: string;\n userId?: string;\n };\n active?: boolean;\n syncUserAttributes?: boolean;\n allowSubdomains?: boolean;\n allowIdpInitiated?: boolean;\n};\n\nexport class SamlConnectionAPI extends AbstractAPI {\n public async getSamlConnectionList(params: SamlConnectionListParams = {}) {\n return this.request>({\n method: 'GET',\n path: basePath,\n queryParams: params,\n });\n }\n\n public async createSamlConnection(params: CreateSamlConnectionParams) {\n return this.request({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n options: {\n deepSnakecaseBodyParamKeys: true,\n },\n });\n }\n\n public async getSamlConnection(samlConnectionId: string) {\n this.requireId(samlConnectionId);\n return this.request({\n method: 'GET',\n path: joinPaths(basePath, samlConnectionId),\n });\n }\n\n public async updateSamlConnection(samlConnectionId: string, params: UpdateSamlConnectionParams = {}) {\n this.requireId(samlConnectionId);\n\n return this.request({\n method: 'PATCH',\n path: joinPaths(basePath, samlConnectionId),\n bodyParams: params,\n options: {\n deepSnakecaseBodyParamKeys: true,\n },\n });\n }\n public async deleteSamlConnection(samlConnectionId: string) {\n this.requireId(samlConnectionId);\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, samlConnectionId),\n });\n }\n}\n","import type { ClerkPaginationRequest, SessionStatus } from '@clerk/types';\n\nimport { joinPaths } from '../../util/path';\nimport type { Cookies } from '../resources/Cookies';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport type { Session } from '../resources/Session';\nimport type { Token } from '../resources/Token';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/sessions';\n\ntype SessionListParams = ClerkPaginationRequest<{\n clientId?: string;\n userId?: string;\n status?: SessionStatus;\n}>;\n\ntype RefreshTokenParams = {\n expired_token: string;\n refresh_token: string;\n request_origin: string;\n request_originating_ip?: string;\n request_headers?: Record;\n suffixed_cookies?: boolean;\n format?: 'token' | 'cookie';\n};\n\ntype CreateSessionParams = {\n userId: string;\n};\n\nexport class SessionAPI extends AbstractAPI {\n public async getSessionList(params: SessionListParams = {}) {\n return this.request>({\n method: 'GET',\n path: basePath,\n queryParams: { ...params, paginated: true },\n });\n }\n\n public async getSession(sessionId: string) {\n this.requireId(sessionId);\n return this.request({\n method: 'GET',\n path: joinPaths(basePath, sessionId),\n });\n }\n\n public async createSession(params: CreateSessionParams) {\n return this.request({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async revokeSession(sessionId: string) {\n this.requireId(sessionId);\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, sessionId, 'revoke'),\n });\n }\n\n public async verifySession(sessionId: string, token: string) {\n this.requireId(sessionId);\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, sessionId, 'verify'),\n bodyParams: { token },\n });\n }\n\n /**\n * Retrieves a session token or generates a JWT using a specified template.\n *\n * @param sessionId - The ID of the session for which to generate the token\n * @param template - Optional name of the JWT template configured in the Clerk Dashboard.\n * @param expiresInSeconds - Optional expiration time for the token in seconds.\n * If not provided, uses the default expiration.\n *\n * @returns A promise that resolves to the generated token\n *\n * @throws {Error} When sessionId is invalid or empty\n */\n public async getToken(sessionId: string, template?: string, expiresInSeconds?: number) {\n this.requireId(sessionId);\n\n const path = template\n ? joinPaths(basePath, sessionId, 'tokens', template)\n : joinPaths(basePath, sessionId, 'tokens');\n\n const requestOptions: any = {\n method: 'POST',\n path,\n };\n\n if (expiresInSeconds !== undefined) {\n requestOptions.bodyParams = { expires_in_seconds: expiresInSeconds };\n }\n\n return this.request(requestOptions);\n }\n\n public async refreshSession(sessionId: string, params: RefreshTokenParams & { format: 'token' }): Promise;\n public async refreshSession(sessionId: string, params: RefreshTokenParams & { format: 'cookie' }): Promise;\n public async refreshSession(sessionId: string, params: RefreshTokenParams): Promise;\n public async refreshSession(sessionId: string, params: RefreshTokenParams): Promise {\n this.requireId(sessionId);\n const { suffixed_cookies, ...restParams } = params;\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, sessionId, 'refresh'),\n bodyParams: restParams,\n queryParams: { suffixed_cookies },\n });\n }\n}\n","import { joinPaths } from '../../util/path';\nimport type { SignInToken } from '../resources/SignInTokens';\nimport { AbstractAPI } from './AbstractApi';\n\ntype CreateSignInTokensParams = {\n userId: string;\n expiresInSeconds: number;\n};\n\nconst basePath = '/sign_in_tokens';\n\nexport class SignInTokenAPI extends AbstractAPI {\n public async createSignInToken(params: CreateSignInTokensParams) {\n return this.request({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async revokeSignInToken(signInTokenId: string) {\n this.requireId(signInTokenId);\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, signInTokenId, 'revoke'),\n });\n }\n}\n","import { joinPaths } from '../../util/path';\nimport type { SignUpAttempt } from '../resources/SignUpAttempt';\nimport { AbstractAPI } from './AbstractApi';\n\ntype UpdateSignUpParams = {\n signUpAttemptId: string;\n externalId?: string | null;\n customAction?: boolean | null;\n};\n\nconst basePath = '/sign_ups';\n\nexport class SignUpAPI extends AbstractAPI {\n public async get(signUpAttemptId: string) {\n this.requireId(signUpAttemptId);\n\n return this.request({\n method: 'GET',\n path: joinPaths(basePath, signUpAttemptId),\n });\n }\n\n public async update(params: UpdateSignUpParams) {\n const { signUpAttemptId, ...bodyParams } = params;\n\n return this.request({\n method: 'PATCH',\n path: joinPaths(basePath, signUpAttemptId),\n bodyParams,\n });\n }\n}\n","import type { TestingToken } from '../resources/TestingToken';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/testing_tokens';\n\nexport class TestingTokenAPI extends AbstractAPI {\n public async createTestingToken() {\n return this.request({\n method: 'POST',\n path: basePath,\n });\n }\n}\n","export { addClerkPrefix, getScriptUrl, getClerkJsMajorVersionOrTag } from '@clerk/shared/url';\nexport { retry } from '@clerk/shared/retry';\nexport {\n isDevelopmentFromSecretKey,\n isProductionFromSecretKey,\n parsePublishableKey,\n getCookieSuffix,\n getSuffixedCookieName,\n} from '@clerk/shared/keys';\nexport { deprecated, deprecatedProperty } from '@clerk/shared/deprecated';\n\nimport { buildErrorThrower } from '@clerk/shared/error';\nimport { createDevOrStagingUrlCache } from '@clerk/shared/keys';\n// TODO: replace packageName with `${PACKAGE_NAME}@${PACKAGE_VERSION}` from tsup.config.ts\nexport const errorThrower = buildErrorThrower({ packageName: '@clerk/backend' });\n\nexport const { isDevOrStagingUrl } = createDevOrStagingUrlCache();\n","import type { ClerkPaginationRequest, OAuthProvider, OrganizationInvitationStatus } from '@clerk/types';\n\nimport { runtime } from '../../runtime';\nimport { joinPaths } from '../../util/path';\nimport { deprecated } from '../../util/shared';\nimport type {\n DeletedObject,\n OauthAccessToken,\n OrganizationInvitation,\n OrganizationMembership,\n User,\n} from '../resources';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport { AbstractAPI } from './AbstractApi';\nimport type { WithSign } from './util-types';\n\nconst basePath = '/users';\n\ntype UserCountParams = {\n emailAddress?: string[];\n phoneNumber?: string[];\n username?: string[];\n web3Wallet?: string[];\n query?: string;\n userId?: string[];\n externalId?: string[];\n};\n\ntype UserListParams = ClerkPaginationRequest<\n UserCountParams & {\n orderBy?: WithSign<\n | 'created_at'\n | 'updated_at'\n | 'email_address'\n | 'web3wallet'\n | 'first_name'\n | 'last_name'\n | 'phone_number'\n | 'username'\n | 'last_active_at'\n | 'last_sign_in_at'\n >;\n last_active_at_since?: number;\n organizationId?: string[];\n }\n>;\n\ntype UserMetadataParams = {\n publicMetadata?: UserPublicMetadata;\n privateMetadata?: UserPrivateMetadata;\n unsafeMetadata?: UserUnsafeMetadata;\n};\n\ntype PasswordHasher =\n | 'argon2i'\n | 'argon2id'\n | 'awscognito'\n | 'bcrypt'\n | 'bcrypt_sha256_django'\n | 'md5'\n | 'pbkdf2_sha256'\n | 'pbkdf2_sha256_django'\n | 'pbkdf2_sha1'\n | 'phpass'\n | 'scrypt_firebase'\n | 'scrypt_werkzeug'\n | 'sha256'\n | 'md5_phpass'\n | 'ldap_ssha';\n\ntype UserPasswordHashingParams = {\n passwordDigest: string;\n passwordHasher: PasswordHasher;\n};\n\ntype CreateUserParams = {\n externalId?: string;\n emailAddress?: string[];\n phoneNumber?: string[];\n username?: string;\n password?: string;\n firstName?: string;\n lastName?: string;\n skipPasswordChecks?: boolean;\n skipPasswordRequirement?: boolean;\n skipLegalChecks?: boolean;\n legalAcceptedAt?: Date;\n totpSecret?: string;\n backupCodes?: string[];\n createdAt?: Date;\n} & UserMetadataParams &\n (UserPasswordHashingParams | object);\n\ntype UpdateUserParams = {\n /** The first name to assign to the user. */\n firstName?: string;\n\n /** The last name of the user. */\n lastName?: string;\n\n /** The username to give to the user. It must be unique across your instance. */\n username?: string;\n\n /** The plaintext password to give the user. Must be at least 8 characters long, and can not be in any list of hacked passwords. */\n password?: string;\n\n /** Set it to true if you're updating the user's password and want to skip any password policy settings check. This parameter can only be used when providing a password. */\n skipPasswordChecks?: boolean;\n\n /** Set to true to sign out the user from all their active sessions once their password is updated. This parameter can only be used when providing a password. */\n signOutOfOtherSessions?: boolean;\n\n /** The ID of the email address to set as primary. It must be verified, and present on the current user. */\n primaryEmailAddressID?: string;\n\n /** If set to true, the user will be notified that their primary email address has changed. By default, no notification is sent. */\n notifyPrimaryEmailAddressChanged?: boolean;\n\n /** The ID of the phone number to set as primary. It must be verified, and present on the current user. */\n primaryPhoneNumberID?: string;\n\n /** The ID of the web3 wallets to set as primary. It must be verified, and present on the current user. */\n primaryWeb3WalletID?: string;\n\n /** The ID of the image to set as the user's profile image */\n profileImageID?: string;\n\n /**\n * In case TOTP is configured on the instance, you can provide the secret to enable it on the specific user without the need to reset it.\n * Please note that currently the supported options are:\n * - Period: 30 seconds\n * - Code length: 6 digits\n * - Algorithm: SHA1\n */\n totpSecret?: string;\n\n /** If Backup Codes are configured on the instance, you can provide them to enable it on the specific user without the need to reset them. You must provide the backup codes in plain format or the corresponding bcrypt digest. */\n backupCodes?: string[];\n\n /** The ID of the user as used in your external systems or your previous authentication solution. Must be unique across your instance. */\n externalId?: string;\n\n /** A custom timestamp denoting when the user signed up to the application, specified in RFC3339 format (e.g. 2012-10-20T07:15:20.902Z). */\n createdAt?: Date;\n\n /** When set to true all legal checks are skipped. It is not recommended to skip legal checks unless you are migrating a user to Clerk. */\n skipLegalChecks?: boolean;\n\n /** A custom timestamp denoting when the user accepted legal requirements, specified in RFC3339 format (e.g. 2012-10-20T07:15:20.902Z). */\n legalAcceptedAt?: Date;\n\n /** If true, the user can delete themselves with the Frontend API. */\n deleteSelfEnabled?: boolean;\n\n /** If true, the user can create organizations with the Frontend API. */\n createOrganizationEnabled?: boolean;\n\n /** The maximum number of organizations the user can create. 0 means unlimited. */\n createOrganizationsLimit?: number;\n} & UserMetadataParams &\n (UserPasswordHashingParams | object);\n\ntype GetOrganizationMembershipListParams = ClerkPaginationRequest<{\n userId: string;\n}>;\n\ntype GetOrganizationInvitationListParams = ClerkPaginationRequest<{\n userId: string;\n status?: OrganizationInvitationStatus;\n}>;\n\ntype VerifyPasswordParams = {\n userId: string;\n password: string;\n};\n\ntype VerifyTOTPParams = {\n userId: string;\n code: string;\n};\n\ntype DeleteUserPasskeyParams = {\n userId: string;\n passkeyIdentificationId: string;\n};\n\ntype DeleteWeb3WalletParams = {\n userId: string;\n web3WalletIdentificationId: string;\n};\n\ntype DeleteUserExternalAccountParams = {\n userId: string;\n externalAccountId: string;\n};\n\ntype UserID = {\n userId: string;\n};\n\nexport class UserAPI extends AbstractAPI {\n public async getUserList(params: UserListParams = {}) {\n const { limit, offset, orderBy, ...userCountParams } = params;\n // TODO(dimkl): Temporary change to populate totalCount using a 2nd BAPI call to /users/count endpoint\n // until we update the /users endpoint to be paginated in a next BAPI version.\n // In some edge cases the data.length != totalCount due to a creation of a user between the 2 api responses\n const [data, totalCount] = await Promise.all([\n this.request({\n method: 'GET',\n path: basePath,\n queryParams: params,\n }),\n this.getCount(userCountParams),\n ]);\n return { data, totalCount } as PaginatedResourceResponse;\n }\n\n public async getUser(userId: string) {\n this.requireId(userId);\n return this.request({\n method: 'GET',\n path: joinPaths(basePath, userId),\n });\n }\n\n public async createUser(params: CreateUserParams) {\n return this.request({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async updateUser(userId: string, params: UpdateUserParams = {}) {\n this.requireId(userId);\n\n return this.request({\n method: 'PATCH',\n path: joinPaths(basePath, userId),\n bodyParams: params,\n });\n }\n\n public async updateUserProfileImage(userId: string, params: { file: Blob | File }) {\n this.requireId(userId);\n\n const formData = new runtime.FormData();\n formData.append('file', params?.file);\n\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, userId, 'profile_image'),\n formData,\n });\n }\n\n public async updateUserMetadata(userId: string, params: UserMetadataParams) {\n this.requireId(userId);\n\n return this.request({\n method: 'PATCH',\n path: joinPaths(basePath, userId, 'metadata'),\n bodyParams: params,\n });\n }\n\n public async deleteUser(userId: string) {\n this.requireId(userId);\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, userId),\n });\n }\n\n public async getCount(params: UserCountParams = {}) {\n return this.request({\n method: 'GET',\n path: joinPaths(basePath, 'count'),\n queryParams: params,\n });\n }\n\n /** @deprecated Use `getUserOauthAccessToken` without the `oauth_` provider prefix . */\n public async getUserOauthAccessToken(\n userId: string,\n provider: `oauth_${OAuthProvider}`,\n ): Promise>;\n public async getUserOauthAccessToken(\n userId: string,\n provider: OAuthProvider,\n ): Promise>;\n public async getUserOauthAccessToken(userId: string, provider: `oauth_${OAuthProvider}` | OAuthProvider) {\n this.requireId(userId);\n const hasPrefix = provider.startsWith('oauth_');\n const _provider = hasPrefix ? provider : `oauth_${provider}`;\n\n if (hasPrefix) {\n deprecated(\n 'getUserOauthAccessToken(userId, provider)',\n 'Remove the `oauth_` prefix from the `provider` argument.',\n );\n }\n\n return this.request>({\n method: 'GET',\n path: joinPaths(basePath, userId, 'oauth_access_tokens', _provider),\n queryParams: { paginated: true },\n });\n }\n\n public async disableUserMFA(userId: string) {\n this.requireId(userId);\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, userId, 'mfa'),\n });\n }\n\n public async getOrganizationMembershipList(params: GetOrganizationMembershipListParams) {\n const { userId, limit, offset } = params;\n this.requireId(userId);\n\n return this.request>({\n method: 'GET',\n path: joinPaths(basePath, userId, 'organization_memberships'),\n queryParams: { limit, offset },\n });\n }\n\n public async getOrganizationInvitationList(params: GetOrganizationInvitationListParams) {\n const { userId, ...queryParams } = params;\n this.requireId(userId);\n\n return this.request>({\n method: 'GET',\n path: joinPaths(basePath, userId, 'organization_invitations'),\n queryParams,\n });\n }\n\n public async verifyPassword(params: VerifyPasswordParams) {\n const { userId, password } = params;\n this.requireId(userId);\n\n return this.request<{ verified: true }>({\n method: 'POST',\n path: joinPaths(basePath, userId, 'verify_password'),\n bodyParams: { password },\n });\n }\n\n public async verifyTOTP(params: VerifyTOTPParams) {\n const { userId, code } = params;\n this.requireId(userId);\n\n return this.request<{ verified: true; code_type: 'totp' }>({\n method: 'POST',\n path: joinPaths(basePath, userId, 'verify_totp'),\n bodyParams: { code },\n });\n }\n\n public async banUser(userId: string) {\n this.requireId(userId);\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, userId, 'ban'),\n });\n }\n\n public async unbanUser(userId: string) {\n this.requireId(userId);\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, userId, 'unban'),\n });\n }\n\n public async lockUser(userId: string) {\n this.requireId(userId);\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, userId, 'lock'),\n });\n }\n\n public async unlockUser(userId: string) {\n this.requireId(userId);\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, userId, 'unlock'),\n });\n }\n\n public async deleteUserProfileImage(userId: string) {\n this.requireId(userId);\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, userId, 'profile_image'),\n });\n }\n\n public async deleteUserPasskey(params: DeleteUserPasskeyParams) {\n this.requireId(params.userId);\n this.requireId(params.passkeyIdentificationId);\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, params.userId, 'passkeys', params.passkeyIdentificationId),\n });\n }\n\n public async deleteUserWeb3Wallet(params: DeleteWeb3WalletParams) {\n this.requireId(params.userId);\n this.requireId(params.web3WalletIdentificationId);\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, params.userId, 'web3_wallets', params.web3WalletIdentificationId),\n });\n }\n\n public async deleteUserExternalAccount(params: DeleteUserExternalAccountParams) {\n this.requireId(params.userId);\n this.requireId(params.externalAccountId);\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, params.userId, 'external_accounts', params.externalAccountId),\n });\n }\n\n public async deleteUserBackupCodes(userId: string) {\n this.requireId(userId);\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, userId, 'backup_code'),\n });\n }\n\n public async deleteUserTOTP(userId: string) {\n this.requireId(userId);\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, userId, 'totp'),\n });\n }\n}\n","import type { ClerkPaginationRequest } from '@clerk/types';\nimport { joinPaths } from 'src/util/path';\n\nimport type { DeletedObject } from '../resources/DeletedObject';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport type { WaitlistEntryStatus } from '../resources/Enums';\nimport type { WaitlistEntry } from '../resources/WaitlistEntry';\nimport { AbstractAPI } from './AbstractApi';\nimport type { WithSign } from './util-types';\n\nconst basePath = '/waitlist_entries';\n\ntype WaitlistEntryListParams = ClerkPaginationRequest<{\n /**\n * Filter waitlist entries by `email_address` or `id`\n */\n query?: string;\n status?: WaitlistEntryStatus;\n orderBy?: WithSign<'created_at' | 'invited_at' | 'email_address'>;\n}>;\n\ntype WaitlistEntryCreateParams = {\n emailAddress: string;\n notify?: boolean;\n};\n\ntype WaitlistEntryInviteParams = {\n /**\n * When true, do not error if an invitation already exists. Default: false.\n */\n ignoreExisting?: boolean;\n};\n\nexport class WaitlistEntryAPI extends AbstractAPI {\n /**\n * List waitlist entries.\n * @param params Optional parameters (e.g., `query`, `status`, `orderBy`).\n */\n public async list(params: WaitlistEntryListParams = {}) {\n return this.request>({\n method: 'GET',\n path: basePath,\n queryParams: params,\n });\n }\n\n /**\n * Create a waitlist entry.\n * @param params The parameters for creating a waitlist entry.\n */\n public async create(params: WaitlistEntryCreateParams) {\n return this.request({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n /**\n * Invite a waitlist entry.\n * @param id The waitlist entry ID.\n * @param params Optional parameters (e.g., `ignoreExisting`).\n */\n public async invite(id: string, params: WaitlistEntryInviteParams = {}) {\n this.requireId(id);\n\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, id, 'invite'),\n bodyParams: params,\n });\n }\n\n /**\n * Reject a waitlist entry.\n * @param id The waitlist entry ID.\n */\n public async reject(id: string) {\n this.requireId(id);\n\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, id, 'reject'),\n });\n }\n\n /**\n * Delete a waitlist entry.\n * @param id The waitlist entry ID.\n */\n public async delete(id: string) {\n this.requireId(id);\n\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, id),\n });\n }\n}\n","import { joinPaths } from '../../util/path';\nimport type { WebhooksSvixJSON } from '../resources/JSON';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/webhooks';\n\nexport class WebhookAPI extends AbstractAPI {\n public async createSvixApp() {\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, 'svix'),\n });\n }\n\n public async generateSvixAuthURL() {\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, 'svix_url'),\n });\n }\n\n public async deleteSvixApp() {\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, 'svix'),\n });\n }\n}\n","import type { ClerkPaginationRequest } from '@clerk/types';\n\nimport { joinPaths } from '../../util/path';\nimport type { BillingPlan } from '../resources/CommercePlan';\nimport type { BillingSubscription } from '../resources/CommerceSubscription';\nimport type { BillingSubscriptionItem } from '../resources/CommerceSubscriptionItem';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/commerce';\nconst organizationBasePath = '/organizations';\nconst userBasePath = '/users';\n\ntype GetOrganizationListParams = ClerkPaginationRequest<{\n payerType: 'org' | 'user';\n}>;\n\ntype CancelSubscriptionItemParams = {\n /**\n * If true, the subscription item will be canceled immediately. If false or undefined, the subscription item will be canceled at the end of the current billing period.\n * @default undefined\n */\n endNow?: boolean;\n};\n\ntype ExtendSubscriptionItemFreeTrialParams = {\n /**\n * RFC3339 timestamp to extend the free trial to.\n * Must be in the future and not more than 365 days from the current trial end.\n */\n extendTo: Date;\n};\n\nexport class BillingAPI extends AbstractAPI {\n /**\n * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes.\n */\n public async getPlanList(params?: GetOrganizationListParams) {\n return this.request>({\n method: 'GET',\n path: joinPaths(basePath, 'plans'),\n queryParams: params,\n });\n }\n\n /**\n * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes.\n */\n public async cancelSubscriptionItem(subscriptionItemId: string, params?: CancelSubscriptionItemParams) {\n this.requireId(subscriptionItemId);\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, 'subscription_items', subscriptionItemId),\n queryParams: params,\n });\n }\n\n /**\n * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes.\n */\n public async extendSubscriptionItemFreeTrial(\n subscriptionItemId: string,\n params: ExtendSubscriptionItemFreeTrialParams,\n ) {\n this.requireId(subscriptionItemId);\n return this.request({\n method: 'POST',\n path: joinPaths('/billing', 'subscription_items', subscriptionItemId, 'extend_free_trial'),\n bodyParams: params,\n });\n }\n\n /**\n * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes.\n */\n public async getOrganizationBillingSubscription(organizationId: string) {\n this.requireId(organizationId);\n return this.request({\n method: 'GET',\n path: joinPaths(organizationBasePath, organizationId, 'billing', 'subscription'),\n });\n }\n\n /**\n * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes.\n */\n public async getUserBillingSubscription(userId: string) {\n this.requireId(userId);\n return this.request({\n method: 'GET',\n path: joinPaths(userBasePath, userId, 'billing', 'subscription'),\n });\n }\n}\n","import { ClerkAPIResponseError, parseError } from '@clerk/shared/error';\nimport type { ClerkAPIError, ClerkAPIErrorJSON } from '@clerk/types';\nimport snakecaseKeys from 'snakecase-keys';\n\nimport { API_URL, API_VERSION, constants, SUPPORTED_BAPI_VERSION, USER_AGENT } from '../constants';\nimport { runtime } from '../runtime';\nimport { assertValidSecretKey } from '../util/optionsAssertions';\nimport { joinPaths } from '../util/path';\nimport { deserialize } from './resources/Deserializer';\n\ntype ClerkBackendApiRequestOptionsUrlOrPath =\n | {\n url: string;\n path?: string;\n }\n | {\n url?: string;\n path: string;\n };\n\ntype ClerkBackendApiRequestOptionsBodyParams =\n | {\n bodyParams: Record | Array>;\n options?: {\n /**\n * If true, snakecases the keys of the bodyParams object recursively.\n * @default false\n */\n deepSnakecaseBodyParamKeys?: boolean;\n };\n }\n | {\n bodyParams?: never;\n options?: {\n deepSnakecaseBodyParamKeys?: never;\n };\n };\n\nexport type ClerkBackendApiRequestOptions = {\n method: 'GET' | 'POST' | 'PATCH' | 'DELETE' | 'PUT';\n queryParams?: Record;\n headerParams?: Record;\n formData?: FormData;\n} & ClerkBackendApiRequestOptionsUrlOrPath &\n ClerkBackendApiRequestOptionsBodyParams;\n\nexport type ClerkBackendApiResponse =\n | {\n data: T;\n errors: null;\n totalCount?: number;\n }\n | {\n data: null;\n errors: ClerkAPIError[];\n totalCount?: never;\n clerkTraceId?: string;\n status?: number;\n statusText?: string;\n retryAfter?: number;\n };\n\nexport type RequestFunction = ReturnType;\n\ntype BuildRequestOptions = {\n /* Secret Key */\n secretKey?: string;\n /* Backend API URL */\n apiUrl?: string;\n /* Backend API version */\n apiVersion?: string;\n /* Library/SDK name */\n userAgent?: string;\n /**\n * Allow requests without specifying a secret key. In most cases this should be set to `false`.\n * @default true\n */\n requireSecretKey?: boolean;\n /**\n * If true, omits the API version from the request URL path.\n * This is required for bapi-proxy endpoints, which do not use versioning in the URL.\n *\n * Note: API versioning for these endpoints is instead handled via the `Clerk-API-Version` HTTP header.\n *\n * @default false\n */\n skipApiVersionInUrl?: boolean;\n /* Machine secret key */\n machineSecretKey?: string;\n /**\n * If true, uses machineSecretKey for authorization instead of secretKey.\n *\n * Note: This is only used for machine-to-machine tokens.\n *\n * @default false\n */\n useMachineSecretKey?: boolean;\n};\n\nexport function buildRequest(options: BuildRequestOptions) {\n const requestFn = async (requestOptions: ClerkBackendApiRequestOptions): Promise> => {\n const {\n secretKey,\n machineSecretKey,\n useMachineSecretKey = false,\n requireSecretKey = true,\n apiUrl = API_URL,\n apiVersion = API_VERSION,\n userAgent = USER_AGENT,\n skipApiVersionInUrl = false,\n } = options;\n const { path, method, queryParams, headerParams, bodyParams, formData, options: opts } = requestOptions;\n const { deepSnakecaseBodyParamKeys = false } = opts || {};\n\n if (requireSecretKey) {\n assertValidSecretKey(secretKey);\n }\n\n const url = skipApiVersionInUrl ? joinPaths(apiUrl, path) : joinPaths(apiUrl, apiVersion, path);\n\n // Build final URL with search parameters\n const finalUrl = new URL(url);\n\n if (queryParams) {\n // Snakecase query parameters\n const snakecasedQueryParams = snakecaseKeys({ ...queryParams });\n\n // Support array values for queryParams such as { foo: [42, 43] }\n for (const [key, val] of Object.entries(snakecasedQueryParams)) {\n if (val) {\n [val].flat().forEach(v => finalUrl.searchParams.append(key, v as string));\n }\n }\n }\n\n // Build headers\n const headers = new Headers({\n 'Clerk-API-Version': SUPPORTED_BAPI_VERSION,\n [constants.Headers.UserAgent]: userAgent,\n ...headerParams,\n });\n\n // If Authorization header already exists, preserve it.\n // Otherwise, use machine secret key if enabled, or fall back to regular secret key\n const authorizationHeader = constants.Headers.Authorization;\n if (!headers.has(authorizationHeader)) {\n if (useMachineSecretKey && machineSecretKey) {\n headers.set(authorizationHeader, `Bearer ${machineSecretKey}`);\n } else if (secretKey) {\n headers.set(authorizationHeader, `Bearer ${secretKey}`);\n }\n }\n\n let res: Response | undefined;\n try {\n if (formData) {\n res = await runtime.fetch(finalUrl.href, {\n method,\n headers,\n body: formData,\n });\n } else {\n // Enforce application/json for all non form-data requests\n headers.set('Content-Type', 'application/json');\n\n const buildBody = () => {\n const hasBody = method !== 'GET' && bodyParams && Object.keys(bodyParams).length > 0;\n if (!hasBody) {\n return null;\n }\n\n const formatKeys = (object: Parameters[0]) =>\n snakecaseKeys(object, { deep: deepSnakecaseBodyParamKeys });\n\n return {\n body: JSON.stringify(Array.isArray(bodyParams) ? bodyParams.map(formatKeys) : formatKeys(bodyParams)),\n };\n };\n\n res = await runtime.fetch(finalUrl.href, {\n method,\n headers,\n ...buildBody(),\n });\n }\n\n // TODO: Parse JSON or Text response based on a response header\n const isJSONResponse =\n res?.headers && res.headers?.get(constants.Headers.ContentType) === constants.ContentTypes.Json;\n const responseBody = await (isJSONResponse ? res.json() : res.text());\n\n if (!res.ok) {\n return {\n data: null,\n errors: parseErrors(responseBody),\n status: res?.status,\n statusText: res?.statusText,\n clerkTraceId: getTraceId(responseBody, res?.headers),\n retryAfter: getRetryAfter(res?.headers),\n };\n }\n\n return {\n ...deserialize(responseBody),\n errors: null,\n };\n } catch (err) {\n if (err instanceof Error) {\n return {\n data: null,\n errors: [\n {\n code: 'unexpected_error',\n message: err.message || 'Unexpected error',\n },\n ],\n clerkTraceId: getTraceId(err, res?.headers),\n };\n }\n\n return {\n data: null,\n errors: parseErrors(err),\n status: res?.status,\n statusText: res?.statusText,\n clerkTraceId: getTraceId(err, res?.headers),\n retryAfter: getRetryAfter(res?.headers),\n };\n }\n };\n\n return withLegacyRequestReturn(requestFn);\n}\n\n// Returns either clerk_trace_id if present in response json, otherwise defaults to CF-Ray header\n// If the request failed before receiving a response, returns undefined\nfunction getTraceId(data: unknown, headers?: Headers): string {\n if (data && typeof data === 'object' && 'clerk_trace_id' in data && typeof data.clerk_trace_id === 'string') {\n return data.clerk_trace_id;\n }\n\n const cfRay = headers?.get('cf-ray');\n return cfRay || '';\n}\n\nfunction getRetryAfter(headers?: Headers): number | undefined {\n const retryAfter = headers?.get('Retry-After');\n if (!retryAfter) {\n return;\n }\n\n const value = parseInt(retryAfter, 10);\n if (isNaN(value)) {\n return;\n }\n\n return value;\n}\n\nfunction parseErrors(data: unknown): ClerkAPIError[] {\n if (!!data && typeof data === 'object' && 'errors' in data) {\n const errors = data.errors as ClerkAPIErrorJSON[];\n return errors.length > 0 ? errors.map(parseError) : [];\n }\n return [];\n}\n\ntype LegacyRequestFunction = (requestOptions: ClerkBackendApiRequestOptions) => Promise;\n\n// TODO(dimkl): Will be probably be dropped in next major version\nfunction withLegacyRequestReturn(cb: any): LegacyRequestFunction {\n return async (...args) => {\n const { data, errors, totalCount, status, statusText, clerkTraceId, retryAfter } = await cb(...args);\n if (errors) {\n // instead of passing `data: errors`, we have set the `error.errors` because\n // the errors returned from callback is already parsed and passing them as `data`\n // will not be able to assign them to the instance\n const error = new ClerkAPIResponseError(statusText || '', {\n data: [],\n status,\n clerkTraceId,\n retryAfter,\n });\n error.errors = errors;\n throw error;\n }\n\n if (typeof totalCount !== 'undefined') {\n return { data, totalCount };\n }\n\n return data;\n };\n}\n","const isObject = value => typeof value === 'object' && value !== null;\n\n// Customized for this use-case\nconst isObjectCustom = value =>\n\tisObject(value)\n\t&& !(value instanceof RegExp)\n\t&& !(value instanceof Error)\n\t&& !(value instanceof Date)\n\t&& !(globalThis.Blob && value instanceof globalThis.Blob);\n\nexport const mapObjectSkip = Symbol('mapObjectSkip');\n\nconst _mapObject = (object, mapper, options, isSeen = new WeakMap()) => {\n\toptions = {\n\t\tdeep: false,\n\t\ttarget: {},\n\t\t...options,\n\t};\n\n\tif (isSeen.has(object)) {\n\t\treturn isSeen.get(object);\n\t}\n\n\tisSeen.set(object, options.target);\n\n\tconst {target} = options;\n\tdelete options.target;\n\n\tconst mapArray = array => array.map(element => isObjectCustom(element) ? _mapObject(element, mapper, options, isSeen) : element);\n\tif (Array.isArray(object)) {\n\t\treturn mapArray(object);\n\t}\n\n\tfor (const [key, value] of Object.entries(object)) {\n\t\tconst mapResult = mapper(key, value, object);\n\n\t\tif (mapResult === mapObjectSkip) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tlet [newKey, newValue, {shouldRecurse = true} = {}] = mapResult;\n\n\t\t// Drop `__proto__` keys.\n\t\tif (newKey === '__proto__') {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (options.deep && shouldRecurse && isObjectCustom(newValue)) {\n\t\t\tnewValue = Array.isArray(newValue)\n\t\t\t\t? mapArray(newValue)\n\t\t\t\t: _mapObject(newValue, mapper, options, isSeen);\n\t\t}\n\n\t\ttarget[newKey] = newValue;\n\t}\n\n\treturn target;\n};\n\nexport default function mapObject(object, mapper, options) {\n\tif (!isObject(object)) {\n\t\tthrow new TypeError(`Expected an object, got \\`${object}\\` (${typeof object})`);\n\t}\n\n\tif (Array.isArray(object)) {\n\t\tthrow new TypeError('Expected an object, got an array');\n\t}\n\n\treturn _mapObject(object, mapper, options);\n}\n","// Regexps involved with splitting words in various case formats.\nconst SPLIT_LOWER_UPPER_RE = /([\\p{Ll}\\d])(\\p{Lu})/gu;\nconst SPLIT_UPPER_UPPER_RE = /(\\p{Lu})([\\p{Lu}][\\p{Ll}])/gu;\n\n// Used to iterate over the initial split result and separate numbers.\nconst SPLIT_SEPARATE_NUMBER_RE = /(\\d)\\p{Ll}|(\\p{L})\\d/u;\n\n// Regexp involved with stripping non-word characters from the result.\nconst DEFAULT_STRIP_REGEXP = /[^\\p{L}\\d]+/giu;\n\n// The replacement value for splits.\nconst SPLIT_REPLACE_VALUE = \"$1\\0$2\";\n\n// The default characters to keep after transforming case.\nconst DEFAULT_PREFIX_SUFFIX_CHARACTERS = \"\";\n\n/**\n * Supported locale values. Use `false` to ignore locale.\n * Defaults to `undefined`, which uses the host environment.\n */\nexport type Locale = string[] | string | false | undefined;\n\n/**\n * Options used for converting strings to pascal/camel case.\n */\nexport interface PascalCaseOptions extends Options {\n mergeAmbiguousCharacters?: boolean;\n}\n\n/**\n * Options used for converting strings to any case.\n */\nexport interface Options {\n locale?: Locale;\n split?: (value: string) => string[];\n /** @deprecated Pass `split: splitSeparateNumbers` instead. */\n separateNumbers?: boolean;\n delimiter?: string;\n prefixCharacters?: string;\n suffixCharacters?: string;\n}\n\n/**\n * Split any cased input strings into an array of words.\n */\nexport function split(value: string) {\n let result = value.trim();\n\n result = result\n .replace(SPLIT_LOWER_UPPER_RE, SPLIT_REPLACE_VALUE)\n .replace(SPLIT_UPPER_UPPER_RE, SPLIT_REPLACE_VALUE);\n\n result = result.replace(DEFAULT_STRIP_REGEXP, \"\\0\");\n\n let start = 0;\n let end = result.length;\n\n // Trim the delimiter from around the output string.\n while (result.charAt(start) === \"\\0\") start++;\n if (start === end) return [];\n while (result.charAt(end - 1) === \"\\0\") end--;\n\n return result.slice(start, end).split(/\\0/g);\n}\n\n/**\n * Split the input string into an array of words, separating numbers.\n */\nexport function splitSeparateNumbers(value: string) {\n const words = split(value);\n for (let i = 0; i < words.length; i++) {\n const word = words[i];\n const match = SPLIT_SEPARATE_NUMBER_RE.exec(word);\n if (match) {\n const offset = match.index + (match[1] ?? match[2]).length;\n words.splice(i, 1, word.slice(0, offset), word.slice(offset));\n }\n }\n return words;\n}\n\n/**\n * Convert a string to space separated lower case (`foo bar`).\n */\nexport function noCase(input: string, options?: Options) {\n const [prefix, words, suffix] = splitPrefixSuffix(input, options);\n return (\n prefix +\n words.map(lowerFactory(options?.locale)).join(options?.delimiter ?? \" \") +\n suffix\n );\n}\n\n/**\n * Convert a string to camel case (`fooBar`).\n */\nexport function camelCase(input: string, options?: PascalCaseOptions) {\n const [prefix, words, suffix] = splitPrefixSuffix(input, options);\n const lower = lowerFactory(options?.locale);\n const upper = upperFactory(options?.locale);\n const transform = options?.mergeAmbiguousCharacters\n ? capitalCaseTransformFactory(lower, upper)\n : pascalCaseTransformFactory(lower, upper);\n return (\n prefix +\n words\n .map((word, index) => {\n if (index === 0) return lower(word);\n return transform(word, index);\n })\n .join(options?.delimiter ?? \"\") +\n suffix\n );\n}\n\n/**\n * Convert a string to pascal case (`FooBar`).\n */\nexport function pascalCase(input: string, options?: PascalCaseOptions) {\n const [prefix, words, suffix] = splitPrefixSuffix(input, options);\n const lower = lowerFactory(options?.locale);\n const upper = upperFactory(options?.locale);\n const transform = options?.mergeAmbiguousCharacters\n ? capitalCaseTransformFactory(lower, upper)\n : pascalCaseTransformFactory(lower, upper);\n return prefix + words.map(transform).join(options?.delimiter ?? \"\") + suffix;\n}\n\n/**\n * Convert a string to pascal snake case (`Foo_Bar`).\n */\nexport function pascalSnakeCase(input: string, options?: Options) {\n return capitalCase(input, { delimiter: \"_\", ...options });\n}\n\n/**\n * Convert a string to capital case (`Foo Bar`).\n */\nexport function capitalCase(input: string, options?: Options) {\n const [prefix, words, suffix] = splitPrefixSuffix(input, options);\n const lower = lowerFactory(options?.locale);\n const upper = upperFactory(options?.locale);\n return (\n prefix +\n words\n .map(capitalCaseTransformFactory(lower, upper))\n .join(options?.delimiter ?? \" \") +\n suffix\n );\n}\n\n/**\n * Convert a string to constant case (`FOO_BAR`).\n */\nexport function constantCase(input: string, options?: Options) {\n const [prefix, words, suffix] = splitPrefixSuffix(input, options);\n return (\n prefix +\n words.map(upperFactory(options?.locale)).join(options?.delimiter ?? \"_\") +\n suffix\n );\n}\n\n/**\n * Convert a string to dot case (`foo.bar`).\n */\nexport function dotCase(input: string, options?: Options) {\n return noCase(input, { delimiter: \".\", ...options });\n}\n\n/**\n * Convert a string to kebab case (`foo-bar`).\n */\nexport function kebabCase(input: string, options?: Options) {\n return noCase(input, { delimiter: \"-\", ...options });\n}\n\n/**\n * Convert a string to path case (`foo/bar`).\n */\nexport function pathCase(input: string, options?: Options) {\n return noCase(input, { delimiter: \"/\", ...options });\n}\n\n/**\n * Convert a string to path case (`Foo bar`).\n */\nexport function sentenceCase(input: string, options?: Options) {\n const [prefix, words, suffix] = splitPrefixSuffix(input, options);\n const lower = lowerFactory(options?.locale);\n const upper = upperFactory(options?.locale);\n const transform = capitalCaseTransformFactory(lower, upper);\n return (\n prefix +\n words\n .map((word, index) => {\n if (index === 0) return transform(word);\n return lower(word);\n })\n .join(options?.delimiter ?? \" \") +\n suffix\n );\n}\n\n/**\n * Convert a string to snake case (`foo_bar`).\n */\nexport function snakeCase(input: string, options?: Options) {\n return noCase(input, { delimiter: \"_\", ...options });\n}\n\n/**\n * Convert a string to header case (`Foo-Bar`).\n */\nexport function trainCase(input: string, options?: Options) {\n return capitalCase(input, { delimiter: \"-\", ...options });\n}\n\nfunction lowerFactory(locale: Locale): (input: string) => string {\n return locale === false\n ? (input: string) => input.toLowerCase()\n : (input: string) => input.toLocaleLowerCase(locale);\n}\n\nfunction upperFactory(locale: Locale): (input: string) => string {\n return locale === false\n ? (input: string) => input.toUpperCase()\n : (input: string) => input.toLocaleUpperCase(locale);\n}\n\nfunction capitalCaseTransformFactory(\n lower: (input: string) => string,\n upper: (input: string) => string,\n) {\n return (word: string) => `${upper(word[0])}${lower(word.slice(1))}`;\n}\n\nfunction pascalCaseTransformFactory(\n lower: (input: string) => string,\n upper: (input: string) => string,\n) {\n return (word: string, index: number) => {\n const char0 = word[0];\n const initial =\n index > 0 && char0 >= \"0\" && char0 <= \"9\" ? \"_\" + char0 : upper(char0);\n return initial + lower(word.slice(1));\n };\n}\n\nfunction splitPrefixSuffix(\n input: string,\n options: Options = {},\n): [string, string[], string] {\n const splitFn =\n options.split ?? (options.separateNumbers ? splitSeparateNumbers : split);\n const prefixCharacters =\n options.prefixCharacters ?? DEFAULT_PREFIX_SUFFIX_CHARACTERS;\n const suffixCharacters =\n options.suffixCharacters ?? DEFAULT_PREFIX_SUFFIX_CHARACTERS;\n let prefixIndex = 0;\n let suffixIndex = input.length;\n\n while (prefixIndex < input.length) {\n const char = input.charAt(prefixIndex);\n if (!prefixCharacters.includes(char)) break;\n prefixIndex++;\n }\n\n while (suffixIndex > prefixIndex) {\n const index = suffixIndex - 1;\n const char = input.charAt(index);\n if (!suffixCharacters.includes(char)) break;\n suffixIndex = index;\n }\n\n return [\n input.slice(0, prefixIndex),\n splitFn(input.slice(prefixIndex, suffixIndex)),\n input.slice(suffixIndex),\n ];\n}\n","'use strict'\n\nimport map from 'map-obj'\nimport { snakeCase } from 'change-case'\n\nconst PlainObjectConstructor = {}.constructor\n\nfunction snakecaseKeys (obj, options) {\n if (Array.isArray(obj)) {\n if (obj.some(item => item.constructor !== PlainObjectConstructor)) {\n throw new Error('obj must be array of plain objects')\n }\n\n options = { deep: true, exclude: [], parsingOptions: {}, ...options }\n const convertCase = options.snakeCase || ((key) => snakeCase(key, options.parsingOptions))\n\n // Handle arrays by mapping each element\n return obj.map(item => {\n return map(item, (key, val) => {\n return [\n matches(options.exclude, key) ? key : convertCase(key),\n val,\n mapperOptions(key, val, options)\n ]\n }, options)\n })\n } else {\n if (obj.constructor !== PlainObjectConstructor) {\n throw new Error('obj must be an plain object')\n }\n }\n\n options = { deep: true, exclude: [], parsingOptions: {}, ...options }\n\n const convertCase = options.snakeCase || ((key) => snakeCase(key, options.parsingOptions))\n\n return map(obj, (key, val) => {\n return [\n matches(options.exclude, key) ? key : convertCase(key),\n val,\n mapperOptions(key, val, options)\n ]\n }, options)\n}\n\nfunction matches (patterns, value) {\n return patterns.some(pattern => {\n return typeof pattern === 'string'\n ? pattern === value\n : pattern.test(value)\n })\n}\n\nfunction mapperOptions (key, val, options) {\n return options.shouldRecurse\n ? { shouldRecurse: options.shouldRecurse(key, val) }\n : undefined\n}\n\nexport default snakecaseKeys\n","export const API_URL = 'https://api.clerk.com';\nexport const API_VERSION = 'v1';\n\nexport const USER_AGENT = `${PACKAGE_NAME}@${PACKAGE_VERSION}`;\nexport const MAX_CACHE_LAST_UPDATED_AT_SECONDS = 5 * 60;\nexport const SUPPORTED_BAPI_VERSION = '2025-04-10';\n\nconst Attributes = {\n AuthToken: '__clerkAuthToken',\n AuthSignature: '__clerkAuthSignature',\n AuthStatus: '__clerkAuthStatus',\n AuthReason: '__clerkAuthReason',\n AuthMessage: '__clerkAuthMessage',\n ClerkUrl: '__clerkUrl',\n} as const;\n\nconst Cookies = {\n Session: '__session',\n Refresh: '__refresh',\n ClientUat: '__client_uat',\n Handshake: '__clerk_handshake',\n DevBrowser: '__clerk_db_jwt',\n RedirectCount: '__clerk_redirect_count',\n HandshakeNonce: '__clerk_handshake_nonce',\n} as const;\n\nconst QueryParameters = {\n ClerkSynced: '__clerk_synced',\n SuffixedCookies: 'suffixed_cookies',\n ClerkRedirectUrl: '__clerk_redirect_url',\n // use the reference to Cookies to indicate that it's the same value\n DevBrowser: Cookies.DevBrowser,\n Handshake: Cookies.Handshake,\n HandshakeHelp: '__clerk_help',\n LegacyDevBrowser: '__dev_session',\n HandshakeReason: '__clerk_hs_reason',\n HandshakeNonce: Cookies.HandshakeNonce,\n HandshakeFormat: 'format',\n} as const;\n\nconst Headers = {\n Accept: 'accept',\n AuthMessage: 'x-clerk-auth-message',\n Authorization: 'authorization',\n AuthReason: 'x-clerk-auth-reason',\n AuthSignature: 'x-clerk-auth-signature',\n AuthStatus: 'x-clerk-auth-status',\n AuthToken: 'x-clerk-auth-token',\n CacheControl: 'cache-control',\n ClerkRedirectTo: 'x-clerk-redirect-to',\n ClerkRequestData: 'x-clerk-request-data',\n ClerkUrl: 'x-clerk-clerk-url',\n CloudFrontForwardedProto: 'cloudfront-forwarded-proto',\n ContentType: 'content-type',\n ContentSecurityPolicy: 'content-security-policy',\n ContentSecurityPolicyReportOnly: 'content-security-policy-report-only',\n EnableDebug: 'x-clerk-debug',\n ForwardedHost: 'x-forwarded-host',\n ForwardedPort: 'x-forwarded-port',\n ForwardedProto: 'x-forwarded-proto',\n Host: 'host',\n Location: 'location',\n Nonce: 'x-nonce',\n Origin: 'origin',\n Referrer: 'referer',\n SecFetchDest: 'sec-fetch-dest',\n SecFetchSite: 'sec-fetch-site',\n UserAgent: 'user-agent',\n ReportingEndpoints: 'reporting-endpoints',\n} as const;\n\nconst ContentTypes = {\n Json: 'application/json',\n} as const;\n\n/**\n * @internal\n */\nexport const constants = {\n Attributes,\n Cookies,\n Headers,\n ContentTypes,\n QueryParameters,\n} as const;\n\nexport type Constants = typeof constants;\n","import { parsePublishableKey } from './shared';\n\nexport function assertValidSecretKey(val: unknown): asserts val is string {\n if (!val || typeof val !== 'string') {\n throw Error('Missing Clerk Secret Key. Go to https://dashboard.clerk.com and get your key for your instance.');\n }\n\n //TODO: Check if the key is invalid and throw error\n}\n\nexport function assertValidPublishableKey(val: unknown): asserts val is string {\n parsePublishableKey(val as string | undefined, { fatal: true });\n}\n","import type { AccountlessApplicationJSON } from './JSON';\n\nexport class AccountlessApplication {\n constructor(\n readonly publishableKey: string,\n readonly secretKey: string,\n readonly claimUrl: string,\n readonly apiKeysUrl: string,\n ) {}\n\n static fromJSON(data: AccountlessApplicationJSON): AccountlessApplication {\n return new AccountlessApplication(data.publishable_key, data.secret_key, data.claim_url, data.api_keys_url);\n }\n}\n","import type { ActorTokenStatus } from './Enums';\nimport type { ActorTokenJSON } from './JSON';\n\nexport class ActorToken {\n constructor(\n readonly id: string,\n readonly status: ActorTokenStatus,\n readonly userId: string,\n readonly actor: Record | null,\n readonly token: string | null | undefined,\n readonly url: string | null | undefined,\n readonly createdAt: number,\n readonly updatedAt: number,\n ) {}\n\n static fromJSON(data: ActorTokenJSON): ActorToken {\n return new ActorToken(\n data.id,\n data.status,\n data.user_id,\n data.actor,\n data.token,\n data.url,\n data.created_at,\n data.updated_at,\n );\n }\n}\n","import type { AllowlistIdentifierType } from './Enums';\nimport type { AllowlistIdentifierJSON } from './JSON';\n\n/**\n * The Backend `AllowlistIdentifier` object represents an identifier that has been added to the allowlist of your application. The Backend `AllowlistIdentifier` object is used in the [Backend API](https://clerk.com/docs/reference/backend-api/tag/Allow-list-Block-list#operation/ListAllowlistIdentifiers) and is not directly accessible from the Frontend API.\n */\nexport class AllowlistIdentifier {\n constructor(\n /**\n * A unique ID for the allowlist identifier.\n */\n readonly id: string,\n /**\n * The [identifier](https://clerk.com/docs/authentication/configuration/sign-up-sign-in-options#identifiers) that was added to the allowlist.\n */\n readonly identifier: string,\n /**\n * The type of the allowlist identifier.\n */\n readonly identifierType: AllowlistIdentifierType,\n /**\n * The date when the allowlist identifier was first created.\n */\n readonly createdAt: number,\n /**\n * The date when the allowlist identifier was last updated.\n */\n readonly updatedAt: number,\n /**\n * The ID of the instance that this allowlist identifier belongs to.\n */\n readonly instanceId?: string,\n /**\n * The ID of the invitation sent to the identifier.\n */\n readonly invitationId?: string,\n ) {}\n\n static fromJSON(data: AllowlistIdentifierJSON): AllowlistIdentifier {\n return new AllowlistIdentifier(\n data.id,\n data.identifier,\n data.identifier_type,\n data.created_at,\n data.updated_at,\n data.instance_id,\n data.invitation_id,\n );\n }\n}\n","import type { APIKeyJSON } from './JSON';\n\nexport class APIKey {\n constructor(\n readonly id: string,\n readonly type: string,\n readonly name: string,\n readonly subject: string,\n readonly scopes: string[],\n readonly claims: Record | null,\n readonly revoked: boolean,\n readonly revocationReason: string | null,\n readonly expired: boolean,\n readonly expiration: number | null,\n readonly createdBy: string | null,\n readonly description: string | null,\n readonly lastUsedAt: number | null,\n readonly createdAt: number,\n readonly updatedAt: number,\n readonly secret?: string,\n ) {}\n\n static fromJSON(data: APIKeyJSON) {\n return new APIKey(\n data.id,\n data.type,\n data.name,\n data.subject,\n data.scopes,\n data.claims,\n data.revoked,\n data.revocation_reason,\n data.expired,\n data.expiration,\n data.created_by,\n data.description,\n data.last_used_at,\n data.created_at,\n data.updated_at,\n data.secret,\n );\n }\n}\n","import type { BlocklistIdentifierType } from './Enums';\nimport type { BlocklistIdentifierJSON } from './JSON';\n\nexport class BlocklistIdentifier {\n constructor(\n readonly id: string,\n readonly identifier: string,\n readonly identifierType: BlocklistIdentifierType,\n readonly createdAt: number,\n readonly updatedAt: number,\n readonly instanceId?: string,\n ) {}\n\n static fromJSON(data: BlocklistIdentifierJSON): BlocklistIdentifier {\n return new BlocklistIdentifier(\n data.id,\n data.identifier,\n data.identifier_type,\n data.created_at,\n data.updated_at,\n data.instance_id,\n );\n }\n}\n","import type { SessionActivityJSON, SessionJSON } from './JSON';\n\n/**\n * The Backend `SessionActivity` object models the activity of a user session, capturing details such as the device type, browser information, and geographical location.\n */\nexport class SessionActivity {\n constructor(\n /**\n * The unique identifier for the session activity record.\n */\n readonly id: string,\n /**\n * Will be set to `true` if the session activity came from a mobile device. Set to `false` otherwise.\n */\n readonly isMobile: boolean,\n /**\n * The IP address from which this session activity originated.\n */\n readonly ipAddress?: string,\n /**\n * The city from which this session activity occurred. Resolved by IP address geo-location.\n */\n readonly city?: string,\n /**\n * The country from which this session activity occurred. Resolved by IP address geo-location.\n */\n readonly country?: string,\n /**\n * The version of the browser from which this session activity occurred.\n */\n readonly browserVersion?: string,\n /**\n * The name of the browser from which this session activity occurred.\n */\n readonly browserName?: string,\n /**\n * The type of the device which was used in this session activity.\n */\n readonly deviceType?: string,\n ) {}\n\n static fromJSON(data: SessionActivityJSON): SessionActivity {\n return new SessionActivity(\n data.id,\n data.is_mobile,\n data.ip_address,\n data.city,\n data.country,\n data.browser_version,\n data.browser_name,\n data.device_type,\n );\n }\n}\n\n/**\n * The Backend `Session` object is similar to the [`Session`](https://clerk.com/docs/references/javascript/session) object as it is an abstraction over an HTTP session and models the period of information exchange between a user and the server. However, the Backend `Session` object is different as it is used in the [Backend API](https://clerk.com/docs/reference/backend-api/tag/Sessions#operation/GetSessionList) and is not directly accessible from the Frontend API.\n */\nexport class Session {\n constructor(\n /**\n * The unique identifier for the `Session`.\n */\n readonly id: string,\n /**\n * The ID of the client associated with the `Session`.\n */\n readonly clientId: string,\n /**\n * The ID of the user associated with the `Session`.\n */\n readonly userId: string,\n /**\n * The current state of the `Session`.\n */\n readonly status: string,\n /**\n * The time the session was last active on the [`Client`](https://clerk.com/docs/references/backend/types/backend-client).\n */\n readonly lastActiveAt: number,\n /**\n * The date when the `Session` will expire.\n */\n readonly expireAt: number,\n /**\n * The date when the `Session` will be abandoned.\n */\n readonly abandonAt: number,\n /**\n * The date when the `Session` was first created.\n */\n readonly createdAt: number,\n /**\n * The date when the `Session` was last updated.\n */\n readonly updatedAt: number,\n /**\n * The ID of the last active organization.\n */\n readonly lastActiveOrganizationId?: string,\n /**\n * An object that provides additional information about this session, focused around user activity data.\n */\n readonly latestActivity?: SessionActivity,\n /**\n * The JWT actor for the session. Holds identifier for the user that is impersonating the current user. Read more about [impersonation](https://clerk.com/docs/users/user-impersonation).\n */\n readonly actor: Record | null = null,\n ) {}\n\n static fromJSON(data: SessionJSON): Session {\n return new Session(\n data.id,\n data.client_id,\n data.user_id,\n data.status,\n data.last_active_at,\n data.expire_at,\n data.abandon_at,\n data.created_at,\n data.updated_at,\n data.last_active_organization_id,\n data.latest_activity && SessionActivity.fromJSON(data.latest_activity),\n data.actor,\n );\n }\n}\n","import type { LastAuthenticationStrategy } from '@clerk/types';\n\nimport type { ClientJSON } from './JSON';\nimport { Session } from './Session';\n\n/**\n * The Backend `Client` object is similar to the [`Client`](https://clerk.com/docs/references/javascript/client) object as it holds information about the authenticated sessions in the current device. However, the Backend `Client` object is different from the `Client` object in that it is used in the [Backend API](https://clerk.com/docs/reference/backend-api/tag/Clients#operation/GetClient) and is not directly accessible from the Frontend API.\n */\nexport class Client {\n constructor(\n /**\n * The unique identifier for the `Client`.\n */\n readonly id: string,\n /**\n * An array of [Session](https://clerk.com/docs/references/backend/types/backend-session){{ target: '_blank' }} IDs associated with the `Client`.\n */\n readonly sessionIds: string[],\n /**\n * An array of [Session](https://clerk.com/docs/references/backend/types/backend-session){{ target: '_blank' }} objects associated with the `Client`.\n */\n readonly sessions: Session[],\n /**\n * The ID of the [`SignIn`](https://clerk.com/docs/references/javascript/sign-in){{ target: '_blank' }}.\n */\n readonly signInId: string | null,\n /**\n * The ID of the [`SignUp`](https://clerk.com/docs/references/javascript/sign-up){{ target: '_blank' }}.\n */\n readonly signUpId: string | null,\n /**\n * The ID of the last active [Session](https://clerk.com/docs/references/backend/types/backend-session).\n */\n readonly lastActiveSessionId: string | null,\n /**\n * The last authentication strategy used by the `Client`.\n */\n readonly lastAuthenticationStrategy: LastAuthenticationStrategy | null,\n /**\n * The date when the `Client` was first created.\n */\n readonly createdAt: number,\n /**\n * The date when the `Client` was last updated.\n */\n readonly updatedAt: number,\n ) {}\n\n static fromJSON(data: ClientJSON): Client {\n return new Client(\n data.id,\n data.session_ids,\n data.sessions.map(x => Session.fromJSON(x)),\n data.sign_in_id,\n data.sign_up_id,\n data.last_active_session_id,\n data.last_authentication_strategy,\n data.created_at,\n data.updated_at,\n );\n }\n}\n","import type { CnameTargetJSON } from './JSON';\n\nexport class CnameTarget {\n constructor(\n readonly host: string,\n readonly value: string,\n readonly required: boolean,\n ) {}\n\n static fromJSON(data: CnameTargetJSON): CnameTarget {\n return new CnameTarget(data.host, data.value, data.required);\n }\n}\n","import type { CookiesJSON } from './JSON';\n\nexport class Cookies {\n constructor(readonly cookies: string[]) {}\n\n static fromJSON(data: CookiesJSON): Cookies {\n return new Cookies(data.cookies);\n }\n}\n","import type { DeletedObjectJSON } from './JSON';\n\nexport class DeletedObject {\n constructor(\n readonly object: string,\n readonly id: string | null,\n readonly slug: string | null,\n readonly deleted: boolean,\n ) {}\n\n static fromJSON(data: DeletedObjectJSON) {\n return new DeletedObject(data.object, data.id || null, data.slug || null, data.deleted);\n }\n}\n","import { CnameTarget } from './CnameTarget';\nimport type { DomainJSON } from './JSON';\n\nexport class Domain {\n constructor(\n readonly id: string,\n readonly name: string,\n readonly isSatellite: boolean,\n readonly frontendApiUrl: string,\n readonly developmentOrigin: string,\n readonly cnameTargets: CnameTarget[],\n readonly accountsPortalUrl?: string | null,\n readonly proxyUrl?: string | null,\n ) {}\n\n static fromJSON(data: DomainJSON): Domain {\n return new Domain(\n data.id,\n data.name,\n data.is_satellite,\n data.frontend_api_url,\n data.development_origin,\n data.cname_targets && data.cname_targets.map(x => CnameTarget.fromJSON(x)),\n data.accounts_portal_url,\n data.proxy_url,\n );\n }\n}\n","import type { EmailJSON } from './JSON';\n\nexport class Email {\n constructor(\n readonly id: string,\n readonly fromEmailName: string,\n readonly emailAddressId: string | null,\n readonly toEmailAddress?: string,\n readonly subject?: string,\n readonly body?: string,\n readonly bodyPlain?: string | null,\n readonly status?: string,\n readonly slug?: string | null,\n readonly data?: Record | null,\n readonly deliveredByClerk?: boolean,\n ) {}\n\n static fromJSON(data: EmailJSON): Email {\n return new Email(\n data.id,\n data.from_email_name,\n data.email_address_id,\n data.to_email_address,\n data.subject,\n data.body,\n data.body_plain,\n data.status,\n data.slug,\n data.data,\n data.delivered_by_clerk,\n );\n }\n}\n","import type { IdentificationLinkJSON } from './JSON';\n\n/**\n * Contains information about any identifications that might be linked to the email address.\n */\nexport class IdentificationLink {\n constructor(\n /**\n * The unique identifier for the identification link.\n */\n readonly id: string,\n /**\n * The type of the identification link, e.g., `\"email_address\"`, `\"phone_number\"`, etc.\n */\n readonly type: string,\n ) {}\n\n static fromJSON(data: IdentificationLinkJSON): IdentificationLink {\n return new IdentificationLink(data.id, data.type);\n }\n}\n","import type { VerificationStatus } from '@clerk/types';\n\nimport type { OrganizationDomainVerificationJSON, VerificationJSON } from './JSON';\n\n/**\n * The Backend `Verification` object describes the state of the verification process of a sign-in or sign-up attempt.\n */\nexport class Verification {\n constructor(\n /**\n * The state of the verification.\n *\n *
    \n *
  • `unverified`: The verification has not been verified yet.
  • \n *
  • `verified`: The verification has been verified.
  • \n *
  • `transferable`: The verification is transferable to between sign-in and sign-up flows.
  • \n *
  • `failed`: The verification has failed.
  • \n *
  • `expired`: The verification has expired.
  • \n *
\n */\n readonly status: VerificationStatus,\n /**\n * The strategy pertaining to the parent sign-up or sign-in attempt.\n */\n readonly strategy: string,\n /**\n * The redirect URL for an external verification.\n */\n readonly externalVerificationRedirectURL: URL | null = null,\n /**\n * The number of attempts related to the verification.\n */\n readonly attempts: number | null = null,\n /**\n * The time the verification will expire at.\n */\n readonly expireAt: number | null = null,\n /**\n * The [nonce](https://en.wikipedia.org/wiki/Cryptographic_nonce) pertaining to the verification.\n */\n readonly nonce: string | null = null,\n /**\n * The message that will be presented to the user's Web3 wallet for signing during authentication. This follows the [Sign-In with Ethereum (SIWE) protocol format](https://docs.login.xyz/general-information/siwe-overview/eip-4361#example-message-to-be-signed), which typically includes details like the requesting service, wallet address, terms acceptance, nonce, timestamp, and any additional resources.\n */\n readonly message: string | null = null,\n ) {}\n\n static fromJSON(data: VerificationJSON): Verification {\n return new Verification(\n data.status,\n data.strategy,\n data.external_verification_redirect_url ? new URL(data.external_verification_redirect_url) : null,\n data.attempts,\n data.expire_at,\n data.nonce,\n );\n }\n}\n\nexport class OrganizationDomainVerification {\n constructor(\n readonly status: string,\n readonly strategy: string,\n readonly attempts: number | null = null,\n readonly expireAt: number | null = null,\n ) {}\n\n static fromJSON(data: OrganizationDomainVerificationJSON): OrganizationDomainVerification {\n return new OrganizationDomainVerification(data.status, data.strategy, data.attempts, data.expires_at);\n }\n}\n","import { IdentificationLink } from './IdentificationLink';\nimport type { EmailAddressJSON } from './JSON';\nimport { Verification } from './Verification';\n\n/**\n * The Backend `EmailAddress` object is a model around an email address. Email addresses are one of the [identifiers](https://clerk.com/docs/authentication/configuration/sign-up-sign-in-options#identifiers) used to provide identification for users.\n *\n * Email addresses must be **verified** to ensure that they are assigned to their rightful owners. The `EmailAddress` object holds all necessary state around the verification process.\n *\n * For implementation examples for adding and verifying email addresses, see the [email link custom flow](https://clerk.com/docs/custom-flows/email-links) and [email code custom flow](https://clerk.com/docs/custom-flows/add-email) guides.\n */\nexport class EmailAddress {\n constructor(\n /**\n * The unique identifier for the email address.\n */\n readonly id: string,\n /**\n * The value of the email address.\n */\n readonly emailAddress: string,\n /**\n * An object holding information on the verification of the email address.\n */\n readonly verification: Verification | null,\n /**\n * An array of objects containing information about any identifications that might be linked to the email address.\n */\n readonly linkedTo: IdentificationLink[],\n ) {}\n\n static fromJSON(data: EmailAddressJSON): EmailAddress {\n return new EmailAddress(\n data.id,\n data.email_address,\n data.verification && Verification.fromJSON(data.verification),\n data.linked_to.map(link => IdentificationLink.fromJSON(link)),\n );\n }\n}\n","import type { ExternalAccountJSON } from './JSON';\nimport { Verification } from './Verification';\n\n/**\n * The Backend `ExternalAccount` object is a model around an identification obtained by an external provider (e.g. a social provider such as Google).\n *\n * External account must be verified, so that you can make sure they can be assigned to their rightful owners. The `ExternalAccount` object holds all necessary state around the verification process.\n */\nexport class ExternalAccount {\n constructor(\n /**\n * The unique identifier for this external account.\n */\n readonly id: string,\n /**\n * The provider name (e.g., `google`).\n */\n readonly provider: string,\n /**\n * The identification with which this external account is associated.\n */\n readonly identificationId: string,\n /**\n * The unique ID of the user in the provider.\n */\n readonly externalId: string,\n /**\n * The scopes that the user has granted access to.\n */\n readonly approvedScopes: string,\n /**\n * The user's email address.\n */\n readonly emailAddress: string,\n /**\n * The user's first name.\n */\n readonly firstName: string,\n /**\n * The user's last name.\n */\n readonly lastName: string,\n /**\n * The user's image URL.\n */\n readonly imageUrl: string,\n /**\n * The user's username.\n */\n readonly username: string | null,\n /**\n * The phone number related to this specific external account.\n */\n readonly phoneNumber: string | null,\n /**\n * Metadata that can be read from the Frontend API and Backend API and can be set only from the Backend API.\n */\n readonly publicMetadata: Record | null = {},\n /**\n * A descriptive label to differentiate multiple external accounts of the same user for the same provider.\n */\n readonly label: string | null,\n /**\n * An object holding information on the verification of this external account.\n */\n readonly verification: Verification | null,\n ) {}\n\n static fromJSON(data: ExternalAccountJSON): ExternalAccount {\n return new ExternalAccount(\n data.id,\n data.provider,\n data.identification_id,\n data.provider_user_id,\n data.approved_scopes,\n data.email_address,\n data.first_name,\n data.last_name,\n data.image_url || '',\n data.username,\n data.phone_number,\n data.public_metadata,\n data.label,\n data.verification && Verification.fromJSON(data.verification),\n );\n }\n}\n","import type { IdPOAuthAccessTokenJSON } from './JSON';\n\nexport class IdPOAuthAccessToken {\n constructor(\n readonly id: string,\n readonly clientId: string,\n readonly type: string,\n readonly subject: string,\n readonly scopes: string[],\n readonly revoked: boolean,\n readonly revocationReason: string | null,\n readonly expired: boolean,\n readonly expiration: number | null,\n readonly createdAt: number,\n readonly updatedAt: number,\n ) {}\n\n static fromJSON(data: IdPOAuthAccessTokenJSON) {\n return new IdPOAuthAccessToken(\n data.id,\n data.client_id,\n data.type,\n data.subject,\n data.scopes,\n data.revoked,\n data.revocation_reason,\n data.expired,\n data.expiration,\n data.created_at,\n data.updated_at,\n );\n }\n}\n","import type { InstanceJSON } from './JSON';\n\nexport class Instance {\n constructor(\n readonly id: string,\n readonly environmentType: string,\n readonly allowedOrigins: Array | null,\n ) {}\n\n static fromJSON(data: InstanceJSON): Instance {\n return new Instance(data.id, data.environment_type, data.allowed_origins);\n }\n}\n","import type { InstanceRestrictionsJSON } from './JSON';\n\nexport class InstanceRestrictions {\n constructor(\n readonly allowlist: boolean,\n readonly blocklist: boolean,\n readonly blockEmailSubaddresses: boolean,\n readonly blockDisposableEmailDomains: boolean,\n readonly ignoreDotsForGmailAddresses: boolean,\n ) {}\n\n static fromJSON(data: InstanceRestrictionsJSON): InstanceRestrictions {\n return new InstanceRestrictions(\n data.allowlist,\n data.blocklist,\n data.block_email_subaddresses,\n data.block_disposable_email_domains,\n data.ignore_dots_for_gmail_addresses,\n );\n }\n}\n","import type { InstanceSettingsJSON } from './JSON';\n\nexport class InstanceSettings {\n constructor(\n readonly id?: string | undefined,\n readonly restrictedToAllowlist?: boolean | undefined,\n readonly fromEmailAddress?: string | undefined,\n readonly progressiveSignUp?: boolean | undefined,\n readonly enhancedEmailDeliverability?: boolean | undefined,\n ) {}\n\n static fromJSON(data: InstanceSettingsJSON): InstanceSettings {\n return new InstanceSettings(\n data.id,\n data.restricted_to_allowlist,\n data.from_email_address,\n data.progressive_sign_up,\n data.enhanced_email_deliverability,\n );\n }\n}\n","import type { InvitationStatus } from './Enums';\nimport type { InvitationJSON } from './JSON';\n\n/**\n * The Backend `Invitation` object represents an invitation to join your application.\n */\nexport class Invitation {\n private _raw: InvitationJSON | null = null;\n\n public get raw(): InvitationJSON | null {\n return this._raw;\n }\n\n constructor(\n /**\n * The unique identifier for the `Invitation`.\n */\n readonly id: string,\n /**\n * The email address that the invitation was sent to.\n */\n readonly emailAddress: string,\n /**\n * [Metadata](https://clerk.com/docs/references/javascript/types/metadata#user-public-metadata){{ target: '_blank' }} that can be read from the Frontend API and [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }} and can be set only from the Backend API. Once the user accepts the invitation and signs up, these metadata will end up in the user's public metadata.\n */\n readonly publicMetadata: Record | null,\n /**\n * The date when the `Invitation` was first created.\n */\n readonly createdAt: number,\n /**\n * The date when the `Invitation` was last updated.\n */\n readonly updatedAt: number,\n /**\n * The status of the `Invitation`.\n */\n readonly status: InvitationStatus,\n /**\n * The URL that the user can use to accept the invitation.\n */\n readonly url?: string,\n /**\n * Whether the `Invitation` has been revoked.\n */\n readonly revoked?: boolean,\n ) {}\n\n static fromJSON(data: InvitationJSON): Invitation {\n const res = new Invitation(\n data.id,\n data.email_address,\n data.public_metadata,\n data.created_at,\n data.updated_at,\n data.status,\n data.url,\n data.revoked,\n );\n res._raw = data;\n return res;\n }\n}\n","import type { LastAuthenticationStrategy, SignUpStatus, VerificationStatus } from '@clerk/types';\n\nimport type {\n ActorTokenStatus,\n AllowlistIdentifierType,\n BlocklistIdentifierType,\n DomainsEnrollmentModes,\n InvitationStatus,\n OrganizationDomainVerificationStatus,\n OrganizationDomainVerificationStrategy,\n OrganizationEnrollmentMode,\n OrganizationInvitationStatus,\n OrganizationMembershipRole,\n SignInStatus,\n SignUpVerificationNextAction,\n WaitlistEntryStatus,\n} from './Enums';\n\nexport const ObjectType = {\n AccountlessApplication: 'accountless_application',\n ActorToken: 'actor_token',\n AllowlistIdentifier: 'allowlist_identifier',\n ApiKey: 'api_key',\n BlocklistIdentifier: 'blocklist_identifier',\n Client: 'client',\n Cookies: 'cookies',\n Domain: 'domain',\n Email: 'email',\n EmailAddress: 'email_address',\n ExternalAccount: 'external_account',\n FacebookAccount: 'facebook_account',\n GoogleAccount: 'google_account',\n Instance: 'instance',\n InstanceRestrictions: 'instance_restrictions',\n InstanceSettings: 'instance_settings',\n Invitation: 'invitation',\n Machine: 'machine',\n MachineScope: 'machine_scope',\n MachineSecretKey: 'machine_secret_key',\n M2MToken: 'machine_to_machine_token',\n JwtTemplate: 'jwt_template',\n OauthAccessToken: 'oauth_access_token',\n IdpOAuthAccessToken: 'clerk_idp_oauth_access_token',\n OAuthApplication: 'oauth_application',\n Organization: 'organization',\n OrganizationDomain: 'organization_domain',\n OrganizationInvitation: 'organization_invitation',\n OrganizationMembership: 'organization_membership',\n OrganizationSettings: 'organization_settings',\n PhoneNumber: 'phone_number',\n ProxyCheck: 'proxy_check',\n RedirectUrl: 'redirect_url',\n SamlAccount: 'saml_account',\n SamlConnection: 'saml_connection',\n Session: 'session',\n SignInAttempt: 'sign_in_attempt',\n SignInToken: 'sign_in_token',\n SignUpAttempt: 'sign_up_attempt',\n SmsMessage: 'sms_message',\n User: 'user',\n WaitlistEntry: 'waitlist_entry',\n Web3Wallet: 'web3_wallet',\n Token: 'token',\n TotalCount: 'total_count',\n TestingToken: 'testing_token',\n Role: 'role',\n Permission: 'permission',\n BillingPayer: 'commerce_payer',\n BillingPaymentAttempt: 'commerce_payment_attempt',\n BillingSubscription: 'commerce_subscription',\n BillingSubscriptionItem: 'commerce_subscription_item',\n BillingPlan: 'commerce_plan',\n Feature: 'feature',\n} as const;\n\nexport type ObjectType = (typeof ObjectType)[keyof typeof ObjectType];\n\nexport interface ClerkResourceJSON {\n /**\n * The type of the resource.\n */\n object: ObjectType;\n /**\n * The unique identifier for the resource.\n */\n id: string;\n}\n\nexport interface CookiesJSON {\n object: typeof ObjectType.Cookies;\n cookies: string[];\n}\n\nexport interface TokenJSON {\n object: typeof ObjectType.Token;\n jwt: string;\n}\n\nexport interface AccountlessApplicationJSON extends ClerkResourceJSON {\n object: typeof ObjectType.AccountlessApplication;\n publishable_key: string;\n secret_key: string;\n claim_url: string;\n api_keys_url: string;\n}\n\nexport interface ActorTokenJSON extends ClerkResourceJSON {\n object: typeof ObjectType.ActorToken;\n id: string;\n status: ActorTokenStatus;\n user_id: string;\n actor: Record | null;\n token?: string | null;\n url?: string | null;\n created_at: number;\n updated_at: number;\n}\n\nexport interface AllowlistIdentifierJSON extends ClerkResourceJSON {\n object: typeof ObjectType.AllowlistIdentifier;\n identifier: string;\n identifier_type: AllowlistIdentifierType;\n instance_id?: string;\n invitation_id?: string;\n created_at: number;\n updated_at: number;\n}\n\nexport interface BlocklistIdentifierJSON extends ClerkResourceJSON {\n object: typeof ObjectType.BlocklistIdentifier;\n identifier: string;\n identifier_type: BlocklistIdentifierType;\n instance_id?: string;\n created_at: number;\n updated_at: number;\n}\n\nexport interface ClientJSON extends ClerkResourceJSON {\n object: typeof ObjectType.Client;\n session_ids: string[];\n sessions: SessionJSON[];\n sign_in_id: string | null;\n sign_up_id: string | null;\n last_active_session_id: string | null;\n last_authentication_strategy: LastAuthenticationStrategy | null;\n created_at: number;\n updated_at: number;\n}\n\nexport interface CnameTargetJSON {\n host: string;\n value: string;\n /**\n * Denotes whether this CNAME target is required to be set in order for the domain to be considered deployed.\n */\n required: boolean;\n}\n\nexport interface DomainJSON extends ClerkResourceJSON {\n object: typeof ObjectType.Domain;\n id: string;\n name: string;\n is_satellite: boolean;\n frontend_api_url: string;\n /**\n * null for satellite domains\n */\n accounts_portal_url?: string | null;\n proxy_url?: string;\n development_origin: string;\n cname_targets: CnameTargetJSON[];\n}\n\nexport interface EmailJSON extends ClerkResourceJSON {\n object: typeof ObjectType.Email;\n slug?: string | null;\n from_email_name: string;\n to_email_address?: string;\n email_address_id: string | null;\n user_id?: string | null;\n subject?: string;\n body?: string;\n body_plain?: string | null;\n status?: string;\n data?: Record | null;\n delivered_by_clerk: boolean;\n}\n\nexport interface EmailAddressJSON extends ClerkResourceJSON {\n object: typeof ObjectType.EmailAddress;\n email_address: string;\n verification: VerificationJSON | null;\n linked_to: IdentificationLinkJSON[];\n}\n\nexport interface ExternalAccountJSON extends ClerkResourceJSON {\n object: typeof ObjectType.ExternalAccount;\n provider: string;\n identification_id: string;\n provider_user_id: string;\n approved_scopes: string;\n email_address: string;\n first_name: string;\n last_name: string;\n image_url?: string;\n username: string | null;\n phone_number: string | null;\n public_metadata?: Record | null;\n label: string | null;\n verification: VerificationJSON | null;\n}\n\nexport interface JwksJSON {\n keys?: JwksKeyJSON[];\n}\n\nexport interface JwksKeyJSON {\n use: string;\n kty: string;\n kid: string;\n alg: string;\n n: string;\n e: string;\n}\n\nexport interface JwtTemplateJSON extends ClerkResourceJSON {\n object: typeof ObjectType.JwtTemplate;\n id: string;\n name: string;\n claims: object;\n lifetime: number;\n allowed_clock_skew: number;\n custom_signing_key: boolean;\n signing_algorithm: string;\n created_at: number;\n updated_at: number;\n}\n\nexport interface SamlAccountJSON extends ClerkResourceJSON {\n object: typeof ObjectType.SamlAccount;\n provider: string;\n provider_user_id: string | null;\n active: boolean;\n email_address: string;\n first_name: string;\n last_name: string;\n verification: VerificationJSON | null;\n saml_connection: SamlAccountConnectionJSON | null;\n}\n\nexport interface IdentificationLinkJSON extends ClerkResourceJSON {\n type: string;\n}\n\nexport interface OrganizationSettingsJSON extends ClerkResourceJSON {\n object: typeof ObjectType.OrganizationSettings;\n enabled: boolean;\n max_allowed_memberships: number;\n max_allowed_roles: number;\n max_allowed_permissions: number;\n creator_role: string;\n admin_delete_enabled: boolean;\n domains_enabled: boolean;\n domains_enrollment_modes: Array;\n domains_default_role: string;\n}\n\nexport interface InstanceJSON extends ClerkResourceJSON {\n object: typeof ObjectType.Instance;\n id: string;\n environment_type: string;\n allowed_origins: Array | null;\n}\n\nexport interface InstanceRestrictionsJSON extends ClerkResourceJSON {\n object: typeof ObjectType.InstanceRestrictions;\n allowlist: boolean;\n blocklist: boolean;\n block_email_subaddresses: boolean;\n block_disposable_email_domains: boolean;\n ignore_dots_for_gmail_addresses: boolean;\n}\n\nexport interface InstanceSettingsJSON extends ClerkResourceJSON {\n object: typeof ObjectType.InstanceSettings;\n id: string;\n restricted_to_allowlist: boolean;\n from_email_address: string;\n progressive_sign_up: boolean;\n enhanced_email_deliverability: boolean;\n}\n\nexport interface InvitationJSON extends ClerkResourceJSON {\n object: typeof ObjectType.Invitation;\n email_address: string;\n public_metadata: Record | null;\n revoked?: boolean;\n status: InvitationStatus;\n url?: string;\n created_at: number;\n updated_at: number;\n}\n\nexport interface OauthAccessTokenJSON {\n external_account_id: string;\n object: typeof ObjectType.OauthAccessToken;\n token: string;\n provider: string;\n public_metadata: Record;\n label: string | null;\n // Only set in OAuth 2.0 tokens\n scopes?: string[];\n // Only set in OAuth 1.0 tokens\n token_secret?: string;\n expires_at?: number;\n}\n\nexport interface OAuthApplicationJSON extends ClerkResourceJSON {\n object: typeof ObjectType.OAuthApplication;\n id: string;\n instance_id: string;\n name: string;\n client_id: string;\n client_uri: string | null;\n client_image_url: string | null;\n dynamically_registered: boolean;\n consent_screen_enabled: boolean;\n pkce_required: boolean;\n public: boolean;\n scopes: string;\n redirect_uris: Array;\n authorize_url: string;\n token_fetch_url: string;\n user_info_url: string;\n discovery_url: string;\n token_introspection_url: string;\n created_at: number;\n updated_at: number;\n client_secret?: string;\n}\n\nexport interface OrganizationJSON extends ClerkResourceJSON {\n object: typeof ObjectType.Organization;\n name: string;\n slug: string;\n image_url?: string;\n has_image: boolean;\n members_count?: number;\n pending_invitations_count?: number;\n max_allowed_memberships: number;\n admin_delete_enabled: boolean;\n public_metadata: OrganizationPublicMetadata | null;\n private_metadata?: OrganizationPrivateMetadata;\n created_by?: string;\n created_at: number;\n updated_at: number;\n}\n\nexport interface OrganizationDomainJSON extends ClerkResourceJSON {\n object: typeof ObjectType.OrganizationDomain;\n id: string;\n name: string;\n organization_id: string;\n enrollment_mode: OrganizationEnrollmentMode;\n verification: OrganizationDomainVerificationJSON | null;\n affiliation_email_address: string | null;\n created_at: number;\n updated_at: number;\n total_pending_invitations: number;\n total_pending_suggestions: number;\n}\n\nexport interface OrganizationDomainVerificationJSON {\n status: OrganizationDomainVerificationStatus;\n strategy: OrganizationDomainVerificationStrategy;\n attempts: number;\n expires_at: number;\n}\n\nexport interface OrganizationInvitationJSON extends ClerkResourceJSON {\n email_address: string;\n role: OrganizationMembershipRole;\n role_name: string;\n organization_id: string;\n public_organization_data?: PublicOrganizationDataJSON | null;\n status?: OrganizationInvitationStatus;\n public_metadata: OrganizationInvitationPublicMetadata;\n private_metadata: OrganizationInvitationPrivateMetadata;\n url: string | null;\n created_at: number;\n updated_at: number;\n expires_at: number;\n}\n\n/**\n * @interface\n */\nexport interface PublicOrganizationDataJSON extends ClerkResourceJSON {\n /**\n * The name of the organization.\n */\n name: string;\n /**\n * The slug of the organization.\n */\n slug: string;\n /**\n * Holds the default organization profile image. Compatible with Clerk's [Image Optimization](https://clerk.com/docs/guides/image-optimization).\n */\n image_url?: string;\n /**\n * Whether the organization has a profile image.\n */\n has_image: boolean;\n}\n\nexport interface OrganizationMembershipJSON extends ClerkResourceJSON {\n object: typeof ObjectType.OrganizationMembership;\n public_metadata: OrganizationMembershipPublicMetadata;\n private_metadata?: OrganizationMembershipPrivateMetadata;\n role: OrganizationMembershipRole;\n permissions: string[];\n created_at: number;\n updated_at: number;\n organization: OrganizationJSON;\n public_user_data: OrganizationMembershipPublicUserDataJSON;\n}\n\nexport interface OrganizationMembershipPublicUserDataJSON {\n identifier: string;\n first_name: string | null;\n last_name: string | null;\n image_url: string;\n has_image: boolean;\n user_id: string;\n}\n\nexport interface PhoneNumberJSON extends ClerkResourceJSON {\n object: typeof ObjectType.PhoneNumber;\n phone_number: string;\n reserved_for_second_factor: boolean;\n default_second_factor: boolean;\n reserved: boolean;\n verification: VerificationJSON | null;\n linked_to: IdentificationLinkJSON[];\n backup_codes: string[];\n}\n\nexport type ProxyCheckJSON = {\n object: typeof ObjectType.ProxyCheck;\n id: string;\n domain_id: string;\n last_run_at: number | null;\n proxy_url: string;\n successful: boolean;\n created_at: number;\n updated_at: number;\n};\n\nexport interface RedirectUrlJSON extends ClerkResourceJSON {\n object: typeof ObjectType.RedirectUrl;\n url: string;\n created_at: number;\n updated_at: number;\n}\n\nexport interface SessionActivityJSON extends ClerkResourceJSON {\n id: string;\n device_type?: string;\n is_mobile: boolean;\n browser_name?: string;\n browser_version?: string;\n ip_address?: string;\n city?: string;\n country?: string;\n}\n\nexport interface SessionJSON extends ClerkResourceJSON {\n object: typeof ObjectType.Session;\n client_id: string;\n user_id: string;\n status: string;\n last_active_organization_id?: string;\n actor: Record | null;\n latest_activity?: SessionActivityJSON;\n last_active_at: number;\n expire_at: number;\n abandon_at: number;\n created_at: number;\n updated_at: number;\n}\n\nexport interface SignInJSON extends ClerkResourceJSON {\n object: typeof ObjectType.SignInToken;\n status: SignInStatus;\n identifier: string;\n created_session_id: string | null;\n}\n\nexport interface SignInTokenJSON extends ClerkResourceJSON {\n object: typeof ObjectType.SignInToken;\n user_id: string;\n token: string;\n status: 'pending' | 'accepted' | 'revoked';\n url: string;\n created_at: number;\n updated_at: number;\n}\n\nexport interface SignUpJSON extends ClerkResourceJSON {\n object: typeof ObjectType.SignUpAttempt;\n id: string;\n status: SignUpStatus;\n required_fields: string[];\n optional_fields: string[];\n missing_fields: string[];\n unverified_fields: string[];\n verifications: SignUpVerificationsJSON;\n username: string | null;\n email_address: string | null;\n phone_number: string | null;\n web3_wallet: string | null;\n password_enabled: boolean;\n first_name: string | null;\n last_name: string | null;\n public_metadata?: Record | null;\n unsafe_metadata?: Record | null;\n custom_action: boolean;\n external_id: string | null;\n created_session_id: string | null;\n created_user_id: string | null;\n abandon_at: number | null;\n legal_accepted_at: number | null;\n\n /**\n * @deprecated Please use `verifications.external_account` instead\n */\n external_account: object | null;\n}\n\nexport interface SignUpVerificationsJSON {\n email_address: SignUpVerificationJSON;\n phone_number: SignUpVerificationJSON;\n web3_wallet: SignUpVerificationJSON;\n external_account: VerificationJSON;\n}\n\nexport interface SignUpVerificationJSON {\n next_action: SignUpVerificationNextAction;\n supported_strategies: string[];\n}\n\nexport interface SMSMessageJSON extends ClerkResourceJSON {\n object: typeof ObjectType.SmsMessage;\n from_phone_number: string;\n to_phone_number: string;\n phone_number_id: string | null;\n user_id?: string;\n message: string;\n status: string;\n slug?: string | null;\n data?: Record | null;\n delivered_by_clerk: boolean;\n}\n\nexport interface UserJSON extends ClerkResourceJSON {\n object: typeof ObjectType.User;\n username: string | null;\n first_name: string | null;\n last_name: string | null;\n image_url: string;\n has_image: boolean;\n primary_email_address_id: string | null;\n primary_phone_number_id: string | null;\n primary_web3_wallet_id: string | null;\n password_enabled: boolean;\n two_factor_enabled: boolean;\n totp_enabled: boolean;\n backup_code_enabled: boolean;\n email_addresses: EmailAddressJSON[];\n phone_numbers: PhoneNumberJSON[];\n web3_wallets: Web3WalletJSON[];\n organization_memberships: OrganizationMembershipJSON[] | null;\n external_accounts: ExternalAccountJSON[];\n saml_accounts: SamlAccountJSON[];\n password_last_updated_at: number | null;\n public_metadata: UserPublicMetadata;\n private_metadata: UserPrivateMetadata;\n unsafe_metadata: UserUnsafeMetadata;\n external_id: string | null;\n last_sign_in_at: number | null;\n banned: boolean;\n locked: boolean;\n lockout_expires_in_seconds: number | null;\n verification_attempts_remaining: number | null;\n created_at: number;\n updated_at: number;\n last_active_at: number | null;\n create_organization_enabled: boolean;\n create_organizations_limit: number | null;\n delete_self_enabled: boolean;\n legal_accepted_at: number | null;\n}\n\nexport interface VerificationJSON extends ClerkResourceJSON {\n status: VerificationStatus;\n strategy: string;\n attempts: number | null;\n expire_at: number | null;\n verified_at_client?: string;\n external_verification_redirect_url?: string | null;\n nonce?: string | null;\n message?: string | null;\n}\n\nexport interface WaitlistEntryJSON extends ClerkResourceJSON {\n object: typeof ObjectType.WaitlistEntry;\n id: string;\n status: WaitlistEntryStatus;\n email_address: string;\n invitation: InvitationJSON | null;\n is_locked: boolean;\n created_at: number;\n updated_at: number;\n}\n\nexport interface Web3WalletJSON extends ClerkResourceJSON {\n object: typeof ObjectType.Web3Wallet;\n web3_wallet: string;\n verification: VerificationJSON | null;\n}\n\nexport interface DeletedObjectJSON {\n object: string;\n id?: string;\n slug?: string;\n deleted: boolean;\n}\n\nexport interface PaginatedResponseJSON {\n data: object[];\n total_count?: number;\n}\n\nexport interface SamlConnectionJSON extends ClerkResourceJSON {\n object: typeof ObjectType.SamlConnection;\n name: string;\n domain: string;\n organization_id: string | null;\n idp_entity_id: string;\n idp_sso_url: string;\n idp_certificate: string;\n idp_metadata_url: string;\n idp_metadata: string;\n acs_url: string;\n sp_entity_id: string;\n sp_metadata_url: string;\n active: boolean;\n provider: string;\n user_count: number;\n sync_user_attributes: boolean;\n allow_subdomains: boolean;\n allow_idp_initiated: boolean;\n created_at: number;\n updated_at: number;\n attribute_mapping: AttributeMappingJSON;\n}\n\nexport interface AttributeMappingJSON {\n user_id: string;\n email_address: string;\n first_name: string;\n last_name: string;\n}\n\nexport interface TestingTokenJSON {\n object: typeof ObjectType.TestingToken;\n token: string;\n expires_at: number;\n}\n\nexport interface RoleJSON extends ClerkResourceJSON {\n object: typeof ObjectType.Role;\n key: string;\n name: string;\n description: string;\n permissions: PermissionJSON[];\n is_creator_eligible: boolean;\n created_at: number;\n updated_at: number;\n}\n\nexport interface PermissionJSON extends ClerkResourceJSON {\n object: typeof ObjectType.Permission;\n key: string;\n name: string;\n description: string;\n created_at: number;\n updated_at: number;\n}\n\nexport interface SamlAccountConnectionJSON extends ClerkResourceJSON {\n id: string;\n name: string;\n domain: string;\n active: boolean;\n provider: string;\n sync_user_attributes: boolean;\n allow_subdomains: boolean;\n allow_idp_initiated: boolean;\n disable_additional_identifications: boolean;\n created_at: number;\n updated_at: number;\n}\n\nexport interface MachineJSON extends ClerkResourceJSON {\n object: typeof ObjectType.Machine;\n id: string;\n name: string;\n instance_id: string;\n created_at: number;\n updated_at: number;\n default_token_ttl: number;\n scoped_machines: MachineJSON[];\n secret_key?: string;\n}\n\nexport interface MachineScopeJSON {\n object: typeof ObjectType.MachineScope;\n from_machine_id: string;\n to_machine_id: string;\n created_at?: number;\n deleted?: boolean;\n}\n\nexport interface MachineSecretKeyJSON {\n object: typeof ObjectType.MachineSecretKey;\n secret: string;\n}\n\nexport interface M2MTokenJSON extends ClerkResourceJSON {\n object: typeof ObjectType.M2MToken;\n token?: string;\n subject: string;\n scopes: string[];\n claims: Record | null;\n revoked: boolean;\n revocation_reason: string | null;\n expired: boolean;\n expiration: number | null;\n created_at: number;\n updated_at: number;\n}\n\nexport interface APIKeyJSON extends ClerkResourceJSON {\n object: typeof ObjectType.ApiKey;\n type: string;\n name: string;\n secret?: string;\n subject: string;\n scopes: string[];\n claims: Record | null;\n revoked: boolean;\n revocation_reason: string | null;\n expired: boolean;\n expiration: number | null;\n created_by: string | null;\n description: string | null;\n last_used_at: number | null;\n created_at: number;\n updated_at: number;\n}\n\nexport interface IdPOAuthAccessTokenJSON extends ClerkResourceJSON {\n object: typeof ObjectType.IdpOAuthAccessToken;\n client_id: string;\n type: string;\n subject: string;\n scopes: string[];\n revoked: boolean;\n revocation_reason: string | null;\n expired: boolean;\n expiration: number | null;\n created_at: number;\n updated_at: number;\n}\n\nexport interface BillingPayerJSON extends ClerkResourceJSON {\n object: typeof ObjectType.BillingPayer;\n instance_id: string;\n user_id?: string;\n first_name?: string;\n last_name?: string;\n email: string;\n organization_id?: string;\n organization_name?: string;\n image_url: string;\n created_at: number;\n updated_at: number;\n}\n\ninterface BillingPayeeJSON {\n id: string;\n gateway_type: string;\n gateway_external_id: string;\n gateway_status: 'active' | 'pending' | 'restricted' | 'disconnected';\n}\n\ninterface BillingMoneyAmountJSON {\n amount: number;\n amount_formatted: string;\n currency: string;\n currency_symbol: string;\n}\n\ninterface BillingTotalsJSON {\n subtotal: BillingMoneyAmountJSON;\n tax_total: BillingMoneyAmountJSON;\n grand_total: BillingMoneyAmountJSON;\n}\n\nexport interface FeatureJSON extends ClerkResourceJSON {\n object: typeof ObjectType.Feature;\n name: string;\n description: string;\n slug: string;\n avatar_url: string;\n}\n\n/**\n * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes.\n */\nexport interface BillingPlanJSON extends ClerkResourceJSON {\n object: typeof ObjectType.BillingPlan;\n id: string;\n product_id: string;\n name: string;\n slug: string;\n description?: string;\n is_default: boolean;\n is_recurring: boolean;\n has_base_fee: boolean;\n publicly_visible: boolean;\n fee: BillingMoneyAmountJSON;\n annual_fee: BillingMoneyAmountJSON;\n annual_monthly_fee: BillingMoneyAmountJSON;\n for_payer_type: 'org' | 'user';\n features: FeatureJSON[];\n}\n\ntype BillingSubscriptionItemStatus =\n | 'abandoned'\n | 'active'\n | 'canceled'\n | 'ended'\n | 'expired'\n | 'incomplete'\n | 'past_due'\n | 'upcoming';\n\n/**\n * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes.\n */\nexport interface BillingSubscriptionItemJSON extends ClerkResourceJSON {\n object: typeof ObjectType.BillingSubscriptionItem;\n status: BillingSubscriptionItemStatus;\n plan_period: 'month' | 'annual';\n payer_id: string;\n period_start: number;\n period_end: number | null;\n is_free_trial?: boolean;\n ended_at: number | null;\n created_at: number;\n updated_at: number;\n canceled_at: number | null;\n past_due_at: number | null;\n lifetime_paid: BillingMoneyAmountJSON;\n next_payment: {\n amount: number;\n date: number;\n } | null;\n amount: BillingMoneyAmountJSON | null;\n plan: BillingPlanJSON;\n plan_id: string;\n}\n\n/**\n * Webhooks specific interface for BillingSubscriptionItem.\n */\nexport interface BillingSubscriptionItemWebhookEventJSON extends ClerkResourceJSON {\n object: typeof ObjectType.BillingSubscriptionItem;\n status: BillingSubscriptionItemStatus;\n credit: {\n amount: BillingMoneyAmountJSON;\n cycle_days_remaining: number;\n cycle_days_total: number;\n cycle_remaining_percent: number;\n };\n proration_date: string;\n plan_period: 'month' | 'annual';\n period_start: number;\n period_end?: number;\n canceled_at?: number;\n past_due_at?: number;\n lifetime_paid: number;\n next_payment_amount: number;\n next_payment_date: number;\n amount: BillingMoneyAmountJSON;\n plan: {\n id: string;\n instance_id: string;\n product_id: string;\n name: string;\n slug: string;\n description?: string;\n is_default: boolean;\n is_recurring: boolean;\n amount: number;\n period: 'month' | 'annual';\n interval: number;\n has_base_fee: boolean;\n currency: string;\n annual_monthly_amount: number;\n publicly_visible: boolean;\n };\n plan_id: string;\n}\n\n/**\n * Webhooks specific interface for BillingPaymentAttempt.\n */\nexport interface BillingPaymentAttemptWebhookEventJSON extends ClerkResourceJSON {\n object: typeof ObjectType.BillingPaymentAttempt;\n instance_id: string;\n payment_id: string;\n statement_id: string;\n gateway_external_id: string;\n status: 'pending' | 'paid' | 'failed';\n created_at: number;\n updated_at: number;\n paid_at?: number;\n failed_at?: number;\n failed_reason?: {\n code: string;\n decline_code: string;\n };\n billing_date: number;\n charge_type: 'checkout' | 'recurring';\n payee: BillingPayeeJSON;\n payer: BillingPayerJSON;\n totals: BillingTotalsJSON;\n payment_source: {\n id: string;\n gateway: string;\n gateway_external_id: string;\n gateway_external_account_id?: string;\n payment_method: string;\n status: 'active' | 'disconnected';\n card_type?: string;\n last4?: string;\n };\n subscription_items: BillingSubscriptionItemWebhookEventJSON[];\n}\n\n/**\n * Webhooks specific interface for BillingSubscription.\n */\nexport interface BillingSubscriptionWebhookEventJSON extends ClerkResourceJSON {\n object: typeof ObjectType.BillingSubscription;\n status: 'abandoned' | 'active' | 'canceled' | 'ended' | 'expired' | 'incomplete' | 'past_due' | 'upcoming';\n active_at?: number;\n canceled_at?: number;\n created_at: number;\n ended_at?: number;\n past_due_at?: number;\n updated_at: number;\n latest_payment_id: string;\n payer_id: string;\n payer: BillingPayerJSON;\n payment_source_id: string;\n items: BillingSubscriptionItemWebhookEventJSON[];\n}\n\nexport interface BillingSubscriptionJSON extends ClerkResourceJSON {\n object: typeof ObjectType.BillingSubscription;\n status: 'active' | 'past_due' | 'canceled' | 'ended' | 'abandoned' | 'incomplete';\n payer_id: string;\n created_at: number;\n updated_at: number;\n active_at: number | null;\n past_due_at: number | null;\n subscription_items: BillingSubscriptionItemJSON[];\n next_payment?: {\n date: number;\n amount: BillingMoneyAmountJSON;\n };\n eligible_for_free_trial?: boolean;\n}\n\nexport interface WebhooksSvixJSON {\n svix_url: string;\n}\n","import type { MachineJSON } from './JSON';\n\n/**\n * The Backend `Machine` object holds information about a machine.\n */\nexport class Machine {\n constructor(\n readonly id: string,\n readonly name: string,\n readonly instanceId: string,\n readonly createdAt: number,\n readonly updatedAt: number,\n readonly scopedMachines: Machine[],\n readonly defaultTokenTtl: number,\n readonly secretKey?: string,\n ) {}\n\n static fromJSON(data: MachineJSON): Machine {\n return new Machine(\n data.id,\n data.name,\n data.instance_id,\n data.created_at,\n data.updated_at,\n data.scoped_machines.map(\n m =>\n new Machine(\n m.id,\n m.name,\n m.instance_id,\n m.created_at,\n m.updated_at,\n [], // Nested machines don't have scoped_machines\n m.default_token_ttl,\n ),\n ),\n data.default_token_ttl,\n data.secret_key,\n );\n }\n}\n","import type { MachineScopeJSON } from './JSON';\n\n/**\n * The Backend `MachineScope` object holds information about a machine scope.\n */\nexport class MachineScope {\n constructor(\n readonly fromMachineId: string,\n readonly toMachineId: string,\n readonly createdAt?: number,\n readonly deleted?: boolean,\n ) {}\n\n static fromJSON(data: MachineScopeJSON): MachineScope {\n return new MachineScope(data.from_machine_id, data.to_machine_id, data.created_at, data.deleted);\n }\n}\n","import type { MachineSecretKeyJSON } from './JSON';\n\n/**\n * The Backend `MachineSecretKey` object holds information about a machine secret key.\n */\nexport class MachineSecretKey {\n constructor(readonly secret: string) {}\n\n static fromJSON(data: MachineSecretKeyJSON): MachineSecretKey {\n return new MachineSecretKey(data.secret);\n }\n}\n","import type { M2MTokenJSON } from './JSON';\n\n/**\n * The Backend `M2MToken` object holds information about a machine-to-machine token.\n */\nexport class M2MToken {\n constructor(\n readonly id: string,\n readonly subject: string,\n readonly scopes: string[],\n readonly claims: Record | null,\n readonly revoked: boolean,\n readonly revocationReason: string | null,\n readonly expired: boolean,\n readonly expiration: number | null,\n readonly createdAt: number,\n readonly updatedAt: number,\n readonly token?: string,\n ) {}\n\n static fromJSON(data: M2MTokenJSON): M2MToken {\n return new M2MToken(\n data.id,\n data.subject,\n data.scopes,\n data.claims,\n data.revoked,\n data.revocation_reason,\n data.expired,\n data.expiration,\n data.created_at,\n data.updated_at,\n data.token,\n );\n }\n}\n","import type { JwtTemplateJSON } from './JSON';\n\nexport class JwtTemplate {\n constructor(\n readonly id: string,\n readonly name: string,\n readonly claims: object,\n readonly lifetime: number,\n readonly allowedClockSkew: number,\n readonly customSigningKey: boolean,\n readonly signingAlgorithm: string,\n readonly createdAt: number,\n readonly updatedAt: number,\n ) {}\n\n static fromJSON(data: JwtTemplateJSON): JwtTemplate {\n return new JwtTemplate(\n data.id,\n data.name,\n data.claims,\n data.lifetime,\n data.allowed_clock_skew,\n data.custom_signing_key,\n data.signing_algorithm,\n data.created_at,\n data.updated_at,\n );\n }\n}\n","import type { OauthAccessTokenJSON } from './JSON';\n\nexport class OauthAccessToken {\n constructor(\n readonly externalAccountId: string,\n readonly provider: string,\n readonly token: string,\n readonly publicMetadata: Record = {},\n readonly label: string,\n readonly scopes?: string[],\n readonly tokenSecret?: string,\n readonly expiresAt?: number,\n ) {}\n\n static fromJSON(data: OauthAccessTokenJSON) {\n return new OauthAccessToken(\n data.external_account_id,\n data.provider,\n data.token,\n data.public_metadata,\n data.label || '',\n data.scopes,\n data.token_secret,\n data.expires_at,\n );\n }\n}\n","import type { OAuthApplicationJSON } from './JSON';\n\n/**\n * The Backend `OAuthApplication` object holds information about an OAuth application.\n */\nexport class OAuthApplication {\n constructor(\n /**\n * The unique identifier for the OAuth application.\n */\n readonly id: string,\n /**\n * The ID of the instance that this OAuth application belongs to.\n */\n readonly instanceId: string,\n /**\n * The name of the new OAuth application.\n */\n readonly name: string,\n /**\n * The ID of the client associated with the OAuth application.\n */\n readonly clientId: string,\n /**\n * The public-facing URL of the OAuth application, often shown on consent screens.\n */\n readonly clientUri: string | null,\n /**\n * The URL of the image or logo representing the OAuth application.\n */\n readonly clientImageUrl: string | null,\n /**\n * Specifies whether the OAuth application is dynamically registered.\n */\n readonly dynamicallyRegistered: boolean,\n /**\n * Specifies whether the consent screen should be displayed in the authentication flow. Cannot be disabled for dynamically registered OAuth applications.\n */\n readonly consentScreenEnabled: boolean,\n /**\n * Specifies whether the Proof Key of Code Exchange (PKCE) flow should be required in the authentication flow.\n */\n readonly pkceRequired: boolean,\n /**\n * Indicates whether the client is public. If true, the Proof Key of Code Exchange (PKCE) flow can be used.\n */\n readonly isPublic: boolean, // NOTE: `public` is reserved\n /**\n * Scopes for the new OAuth application.\n */\n readonly scopes: string,\n /**\n * An array of redirect URIs of the new OAuth application.\n */\n readonly redirectUris: Array,\n /**\n * The URL used to authorize the user and obtain an authorization code.\n */\n readonly authorizeUrl: string,\n /**\n * The URL used by the client to exchange an authorization code for an access token.\n */\n readonly tokenFetchUrl: string,\n /**\n * The URL where the client can retrieve user information using an access token.\n */\n readonly userInfoUrl: string,\n /**\n * The OpenID Connect discovery endpoint URL for this OAuth application.\n */\n readonly discoveryUrl: string,\n /**\n * The URL used to introspect and validate issued access tokens.\n */\n readonly tokenIntrospectionUrl: string,\n /**\n * The date when the OAuth application was first created.\n */\n readonly createdAt: number,\n /**\n * The date when the OAuth application was last updated.\n */\n readonly updatedAt: number,\n /**\n * The client secret associated with the OAuth application. Empty if public client.\n */\n readonly clientSecret?: string,\n ) {}\n\n static fromJSON(data: OAuthApplicationJSON) {\n return new OAuthApplication(\n data.id,\n data.instance_id,\n data.name,\n data.client_id,\n data.client_uri,\n data.client_image_url,\n data.dynamically_registered,\n data.consent_screen_enabled,\n data.pkce_required,\n data.public,\n data.scopes,\n data.redirect_uris,\n data.authorize_url,\n data.token_fetch_url,\n data.user_info_url,\n data.discovery_url,\n data.token_introspection_url,\n data.created_at,\n data.updated_at,\n data.client_secret,\n );\n }\n}\n","import type { OrganizationJSON } from './JSON';\n\n/**\n * The Backend `Organization` object is similar to the [`Organization`](https://clerk.com/docs/references/javascript/organization) object as it holds information about an organization, as well as methods for managing it. However, the Backend `Organization` object is different in that it is used in the [Backend API](https://clerk.com/docs/reference/backend-api/tag/Organizations#operation/ListOrganizations){{ target: '_blank' }} and is not directly accessible from the Frontend API.\n */\nexport class Organization {\n private _raw: OrganizationJSON | null = null;\n\n public get raw(): OrganizationJSON | null {\n return this._raw;\n }\n\n constructor(\n /**\n * The unique identifier for the organization.\n */\n readonly id: string,\n /**\n * The name of the organization.\n */\n readonly name: string,\n /**\n * The URL-friendly identifier of the user's active organization. If supplied, it must be unique for the instance.\n */\n readonly slug: string,\n /**\n * Holds the organization's logo. Compatible with Clerk's [Image Optimization](https://clerk.com/docs/guides/image-optimization).\n */\n readonly imageUrl: string,\n /**\n * Whether the organization has an image.\n */\n readonly hasImage: boolean,\n /**\n * The date when the organization was first created.\n */\n readonly createdAt: number,\n /**\n * The date when the organization was last updated.\n */\n readonly updatedAt: number,\n /**\n * Metadata that can be read from the Frontend API and [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }} and can be set only from the Backend API.\n */\n readonly publicMetadata: OrganizationPublicMetadata | null = {},\n /**\n * Metadata that can be read and set only from the [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }}.\n */\n readonly privateMetadata: OrganizationPrivateMetadata = {},\n /**\n * The maximum number of memberships allowed in the organization.\n */\n readonly maxAllowedMemberships: number,\n /**\n * Whether the organization allows admins to delete users.\n */\n readonly adminDeleteEnabled: boolean,\n /**\n * The number of members in the organization.\n */\n readonly membersCount?: number,\n /**\n * The ID of the user who created the organization.\n */\n readonly createdBy?: string,\n ) {}\n\n static fromJSON(data: OrganizationJSON): Organization {\n const res = new Organization(\n data.id,\n data.name,\n data.slug,\n data.image_url || '',\n data.has_image,\n data.created_at,\n data.updated_at,\n data.public_metadata,\n data.private_metadata,\n data.max_allowed_memberships,\n data.admin_delete_enabled,\n data.members_count,\n data.created_by,\n );\n res._raw = data;\n return res;\n }\n}\n","import type { OrganizationInvitationStatus, OrganizationMembershipRole } from './Enums';\nimport type { OrganizationInvitationJSON, PublicOrganizationDataJSON } from './JSON';\n\n/**\n * The Backend `OrganizationInvitation` object is similar to the [`OrganizationInvitation`](https://clerk.com/docs/references/javascript/types/organization-invitation) object as it's the model around an organization invitation. However, the Backend `OrganizationInvitation` object is different in that it's used in the [Backend API](https://clerk.com/docs/reference/backend-api/tag/Organization-Invitations#operation/CreateOrganizationInvitation){{ target: '_blank' }} and is not directly accessible from the Frontend API.\n */\nexport class OrganizationInvitation {\n private _raw: OrganizationInvitationJSON | null = null;\n\n public get raw(): OrganizationInvitationJSON | null {\n return this._raw;\n }\n\n constructor(\n /**\n * The unique identifier for the `OrganizationInvitation`.\n */\n readonly id: string,\n /**\n * The email address of the user who is invited to the [`Organization`](https://clerk.com/docs/references/backend/types/backend-organization).\n */\n readonly emailAddress: string,\n /**\n * The role of the invited user.\n */\n readonly role: OrganizationMembershipRole,\n /**\n * The name of the role of the invited user.\n */\n readonly roleName: string,\n /**\n * The ID of the [`Organization`](https://clerk.com/docs/references/backend/types/backend-organization) that the user is invited to.\n */\n readonly organizationId: string,\n /**\n * The date when the invitation was first created.\n */\n readonly createdAt: number,\n /**\n * The date when the invitation was last updated.\n */\n readonly updatedAt: number,\n /**\n * The date when the invitation expires.\n */\n readonly expiresAt: number,\n /**\n * The URL that the user can use to accept the invitation.\n */\n readonly url: string | null,\n /**\n * The status of the invitation.\n */\n readonly status?: OrganizationInvitationStatus,\n /**\n * Metadata that can be read from the Frontend API and [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }} and can be set only from the Backend API.\n */\n readonly publicMetadata: OrganizationInvitationPublicMetadata = {},\n /**\n * Metadata that can be read and set only from the [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }}.\n */\n readonly privateMetadata: OrganizationInvitationPrivateMetadata = {},\n /**\n * Public data about the organization that the user is invited to.\n */\n readonly publicOrganizationData?: PublicOrganizationDataJSON | null,\n ) {}\n\n static fromJSON(data: OrganizationInvitationJSON) {\n const res = new OrganizationInvitation(\n data.id,\n data.email_address,\n data.role,\n data.role_name,\n data.organization_id,\n data.created_at,\n data.updated_at,\n data.expires_at,\n data.url,\n data.status,\n data.public_metadata,\n data.private_metadata,\n data.public_organization_data,\n );\n res._raw = data;\n return res;\n }\n}\n","import { Organization } from '../resources';\nimport type { OrganizationMembershipRole } from './Enums';\nimport type { OrganizationMembershipJSON, OrganizationMembershipPublicUserDataJSON } from './JSON';\n\n/**\n * The Backend `OrganizationMembership` object is similar to the [`OrganizationMembership`](https://clerk.com/docs/references/javascript/types/organization-membership) object as it's the model around an organization membership entity and describes the relationship between users and organizations. However, the Backend `OrganizationMembership` object is different in that it's used in the [Backend API](https://clerk.com/docs/reference/backend-api/tag/Organization-Memberships#operation/CreateOrganizationMembership){{ target: '_blank' }} and is not directly accessible from the Frontend API.\n */\nexport class OrganizationMembership {\n private _raw: OrganizationMembershipJSON | null = null;\n\n public get raw(): OrganizationMembershipJSON | null {\n return this._raw;\n }\n\n constructor(\n /**\n * The unique identifier for the membership.\n */\n readonly id: string,\n /**\n * The role of the user.\n */\n readonly role: OrganizationMembershipRole,\n /**\n * The permissions granted to the user in the organization.\n */\n readonly permissions: string[],\n /**\n * Metadata that can be read from the Frontend API and [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }} and can be set only from the Backend API.\n */\n readonly publicMetadata: OrganizationMembershipPublicMetadata = {},\n /**\n * Metadata that can be read and set only from the [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }}.\n */\n readonly privateMetadata: OrganizationMembershipPrivateMetadata = {},\n /**\n * The date when the membership was first created.\n */\n readonly createdAt: number,\n /**\n * The date when the membership was last updated.\n */\n readonly updatedAt: number,\n /**\n * The organization that the user is a member of.\n */\n readonly organization: Organization,\n /**\n * Public information about the user that this membership belongs to.\n */\n readonly publicUserData?: OrganizationMembershipPublicUserData | null,\n ) {}\n\n static fromJSON(data: OrganizationMembershipJSON) {\n const res = new OrganizationMembership(\n data.id,\n data.role,\n data.permissions,\n data.public_metadata,\n data.private_metadata,\n data.created_at,\n data.updated_at,\n Organization.fromJSON(data.organization),\n OrganizationMembershipPublicUserData.fromJSON(data.public_user_data),\n );\n res._raw = data;\n return res;\n }\n}\n\n/**\n * @class\n */\nexport class OrganizationMembershipPublicUserData {\n constructor(\n /**\n * The [identifier](https://clerk.com/docs/authentication/configuration/sign-up-sign-in-options#identifiers) of the user.\n */\n readonly identifier: string,\n /**\n * The first name of the user.\n */\n readonly firstName: string | null,\n /**\n * The last name of the user.\n */\n readonly lastName: string | null,\n /**\n * Holds the default avatar or user's uploaded profile image. Compatible with Clerk's [Image Optimization](https://clerk.com/docs/guides/image-optimization).\n */\n readonly imageUrl: string,\n /**\n * Whether the user has a profile picture.\n */\n readonly hasImage: boolean,\n /**\n * The ID of the user that this public data belongs to.\n */\n readonly userId: string,\n ) {}\n\n static fromJSON(data: OrganizationMembershipPublicUserDataJSON) {\n return new OrganizationMembershipPublicUserData(\n data.identifier,\n data.first_name,\n data.last_name,\n data.image_url,\n data.has_image,\n data.user_id,\n );\n }\n}\n","import type { DomainsEnrollmentModes } from './Enums';\nimport type { OrganizationSettingsJSON } from './JSON';\n\nexport class OrganizationSettings {\n constructor(\n readonly enabled: boolean,\n readonly maxAllowedMemberships: number,\n readonly maxAllowedRoles: number,\n readonly maxAllowedPermissions: number,\n readonly creatorRole: string,\n readonly adminDeleteEnabled: boolean,\n readonly domainsEnabled: boolean,\n readonly domainsEnrollmentModes: Array,\n readonly domainsDefaultRole: string,\n ) {}\n\n static fromJSON(data: OrganizationSettingsJSON): OrganizationSettings {\n return new OrganizationSettings(\n data.enabled,\n data.max_allowed_memberships,\n data.max_allowed_roles,\n data.max_allowed_permissions,\n data.creator_role,\n data.admin_delete_enabled,\n data.domains_enabled,\n data.domains_enrollment_modes,\n data.domains_default_role,\n );\n }\n}\n","import { IdentificationLink } from './IdentificationLink';\nimport type { PhoneNumberJSON } from './JSON';\nimport { Verification } from './Verification';\n\n/**\n * The Backend `PhoneNumber` object describes a phone number. Phone numbers can be used as a proof of identification for users, or simply as a means of contacting users.\n *\n * Phone numbers must be **verified** to ensure that they can be assigned to their rightful owners. The `PhoneNumber` object holds all the necessary state around the verification process.\n *\n * Finally, phone numbers can be used as part of [multi-factor authentication](https://clerk.com/docs/authentication/configuration/sign-up-sign-in-options#multi-factor-authentication). During sign in, users can opt in to an extra verification step where they will receive an SMS message with a one-time code. This code must be entered to complete the sign in process.\n */\nexport class PhoneNumber {\n constructor(\n /**\n * The unique identifier for this phone number.\n */\n readonly id: string,\n /**\n * The value of this phone number, in [E.164 format](https://en.wikipedia.org/wiki/E.164).\n */\n readonly phoneNumber: string,\n /**\n * Set to `true` if this phone number is reserved for multi-factor authentication (2FA). Set to `false` otherwise.\n */\n readonly reservedForSecondFactor: boolean,\n /**\n * Set to `true` if this phone number is the default second factor. Set to `false` otherwise. A user must have exactly one default second factor, if multi-factor authentication (2FA) is enabled.\n */\n readonly defaultSecondFactor: boolean,\n /**\n * An object holding information on the verification of this phone number.\n */\n readonly verification: Verification | null,\n /**\n * An object containing information about any other identification that might be linked to this phone number.\n */\n readonly linkedTo: IdentificationLink[],\n ) {}\n\n static fromJSON(data: PhoneNumberJSON): PhoneNumber {\n return new PhoneNumber(\n data.id,\n data.phone_number,\n data.reserved_for_second_factor,\n data.default_second_factor,\n data.verification && Verification.fromJSON(data.verification),\n data.linked_to.map(link => IdentificationLink.fromJSON(link)),\n );\n }\n}\n","import type { ProxyCheckJSON } from './JSON';\n\nexport class ProxyCheck {\n constructor(\n readonly id: string,\n readonly domainId: string,\n readonly lastRunAt: number | null,\n readonly proxyUrl: string,\n readonly successful: boolean,\n readonly createdAt: number,\n readonly updatedAt: number,\n ) {}\n\n static fromJSON(data: ProxyCheckJSON): ProxyCheck {\n return new ProxyCheck(\n data.id,\n data.domain_id,\n data.last_run_at,\n data.proxy_url,\n data.successful,\n data.created_at,\n data.updated_at,\n );\n }\n}\n","import type { RedirectUrlJSON } from './JSON';\n\n/**\n * Redirect URLs are whitelisted URLs that facilitate secure authentication flows in native applications (e.g. React Native, Expo). In these contexts, Clerk ensures that security-critical nonces are passed only to the whitelisted URLs.\n\nThe Backend `RedirectUrl` object represents a redirect URL in your application. This object is used in the Backend API.\n */\nexport class RedirectUrl {\n constructor(\n /**\n * The unique identifier for the redirect URL.\n */\n readonly id: string,\n /**\n * The full URL value prefixed with `https://` or a custom scheme.\n * @example https://my-app.com/oauth-callback\n * @example my-app://oauth-callback\n */\n readonly url: string,\n /**\n * The date when the redirect URL was first created.\n */\n readonly createdAt: number,\n /**\n * The date when the redirect URL was last updated.\n */\n readonly updatedAt: number,\n ) {}\n\n static fromJSON(data: RedirectUrlJSON): RedirectUrl {\n return new RedirectUrl(data.id, data.url, data.created_at, data.updated_at);\n }\n}\n","import type { AttributeMappingJSON, SamlAccountConnectionJSON, SamlConnectionJSON } from './JSON';\n\n/**\n * The Backend `SamlConnection` object holds information about a SAML connection for an organization.\n */\nexport class SamlConnection {\n constructor(\n /**\n * The unique identifier for the connection.\n */\n readonly id: string,\n /**\n * The name to use as a label for the connection.\n */\n readonly name: string,\n /**\n * The domain of your organization. Sign in flows using an email with this domain will use the connection.\n */\n readonly domain: string,\n /**\n * The organization ID of the organization.\n */\n readonly organizationId: string | null,\n /**\n * The Entity ID as provided by the Identity Provider (IdP).\n */\n readonly idpEntityId: string | null,\n /**\n * The Single-Sign On URL as provided by the Identity Provider (IdP).\n */\n readonly idpSsoUrl: string | null,\n /**\n * The X.509 certificate as provided by the Identity Provider (IdP).\n */\n readonly idpCertificate: string | null,\n /**\n * The URL which serves the Identity Provider (IdP) metadata. If present, it takes priority over the corresponding individual properties.\n */\n readonly idpMetadataUrl: string | null,\n /**\n * The XML content of the Identity Provider (IdP) metadata file. If present, it takes priority over the corresponding individual properties.\n */\n readonly idpMetadata: string | null,\n /**\n * The Assertion Consumer Service (ACS) URL of the connection.\n */\n readonly acsUrl: string,\n /**\n * The Entity ID as provided by the Service Provider (Clerk).\n */\n readonly spEntityId: string,\n /**\n * The metadata URL as provided by the Service Provider (Clerk).\n */\n readonly spMetadataUrl: string,\n /**\n * Indicates whether the connection is active or not.\n */\n readonly active: boolean,\n /**\n * The Identity Provider (IdP) of the connection.\n */\n readonly provider: string,\n /**\n * The number of users associated with the connection.\n */\n readonly userCount: number,\n /**\n * Indicates whether the connection syncs user attributes between the Service Provider (SP) and Identity Provider (IdP) or not.\n */\n readonly syncUserAttributes: boolean,\n /**\n * Indicates whether users with an email address subdomain are allowed to use this connection in order to authenticate or not.\n */\n readonly allowSubdomains: boolean,\n /**\n * Indicates whether the connection allows Identity Provider (IdP) initiated flows or not.\n */\n readonly allowIdpInitiated: boolean,\n /**\n * The date when the connection was first created.\n */\n readonly createdAt: number,\n /**\n * The date when the SAML connection was last updated.\n */\n readonly updatedAt: number,\n /**\n * Defines the attribute name mapping between the Identity Provider (IdP) and Clerk's [`User`](https://clerk.com/docs/references/javascript/user) properties.\n */\n readonly attributeMapping: AttributeMapping,\n ) {}\n static fromJSON(data: SamlConnectionJSON): SamlConnection {\n return new SamlConnection(\n data.id,\n data.name,\n data.domain,\n data.organization_id,\n data.idp_entity_id,\n data.idp_sso_url,\n data.idp_certificate,\n data.idp_metadata_url,\n data.idp_metadata,\n data.acs_url,\n data.sp_entity_id,\n data.sp_metadata_url,\n data.active,\n data.provider,\n data.user_count,\n data.sync_user_attributes,\n data.allow_subdomains,\n data.allow_idp_initiated,\n data.created_at,\n data.updated_at,\n data.attribute_mapping && AttributeMapping.fromJSON(data.attribute_mapping),\n );\n }\n}\n\nexport class SamlAccountConnection {\n constructor(\n readonly id: string,\n readonly name: string,\n readonly domain: string,\n readonly active: boolean,\n readonly provider: string,\n readonly syncUserAttributes: boolean,\n readonly allowSubdomains: boolean,\n readonly allowIdpInitiated: boolean,\n readonly createdAt: number,\n readonly updatedAt: number,\n ) {}\n static fromJSON(data: SamlAccountConnectionJSON): SamlAccountConnection {\n return new SamlAccountConnection(\n data.id,\n data.name,\n data.domain,\n data.active,\n data.provider,\n data.sync_user_attributes,\n data.allow_subdomains,\n data.allow_idp_initiated,\n data.created_at,\n data.updated_at,\n );\n }\n}\n\nclass AttributeMapping {\n constructor(\n /**\n * The user ID attribute name.\n */\n readonly userId: string,\n /**\n * The email address attribute name.\n */\n readonly emailAddress: string,\n /**\n * The first name attribute name.\n */\n readonly firstName: string,\n /**\n * The last name attribute name.\n */\n readonly lastName: string,\n ) {}\n\n static fromJSON(data: AttributeMappingJSON): AttributeMapping {\n return new AttributeMapping(data.user_id, data.email_address, data.first_name, data.last_name);\n }\n}\n","import type { SamlAccountJSON } from './JSON';\nimport { SamlAccountConnection } from './SamlConnection';\nimport { Verification } from './Verification';\n\n/**\n * The Backend `SamlAccount` object describes a SAML account.\n */\nexport class SamlAccount {\n constructor(\n /**\n * The unique identifier for the SAML account.\n */\n readonly id: string,\n /**\n * The provider of the SAML account.\n */\n readonly provider: string,\n /**\n * The user's ID as used in the provider.\n */\n readonly providerUserId: string | null,\n /**\n * A boolean that indicates whether the SAML account is active.\n */\n readonly active: boolean,\n /**\n * The email address of the SAML account.\n */\n readonly emailAddress: string,\n /**\n * The first name of the SAML account.\n */\n readonly firstName: string,\n /**\n * The last name of the SAML account.\n */\n readonly lastName: string,\n /**\n * The verification of the SAML account.\n */\n readonly verification: Verification | null,\n /**\n * The SAML connection of the SAML account.\n */\n readonly samlConnection: SamlAccountConnection | null,\n ) {}\n\n static fromJSON(data: SamlAccountJSON): SamlAccount {\n return new SamlAccount(\n data.id,\n data.provider,\n data.provider_user_id,\n data.active,\n data.email_address,\n data.first_name,\n data.last_name,\n data.verification && Verification.fromJSON(data.verification),\n data.saml_connection && SamlAccountConnection.fromJSON(data.saml_connection),\n );\n }\n}\n","import type { SignInTokenJSON } from './JSON';\n\nexport class SignInToken {\n constructor(\n readonly id: string,\n readonly userId: string,\n readonly token: string,\n readonly status: string,\n readonly url: string,\n readonly createdAt: number,\n readonly updatedAt: number,\n ) {}\n\n static fromJSON(data: SignInTokenJSON): SignInToken {\n return new SignInToken(data.id, data.user_id, data.token, data.status, data.url, data.created_at, data.updated_at);\n }\n}\n","import type { SignUpStatus } from '@clerk/types';\n\nimport type { SignUpVerificationNextAction } from './Enums';\nimport type { SignUpJSON, SignUpVerificationJSON, SignUpVerificationsJSON } from './JSON';\n\nexport class SignUpAttemptVerification {\n constructor(\n readonly nextAction: SignUpVerificationNextAction,\n readonly supportedStrategies: string[],\n ) {}\n\n static fromJSON(data: SignUpVerificationJSON): SignUpAttemptVerification {\n return new SignUpAttemptVerification(data.next_action, data.supported_strategies);\n }\n}\n\nexport class SignUpAttemptVerifications {\n constructor(\n readonly emailAddress: SignUpAttemptVerification | null,\n readonly phoneNumber: SignUpAttemptVerification | null,\n readonly web3Wallet: SignUpAttemptVerification | null,\n readonly externalAccount: object | null,\n ) {}\n\n static fromJSON(data: SignUpVerificationsJSON): SignUpAttemptVerifications {\n return new SignUpAttemptVerifications(\n data.email_address && SignUpAttemptVerification.fromJSON(data.email_address),\n data.phone_number && SignUpAttemptVerification.fromJSON(data.phone_number),\n data.web3_wallet && SignUpAttemptVerification.fromJSON(data.web3_wallet),\n data.external_account,\n );\n }\n}\n\nexport class SignUpAttempt {\n constructor(\n readonly id: string,\n readonly status: SignUpStatus,\n readonly requiredFields: string[],\n readonly optionalFields: string[],\n readonly missingFields: string[],\n readonly unverifiedFields: string[],\n readonly verifications: SignUpAttemptVerifications | null,\n readonly username: string | null,\n readonly emailAddress: string | null,\n readonly phoneNumber: string | null,\n readonly web3Wallet: string | null,\n readonly passwordEnabled: boolean,\n readonly firstName: string | null,\n readonly lastName: string | null,\n readonly customAction: boolean,\n readonly externalId: string | null,\n readonly createdSessionId: string | null,\n readonly createdUserId: string | null,\n readonly abandonAt: number | null,\n readonly legalAcceptedAt: number | null,\n readonly publicMetadata?: Record | null,\n readonly unsafeMetadata?: Record | null,\n ) {}\n\n static fromJSON(data: SignUpJSON): SignUpAttempt {\n return new SignUpAttempt(\n data.id,\n data.status,\n data.required_fields,\n data.optional_fields,\n data.missing_fields,\n data.unverified_fields,\n data.verifications ? SignUpAttemptVerifications.fromJSON(data.verifications) : null,\n data.username,\n data.email_address,\n data.phone_number,\n data.web3_wallet,\n data.password_enabled,\n data.first_name,\n data.last_name,\n data.custom_action,\n data.external_id,\n data.created_session_id,\n data.created_user_id,\n data.abandon_at,\n data.legal_accepted_at,\n data.public_metadata,\n data.unsafe_metadata,\n );\n }\n}\n","import type { SMSMessageJSON } from './JSON';\n\nexport class SMSMessage {\n constructor(\n readonly id: string,\n readonly fromPhoneNumber: string,\n readonly toPhoneNumber: string,\n readonly message: string,\n readonly status: string,\n readonly phoneNumberId: string | null,\n readonly data?: Record | null,\n ) {}\n\n static fromJSON(data: SMSMessageJSON): SMSMessage {\n return new SMSMessage(\n data.id,\n data.from_phone_number,\n data.to_phone_number,\n data.message,\n data.status,\n data.phone_number_id,\n data.data,\n );\n }\n}\n","import type { TokenJSON } from './JSON';\n\nexport class Token {\n constructor(readonly jwt: string) {}\n\n static fromJSON(data: TokenJSON): Token {\n return new Token(data.jwt);\n }\n}\n","import type { Web3WalletJSON } from './JSON';\nimport { Verification } from './Verification';\n\n/**\n * The Backend `Web3Wallet` object describes a Web3 wallet address. The address can be used as a proof of identification for users.\n *\n * Web3 addresses must be verified to ensure that they can be assigned to their rightful owners. The verification is completed via Web3 wallet browser extensions, such as [Metamask](https://metamask.io/), [Coinbase Wallet](https://www.coinbase.com/wallet), and [OKX Wallet](https://www.okx.com/help/section/faq-web3-wallet). The `Web3Wallet3` object holds all the necessary state around the verification process.\n */\nexport class Web3Wallet {\n constructor(\n /**\n * The unique ID for the Web3 wallet.\n */\n readonly id: string,\n /**\n * The Web3 wallet address, made up of 0x + 40 hexadecimal characters.\n */\n readonly web3Wallet: string,\n /**\n * An object holding information on the verification of this Web3 wallet.\n */\n readonly verification: Verification | null,\n ) {}\n\n static fromJSON(data: Web3WalletJSON): Web3Wallet {\n return new Web3Wallet(data.id, data.web3_wallet, data.verification && Verification.fromJSON(data.verification));\n }\n}\n","import { EmailAddress } from './EmailAddress';\nimport { ExternalAccount } from './ExternalAccount';\nimport type { ExternalAccountJSON, SamlAccountJSON, UserJSON } from './JSON';\nimport { PhoneNumber } from './PhoneNumber';\nimport { SamlAccount } from './SamlAccount';\nimport { Web3Wallet } from './Web3Wallet';\n\n/**\n * The Backend `User` object is similar to the `User` object as it holds information about a user of your application, such as their unique identifier, name, email addresses, phone numbers, and more. However, the Backend `User` object is different from the `User` object in that it is used in the [Backend API](https://clerk.com/docs/reference/backend-api/tag/Users#operation/GetUser){{ target: '_blank' }} and is not directly accessible from the Frontend API.\n */\nexport class User {\n private _raw: UserJSON | null = null;\n\n public get raw(): UserJSON | null {\n return this._raw;\n }\n\n constructor(\n /**\n * The unique identifier for the user.\n */\n readonly id: string,\n /**\n * A boolean indicating whether the user has a password on their account.\n */\n readonly passwordEnabled: boolean,\n /**\n * A boolean indicating whether the user has enabled TOTP by generating a TOTP secret and verifying it via an authenticator app.\n */\n readonly totpEnabled: boolean,\n /**\n * A boolean indicating whether the user has enabled Backup codes.\n */\n readonly backupCodeEnabled: boolean,\n /**\n * A boolean indicating whether the user has enabled two-factor authentication.\n */\n readonly twoFactorEnabled: boolean,\n /**\n * A boolean indicating whether the user is banned or not.\n */\n readonly banned: boolean,\n /**\n * A boolean indicating whether the user is banned or not.\n */\n readonly locked: boolean,\n /**\n * The date when the user was first created.\n */\n readonly createdAt: number,\n /**\n * The date when the user was last updated.\n */\n readonly updatedAt: number,\n /**\n * The URL of the user's profile image.\n */\n readonly imageUrl: string,\n /**\n * A getter boolean to check if the user has uploaded an image or one was copied from OAuth. Returns `false` if Clerk is displaying an avatar for the user.\n */\n readonly hasImage: boolean,\n /**\n * The ID for the `EmailAddress` that the user has set as primary.\n */\n readonly primaryEmailAddressId: string | null,\n /**\n * The ID for the `PhoneNumber` that the user has set as primary.\n */\n readonly primaryPhoneNumberId: string | null,\n /**\n * The ID for the [`Web3Wallet`](https://clerk.com/docs/references/backend/types/backend-web3-wallet) that the user signed up with.\n */\n readonly primaryWeb3WalletId: string | null,\n /**\n * The date when the user last signed in. May be empty if the user has never signed in.\n */\n readonly lastSignInAt: number | null,\n /**\n * The ID of the user as used in your external systems. Must be unique across your instance.\n */\n readonly externalId: string | null,\n /**\n * The user's username.\n */\n readonly username: string | null,\n /**\n * The user's first name.\n */\n readonly firstName: string | null,\n /**\n * The user's last name.\n */\n readonly lastName: string | null,\n /**\n * Metadata that can be read from the Frontend API and [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }} and can be set only from the Backend API.\n */\n readonly publicMetadata: UserPublicMetadata = {},\n /**\n * Metadata that can be read and set only from the [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }}.\n */\n readonly privateMetadata: UserPrivateMetadata = {},\n /**\n * Metadata that can be read and set from the Frontend API. It's considered unsafe because it can be modified from the frontend.\n */\n readonly unsafeMetadata: UserUnsafeMetadata = {},\n /**\n * An array of all the `EmailAddress` objects associated with the user. Includes the primary.\n */\n readonly emailAddresses: EmailAddress[] = [],\n /**\n * An array of all the `PhoneNumber` objects associated with the user. Includes the primary.\n */\n readonly phoneNumbers: PhoneNumber[] = [],\n /**\n * An array of all the `Web3Wallet` objects associated with the user. Includes the primary.\n */\n readonly web3Wallets: Web3Wallet[] = [],\n /**\n * An array of all the `ExternalAccount` objects associated with the user via OAuth. **Note**: This includes both verified & unverified external accounts.\n */\n readonly externalAccounts: ExternalAccount[] = [],\n /**\n * An array of all the `SamlAccount` objects associated with the user via SAML.\n */\n readonly samlAccounts: SamlAccount[] = [],\n /**\n * Date when the user was last active.\n */\n readonly lastActiveAt: number | null,\n /**\n * A boolean indicating whether the organization creation is enabled for the user or not.\n */\n readonly createOrganizationEnabled: boolean,\n /**\n * An integer indicating the number of organizations that can be created by the user. If the value is `0`, then the user can create unlimited organizations. Default is `null`.\n */\n readonly createOrganizationsLimit: number | null = null,\n /**\n * A boolean indicating whether the user can delete their own account.\n */\n readonly deleteSelfEnabled: boolean,\n /**\n * The unix timestamp of when the user accepted the legal requirements. `null` if [**Require express consent to legal documents**](https://clerk.com/docs/authentication/configuration/legal-compliance) is not enabled.\n */\n readonly legalAcceptedAt: number | null,\n ) {}\n\n static fromJSON(data: UserJSON): User {\n const res = new User(\n data.id,\n data.password_enabled,\n data.totp_enabled,\n data.backup_code_enabled,\n data.two_factor_enabled,\n data.banned,\n data.locked,\n data.created_at,\n data.updated_at,\n data.image_url,\n data.has_image,\n data.primary_email_address_id,\n data.primary_phone_number_id,\n data.primary_web3_wallet_id,\n data.last_sign_in_at,\n data.external_id,\n data.username,\n data.first_name,\n data.last_name,\n data.public_metadata,\n data.private_metadata,\n data.unsafe_metadata,\n (data.email_addresses || []).map(x => EmailAddress.fromJSON(x)),\n (data.phone_numbers || []).map(x => PhoneNumber.fromJSON(x)),\n (data.web3_wallets || []).map(x => Web3Wallet.fromJSON(x)),\n (data.external_accounts || []).map((x: ExternalAccountJSON) => ExternalAccount.fromJSON(x)),\n (data.saml_accounts || []).map((x: SamlAccountJSON) => SamlAccount.fromJSON(x)),\n data.last_active_at,\n data.create_organization_enabled,\n data.create_organizations_limit,\n data.delete_self_enabled,\n data.legal_accepted_at,\n );\n res._raw = data;\n return res;\n }\n\n /**\n * The primary email address of the user.\n */\n get primaryEmailAddress() {\n return this.emailAddresses.find(({ id }) => id === this.primaryEmailAddressId) ?? null;\n }\n\n /**\n * The primary phone number of the user.\n */\n get primaryPhoneNumber() {\n return this.phoneNumbers.find(({ id }) => id === this.primaryPhoneNumberId) ?? null;\n }\n\n /**\n * The primary web3 wallet of the user.\n */\n get primaryWeb3Wallet() {\n return this.web3Wallets.find(({ id }) => id === this.primaryWeb3WalletId) ?? null;\n }\n\n /**\n * The full name of the user.\n */\n get fullName() {\n return [this.firstName, this.lastName].join(' ').trim() || null;\n }\n}\n","import type { WaitlistEntryStatus } from './Enums';\nimport { Invitation } from './Invitation';\nimport type { WaitlistEntryJSON } from './JSON';\n\nexport class WaitlistEntry {\n constructor(\n readonly id: string,\n readonly emailAddress: string,\n readonly status: WaitlistEntryStatus,\n readonly invitation: Invitation | null,\n readonly createdAt: number,\n readonly updatedAt: number,\n readonly isLocked?: boolean,\n ) {}\n\n static fromJSON(data: WaitlistEntryJSON): WaitlistEntry {\n return new WaitlistEntry(\n data.id,\n data.email_address,\n data.status,\n data.invitation && Invitation.fromJSON(data.invitation),\n data.created_at,\n data.updated_at,\n data.is_locked,\n );\n }\n}\n","import type { FeatureJSON } from './JSON';\n\n/**\n * The `Feature` object represents a feature of a subscription plan.\n *\n * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes.\n */\nexport class Feature {\n constructor(\n /**\n * The unique identifier for the feature.\n */\n readonly id: string,\n /**\n * The name of the feature.\n */\n readonly name: string,\n /**\n * The description of the feature.\n */\n readonly description: string,\n /**\n * The URL-friendly identifier of the feature.\n */\n readonly slug: string,\n /**\n * The URL of the feature's avatar image.\n */\n readonly avatarUrl: string,\n ) {}\n\n static fromJSON(data: FeatureJSON): Feature {\n return new Feature(data.id, data.name, data.description, data.slug, data.avatar_url);\n }\n}\n","import type { BillingMoneyAmount } from '@clerk/types';\n\nimport { Feature } from './Feature';\nimport type { BillingPlanJSON } from './JSON';\n\n/**\n * The `BillingPlan` object is similar to the [`BillingPlanResource`](/docs/references/javascript/types/billing-plan-resource) object as it holds information about a plan, as well as methods for managing it. However, the `BillingPlan` object is different in that it is used in the [Backend API](https://clerk.com/docs/reference/backend-api/tag/commerce/get/commerce/plans) and is not directly accessible from the Frontend API.\n *\n * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes.\n */\nexport class BillingPlan {\n constructor(\n /**\n * The unique identifier for the plan.\n */\n readonly id: string,\n /**\n * The ID of the product the plan belongs to.\n */\n readonly productId: string,\n /**\n * The name of the plan.\n */\n readonly name: string,\n /**\n * The URL-friendly identifier of the plan.\n */\n readonly slug: string,\n /**\n * The description of the plan.\n */\n readonly description: string | undefined,\n /**\n * Whether the plan is the default plan.\n */\n readonly isDefault: boolean,\n /**\n * Whether the plan is recurring.\n */\n readonly isRecurring: boolean,\n /**\n * Whether the plan has a base fee.\n */\n readonly hasBaseFee: boolean,\n /**\n * Whether the plan is displayed in the `` component.\n */\n readonly publiclyVisible: boolean,\n /**\n * The monthly fee of the plan.\n */\n readonly fee: BillingMoneyAmount,\n /**\n * The annual fee of the plan.\n */\n readonly annualFee: BillingMoneyAmount,\n /**\n * The annual fee of the plan on a monthly basis.\n */\n readonly annualMonthlyFee: BillingMoneyAmount,\n /**\n * The type of payer for the plan.\n */\n readonly forPayerType: 'org' | 'user',\n /**\n * The features the plan offers.\n */\n readonly features: Feature[],\n ) {}\n\n static fromJSON(data: BillingPlanJSON): BillingPlan {\n const formatAmountJSON = (fee: BillingPlanJSON['fee']) => {\n return {\n amount: fee.amount,\n amountFormatted: fee.amount_formatted,\n currency: fee.currency,\n currencySymbol: fee.currency_symbol,\n };\n };\n return new BillingPlan(\n data.id,\n data.product_id,\n data.name,\n data.slug,\n data.description,\n data.is_default,\n data.is_recurring,\n data.has_base_fee,\n data.publicly_visible,\n formatAmountJSON(data.fee),\n formatAmountJSON(data.annual_fee),\n formatAmountJSON(data.annual_monthly_fee),\n data.for_payer_type,\n data.features.map(feature => Feature.fromJSON(feature)),\n );\n }\n}\n","import type { BillingMoneyAmount, BillingMoneyAmountJSON } from '@clerk/types';\n\nimport { BillingPlan } from './CommercePlan';\nimport type { BillingSubscriptionItemJSON } from './JSON';\n\n/**\n * The `BillingSubscriptionItem` object is similar to the [`BillingSubscriptionItemResource`](/docs/references/javascript/types/commerce-subscription-item-resource) object as it holds information about a subscription item, as well as methods for managing it. However, the `BillingSubscriptionItem` object is different in that it is used in the [Backend API](https://clerk.com/docs/reference/backend-api/tag/commerce/get/commerce/subscription_items) and is not directly accessible from the Frontend API.\n *\n * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes.\n */\nexport class BillingSubscriptionItem {\n constructor(\n /**\n * The unique identifier for the subscription item.\n */\n readonly id: string,\n /**\n * The status of the subscription item.\n */\n readonly status: BillingSubscriptionItemJSON['status'],\n /**\n * The plan period for the subscription item.\n */\n readonly planPeriod: 'month' | 'annual',\n /**\n * Unix timestamp (milliseconds) of when the current period starts.\n */\n readonly periodStart: number,\n /**\n * The next payment information.\n */\n readonly nextPayment: {\n /**\n * The amount of the next payment.\n */\n amount: number;\n /**\n * Unix timestamp (milliseconds) of when the next payment is scheduled.\n */\n date: number;\n } | null,\n /**\n * The current amount for the subscription item.\n */\n readonly amount: BillingMoneyAmount | null | undefined,\n /**\n * The plan associated with this subscription item.\n */\n readonly plan: BillingPlan,\n /**\n * The plan ID.\n */\n readonly planId: string,\n /**\n * Unix timestamp (milliseconds) of when the subscription item was created.\n */\n readonly createdAt: number,\n /**\n * Unix timestamp (milliseconds) of when the subscription item was last updated.\n */\n readonly updatedAt: number,\n /**\n * Unix timestamp (milliseconds) of when the current period ends.\n */\n readonly periodEnd: number | null,\n /**\n * Unix timestamp (milliseconds) of when the subscription item was canceled.\n */\n readonly canceledAt: number | null,\n /**\n * Unix timestamp (milliseconds) of when the subscription item became past due.\n */\n readonly pastDueAt: number | null,\n /**\n * Unix timestamp (milliseconds) of when the subscription item ended.\n */\n readonly endedAt: number | null,\n /**\n * The payer ID.\n */\n readonly payerId: string,\n /**\n * Whether this subscription item is currently in a free trial period.\n */\n readonly isFreeTrial?: boolean,\n /**\n * The lifetime amount paid for this subscription item.\n */\n readonly lifetimePaid?: BillingMoneyAmount | null,\n ) {}\n\n static fromJSON(data: BillingSubscriptionItemJSON): BillingSubscriptionItem {\n function formatAmountJSON(\n amount: BillingMoneyAmountJSON | null | undefined,\n ): BillingMoneyAmount | null | undefined {\n if (!amount) {\n return amount;\n }\n\n return {\n amount: amount.amount,\n amountFormatted: amount.amount_formatted,\n currency: amount.currency,\n currencySymbol: amount.currency_symbol,\n };\n }\n\n return new BillingSubscriptionItem(\n data.id,\n data.status,\n data.plan_period,\n data.period_start,\n data.next_payment,\n formatAmountJSON(data.amount),\n BillingPlan.fromJSON(data.plan),\n data.plan_id,\n data.created_at,\n data.updated_at,\n data.period_end,\n data.canceled_at,\n data.past_due_at,\n data.ended_at,\n data.payer_id,\n data.is_free_trial,\n formatAmountJSON(data.lifetime_paid),\n );\n }\n}\n","import type { BillingMoneyAmount } from '@clerk/types';\n\nimport { BillingSubscriptionItem } from './CommerceSubscriptionItem';\nimport type { BillingSubscriptionJSON } from './JSON';\n\n/**\n * The `BillingSubscription` object is similar to the [`BillingSubscriptionResource`](/docs/references/javascript/types/commerce-subscription-resource) object as it holds information about a subscription, as well as methods for managing it. However, the `BillingSubscription` object is different in that it is used in the [Backend API](https://clerk.com/docs/reference/backend-api/tag/billing/get/organizations/%7Borganization_id%7D/billing/subscription) and is not directly accessible from the Frontend API.\n *\n * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes.\n */\nexport class BillingSubscription {\n constructor(\n /**\n * The unique identifier for the billing subscription.\n */\n readonly id: string,\n /**\n * The current status of the subscription.\n */\n readonly status: BillingSubscriptionJSON['status'],\n /**\n * The ID of the payer for this subscription.\n */\n readonly payerId: string,\n /**\n * Unix timestamp (milliseconds) of when the subscription was created.\n */\n readonly createdAt: number,\n /**\n * Unix timestamp (milliseconds) of when the subscription was last updated.\n */\n readonly updatedAt: number,\n /**\n * Unix timestamp (milliseconds) of when the subscription became active.\n */\n readonly activeAt: number | null,\n /**\n * Unix timestamp (milliseconds) of when the subscription became past due.\n */\n readonly pastDueAt: number | null,\n /**\n * Array of subscription items in this subscription.\n */\n readonly subscriptionItems: BillingSubscriptionItem[],\n /**\n * Information about the next scheduled payment.\n */\n readonly nextPayment: { date: number; amount: BillingMoneyAmount } | null,\n /**\n * Whether the payer is eligible for a free trial.\n */\n readonly eligibleForFreeTrial: boolean,\n ) {}\n\n static fromJSON(data: BillingSubscriptionJSON): BillingSubscription {\n const nextPayment = data.next_payment\n ? {\n date: data.next_payment.date,\n amount: {\n amount: data.next_payment.amount.amount,\n amountFormatted: data.next_payment.amount.amount_formatted,\n currency: data.next_payment.amount.currency,\n currencySymbol: data.next_payment.amount.currency_symbol,\n },\n }\n : null;\n\n return new BillingSubscription(\n data.id,\n data.status,\n data.payer_id,\n data.created_at,\n data.updated_at,\n data.active_at ?? null,\n data.past_due_at ?? null,\n data.subscription_items.map(item => BillingSubscriptionItem.fromJSON(item)),\n nextPayment,\n data.eligible_for_free_trial ?? false,\n );\n }\n}\n","import {\n ActorToken,\n AllowlistIdentifier,\n APIKey,\n BlocklistIdentifier,\n Client,\n Cookies,\n DeletedObject,\n Domain,\n Email,\n EmailAddress,\n IdPOAuthAccessToken,\n Instance,\n InstanceRestrictions,\n InstanceSettings,\n Invitation,\n JwtTemplate,\n M2MToken,\n Machine,\n MachineScope,\n MachineSecretKey,\n OauthAccessToken,\n OAuthApplication,\n Organization,\n OrganizationInvitation,\n OrganizationMembership,\n OrganizationSettings,\n PhoneNumber,\n ProxyCheck,\n RedirectUrl,\n SamlConnection,\n Session,\n SignInToken,\n SignUpAttempt,\n SMSMessage,\n Token,\n User,\n} from '.';\nimport { AccountlessApplication } from './AccountlessApplication';\nimport { BillingPlan } from './CommercePlan';\nimport { BillingSubscription } from './CommerceSubscription';\nimport { BillingSubscriptionItem } from './CommerceSubscriptionItem';\nimport { Feature } from './Feature';\nimport type { PaginatedResponseJSON } from './JSON';\nimport { ObjectType } from './JSON';\nimport { WaitlistEntry } from './WaitlistEntry';\n\ntype ResourceResponse = {\n /**\n * An array that contains the fetched data.\n */\n data: T;\n};\n\n/**\n * An interface that describes the response of a method that returns a paginated list of resources.\n *\n * If the promise resolves, you will get back the [properties](#properties) listed below. `data` will be an array of the resource type you requested. You can use the `totalCount` property to determine how many total items exist remotely.\n *\n * Some methods that return this type allow pagination with the `limit` and `offset` parameters, in which case the first 10 items will be returned by default. For methods such as [`getAllowlistIdentifierList()`](https://clerk.com/docs/references/backend/allowlist/get-allowlist-identifier-list), which do not take a `limit` or `offset`, all items will be returned.\n *\n * If the promise is rejected, you will receive a `ClerkAPIResponseError` or network error.\n *\n * @interface\n */\nexport type PaginatedResourceResponse = ResourceResponse & {\n /**\n * The total count of data that exist remotely.\n */\n totalCount: number;\n};\n\nexport function deserialize(payload: unknown): PaginatedResourceResponse | ResourceResponse {\n let data, totalCount: number | undefined;\n\n if (Array.isArray(payload)) {\n const data = payload.map(item => jsonToObject(item)) as U;\n return { data };\n } else if (isPaginated(payload)) {\n data = payload.data.map(item => jsonToObject(item)) as U;\n totalCount = payload.total_count;\n\n return { data, totalCount };\n } else {\n return { data: jsonToObject(payload) };\n }\n}\n\nfunction isPaginated(payload: unknown): payload is PaginatedResponseJSON {\n if (!payload || typeof payload !== 'object' || !('data' in payload)) {\n return false;\n }\n\n return Array.isArray(payload.data) && payload.data !== undefined;\n}\n\nfunction getCount(item: PaginatedResponseJSON) {\n return item.total_count;\n}\n\n// TODO: Revise response deserialization\nfunction jsonToObject(item: any): any {\n // Special case: DeletedObject\n // TODO: Improve this check\n if (typeof item !== 'string' && 'object' in item && 'deleted' in item) {\n return DeletedObject.fromJSON(item);\n }\n\n switch (item.object) {\n case ObjectType.AccountlessApplication:\n return AccountlessApplication.fromJSON(item);\n case ObjectType.ActorToken:\n return ActorToken.fromJSON(item);\n case ObjectType.AllowlistIdentifier:\n return AllowlistIdentifier.fromJSON(item);\n case ObjectType.ApiKey:\n return APIKey.fromJSON(item);\n case ObjectType.BlocklistIdentifier:\n return BlocklistIdentifier.fromJSON(item);\n case ObjectType.Client:\n return Client.fromJSON(item);\n case ObjectType.Cookies:\n return Cookies.fromJSON(item);\n case ObjectType.Domain:\n return Domain.fromJSON(item);\n case ObjectType.EmailAddress:\n return EmailAddress.fromJSON(item);\n case ObjectType.Email:\n return Email.fromJSON(item);\n case ObjectType.IdpOAuthAccessToken:\n return IdPOAuthAccessToken.fromJSON(item);\n case ObjectType.Instance:\n return Instance.fromJSON(item);\n case ObjectType.InstanceRestrictions:\n return InstanceRestrictions.fromJSON(item);\n case ObjectType.InstanceSettings:\n return InstanceSettings.fromJSON(item);\n case ObjectType.Invitation:\n return Invitation.fromJSON(item);\n case ObjectType.JwtTemplate:\n return JwtTemplate.fromJSON(item);\n case ObjectType.Machine:\n return Machine.fromJSON(item);\n case ObjectType.MachineScope:\n return MachineScope.fromJSON(item);\n case ObjectType.MachineSecretKey:\n return MachineSecretKey.fromJSON(item);\n case ObjectType.M2MToken:\n return M2MToken.fromJSON(item);\n case ObjectType.OauthAccessToken:\n return OauthAccessToken.fromJSON(item);\n case ObjectType.OAuthApplication:\n return OAuthApplication.fromJSON(item);\n case ObjectType.Organization:\n return Organization.fromJSON(item);\n case ObjectType.OrganizationInvitation:\n return OrganizationInvitation.fromJSON(item);\n case ObjectType.OrganizationMembership:\n return OrganizationMembership.fromJSON(item);\n case ObjectType.OrganizationSettings:\n return OrganizationSettings.fromJSON(item);\n case ObjectType.PhoneNumber:\n return PhoneNumber.fromJSON(item);\n case ObjectType.ProxyCheck:\n return ProxyCheck.fromJSON(item);\n case ObjectType.RedirectUrl:\n return RedirectUrl.fromJSON(item);\n case ObjectType.SamlConnection:\n return SamlConnection.fromJSON(item);\n case ObjectType.SignInToken:\n return SignInToken.fromJSON(item);\n case ObjectType.SignUpAttempt:\n return SignUpAttempt.fromJSON(item);\n case ObjectType.Session:\n return Session.fromJSON(item);\n case ObjectType.SmsMessage:\n return SMSMessage.fromJSON(item);\n case ObjectType.Token:\n return Token.fromJSON(item);\n case ObjectType.TotalCount:\n return getCount(item);\n case ObjectType.User:\n return User.fromJSON(item);\n case ObjectType.WaitlistEntry:\n return WaitlistEntry.fromJSON(item);\n case ObjectType.BillingPlan:\n return BillingPlan.fromJSON(item);\n case ObjectType.BillingSubscription:\n return BillingSubscription.fromJSON(item);\n case ObjectType.BillingSubscriptionItem:\n return BillingSubscriptionItem.fromJSON(item);\n case ObjectType.Feature:\n return Feature.fromJSON(item);\n default:\n return item;\n }\n}\n","import {\n AccountlessApplicationAPI,\n ActorTokenAPI,\n AllowlistIdentifierAPI,\n APIKeysAPI,\n BetaFeaturesAPI,\n BlocklistIdentifierAPI,\n ClientAPI,\n DomainAPI,\n EmailAddressAPI,\n IdPOAuthAccessTokenApi,\n InstanceAPI,\n InvitationAPI,\n JwksAPI,\n JwtTemplatesApi,\n M2MTokenApi,\n MachineApi,\n OAuthApplicationsApi,\n OrganizationAPI,\n PhoneNumberAPI,\n ProxyCheckAPI,\n RedirectUrlAPI,\n SamlConnectionAPI,\n SessionAPI,\n SignInTokenAPI,\n SignUpAPI,\n TestingTokenAPI,\n UserAPI,\n WaitlistEntryAPI,\n WebhookAPI,\n} from './endpoints';\nimport { BillingAPI } from './endpoints/BillingApi';\nimport { buildRequest } from './request';\n\nexport type CreateBackendApiOptions = Parameters[0];\n\nexport type ApiClient = ReturnType;\n\nexport function createBackendApiClient(options: CreateBackendApiOptions) {\n const request = buildRequest(options);\n\n return {\n __experimental_accountlessApplications: new AccountlessApplicationAPI(\n buildRequest({ ...options, requireSecretKey: false }),\n ),\n actorTokens: new ActorTokenAPI(request),\n allowlistIdentifiers: new AllowlistIdentifierAPI(request),\n apiKeys: new APIKeysAPI(\n buildRequest({\n ...options,\n skipApiVersionInUrl: true,\n }),\n ),\n betaFeatures: new BetaFeaturesAPI(request),\n blocklistIdentifiers: new BlocklistIdentifierAPI(request),\n /**\n * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes.\n */\n billing: new BillingAPI(request),\n clients: new ClientAPI(request),\n domains: new DomainAPI(request),\n emailAddresses: new EmailAddressAPI(request),\n idPOAuthAccessToken: new IdPOAuthAccessTokenApi(\n buildRequest({\n ...options,\n skipApiVersionInUrl: true,\n }),\n ),\n instance: new InstanceAPI(request),\n invitations: new InvitationAPI(request),\n jwks: new JwksAPI(request),\n jwtTemplates: new JwtTemplatesApi(request),\n machines: new MachineApi(request),\n m2m: new M2MTokenApi(\n buildRequest({\n ...options,\n skipApiVersionInUrl: true,\n requireSecretKey: false,\n useMachineSecretKey: true,\n }),\n ),\n oauthApplications: new OAuthApplicationsApi(request),\n organizations: new OrganizationAPI(request),\n phoneNumbers: new PhoneNumberAPI(request),\n proxyChecks: new ProxyCheckAPI(request),\n redirectUrls: new RedirectUrlAPI(request),\n samlConnections: new SamlConnectionAPI(request),\n sessions: new SessionAPI(request),\n signInTokens: new SignInTokenAPI(request),\n signUps: new SignUpAPI(request),\n testingTokens: new TestingTokenAPI(request),\n users: new UserAPI(request),\n waitlistEntries: new WaitlistEntryAPI(request),\n webhooks: new WebhookAPI(request),\n };\n}\n","import type { JwtReturnType } from './types';\n\n// TODO(dimkl): Will be probably be dropped in next major version\nexport function withLegacyReturn Promise>>(cb: T) {\n return async (...args: Parameters): Promise>['data']>> | never => {\n const { data, errors } = await cb(...args);\n if (errors) {\n throw errors[0];\n }\n return data;\n };\n}\n\n// TODO(dimkl): Will be probably be dropped in next major version\nexport function withLegacySyncReturn JwtReturnType>(cb: T) {\n return (...args: Parameters): NonNullable>['data']> | never => {\n const { data, errors } = cb(...args);\n if (errors) {\n throw errors[0];\n }\n return data;\n };\n}\n","export function mergePreDefinedOptions>(preDefinedOptions: T, options: Partial): T {\n return Object.keys(preDefinedOptions).reduce(\n (obj: T, key: string) => {\n return { ...obj, [key]: options[key] || obj[key] };\n },\n { ...preDefinedOptions },\n );\n}\n","export type TokenCarrier = 'header' | 'cookie';\n\nexport const TokenVerificationErrorCode = {\n InvalidSecretKey: 'clerk_key_invalid',\n};\n\nexport type TokenVerificationErrorCode = (typeof TokenVerificationErrorCode)[keyof typeof TokenVerificationErrorCode];\n\nexport const TokenVerificationErrorReason = {\n TokenExpired: 'token-expired',\n TokenInvalid: 'token-invalid',\n TokenInvalidAlgorithm: 'token-invalid-algorithm',\n TokenInvalidAuthorizedParties: 'token-invalid-authorized-parties',\n TokenInvalidSignature: 'token-invalid-signature',\n TokenNotActiveYet: 'token-not-active-yet',\n TokenIatInTheFuture: 'token-iat-in-the-future',\n TokenVerificationFailed: 'token-verification-failed',\n InvalidSecretKey: 'secret-key-invalid',\n LocalJWKMissing: 'jwk-local-missing',\n RemoteJWKFailedToLoad: 'jwk-remote-failed-to-load',\n RemoteJWKInvalid: 'jwk-remote-invalid',\n RemoteJWKMissing: 'jwk-remote-missing',\n JWKFailedToResolve: 'jwk-failed-to-resolve',\n JWKKidMismatch: 'jwk-kid-mismatch',\n};\n\nexport type TokenVerificationErrorReason =\n (typeof TokenVerificationErrorReason)[keyof typeof TokenVerificationErrorReason];\n\nexport const TokenVerificationErrorAction = {\n ContactSupport: 'Contact support@clerk.com',\n EnsureClerkJWT: 'Make sure that this is a valid Clerk generate JWT.',\n SetClerkJWTKey: 'Set the CLERK_JWT_KEY environment variable.',\n SetClerkSecretKey: 'Set the CLERK_SECRET_KEY environment variable.',\n EnsureClockSync: 'Make sure your system clock is in sync (e.g. turn off and on automatic time synchronization).',\n};\n\nexport type TokenVerificationErrorAction =\n (typeof TokenVerificationErrorAction)[keyof typeof TokenVerificationErrorAction];\n\nexport class TokenVerificationError extends Error {\n action?: TokenVerificationErrorAction;\n reason: TokenVerificationErrorReason;\n tokenCarrier?: TokenCarrier;\n\n constructor({\n action,\n message,\n reason,\n }: {\n action?: TokenVerificationErrorAction;\n message: string;\n reason: TokenVerificationErrorReason;\n }) {\n super(message);\n\n Object.setPrototypeOf(this, TokenVerificationError.prototype);\n\n this.reason = reason;\n this.message = message;\n this.action = action;\n }\n\n public getFullMessage() {\n return `${[this.message, this.action].filter(m => m).join(' ')} (reason=${this.reason}, token-carrier=${\n this.tokenCarrier\n })`;\n }\n}\n\nexport class SignJWTError extends Error {}\n\nexport const MachineTokenVerificationErrorCode = {\n TokenInvalid: 'token-invalid',\n InvalidSecretKey: 'secret-key-invalid',\n UnexpectedError: 'unexpected-error',\n} as const;\n\nexport type MachineTokenVerificationErrorCode =\n (typeof MachineTokenVerificationErrorCode)[keyof typeof MachineTokenVerificationErrorCode];\n\nexport class MachineTokenVerificationError extends Error {\n code: MachineTokenVerificationErrorCode;\n long_message?: string;\n status: number;\n\n constructor({ message, code, status }: { message: string; code: MachineTokenVerificationErrorCode; status: number }) {\n super(message);\n Object.setPrototypeOf(this, MachineTokenVerificationError.prototype);\n\n this.code = code;\n this.status = status;\n }\n\n public getFullMessage() {\n return `${this.message} (code=${this.code}, status=${this.status})`;\n }\n}\n","/**\n * The base64url helper was extracted from the rfc4648 package\n * in order to resolve CSJ/ESM interoperability issues\n *\n * https://github.com/swansontec/rfc4648.js\n *\n * For more context please refer to:\n * - https://github.com/evanw/esbuild/issues/1719\n * - https://github.com/evanw/esbuild/issues/532\n * - https://github.com/swansontec/rollup-plugin-mjs-entry\n */\nexport const base64url = {\n parse(string: string, opts?: ParseOptions): Uint8Array {\n return parse(string, base64UrlEncoding, opts);\n },\n\n stringify(data: ArrayLike, opts?: StringifyOptions): string {\n return stringify(data, base64UrlEncoding, opts);\n },\n};\n\nconst base64UrlEncoding: Encoding = {\n chars: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',\n bits: 6,\n};\n\ninterface Encoding {\n bits: number;\n chars: string;\n codes?: { [char: string]: number };\n}\n\ninterface ParseOptions {\n loose?: boolean;\n out?: new (size: number) => { [index: number]: number };\n}\n\ninterface StringifyOptions {\n pad?: boolean;\n}\n\nfunction parse(string: string, encoding: Encoding, opts: ParseOptions = {}): Uint8Array {\n // Build the character lookup table:\n if (!encoding.codes) {\n encoding.codes = {};\n for (let i = 0; i < encoding.chars.length; ++i) {\n encoding.codes[encoding.chars[i]] = i;\n }\n }\n\n // The string must have a whole number of bytes:\n if (!opts.loose && (string.length * encoding.bits) & 7) {\n throw new SyntaxError('Invalid padding');\n }\n\n // Count the padding bytes:\n let end = string.length;\n while (string[end - 1] === '=') {\n --end;\n\n // If we get a whole number of bytes, there is too much padding:\n if (!opts.loose && !(((string.length - end) * encoding.bits) & 7)) {\n throw new SyntaxError('Invalid padding');\n }\n }\n\n // Allocate the output:\n const out = new (opts.out ?? Uint8Array)(((end * encoding.bits) / 8) | 0) as Uint8Array;\n\n // Parse the data:\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n let written = 0; // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = encoding.codes[string[i]];\n if (value === undefined) {\n throw new SyntaxError('Invalid character ' + string[i]);\n }\n\n // Append the bits to the buffer:\n buffer = (buffer << encoding.bits) | value;\n bits += encoding.bits;\n\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8;\n out[written++] = 0xff & (buffer >> bits);\n }\n }\n\n // Verify that we have received just enough bits:\n if (bits >= encoding.bits || 0xff & (buffer << (8 - bits))) {\n throw new SyntaxError('Unexpected end of data');\n }\n\n return out;\n}\n\nfunction stringify(data: ArrayLike, encoding: Encoding, opts: StringifyOptions = {}): string {\n const { pad = true } = opts;\n const mask = (1 << encoding.bits) - 1;\n let out = '';\n\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | (0xff & data[i]);\n bits += 8;\n\n // Write out as much as we can:\n while (bits > encoding.bits) {\n bits -= encoding.bits;\n out += encoding.chars[mask & (buffer >> bits)];\n }\n }\n\n // Partial character:\n if (bits) {\n out += encoding.chars[mask & (buffer << (encoding.bits - bits))];\n }\n\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while ((out.length * encoding.bits) & 7) {\n out += '=';\n }\n }\n\n return out;\n}\n","const algToHash: Record = {\n RS256: 'SHA-256',\n RS384: 'SHA-384',\n RS512: 'SHA-512',\n};\nconst RSA_ALGORITHM_NAME = 'RSASSA-PKCS1-v1_5';\n\nconst jwksAlgToCryptoAlg: Record = {\n RS256: RSA_ALGORITHM_NAME,\n RS384: RSA_ALGORITHM_NAME,\n RS512: RSA_ALGORITHM_NAME,\n};\n\nexport const algs = Object.keys(algToHash);\n\nexport function getCryptoAlgorithm(algorithmName: string): RsaHashedImportParams {\n const hash = algToHash[algorithmName];\n const name = jwksAlgToCryptoAlg[algorithmName];\n\n if (!hash || !name) {\n throw new Error(`Unsupported algorithm ${algorithmName}, expected one of ${algs.join(',')}.`);\n }\n\n return {\n hash: { name: algToHash[algorithmName] },\n name: jwksAlgToCryptoAlg[algorithmName],\n };\n}\n","import { TokenVerificationError, TokenVerificationErrorAction, TokenVerificationErrorReason } from '../errors';\nimport { algs } from './algorithms';\n\nexport type IssuerResolver = string | ((iss: string) => boolean);\n\nconst isArrayString = (s: unknown): s is string[] => {\n return Array.isArray(s) && s.length > 0 && s.every(a => typeof a === 'string');\n};\n\nexport const assertAudienceClaim = (aud?: unknown, audience?: unknown) => {\n const audienceList = [audience].flat().filter(a => !!a);\n const audList = [aud].flat().filter(a => !!a);\n const shouldVerifyAudience = audienceList.length > 0 && audList.length > 0;\n\n if (!shouldVerifyAudience) {\n // Notice: Clerk JWTs use AZP claim instead of Audience\n //\n // return {\n // valid: false,\n // reason: `Invalid JWT audience claim (aud) ${JSON.stringify(\n // aud,\n // )}. Expected a string or a non-empty array of strings.`,\n // };\n return;\n }\n\n if (typeof aud === 'string') {\n if (!audienceList.includes(aud)) {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.EnsureClerkJWT,\n reason: TokenVerificationErrorReason.TokenVerificationFailed,\n message: `Invalid JWT audience claim (aud) ${JSON.stringify(aud)}. Is not included in \"${JSON.stringify(\n audienceList,\n )}\".`,\n });\n }\n } else if (isArrayString(aud)) {\n if (!aud.some(a => audienceList.includes(a))) {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.EnsureClerkJWT,\n reason: TokenVerificationErrorReason.TokenVerificationFailed,\n message: `Invalid JWT audience claim array (aud) ${JSON.stringify(aud)}. Is not included in \"${JSON.stringify(\n audienceList,\n )}\".`,\n });\n }\n }\n};\n\nexport const assertHeaderType = (typ?: unknown) => {\n if (typeof typ === 'undefined') {\n return;\n }\n\n if (typ !== 'JWT') {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.EnsureClerkJWT,\n reason: TokenVerificationErrorReason.TokenInvalid,\n message: `Invalid JWT type ${JSON.stringify(typ)}. Expected \"JWT\".`,\n });\n }\n};\n\nexport const assertHeaderAlgorithm = (alg: string) => {\n if (!algs.includes(alg)) {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.EnsureClerkJWT,\n reason: TokenVerificationErrorReason.TokenInvalidAlgorithm,\n message: `Invalid JWT algorithm ${JSON.stringify(alg)}. Supported: ${algs}.`,\n });\n }\n};\n\nexport const assertSubClaim = (sub?: string) => {\n if (typeof sub !== 'string') {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.EnsureClerkJWT,\n reason: TokenVerificationErrorReason.TokenVerificationFailed,\n message: `Subject claim (sub) is required and must be a string. Received ${JSON.stringify(sub)}.`,\n });\n }\n};\n\nexport const assertAuthorizedPartiesClaim = (azp?: string, authorizedParties?: string[]) => {\n if (!azp || !authorizedParties || authorizedParties.length === 0) {\n return;\n }\n\n if (!authorizedParties.includes(azp)) {\n throw new TokenVerificationError({\n reason: TokenVerificationErrorReason.TokenInvalidAuthorizedParties,\n message: `Invalid JWT Authorized party claim (azp) ${JSON.stringify(azp)}. Expected \"${authorizedParties}\".`,\n });\n }\n};\n\nexport const assertExpirationClaim = (exp: number, clockSkewInMs: number) => {\n if (typeof exp !== 'number') {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.EnsureClerkJWT,\n reason: TokenVerificationErrorReason.TokenVerificationFailed,\n message: `Invalid JWT expiry date claim (exp) ${JSON.stringify(exp)}. Expected number.`,\n });\n }\n\n const currentDate = new Date(Date.now());\n const expiryDate = new Date(0);\n expiryDate.setUTCSeconds(exp);\n\n const expired = expiryDate.getTime() <= currentDate.getTime() - clockSkewInMs;\n if (expired) {\n throw new TokenVerificationError({\n reason: TokenVerificationErrorReason.TokenExpired,\n message: `JWT is expired. Expiry date: ${expiryDate.toUTCString()}, Current date: ${currentDate.toUTCString()}.`,\n });\n }\n};\n\nexport const assertActivationClaim = (nbf: number | undefined, clockSkewInMs: number) => {\n if (typeof nbf === 'undefined') {\n return;\n }\n\n if (typeof nbf !== 'number') {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.EnsureClerkJWT,\n reason: TokenVerificationErrorReason.TokenVerificationFailed,\n message: `Invalid JWT not before date claim (nbf) ${JSON.stringify(nbf)}. Expected number.`,\n });\n }\n\n const currentDate = new Date(Date.now());\n const notBeforeDate = new Date(0);\n notBeforeDate.setUTCSeconds(nbf);\n\n const early = notBeforeDate.getTime() > currentDate.getTime() + clockSkewInMs;\n if (early) {\n throw new TokenVerificationError({\n reason: TokenVerificationErrorReason.TokenNotActiveYet,\n message: `JWT cannot be used prior to not before date claim (nbf). Not before date: ${notBeforeDate.toUTCString()}; Current date: ${currentDate.toUTCString()};`,\n });\n }\n};\n\nexport const assertIssuedAtClaim = (iat: number | undefined, clockSkewInMs: number) => {\n if (typeof iat === 'undefined') {\n return;\n }\n\n if (typeof iat !== 'number') {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.EnsureClerkJWT,\n reason: TokenVerificationErrorReason.TokenVerificationFailed,\n message: `Invalid JWT issued at date claim (iat) ${JSON.stringify(iat)}. Expected number.`,\n });\n }\n\n const currentDate = new Date(Date.now());\n const issuedAtDate = new Date(0);\n issuedAtDate.setUTCSeconds(iat);\n\n const postIssued = issuedAtDate.getTime() > currentDate.getTime() + clockSkewInMs;\n if (postIssued) {\n throw new TokenVerificationError({\n reason: TokenVerificationErrorReason.TokenIatInTheFuture,\n message: `JWT issued at date claim (iat) is in the future. Issued at date: ${issuedAtDate.toUTCString()}; Current date: ${currentDate.toUTCString()};`,\n });\n }\n};\n","import { isomorphicAtob } from '@clerk/shared/isomorphicAtob';\n\nimport { runtime } from '../runtime';\n\n// https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/importKey#pkcs_8_import\nfunction pemToBuffer(secret: string): ArrayBuffer {\n const trimmed = secret\n .replace(/-----BEGIN.*?-----/g, '')\n .replace(/-----END.*?-----/g, '')\n .replace(/\\s/g, '');\n\n const decoded = isomorphicAtob(trimmed);\n\n const buffer = new ArrayBuffer(decoded.length);\n const bufView = new Uint8Array(buffer);\n\n for (let i = 0, strLen = decoded.length; i < strLen; i++) {\n bufView[i] = decoded.charCodeAt(i);\n }\n\n return bufView;\n}\n\nexport function importKey(\n key: JsonWebKey | string,\n algorithm: RsaHashedImportParams,\n keyUsage: 'verify' | 'sign',\n): Promise {\n if (typeof key === 'object') {\n return runtime.crypto.subtle.importKey('jwk', key, algorithm, false, [keyUsage]);\n }\n\n const keyData = pemToBuffer(key);\n const format = keyUsage === 'sign' ? 'pkcs8' : 'spki';\n\n return runtime.crypto.subtle.importKey(format, keyData, algorithm, false, [keyUsage]);\n}\n","import type { Jwt, JwtPayload } from '@clerk/types';\n\nimport { TokenVerificationError, TokenVerificationErrorAction, TokenVerificationErrorReason } from '../errors';\nimport { runtime } from '../runtime';\nimport { base64url } from '../util/rfc4648';\nimport { getCryptoAlgorithm } from './algorithms';\nimport {\n assertActivationClaim,\n assertAudienceClaim,\n assertAuthorizedPartiesClaim,\n assertExpirationClaim,\n assertHeaderAlgorithm,\n assertHeaderType,\n assertIssuedAtClaim,\n assertSubClaim,\n} from './assertions';\nimport { importKey } from './cryptoKeys';\nimport type { JwtReturnType } from './types';\n\nconst DEFAULT_CLOCK_SKEW_IN_MS = 5 * 1000;\n\nexport async function hasValidSignature(jwt: Jwt, key: JsonWebKey | string): Promise> {\n const { header, signature, raw } = jwt;\n const encoder = new TextEncoder();\n const data = encoder.encode([raw.header, raw.payload].join('.'));\n const algorithm = getCryptoAlgorithm(header.alg);\n\n try {\n const cryptoKey = await importKey(key, algorithm, 'verify');\n\n const verified = await runtime.crypto.subtle.verify(algorithm.name, cryptoKey, signature, data);\n return { data: verified };\n } catch (error) {\n return {\n errors: [\n new TokenVerificationError({\n reason: TokenVerificationErrorReason.TokenInvalidSignature,\n message: (error as Error)?.message,\n }),\n ],\n };\n }\n}\n\nexport function decodeJwt(token: string): JwtReturnType {\n const tokenParts = (token || '').toString().split('.');\n if (tokenParts.length !== 3) {\n return {\n errors: [\n new TokenVerificationError({\n reason: TokenVerificationErrorReason.TokenInvalid,\n message: `Invalid JWT form. A JWT consists of three parts separated by dots.`,\n }),\n ],\n };\n }\n\n const [rawHeader, rawPayload, rawSignature] = tokenParts;\n\n const decoder = new TextDecoder();\n\n // To verify a JWS with SubtleCrypto you need to be careful to encode and decode\n // the data properly between binary and base64url representation. Unfortunately\n // the standard implementation in the V8 of btoa() and atob() are difficult to\n // work with as they use \"a Unicode string containing only characters in the\n // range U+0000 to U+00FF, each representing a binary byte with values 0x00 to\n // 0xFF respectively\" as the representation of binary data.\n\n // A better solution to represent binary data in Javascript is to use ES6 TypedArray\n // and use a Javascript library to convert them to base64url that honors RFC 4648.\n\n // Side note: The difference between base64 and base64url is the characters selected\n // for value 62 and 63 in the standard, base64 encode them to + and / while base64url\n // encode - and _.\n\n // More info at https://stackoverflow.com/questions/54062583/how-to-verify-a-signed-jwt-with-subtlecrypto-of-the-web-crypto-API\n const header = JSON.parse(decoder.decode(base64url.parse(rawHeader, { loose: true })));\n const payload = JSON.parse(decoder.decode(base64url.parse(rawPayload, { loose: true })));\n\n const signature = base64url.parse(rawSignature, { loose: true });\n\n const data = {\n header,\n payload,\n signature,\n raw: {\n header: rawHeader,\n payload: rawPayload,\n signature: rawSignature,\n text: token,\n },\n } satisfies Jwt;\n\n return { data };\n}\n\n/**\n * @inline\n */\nexport type VerifyJwtOptions = {\n /**\n * A string or list of [audiences](https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.3). If passed, it is checked against the `aud` claim in the token.\n */\n audience?: string | string[];\n /**\n * An allowlist of origins to verify against, to protect your application from the subdomain cookie leaking attack.\n * @example\n * ```ts\n * ['http://localhost:3000', 'https://example.com']\n * ```\n */\n authorizedParties?: string[];\n /**\n * Specifies the allowed time difference (in milliseconds) between the Clerk server (which generates the token) and the clock of the user's application server when validating a token.\n * @default 5000\n */\n clockSkewInMs?: number;\n /**\n * @internal\n */\n key: JsonWebKey | string;\n};\n\nexport async function verifyJwt(\n token: string,\n options: VerifyJwtOptions,\n): Promise> {\n const { audience, authorizedParties, clockSkewInMs, key } = options;\n const clockSkew = clockSkewInMs || DEFAULT_CLOCK_SKEW_IN_MS;\n\n const { data: decoded, errors } = decodeJwt(token);\n if (errors) {\n return { errors };\n }\n\n const { header, payload } = decoded;\n try {\n // Header verifications\n const { typ, alg } = header;\n\n assertHeaderType(typ);\n assertHeaderAlgorithm(alg);\n\n // Payload verifications\n const { azp, sub, aud, iat, exp, nbf } = payload;\n\n assertSubClaim(sub);\n assertAudienceClaim([aud], [audience]);\n assertAuthorizedPartiesClaim(azp, authorizedParties);\n assertExpirationClaim(exp, clockSkew);\n assertActivationClaim(nbf, clockSkew);\n assertIssuedAtClaim(iat, clockSkew);\n } catch (err) {\n return { errors: [err as TokenVerificationError] };\n }\n\n const { data: signatureValid, errors: signatureErrors } = await hasValidSignature(decoded, key);\n if (signatureErrors) {\n return {\n errors: [\n new TokenVerificationError({\n action: TokenVerificationErrorAction.EnsureClerkJWT,\n reason: TokenVerificationErrorReason.TokenVerificationFailed,\n message: `Error verifying JWT signature. ${signatureErrors[0]}`,\n }),\n ],\n };\n }\n\n if (!signatureValid) {\n return {\n errors: [\n new TokenVerificationError({\n reason: TokenVerificationErrorReason.TokenInvalidSignature,\n message: 'JWT signature is invalid.',\n }),\n ],\n };\n }\n\n return { data: payload };\n}\n","import { buildAccountsBaseUrl } from '@clerk/shared/buildAccountsBaseUrl';\nimport { isCurrentDevAccountPortalOrigin, isLegacyDevAccountPortalOrigin } from '@clerk/shared/url';\nimport type { Jwt } from '@clerk/types';\n\nimport { constants } from '../constants';\nimport { decodeJwt } from '../jwt/verifyJwt';\nimport { runtime } from '../runtime';\nimport { assertValidPublishableKey } from '../util/optionsAssertions';\nimport { getCookieSuffix, getSuffixedCookieName, parsePublishableKey } from '../util/shared';\nimport type { ClerkRequest } from './clerkRequest';\nimport { TokenType } from './tokenTypes';\nimport type { AuthenticateRequestOptions } from './types';\n\ninterface AuthenticateContext extends AuthenticateRequestOptions {\n // header-based values\n accept: string | undefined;\n forwardedHost: string | undefined;\n forwardedProto: string | undefined;\n host: string | undefined;\n origin: string | undefined;\n referrer: string | undefined;\n secFetchDest: string | undefined;\n tokenInHeader: string | undefined;\n userAgent: string | undefined;\n\n // cookie-based values\n clientUat: number;\n refreshTokenInCookie: string | undefined;\n sessionTokenInCookie: string | undefined;\n\n // handshake-related values\n devBrowserToken: string | undefined;\n handshakeNonce: string | undefined;\n handshakeRedirectLoopCounter: number;\n handshakeToken: string | undefined;\n\n // url derived from headers\n clerkUrl: URL;\n // enforce existence of the following props\n frontendApi: string;\n instanceType: string;\n publishableKey: string;\n}\n\n/**\n * All data required to authenticate a request.\n * This is the data we use to decide whether a request\n * is in a signed in or signed out state or if we need\n * to perform a handshake.\n */\nclass AuthenticateContext implements AuthenticateContext {\n /**\n * The original Clerk frontend API URL, extracted from publishable key before proxy URL override.\n * Used for backend operations like token validation and issuer checking.\n */\n private originalFrontendApi: string = '';\n\n /**\n * Retrieves the session token from either the cookie or the header.\n *\n * @returns {string | undefined} The session token if available, otherwise undefined.\n */\n public get sessionToken(): string | undefined {\n return this.sessionTokenInCookie || this.tokenInHeader;\n }\n\n public constructor(\n private cookieSuffix: string,\n private clerkRequest: ClerkRequest,\n options: AuthenticateRequestOptions,\n ) {\n if (options.acceptsToken === TokenType.M2MToken || options.acceptsToken === TokenType.ApiKey) {\n // For non-session tokens, we only want to set the header values.\n this.initHeaderValues();\n } else {\n // Even though the options are assigned to this later in this function\n // we set the publishableKey here because it is being used in cookies/headers/handshake-values\n // as part of getMultipleAppsCookie.\n this.initPublishableKeyValues(options);\n this.initHeaderValues();\n // initCookieValues should be used before initHandshakeValues because it depends on suffixedCookies\n this.initCookieValues();\n this.initHandshakeValues();\n }\n\n Object.assign(this, options);\n this.clerkUrl = this.clerkRequest.clerkUrl;\n }\n\n public usesSuffixedCookies(): boolean {\n const suffixedClientUat = this.getSuffixedCookie(constants.Cookies.ClientUat);\n const clientUat = this.getCookie(constants.Cookies.ClientUat);\n const suffixedSession = this.getSuffixedCookie(constants.Cookies.Session) || '';\n const session = this.getCookie(constants.Cookies.Session) || '';\n\n // In the case of malformed session cookies (eg missing the iss claim), we should\n // use the un-suffixed cookies to return signed-out state instead of triggering\n // handshake\n if (session && !this.tokenHasIssuer(session)) {\n return false;\n }\n\n // If there's a token in un-suffixed, and it doesn't belong to this\n // instance, then we must trust suffixed\n if (session && !this.tokenBelongsToInstance(session)) {\n return true;\n }\n\n // If there are no suffixed cookies use un-suffixed\n if (!suffixedClientUat && !suffixedSession) {\n return false;\n }\n\n const { data: sessionData } = decodeJwt(session);\n const sessionIat = sessionData?.payload.iat || 0;\n const { data: suffixedSessionData } = decodeJwt(suffixedSession);\n const suffixedSessionIat = suffixedSessionData?.payload.iat || 0;\n\n // Both indicate signed in, but un-suffixed is newer\n // Trust un-suffixed because it's newer\n if (suffixedClientUat !== '0' && clientUat !== '0' && sessionIat > suffixedSessionIat) {\n return false;\n }\n\n // Suffixed indicates signed out, but un-suffixed indicates signed in\n // Trust un-suffixed because it gets set with both new and old clerk.js,\n // so we can assume it's newer\n if (suffixedClientUat === '0' && clientUat !== '0') {\n return false;\n }\n\n // Suffixed indicates signed in, un-suffixed indicates signed out\n // This is the tricky one\n\n // In production, suffixed_uat should be set reliably, since it's\n // set by FAPI and not clerk.js. So in the scenario where a developer\n // downgrades, the state will look like this:\n // - un-suffixed session cookie: empty\n // - un-suffixed uat: 0\n // - suffixed session cookie: (possibly filled, possibly empty)\n // - suffixed uat: 0\n\n // Our SDK honors client_uat over the session cookie, so we don't\n // need a special case for production. We can rely on suffixed,\n // and the fact that the suffixed uat is set properly means and\n // suffixed session cookie will be ignored.\n\n // The important thing to make sure we have a test that confirms\n // the user ends up as signed out in this scenario, and the suffixed\n // session cookie is ignored\n\n // In development, suffixed_uat is not set reliably, since it's done\n // by clerk.js. If the developer downgrades to a pinned version of\n // clerk.js, the suffixed uat will no longer be updated\n\n // The best we can do is look to see if the suffixed token is expired.\n // This means that, if a developer downgrades, and then immediately\n // signs out, all in the span of 1 minute, then they will inadvertently\n // remain signed in for the rest of that minute. This is a known\n // limitation of the strategy but seems highly unlikely.\n if (this.instanceType !== 'production') {\n const isSuffixedSessionExpired = this.sessionExpired(suffixedSessionData);\n if (suffixedClientUat !== '0' && clientUat === '0' && isSuffixedSessionExpired) {\n return false;\n }\n }\n\n // If a suffixed session cookie exists but the corresponding client_uat cookie is missing, fallback to using\n // unsuffixed cookies.\n // This handles the scenario where an app has been deployed using an SDK version that supports suffixed\n // cookies, but FAPI for its Clerk instance has the feature disabled (eg: if we need to temporarily disable the feature).\n if (!suffixedClientUat && suffixedSession) {\n return false;\n }\n\n return true;\n }\n\n /**\n * Determines if the request came from a different origin based on the referrer header.\n * Used for cross-origin detection in multi-domain authentication flows.\n *\n * @returns {boolean} True if referrer exists and is from a different origin, false otherwise.\n */\n public isCrossOriginReferrer(): boolean {\n if (!this.referrer || !this.clerkUrl.origin) {\n return false;\n }\n\n try {\n const referrerOrigin = new URL(this.referrer).origin;\n return referrerOrigin !== this.clerkUrl.origin;\n } catch {\n // Invalid referrer URL format\n return false;\n }\n }\n\n /**\n * Determines if the referrer URL is from a Clerk domain (accounts portal or FAPI).\n * This includes both development and production account portal domains, as well as FAPI domains\n * used for redirect-based authentication flows.\n *\n * @returns {boolean} True if the referrer is from a Clerk accounts portal or FAPI domain, false otherwise\n */\n public isKnownClerkReferrer(): boolean {\n if (!this.referrer) {\n return false;\n }\n\n try {\n const referrerOrigin = new URL(this.referrer);\n const referrerHost = referrerOrigin.hostname;\n\n // Check if referrer is the FAPI domain itself (redirect-based auth flows)\n if (this.frontendApi) {\n const fapiHost = this.frontendApi.startsWith('http') ? new URL(this.frontendApi).hostname : this.frontendApi;\n if (referrerHost === fapiHost) {\n return true;\n }\n }\n\n // Check for development account portal patterns\n if (isLegacyDevAccountPortalOrigin(referrerHost) || isCurrentDevAccountPortalOrigin(referrerHost)) {\n return true;\n }\n\n // Check for production account portal by comparing with expected accounts URL\n const expectedAccountsUrl = buildAccountsBaseUrl(this.frontendApi);\n if (expectedAccountsUrl) {\n const expectedAccountsOrigin = new URL(expectedAccountsUrl).origin;\n if (referrerOrigin.origin === expectedAccountsOrigin) {\n return true;\n }\n }\n\n // Check for generic production accounts patterns (accounts.*)\n if (referrerHost.startsWith('accounts.')) {\n return true;\n }\n\n return false;\n } catch {\n // Invalid URL format\n return false;\n }\n }\n\n private initPublishableKeyValues(options: AuthenticateRequestOptions) {\n assertValidPublishableKey(options.publishableKey);\n this.publishableKey = options.publishableKey;\n\n const originalPk = parsePublishableKey(this.publishableKey, {\n fatal: true,\n domain: options.domain,\n isSatellite: options.isSatellite,\n });\n this.originalFrontendApi = originalPk.frontendApi;\n\n const pk = parsePublishableKey(this.publishableKey, {\n fatal: true,\n proxyUrl: options.proxyUrl,\n domain: options.domain,\n isSatellite: options.isSatellite,\n });\n this.instanceType = pk.instanceType;\n this.frontendApi = pk.frontendApi;\n }\n\n private initHeaderValues() {\n this.tokenInHeader = this.parseAuthorizationHeader(this.getHeader(constants.Headers.Authorization));\n this.origin = this.getHeader(constants.Headers.Origin);\n this.host = this.getHeader(constants.Headers.Host);\n this.forwardedHost = this.getHeader(constants.Headers.ForwardedHost);\n this.forwardedProto =\n this.getHeader(constants.Headers.CloudFrontForwardedProto) || this.getHeader(constants.Headers.ForwardedProto);\n this.referrer = this.getHeader(constants.Headers.Referrer);\n this.userAgent = this.getHeader(constants.Headers.UserAgent);\n this.secFetchDest = this.getHeader(constants.Headers.SecFetchDest);\n this.accept = this.getHeader(constants.Headers.Accept);\n }\n\n private initCookieValues() {\n // suffixedCookies needs to be set first because it's used in getMultipleAppsCookie\n this.sessionTokenInCookie = this.getSuffixedOrUnSuffixedCookie(constants.Cookies.Session);\n this.refreshTokenInCookie = this.getSuffixedCookie(constants.Cookies.Refresh);\n this.clientUat = Number.parseInt(this.getSuffixedOrUnSuffixedCookie(constants.Cookies.ClientUat) || '') || 0;\n }\n\n private initHandshakeValues() {\n this.devBrowserToken =\n this.getQueryParam(constants.QueryParameters.DevBrowser) ||\n this.getSuffixedOrUnSuffixedCookie(constants.Cookies.DevBrowser);\n // Using getCookie since we don't suffix the handshake token cookie\n this.handshakeToken =\n this.getQueryParam(constants.QueryParameters.Handshake) || this.getCookie(constants.Cookies.Handshake);\n this.handshakeRedirectLoopCounter = Number(this.getCookie(constants.Cookies.RedirectCount)) || 0;\n this.handshakeNonce =\n this.getQueryParam(constants.QueryParameters.HandshakeNonce) || this.getCookie(constants.Cookies.HandshakeNonce);\n }\n\n private getQueryParam(name: string) {\n return this.clerkRequest.clerkUrl.searchParams.get(name);\n }\n\n private getHeader(name: string) {\n return this.clerkRequest.headers.get(name) || undefined;\n }\n\n private getCookie(name: string) {\n return this.clerkRequest.cookies.get(name) || undefined;\n }\n\n private getSuffixedCookie(name: string) {\n return this.getCookie(getSuffixedCookieName(name, this.cookieSuffix)) || undefined;\n }\n\n private getSuffixedOrUnSuffixedCookie(cookieName: string) {\n if (this.usesSuffixedCookies()) {\n return this.getSuffixedCookie(cookieName);\n }\n return this.getCookie(cookieName);\n }\n\n private parseAuthorizationHeader(authorizationHeader: string | undefined | null): string | undefined {\n if (!authorizationHeader) {\n return undefined;\n }\n\n const [scheme, token] = authorizationHeader.split(' ', 2);\n\n if (!token) {\n // No scheme specified, treat the entire value as the token\n return scheme;\n }\n\n if (scheme === 'Bearer') {\n return token;\n }\n\n // Skip all other schemes\n return undefined;\n }\n\n private tokenHasIssuer(token: string): boolean {\n const { data, errors } = decodeJwt(token);\n if (errors) {\n return false;\n }\n return !!data.payload.iss;\n }\n\n private tokenBelongsToInstance(token: string): boolean {\n if (!token) {\n return false;\n }\n\n const { data, errors } = decodeJwt(token);\n if (errors) {\n return false;\n }\n const tokenIssuer = data.payload.iss.replace(/https?:\\/\\//gi, '');\n // Use original frontend API for token validation since tokens are issued by the actual Clerk API, not proxy\n return this.originalFrontendApi === tokenIssuer;\n }\n\n private sessionExpired(jwt: Jwt | undefined): boolean {\n return !!jwt && jwt?.payload.exp <= (Date.now() / 1000) >> 0;\n }\n}\n\nexport type { AuthenticateContext };\n\nexport const createAuthenticateContext = async (\n clerkRequest: ClerkRequest,\n options: AuthenticateRequestOptions,\n): Promise => {\n const cookieSuffix = options.publishableKey\n ? await getCookieSuffix(options.publishableKey, runtime.crypto.subtle)\n : '';\n return new AuthenticateContext(cookieSuffix, clerkRequest, options);\n};\n","export const TokenType = {\n SessionToken: 'session_token',\n ApiKey: 'api_key',\n M2MToken: 'm2m_token',\n OAuthToken: 'oauth_token',\n} as const;\n\n/**\n * @inline\n */\nexport type TokenType = (typeof TokenType)[keyof typeof TokenType];\n\n/**\n * @inline\n */\nexport type SessionTokenType = typeof TokenType.SessionToken;\n/**\n * @inline\n */\nexport type MachineTokenType = Exclude;\n","import { createCheckAuthorization } from '@clerk/shared/authorization';\nimport { __experimental_JWTPayloadToAuthObjectProperties } from '@clerk/shared/jwtPayloadParser';\nimport type {\n CheckAuthorizationFromSessionClaims,\n Jwt,\n JwtPayload,\n PendingSessionOptions,\n ServerGetToken,\n ServerGetTokenOptions,\n SessionStatusClaim,\n SharedSignedInAuthObjectProperties,\n} from '@clerk/types';\n\nimport type { APIKey, CreateBackendApiOptions, IdPOAuthAccessToken, M2MToken } from '../api';\nimport { createBackendApiClient } from '../api';\nimport { isTokenTypeAccepted } from '../internal';\nimport type { AuthenticateContext } from './authenticateContext';\nimport { isMachineTokenType } from './machine';\nimport type { MachineTokenType, SessionTokenType } from './tokenTypes';\nimport { TokenType } from './tokenTypes';\nimport type { AuthenticateRequestOptions, MachineAuthType } from './types';\n\n/**\n * @inline\n */\ntype AuthObjectDebugData = Record;\n/**\n * @inline\n */\ntype AuthObjectDebug = () => AuthObjectDebugData;\n\ntype Claims = Record;\n\n/**\n * @internal\n */\nexport type SignedInAuthObjectOptions = CreateBackendApiOptions & {\n token: string;\n};\n\n/**\n * @internal\n */\nexport type SignedInAuthObject = SharedSignedInAuthObjectProperties & {\n /**\n * The allowed token type.\n */\n tokenType: SessionTokenType;\n /**\n * A function that gets the current user's [session token](https://clerk.com/docs/backend-requests/resources/session-tokens) or a [custom JWT template](https://clerk.com/docs/backend-requests/jwt-templates).\n */\n getToken: ServerGetToken;\n /**\n * A function that checks if the user has an organization role or custom permission.\n */\n has: CheckAuthorizationFromSessionClaims;\n /**\n * Used to help debug issues when using Clerk in development.\n */\n debug: AuthObjectDebug;\n isAuthenticated: true;\n};\n\n/**\n * @internal\n */\nexport type SignedOutAuthObject = {\n sessionClaims: null;\n sessionId: null;\n sessionStatus: SessionStatusClaim | null;\n actor: null;\n tokenType: SessionTokenType;\n userId: null;\n orgId: null;\n orgRole: null;\n orgSlug: null;\n orgPermissions: null;\n factorVerificationAge: null;\n getToken: ServerGetToken;\n has: CheckAuthorizationFromSessionClaims;\n debug: AuthObjectDebug;\n isAuthenticated: false;\n};\n\n/**\n * Extended properties specific to each machine token type.\n * While all machine token types share common properties (id, name, subject, etc),\n * this type defines the additional properties that are unique to each token type.\n *\n * @template TAuthenticated - Whether the machine object is authenticated or not\n */\ntype MachineObjectExtendedProperties = {\n api_key: TAuthenticated extends true\n ?\n | { name: string; claims: Claims | null; userId: string; orgId: null }\n | { name: string; claims: Claims | null; userId: null; orgId: string }\n : { name: null; claims: null; userId: null; orgId: null };\n m2m_token: {\n claims: TAuthenticated extends true ? Claims | null : null;\n machineId: TAuthenticated extends true ? string : null;\n };\n oauth_token: {\n userId: TAuthenticated extends true ? string : null;\n clientId: TAuthenticated extends true ? string : null;\n };\n};\n\n/**\n * @internal\n *\n * Uses `T extends any` to create a distributive conditional type.\n * This ensures that union types like `'api_key' | 'oauth_token'` are processed\n * individually, creating proper discriminated unions where each token type\n * gets its own distinct properties (e.g., oauth_token won't have claims).\n */\nexport type AuthenticatedMachineObject = T extends any\n ? {\n id: string;\n subject: string;\n scopes: string[];\n getToken: () => Promise;\n has: CheckAuthorizationFromSessionClaims;\n debug: AuthObjectDebug;\n tokenType: T;\n isAuthenticated: true;\n } & MachineObjectExtendedProperties[T]\n : never;\n\n/**\n * @internal\n *\n * Uses `T extends any` to create a distributive conditional type.\n * This ensures that union types like `'api_key' | 'oauth_token'` are processed\n * individually, creating proper discriminated unions where each token type\n * gets its own distinct properties (e.g., oauth_token won't have claims).\n */\nexport type UnauthenticatedMachineObject = T extends any\n ? {\n id: null;\n subject: null;\n scopes: null;\n getToken: () => Promise;\n has: CheckAuthorizationFromSessionClaims;\n debug: AuthObjectDebug;\n tokenType: T;\n isAuthenticated: false;\n } & MachineObjectExtendedProperties[T]\n : never;\n\nexport type InvalidTokenAuthObject = {\n isAuthenticated: false;\n tokenType: null;\n getToken: () => Promise;\n has: () => false;\n debug: AuthObjectDebug;\n};\n\n/**\n * @interface\n */\nexport type AuthObject =\n | SignedInAuthObject\n | SignedOutAuthObject\n | AuthenticatedMachineObject\n | UnauthenticatedMachineObject\n | InvalidTokenAuthObject;\n\nconst createDebug = (data: AuthObjectDebugData | undefined) => {\n return () => {\n const res = { ...data };\n res.secretKey = (res.secretKey || '').substring(0, 7);\n res.jwtKey = (res.jwtKey || '').substring(0, 7);\n return { ...res };\n };\n};\n\n/**\n * @internal\n */\nexport function signedInAuthObject(\n authenticateContext: Partial,\n sessionToken: string,\n sessionClaims: JwtPayload,\n): SignedInAuthObject {\n const { actor, sessionId, sessionStatus, userId, orgId, orgRole, orgSlug, orgPermissions, factorVerificationAge } =\n __experimental_JWTPayloadToAuthObjectProperties(sessionClaims);\n const apiClient = createBackendApiClient(authenticateContext);\n const getToken = createGetToken({\n sessionId,\n sessionToken,\n fetcher: async (sessionId, template, expiresInSeconds) =>\n (await apiClient.sessions.getToken(sessionId, template || '', expiresInSeconds)).jwt,\n });\n return {\n tokenType: TokenType.SessionToken,\n actor,\n sessionClaims,\n sessionId,\n sessionStatus,\n userId,\n orgId,\n orgRole,\n orgSlug,\n orgPermissions,\n factorVerificationAge,\n getToken,\n has: createCheckAuthorization({\n orgId,\n orgRole,\n orgPermissions,\n userId,\n factorVerificationAge,\n features: (sessionClaims.fea as string) || '',\n plans: (sessionClaims.pla as string) || '',\n }),\n debug: createDebug({ ...authenticateContext, sessionToken }),\n isAuthenticated: true,\n };\n}\n\n/**\n * @internal\n */\nexport function signedOutAuthObject(\n debugData?: AuthObjectDebugData,\n initialSessionStatus?: SessionStatusClaim,\n): SignedOutAuthObject {\n return {\n tokenType: TokenType.SessionToken,\n sessionClaims: null,\n sessionId: null,\n sessionStatus: initialSessionStatus ?? null,\n userId: null,\n actor: null,\n orgId: null,\n orgRole: null,\n orgSlug: null,\n orgPermissions: null,\n factorVerificationAge: null,\n getToken: () => Promise.resolve(null),\n has: () => false,\n debug: createDebug(debugData),\n isAuthenticated: false,\n };\n}\n\n/**\n * @internal\n */\nexport function authenticatedMachineObject(\n tokenType: T,\n token: string,\n verificationResult: MachineAuthType,\n debugData?: AuthObjectDebugData,\n): AuthenticatedMachineObject {\n const baseObject = {\n id: verificationResult.id,\n subject: verificationResult.subject,\n getToken: () => Promise.resolve(token),\n has: () => false,\n debug: createDebug(debugData),\n isAuthenticated: true,\n };\n\n // Type assertions are safe here since we know the verification result type matches the tokenType.\n // We need these assertions because TS can't infer the specific type\n // just from the tokenType discriminator.\n\n switch (tokenType) {\n case TokenType.ApiKey: {\n const result = verificationResult as APIKey;\n return {\n ...baseObject,\n tokenType,\n name: result.name,\n claims: result.claims,\n scopes: result.scopes,\n userId: result.subject.startsWith('user_') ? result.subject : null,\n orgId: result.subject.startsWith('org_') ? result.subject : null,\n } as unknown as AuthenticatedMachineObject;\n }\n case TokenType.M2MToken: {\n const result = verificationResult as M2MToken;\n return {\n ...baseObject,\n tokenType,\n claims: result.claims,\n scopes: result.scopes,\n machineId: result.subject,\n } as unknown as AuthenticatedMachineObject;\n }\n case TokenType.OAuthToken: {\n const result = verificationResult as IdPOAuthAccessToken;\n return {\n ...baseObject,\n tokenType,\n scopes: result.scopes,\n userId: result.subject,\n clientId: result.clientId,\n } as unknown as AuthenticatedMachineObject;\n }\n default:\n throw new Error(`Invalid token type: ${tokenType}`);\n }\n}\n\n/**\n * @internal\n */\nexport function unauthenticatedMachineObject(\n tokenType: T,\n debugData?: AuthObjectDebugData,\n): UnauthenticatedMachineObject {\n const baseObject = {\n id: null,\n subject: null,\n scopes: null,\n has: () => false,\n getToken: () => Promise.resolve(null),\n debug: createDebug(debugData),\n isAuthenticated: false,\n };\n\n switch (tokenType) {\n case TokenType.ApiKey: {\n return {\n ...baseObject,\n tokenType,\n name: null,\n claims: null,\n scopes: null,\n userId: null,\n orgId: null,\n } as unknown as UnauthenticatedMachineObject;\n }\n case TokenType.M2MToken: {\n return {\n ...baseObject,\n tokenType,\n claims: null,\n scopes: null,\n machineId: null,\n } as unknown as UnauthenticatedMachineObject;\n }\n case TokenType.OAuthToken: {\n return {\n ...baseObject,\n tokenType,\n scopes: null,\n userId: null,\n clientId: null,\n } as unknown as UnauthenticatedMachineObject;\n }\n default:\n throw new Error(`Invalid token type: ${tokenType}`);\n }\n}\n\n/**\n * @internal\n */\nexport function invalidTokenAuthObject(): InvalidTokenAuthObject {\n return {\n isAuthenticated: false,\n tokenType: null,\n getToken: () => Promise.resolve(null),\n has: () => false,\n debug: () => ({}),\n };\n}\n\n/**\n * Auth objects moving through the server -> client boundary need to be serializable\n * as we need to ensure that they can be transferred via the network as pure strings.\n * Some frameworks like Remix or Next (/pages dir only) handle this serialization by simply\n * ignoring any non-serializable keys, however Nextjs /app directory is stricter and\n * throws an error if a non-serializable value is found.\n *\n * @internal\n */\nexport const makeAuthObjectSerializable = >(obj: T): T => {\n // remove any non-serializable props from the returned object\n\n const { debug, getToken, has, ...rest } = obj as unknown as AuthObject;\n return rest as unknown as T;\n};\n\n/**\n * A function that fetches a session token from the Clerk API.\n *\n * @param sessionId - The ID of the session\n * @param template - The JWT template name to use for token generation\n * @param expiresInSeconds - Optional expiration time in seconds for the token\n * @returns A promise that resolves to the token string\n */\ntype TokenFetcher = (sessionId: string, template?: string, expiresInSeconds?: number) => Promise;\n\n/**\n * Factory function type that creates a getToken function for auth objects.\n *\n * @param params - Configuration object containing session information and token fetcher\n * @returns A ServerGetToken function that can be used to retrieve tokens\n */\ntype CreateGetToken = (params: { sessionId: string; sessionToken: string; fetcher: TokenFetcher }) => ServerGetToken;\n\n/**\n * Creates a token retrieval function for authenticated sessions.\n *\n * This factory function returns a getToken function that can either return the raw session token\n * or generate a JWT using a specified template with optional custom expiration.\n *\n * @param params - Configuration object\n * @param params.sessionId - The session ID for token generation\n * @param params.sessionToken - The raw session token to return when no template is specified\n * @param params.fetcher - Function to fetch tokens from the Clerk API\n *\n * @returns A function that retrieves tokens based on the provided options\n */\nconst createGetToken: CreateGetToken = params => {\n const { fetcher, sessionToken, sessionId } = params || {};\n\n return async (options: ServerGetTokenOptions = {}) => {\n if (!sessionId) {\n return null;\n }\n\n if (options.template || options.expiresInSeconds !== undefined) {\n return fetcher(sessionId, options.template, options.expiresInSeconds);\n }\n\n return sessionToken;\n };\n};\n\n/**\n * @internal\n */\nexport const getAuthObjectFromJwt = (\n jwt: Jwt,\n { treatPendingAsSignedOut = true, ...options }: PendingSessionOptions & Partial,\n) => {\n const authObject = signedInAuthObject(options, jwt.raw.text, jwt.payload);\n\n if (treatPendingAsSignedOut && authObject.sessionStatus === 'pending') {\n return signedOutAuthObject(options, authObject.sessionStatus);\n }\n\n return authObject;\n};\n\n/**\n * @internal\n * Returns an auth object matching the requested token type(s).\n *\n * If the parsed token type does not match any in acceptsToken, returns:\n * - an invalid token auth object if the token is not in the accepted array\n * - an unauthenticated machine object for machine tokens, or\n * - a signed-out session object otherwise.\n *\n * This ensures the returned object always matches the developer's intent.\n */\nexport const getAuthObjectForAcceptedToken = ({\n authObject,\n acceptsToken = TokenType.SessionToken,\n}: {\n authObject: AuthObject;\n acceptsToken: AuthenticateRequestOptions['acceptsToken'];\n}): AuthObject => {\n // 1. any token: return as-is\n if (acceptsToken === 'any') {\n return authObject;\n }\n\n // 2. array of tokens: must match one of the accepted types\n if (Array.isArray(acceptsToken)) {\n if (!isTokenTypeAccepted(authObject.tokenType, acceptsToken)) {\n return invalidTokenAuthObject();\n }\n return authObject;\n }\n\n // 3. single token: must match exactly, else return appropriate unauthenticated object\n if (!isTokenTypeAccepted(authObject.tokenType, acceptsToken)) {\n if (isMachineTokenType(acceptsToken)) {\n return unauthenticatedMachineObject(acceptsToken, authObject.debug);\n }\n return signedOutAuthObject(authObject.debug);\n }\n\n // 4. default: return as-is\n return authObject;\n};\n","import { buildAccountsBaseUrl } from '@clerk/shared/buildAccountsBaseUrl';\nimport type { SessionStatusClaim } from '@clerk/types';\n\nimport { constants } from './constants';\nimport { errorThrower, parsePublishableKey } from './util/shared';\n\nconst buildUrl = (\n _baseUrl: string | URL,\n _targetUrl: string | URL,\n _returnBackUrl?: string | URL | null,\n _devBrowserToken?: string | null,\n) => {\n if (_baseUrl === '') {\n return legacyBuildUrl(_targetUrl.toString(), _returnBackUrl?.toString());\n }\n\n const baseUrl = new URL(_baseUrl);\n const returnBackUrl = _returnBackUrl ? new URL(_returnBackUrl, baseUrl) : undefined;\n const res = new URL(_targetUrl, baseUrl);\n const isCrossOriginRedirect = `${baseUrl.hostname}:${baseUrl.port}` !== `${res.hostname}:${res.port}`;\n\n if (returnBackUrl) {\n if (isCrossOriginRedirect) {\n returnBackUrl.searchParams.delete(constants.QueryParameters.ClerkSynced);\n }\n\n res.searchParams.set('redirect_url', returnBackUrl.toString());\n }\n // For cross-origin redirects, we need to pass the dev browser token for URL session syncing\n if (isCrossOriginRedirect && _devBrowserToken) {\n res.searchParams.set(constants.QueryParameters.DevBrowser, _devBrowserToken);\n }\n return res.toString();\n};\n\n/**\n * In v5, we deprecated the top-level redirectToSignIn and redirectToSignUp functions\n * in favor of the new auth().redirectToSignIn helpers\n * In order to allow for a smooth transition, we need to support the legacy redirectToSignIn for now\n * as we will remove it in v6.\n * In order to make sure that the legacy function works as expected, we will use legacyBuildUrl\n * to build the url if baseUrl is not provided (which is the case for legacy redirectToSignIn)\n * This function can be safely removed when we remove the legacy redirectToSignIn function\n */\nconst legacyBuildUrl = (targetUrl: string, redirectUrl?: string) => {\n let url;\n if (!targetUrl.startsWith('http')) {\n if (!redirectUrl || !redirectUrl.startsWith('http')) {\n throw new Error('destination url or return back url should be an absolute path url!');\n }\n\n const baseURL = new URL(redirectUrl);\n url = new URL(targetUrl, baseURL.origin);\n } else {\n url = new URL(targetUrl);\n }\n\n if (redirectUrl) {\n url.searchParams.set('redirect_url', redirectUrl);\n }\n\n return url.toString();\n};\n\ntype RedirectAdapter = (url: string) => RedirectReturn;\ntype RedirectToParams = { returnBackUrl?: string | URL | null };\nexport type RedirectFun = (params?: RedirectToParams) => ReturnType;\n\n/**\n * @internal\n */\ntype CreateRedirect = (params: {\n publishableKey: string;\n devBrowserToken?: string;\n redirectAdapter: RedirectAdapter;\n baseUrl: URL | string;\n signInUrl?: URL | string;\n signUpUrl?: URL | string;\n sessionStatus?: SessionStatusClaim | null;\n}) => {\n redirectToSignIn: RedirectFun;\n redirectToSignUp: RedirectFun;\n};\n\nexport const createRedirect: CreateRedirect = params => {\n const { publishableKey, redirectAdapter, signInUrl, signUpUrl, baseUrl, sessionStatus } = params;\n const parsedPublishableKey = parsePublishableKey(publishableKey);\n const frontendApi = parsedPublishableKey?.frontendApi;\n const isDevelopment = parsedPublishableKey?.instanceType === 'development';\n const accountsBaseUrl = buildAccountsBaseUrl(frontendApi);\n const hasPendingStatus = sessionStatus === 'pending';\n\n const redirectToTasks = (url: string | URL, { returnBackUrl }: RedirectToParams) => {\n return redirectAdapter(\n buildUrl(baseUrl, `${url}/tasks`, returnBackUrl, isDevelopment ? params.devBrowserToken : null),\n );\n };\n\n const redirectToSignUp = ({ returnBackUrl }: RedirectToParams = {}) => {\n if (!signUpUrl && !accountsBaseUrl) {\n errorThrower.throwMissingPublishableKeyError();\n }\n\n const accountsSignUpUrl = `${accountsBaseUrl}/sign-up`;\n\n // Allows redirection to SignInOrUp path\n function buildSignUpUrl(signIn: string | URL | undefined) {\n if (!signIn) {\n return;\n }\n const url = new URL(signIn, baseUrl);\n url.pathname = `${url.pathname}/create`;\n return url.toString();\n }\n\n const targetUrl = signUpUrl || buildSignUpUrl(signInUrl) || accountsSignUpUrl;\n\n if (hasPendingStatus) {\n return redirectToTasks(targetUrl, { returnBackUrl });\n }\n\n return redirectAdapter(buildUrl(baseUrl, targetUrl, returnBackUrl, isDevelopment ? params.devBrowserToken : null));\n };\n\n const redirectToSignIn = ({ returnBackUrl }: RedirectToParams = {}) => {\n if (!signInUrl && !accountsBaseUrl) {\n errorThrower.throwMissingPublishableKeyError();\n }\n\n const accountsSignInUrl = `${accountsBaseUrl}/sign-in`;\n const targetUrl = signInUrl || accountsSignInUrl;\n\n if (hasPendingStatus) {\n return redirectToTasks(targetUrl, { returnBackUrl });\n }\n\n return redirectAdapter(buildUrl(baseUrl, targetUrl, returnBackUrl, isDevelopment ? params.devBrowserToken : null));\n };\n\n return { redirectToSignUp, redirectToSignIn };\n};\n","import { parse } from 'cookie';\n\nimport { constants } from '../constants';\nimport type { ClerkUrl } from './clerkUrl';\nimport { createClerkUrl } from './clerkUrl';\n\n/**\n * A class that extends the native Request class,\n * adds cookies helpers and a normalised clerkUrl that is constructed by using the values found\n * in req.headers so it is able to work reliably when the app is running behind a proxy server.\n */\nclass ClerkRequest extends Request {\n readonly clerkUrl: ClerkUrl;\n readonly cookies: Map;\n\n public constructor(input: ClerkRequest | Request | RequestInfo, init?: RequestInit) {\n // The usual way to duplicate a request object is to\n // pass the original request object to the Request constructor\n // both as the `input` and `init` parameters, eg: super(req, req)\n // However, this fails in certain environments like Vercel Edge Runtime\n // when a framework like Remix polyfills the global Request object.\n // This happens because `undici` performs the following instanceof check\n // which, instead of testing against the global Request object, tests against\n // the Request class defined in the same file (local Request class).\n // For more details, please refer to:\n // https://github.com/nodejs/undici/issues/2155\n // https://github.com/nodejs/undici/blob/7153a1c78d51840bbe16576ce353e481c3934701/lib/fetch/request.js#L854\n const url = typeof input !== 'string' && 'url' in input ? input.url : String(input);\n super(url, init || typeof input === 'string' ? undefined : input);\n this.clerkUrl = this.deriveUrlFromHeaders(this);\n this.cookies = this.parseCookies(this);\n }\n\n public toJSON() {\n return {\n url: this.clerkUrl.href,\n method: this.method,\n headers: JSON.stringify(Object.fromEntries(this.headers)),\n clerkUrl: this.clerkUrl.toString(),\n cookies: JSON.stringify(Object.fromEntries(this.cookies)),\n };\n }\n\n /**\n * Used to fix request.url using the x-forwarded-* headers\n * TODO add detailed description of the issues this solves\n */\n private deriveUrlFromHeaders(req: Request) {\n const initialUrl = new URL(req.url);\n const forwardedProto = req.headers.get(constants.Headers.ForwardedProto);\n const forwardedHost = req.headers.get(constants.Headers.ForwardedHost);\n const host = req.headers.get(constants.Headers.Host);\n const protocol = initialUrl.protocol;\n\n const resolvedHost = this.getFirstValueFromHeader(forwardedHost) ?? host;\n const resolvedProtocol = this.getFirstValueFromHeader(forwardedProto) ?? protocol?.replace(/[:/]/, '');\n const origin = resolvedHost && resolvedProtocol ? `${resolvedProtocol}://${resolvedHost}` : initialUrl.origin;\n\n if (origin === initialUrl.origin) {\n return createClerkUrl(initialUrl);\n }\n return createClerkUrl(initialUrl.pathname + initialUrl.search, origin);\n }\n\n private getFirstValueFromHeader(value?: string | null) {\n return value?.split(',')[0];\n }\n\n private parseCookies(req: Request) {\n const cookiesRecord = parse(this.decodeCookieValue(req.headers.get('cookie') || ''));\n return new Map(Object.entries(cookiesRecord));\n }\n\n private decodeCookieValue(str: string) {\n return str ? str.replace(/(%[0-9A-Z]{2})+/g, decodeURIComponent) : str;\n }\n}\n\nexport const createClerkRequest = (...args: ConstructorParameters): ClerkRequest => {\n return args[0] instanceof ClerkRequest ? args[0] : new ClerkRequest(...args);\n};\n\nexport type { ClerkRequest };\n","class ClerkUrl extends URL {\n public isCrossOrigin(other: URL | string) {\n return this.origin !== new URL(other.toString()).origin;\n }\n}\n\nexport type WithClerkUrl = T & {\n /**\n * When a NextJs app is hosted on a platform different from Vercel\n * or inside a container (Netlify, Fly.io, AWS Amplify, docker etc),\n * req.url is always set to `localhost:3000` instead of the actual host of the app.\n *\n * The `authMiddleware` uses the value of the available req.headers in order to construct\n * and use the correct url internally. This url is then exposed as `experimental_clerkUrl`,\n * intended to be used within `beforeAuth` and `afterAuth` if needed.\n */\n clerkUrl: ClerkUrl;\n};\n\nexport const createClerkUrl = (...args: ConstructorParameters): ClerkUrl => {\n return new ClerkUrl(...args);\n};\n\nexport type { ClerkUrl };\n","export { constants } from './constants';\nexport { createRedirect } from './createRedirect';\nexport type { RedirectFun } from './createRedirect';\n\nexport type { CreateAuthenticateRequestOptions } from './tokens/factory';\nexport { createAuthenticateRequest } from './tokens/factory';\n\nexport { debugRequestState } from './tokens/request';\n\nexport type {\n AuthenticateRequestOptions,\n OrganizationSyncOptions,\n InferAuthObjectFromToken,\n InferAuthObjectFromTokenArray,\n GetAuthFn,\n} from './tokens/types';\n\nexport { TokenType } from './tokens/tokenTypes';\nexport type { SessionTokenType, MachineTokenType } from './tokens/tokenTypes';\n\nexport type {\n SignedInAuthObjectOptions,\n SignedInAuthObject,\n SignedOutAuthObject,\n AuthenticatedMachineObject,\n UnauthenticatedMachineObject,\n} from './tokens/authObjects';\nexport {\n makeAuthObjectSerializable,\n signedOutAuthObject,\n signedInAuthObject,\n authenticatedMachineObject,\n unauthenticatedMachineObject,\n invalidTokenAuthObject,\n getAuthObjectFromJwt,\n getAuthObjectForAcceptedToken,\n} from './tokens/authObjects';\n\nexport { AuthStatus } from './tokens/authStatus';\nexport type {\n RequestState,\n SignedInState,\n SignedOutState,\n AuthenticatedState,\n UnauthenticatedState,\n} from './tokens/authStatus';\n\nexport { decorateObjectWithResources, stripPrivateDataFromObject } from './util/decorateObjectWithResources';\n\nexport { createClerkRequest } from './tokens/clerkRequest';\nexport type { ClerkRequest } from './tokens/clerkRequest';\n\nexport { reverificationError, reverificationErrorResponse } from '@clerk/shared/authorization-errors';\n\nexport { verifyMachineAuthToken } from './tokens/verify';\n\nexport { isMachineTokenByPrefix, isMachineTokenType, getMachineTokenType, isTokenTypeAccepted } from './tokens/machine';\n","import { isClerkAPIResponseError } from '@clerk/shared/error';\nimport type { JwtPayload } from '@clerk/types';\n\nimport type { APIKey, IdPOAuthAccessToken, M2MToken } from '../api';\nimport { createBackendApiClient } from '../api/factory';\nimport {\n MachineTokenVerificationError,\n MachineTokenVerificationErrorCode,\n TokenVerificationError,\n TokenVerificationErrorAction,\n TokenVerificationErrorReason,\n} from '../errors';\nimport type { VerifyJwtOptions } from '../jwt';\nimport type { JwtReturnType, MachineTokenReturnType } from '../jwt/types';\nimport { decodeJwt, verifyJwt } from '../jwt/verifyJwt';\nimport type { LoadClerkJWKFromRemoteOptions } from './keys';\nimport { loadClerkJWKFromLocal, loadClerkJWKFromRemote } from './keys';\nimport { API_KEY_PREFIX, M2M_TOKEN_PREFIX, OAUTH_TOKEN_PREFIX } from './machine';\nimport type { MachineTokenType } from './tokenTypes';\nimport { TokenType } from './tokenTypes';\n\n/**\n * @interface\n */\nexport type VerifyTokenOptions = Omit &\n Omit & {\n /**\n * Used to verify the session token in a networkless manner. Supply the PEM public key from the **[**API keys**](https://dashboard.clerk.com/last-active?path=api-keys) page -> Show JWT public key -> PEM Public Key** section in the Clerk Dashboard. **It's recommended to use [the environment variable](https://clerk.com/docs/deployments/clerk-environment-variables) instead.** For more information, refer to [Manual JWT verification](https://clerk.com/docs/backend-requests/manual-jwt).\n */\n jwtKey?: string;\n };\n\n/**\n * > [!WARNING]\n * > This is a lower-level method intended for more advanced use-cases. It's recommended to use [`authenticateRequest()`](https://clerk.com/docs/references/backend/authenticate-request), which fully authenticates a token passed from the `request` object.\n *\n * Verifies a Clerk-generated token signature. Networkless if the `jwtKey` is provided. Otherwise, performs a network call to retrieve the JWKS from the [Backend API](https://clerk.com/docs/reference/backend-api/tag/JWKS#operation/GetJWKS){{ target: '_blank' }}.\n *\n * @param token - The token to verify.\n * @param options - Options for verifying the token.\n *\n * @displayFunctionSignature\n *\n * @paramExtension\n *\n * ### `VerifyTokenOptions`\n *\n * It is recommended to set these options as [environment variables](/docs/deployments/clerk-environment-variables#api-and-sdk-configuration) where possible, and then pass them to the function. For example, you can set the `secretKey` option using the `CLERK_SECRET_KEY` environment variable, and then pass it to the function like this: `createClerkClient({ secretKey: process.env.CLERK_SECRET_KEY })`.\n *\n * > [!WARNING]\n * You must provide either `jwtKey` or `secretKey`.\n *\n * \n *\n * @example\n *\n * The following example demonstrates how to use the [JavaScript Backend SDK](https://clerk.com/docs/references/backend/overview) to verify the token signature.\n *\n * In the following example:\n *\n * 1. The **JWKS Public Key** from the Clerk Dashboard is set in the environment variable `CLERK_JWT_KEY`.\n * 1. The session token is retrieved from the `__session` cookie or the Authorization header.\n * 1. The token is verified in a networkless manner by passing the `jwtKey` prop.\n * 1. The `authorizedParties` prop is passed to verify that the session token is generated from the expected frontend application.\n * 1. If the token is valid, the response contains the verified token.\n *\n * ```ts\n * import { verifyToken } from '@clerk/backend'\n * import { cookies } from 'next/headers'\n *\n * export async function GET(request: Request) {\n * const cookieStore = cookies()\n * const sessToken = cookieStore.get('__session')?.value\n * const bearerToken = request.headers.get('Authorization')?.replace('Bearer ', '')\n * const token = sessToken || bearerToken\n *\n * if (!token) {\n * return Response.json({ error: 'Token not found. User must sign in.' }, { status: 401 })\n * }\n *\n * try {\n * const verifiedToken = await verifyToken(token, {\n * jwtKey: process.env.CLERK_JWT_KEY,\n * authorizedParties: ['http://localhost:3001', 'api.example.com'], // Replace with your authorized parties\n * })\n *\n * return Response.json({ verifiedToken })\n * } catch (error) {\n * return Response.json({ error: 'Token not verified.' }, { status: 401 })\n * }\n * }\n * ```\n *\n * If the token is valid, the response will contain a JSON object that looks something like this:\n *\n * ```json\n * {\n * \"verifiedToken\": {\n * \"azp\": \"http://localhost:3000\",\n * \"exp\": 1687906422,\n * \"iat\": 1687906362,\n * \"iss\": \"https://magical-marmoset-51.clerk.accounts.dev\",\n * \"nbf\": 1687906352,\n * \"sid\": \"sess_2Ro7e2IxrffdqBboq8KfB6eGbIy\",\n * \"sub\": \"user_2RfWKJREkjKbHZy0Wqa5qrHeAnb\"\n * }\n * }\n * ```\n */\nexport async function verifyToken(\n token: string,\n options: VerifyTokenOptions,\n): Promise> {\n const { data: decodedResult, errors } = decodeJwt(token);\n if (errors) {\n return { errors };\n }\n\n const { header } = decodedResult;\n const { kid } = header;\n\n try {\n let key;\n\n if (options.jwtKey) {\n key = loadClerkJWKFromLocal(options.jwtKey);\n } else if (options.secretKey) {\n // Fetch JWKS from Backend API using the key\n key = await loadClerkJWKFromRemote({ ...options, kid });\n } else {\n return {\n errors: [\n new TokenVerificationError({\n action: TokenVerificationErrorAction.SetClerkJWTKey,\n message: 'Failed to resolve JWK during verification.',\n reason: TokenVerificationErrorReason.JWKFailedToResolve,\n }),\n ],\n };\n }\n\n return await verifyJwt(token, { ...options, key });\n } catch (error) {\n return { errors: [error as TokenVerificationError] };\n }\n}\n\n/**\n * Handles errors from Clerk API responses for machine tokens\n * @param tokenType - The type of machine token\n * @param err - The error from the Clerk API\n * @param notFoundMessage - Custom message for 404 errors\n */\nfunction handleClerkAPIError(\n tokenType: MachineTokenType,\n err: any,\n notFoundMessage: string,\n): MachineTokenReturnType {\n if (isClerkAPIResponseError(err)) {\n let code: MachineTokenVerificationErrorCode;\n let message: string;\n\n switch (err.status) {\n case 401:\n code = MachineTokenVerificationErrorCode.InvalidSecretKey;\n message = err.errors[0]?.message || 'Invalid secret key';\n break;\n case 404:\n code = MachineTokenVerificationErrorCode.TokenInvalid;\n message = notFoundMessage;\n break;\n default:\n code = MachineTokenVerificationErrorCode.UnexpectedError;\n message = 'Unexpected error';\n }\n\n return {\n data: undefined,\n tokenType,\n errors: [\n new MachineTokenVerificationError({\n message,\n code,\n status: err.status,\n }),\n ],\n };\n }\n\n return {\n data: undefined,\n tokenType,\n errors: [\n new MachineTokenVerificationError({\n message: 'Unexpected error',\n code: MachineTokenVerificationErrorCode.UnexpectedError,\n status: err.status,\n }),\n ],\n };\n}\n\nasync function verifyM2MToken(\n token: string,\n options: VerifyTokenOptions & { machineSecretKey?: string },\n): Promise> {\n try {\n const client = createBackendApiClient(options);\n const verifiedToken = await client.m2m.verifyToken({ token });\n return { data: verifiedToken, tokenType: TokenType.M2MToken, errors: undefined };\n } catch (err: any) {\n return handleClerkAPIError(TokenType.M2MToken, err, 'Machine token not found');\n }\n}\n\nasync function verifyOAuthToken(\n accessToken: string,\n options: VerifyTokenOptions,\n): Promise> {\n try {\n const client = createBackendApiClient(options);\n const verifiedToken = await client.idPOAuthAccessToken.verifyAccessToken(accessToken);\n return { data: verifiedToken, tokenType: TokenType.OAuthToken, errors: undefined };\n } catch (err: any) {\n return handleClerkAPIError(TokenType.OAuthToken, err, 'OAuth token not found');\n }\n}\n\nasync function verifyAPIKey(\n secret: string,\n options: VerifyTokenOptions,\n): Promise> {\n try {\n const client = createBackendApiClient(options);\n const verifiedToken = await client.apiKeys.verifySecret(secret);\n return { data: verifiedToken, tokenType: TokenType.ApiKey, errors: undefined };\n } catch (err: any) {\n return handleClerkAPIError(TokenType.ApiKey, err, 'API key not found');\n }\n}\n\n/**\n * Verifies any type of machine token by detecting its type from the prefix.\n *\n * @param token - The token to verify (e.g. starts with \"m2m_\", \"oauth_\", \"api_key_\", etc.)\n * @param options - Options including secretKey for BAPI authorization\n */\nexport async function verifyMachineAuthToken(token: string, options: VerifyTokenOptions) {\n if (token.startsWith(M2M_TOKEN_PREFIX)) {\n return verifyM2MToken(token, options);\n }\n if (token.startsWith(OAUTH_TOKEN_PREFIX)) {\n return verifyOAuthToken(token, options);\n }\n if (token.startsWith(API_KEY_PREFIX)) {\n return verifyAPIKey(token, options);\n }\n\n throw new Error('Unknown machine token type');\n}\n","import {\n API_URL,\n API_VERSION,\n MAX_CACHE_LAST_UPDATED_AT_SECONDS,\n SUPPORTED_BAPI_VERSION,\n USER_AGENT,\n} from '../constants';\nimport {\n TokenVerificationError,\n TokenVerificationErrorAction,\n TokenVerificationErrorCode,\n TokenVerificationErrorReason,\n} from '../errors';\nimport { runtime } from '../runtime';\nimport { joinPaths } from '../util/path';\nimport { retry } from '../util/shared';\n\ntype JsonWebKeyWithKid = JsonWebKey & { kid: string };\n\ntype JsonWebKeyCache = Record;\n\nlet cache: JsonWebKeyCache = {};\nlet lastUpdatedAt = 0;\n\nfunction getFromCache(kid: string) {\n return cache[kid];\n}\n\nfunction getCacheValues() {\n return Object.values(cache);\n}\n\nfunction setInCache(jwk: JsonWebKeyWithKid, shouldExpire = true) {\n cache[jwk.kid] = jwk;\n lastUpdatedAt = shouldExpire ? Date.now() : -1;\n}\n\nconst LocalJwkKid = 'local';\nconst PEM_HEADER = '-----BEGIN PUBLIC KEY-----';\nconst PEM_TRAILER = '-----END PUBLIC KEY-----';\nconst RSA_PREFIX = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA';\nconst RSA_SUFFIX = 'IDAQAB';\n\n/**\n *\n * Loads a local PEM key usually from process.env and transform it to JsonWebKey format.\n * The result is also cached on the module level to avoid unnecessary computations in subsequent invocations.\n *\n * @param {string} localKey\n * @returns {JsonWebKey} key\n */\nexport function loadClerkJWKFromLocal(localKey?: string): JsonWebKey {\n if (!getFromCache(LocalJwkKid)) {\n if (!localKey) {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.SetClerkJWTKey,\n message: 'Missing local JWK.',\n reason: TokenVerificationErrorReason.LocalJWKMissing,\n });\n }\n\n const modulus = localKey\n .replace(/\\r\\n|\\n|\\r/g, '')\n .replace(PEM_HEADER, '')\n .replace(PEM_TRAILER, '')\n .replace(RSA_PREFIX, '')\n .replace(RSA_SUFFIX, '')\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_');\n\n // JWK https://datatracker.ietf.org/doc/html/rfc7517\n setInCache(\n {\n kid: 'local',\n kty: 'RSA',\n alg: 'RS256',\n n: modulus,\n e: 'AQAB',\n },\n false, // local key never expires in cache\n );\n }\n\n return getFromCache(LocalJwkKid);\n}\n\n/**\n * @internal\n */\nexport type LoadClerkJWKFromRemoteOptions = {\n /**\n * @internal\n */\n kid: string;\n /**\n * @deprecated This cache TTL will be removed in the next major version. Specifying a cache TTL is a no-op.\n */\n jwksCacheTtlInMs?: number;\n /**\n * A flag to ignore the JWKS cache and always fetch JWKS before each JWT verification.\n */\n skipJwksCache?: boolean;\n /**\n * The Clerk Secret Key from the [**API keys**](https://dashboard.clerk.com/last-active?path=api-keys) page in the Clerk Dashboard.\n */\n secretKey?: string;\n /**\n * The [Clerk Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }} endpoint.\n * @default 'https://api.clerk.com'\n */\n apiUrl?: string;\n /**\n * The version passed to the Clerk API.\n * @default 'v1'\n */\n apiVersion?: string;\n};\n\n/**\n *\n * Loads a key from JWKS retrieved from the well-known Frontend API endpoint of the issuer.\n * The result is also cached on the module level to avoid network requests in subsequent invocations.\n * The cache lasts up to 5 minutes.\n *\n * @param {Object} options\n * @param {string} options.kid - The id of the key that the JWT was signed with\n * @param {string} options.alg - The algorithm of the JWT\n * @returns {JsonWebKey} key\n */\nexport async function loadClerkJWKFromRemote({\n secretKey,\n apiUrl = API_URL,\n apiVersion = API_VERSION,\n kid,\n skipJwksCache,\n}: LoadClerkJWKFromRemoteOptions): Promise {\n if (skipJwksCache || cacheHasExpired() || !getFromCache(kid)) {\n if (!secretKey) {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.ContactSupport,\n message: 'Failed to load JWKS from Clerk Backend or Frontend API.',\n reason: TokenVerificationErrorReason.RemoteJWKFailedToLoad,\n });\n }\n const fetcher = () => fetchJWKSFromBAPI(apiUrl, secretKey, apiVersion) as Promise<{ keys: JsonWebKeyWithKid[] }>;\n const { keys } = await retry(fetcher);\n\n if (!keys || !keys.length) {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.ContactSupport,\n message: 'The JWKS endpoint did not contain any signing keys. Contact support@clerk.com.',\n reason: TokenVerificationErrorReason.RemoteJWKFailedToLoad,\n });\n }\n\n keys.forEach(key => setInCache(key));\n }\n\n const jwk = getFromCache(kid);\n\n if (!jwk) {\n const cacheValues = getCacheValues();\n const jwkKeys = cacheValues\n .map(jwk => jwk.kid)\n .sort()\n .join(', ');\n\n throw new TokenVerificationError({\n action: `Go to your Dashboard and validate your secret and public keys are correct. ${TokenVerificationErrorAction.ContactSupport} if the issue persists.`,\n message: `Unable to find a signing key in JWKS that matches the kid='${kid}' of the provided session token. Please make sure that the __session cookie or the HTTP authorization header contain a Clerk-generated session JWT. The following kid is available: ${jwkKeys}`,\n reason: TokenVerificationErrorReason.JWKKidMismatch,\n });\n }\n\n return jwk;\n}\n\nasync function fetchJWKSFromBAPI(apiUrl: string, key: string, apiVersion: string) {\n if (!key) {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.SetClerkSecretKey,\n message:\n 'Missing Clerk Secret Key or API Key. Go to https://dashboard.clerk.com and get your key for your instance.',\n reason: TokenVerificationErrorReason.RemoteJWKFailedToLoad,\n });\n }\n\n const url = new URL(apiUrl);\n url.pathname = joinPaths(url.pathname, apiVersion, '/jwks');\n\n const response = await runtime.fetch(url.href, {\n headers: {\n Authorization: `Bearer ${key}`,\n 'Clerk-API-Version': SUPPORTED_BAPI_VERSION,\n 'Content-Type': 'application/json',\n 'User-Agent': USER_AGENT,\n },\n });\n\n if (!response.ok) {\n const json = await response.json();\n const invalidSecretKeyError = getErrorObjectByCode(json?.errors, TokenVerificationErrorCode.InvalidSecretKey);\n\n if (invalidSecretKeyError) {\n const reason = TokenVerificationErrorReason.InvalidSecretKey;\n\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.ContactSupport,\n message: invalidSecretKeyError.message,\n reason,\n });\n }\n\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.ContactSupport,\n message: `Error loading Clerk JWKS from ${url.href} with code=${response.status}`,\n reason: TokenVerificationErrorReason.RemoteJWKFailedToLoad,\n });\n }\n\n return response.json();\n}\n\nfunction cacheHasExpired() {\n // If lastUpdatedAt is -1, it means that we're using a local JWKS and it never expires\n if (lastUpdatedAt === -1) {\n return false;\n }\n\n // If the cache has expired, clear the value so we don't attempt to make decisions based on stale data\n const isExpired = Date.now() - lastUpdatedAt >= MAX_CACHE_LAST_UPDATED_AT_SECONDS * 1000;\n\n if (isExpired) {\n cache = {};\n }\n\n return isExpired;\n}\n\ntype ErrorFields = {\n message: string;\n long_message: string;\n code: string;\n};\n\nconst getErrorObjectByCode = (errors: ErrorFields[], code: string) => {\n if (!errors) {\n return null;\n }\n\n return errors.find((err: ErrorFields) => err.code === code);\n};\n","import type { AuthenticateRequestOptions } from '../tokens/types';\nimport type { MachineTokenType } from './tokenTypes';\nimport { TokenType } from './tokenTypes';\n\nexport const M2M_TOKEN_PREFIX = 'mt_';\nexport const OAUTH_TOKEN_PREFIX = 'oat_';\nexport const API_KEY_PREFIX = 'ak_';\n\nconst MACHINE_TOKEN_PREFIXES = [M2M_TOKEN_PREFIX, OAUTH_TOKEN_PREFIX, API_KEY_PREFIX] as const;\n\n/**\n * Checks if a token is a machine token by looking at its prefix.\n *\n * @remarks\n * In the future, this will support custom prefixes that can be prepended to the base prefixes\n * (e.g. \"org_a_m2m_\", \"org_a_oauth_access_\", \"org_a_api_key_\")\n *\n * @param token - The token string to check\n * @returns true if the token starts with a recognized machine token prefix\n */\nexport function isMachineTokenByPrefix(token: string): boolean {\n return MACHINE_TOKEN_PREFIXES.some(prefix => token.startsWith(prefix));\n}\n\n/**\n * Gets the specific type of machine token based on its prefix.\n *\n * @remarks\n * In the future, this will support custom prefixes that can be prepended to the base prefixes\n * (e.g. \"org_a_m2m_\", \"org_a_oauth_access_\", \"org_a_api_key_\")\n *\n * @param token - The token string to check\n * @returns The specific MachineTokenType\n * @throws Error if the token doesn't match any known machine token prefix\n */\nexport function getMachineTokenType(token: string): MachineTokenType {\n if (token.startsWith(M2M_TOKEN_PREFIX)) {\n return TokenType.M2MToken;\n }\n\n if (token.startsWith(OAUTH_TOKEN_PREFIX)) {\n return TokenType.OAuthToken;\n }\n\n if (token.startsWith(API_KEY_PREFIX)) {\n return TokenType.ApiKey;\n }\n\n throw new Error('Unknown machine token type');\n}\n\n/**\n * Check if a token type is accepted given a requested token type or list of token types.\n *\n * @param tokenType - The token type to check (can be null if the token is invalid)\n * @param acceptsToken - The requested token type or list of token types\n * @returns true if the token type is accepted\n */\nexport const isTokenTypeAccepted = (\n tokenType: TokenType | null,\n acceptsToken: NonNullable,\n): boolean => {\n if (!tokenType) {\n return false;\n }\n\n if (acceptsToken === 'any') {\n return true;\n }\n\n const tokenTypes = Array.isArray(acceptsToken) ? acceptsToken : [acceptsToken];\n return tokenTypes.includes(tokenType);\n};\n\n/**\n * Checks if a token type string is a machine token type (api_key, m2m_token, or oauth_token).\n *\n * @param type - The token type string to check\n * @returns true if the type is a machine token type\n */\nexport function isMachineTokenType(type: string): type is MachineTokenType {\n return type === TokenType.ApiKey || type === TokenType.M2MToken || type === TokenType.OAuthToken;\n}\n","import type { JwtPayload, PendingSessionOptions } from '@clerk/types';\n\nimport { constants } from '../constants';\nimport type { TokenVerificationErrorReason } from '../errors';\nimport type { AuthenticateContext } from './authenticateContext';\nimport type {\n AuthenticatedMachineObject,\n InvalidTokenAuthObject,\n SignedInAuthObject,\n SignedOutAuthObject,\n UnauthenticatedMachineObject,\n} from './authObjects';\nimport {\n authenticatedMachineObject,\n invalidTokenAuthObject,\n signedInAuthObject,\n signedOutAuthObject,\n unauthenticatedMachineObject,\n} from './authObjects';\nimport type { MachineTokenType, SessionTokenType } from './tokenTypes';\nimport { TokenType } from './tokenTypes';\nimport type { MachineAuthType } from './types';\n\nexport const AuthStatus = {\n SignedIn: 'signed-in',\n SignedOut: 'signed-out',\n Handshake: 'handshake',\n} as const;\n\nexport type AuthStatus = (typeof AuthStatus)[keyof typeof AuthStatus];\n\ntype ToAuth = T extends null\n ? () => InvalidTokenAuthObject\n : T extends SessionTokenType\n ? Authenticated extends true\n ? (opts?: PendingSessionOptions) => SignedInAuthObject\n : () => SignedOutAuthObject\n : Authenticated extends true\n ? () => AuthenticatedMachineObject>\n : () => UnauthenticatedMachineObject>;\n\nexport type AuthenticatedState = {\n status: typeof AuthStatus.SignedIn;\n reason: null;\n message: null;\n proxyUrl?: string;\n publishableKey: string;\n isSatellite: boolean;\n domain: string;\n signInUrl: string;\n signUpUrl: string;\n afterSignInUrl: string;\n afterSignUpUrl: string;\n /**\n * @deprecated Use `isAuthenticated` instead.\n */\n isSignedIn: true;\n isAuthenticated: true;\n headers: Headers;\n token: string;\n tokenType: T;\n toAuth: ToAuth;\n};\n\nexport type UnauthenticatedState = {\n status: typeof AuthStatus.SignedOut;\n reason: AuthReason;\n message: string;\n proxyUrl?: string;\n publishableKey: string;\n isSatellite: boolean;\n domain: string;\n signInUrl: string;\n signUpUrl: string;\n afterSignInUrl: string;\n afterSignUpUrl: string;\n /**\n * @deprecated Use `isAuthenticated` instead.\n */\n isSignedIn: false;\n isAuthenticated: false;\n tokenType: T;\n headers: Headers;\n token: null;\n toAuth: ToAuth;\n};\n\nexport type HandshakeState = Omit, 'status' | 'toAuth' | 'tokenType'> & {\n tokenType: SessionTokenType;\n status: typeof AuthStatus.Handshake;\n headers: Headers;\n toAuth: () => null;\n};\n\n/**\n * @deprecated Use AuthenticatedState instead\n */\nexport type SignedInState = AuthenticatedState;\n\n/**\n * @deprecated Use UnauthenticatedState instead\n */\nexport type SignedOutState = UnauthenticatedState;\n\nexport const AuthErrorReason = {\n ClientUATWithoutSessionToken: 'client-uat-but-no-session-token',\n DevBrowserMissing: 'dev-browser-missing',\n DevBrowserSync: 'dev-browser-sync',\n PrimaryRespondsToSyncing: 'primary-responds-to-syncing',\n PrimaryDomainCrossOriginSync: 'primary-domain-cross-origin-sync',\n SatelliteCookieNeedsSyncing: 'satellite-needs-syncing',\n SessionTokenAndUATMissing: 'session-token-and-uat-missing',\n SessionTokenMissing: 'session-token-missing',\n SessionTokenExpired: 'session-token-expired',\n SessionTokenIATBeforeClientUAT: 'session-token-iat-before-client-uat',\n SessionTokenNBF: 'session-token-nbf',\n SessionTokenIatInTheFuture: 'session-token-iat-in-the-future',\n SessionTokenWithoutClientUAT: 'session-token-but-no-client-uat',\n ActiveOrganizationMismatch: 'active-organization-mismatch',\n TokenTypeMismatch: 'token-type-mismatch',\n UnexpectedError: 'unexpected-error',\n} as const;\n\nexport type AuthErrorReason = (typeof AuthErrorReason)[keyof typeof AuthErrorReason];\n\nexport type AuthReason = AuthErrorReason | TokenVerificationErrorReason;\n\nexport type RequestState =\n | AuthenticatedState\n | UnauthenticatedState\n | (T extends SessionTokenType ? HandshakeState : never);\n\ntype BaseSignedInParams = {\n authenticateContext: AuthenticateContext;\n headers?: Headers;\n token: string;\n tokenType: TokenType;\n};\n\ntype SignedInParams =\n | (BaseSignedInParams & { tokenType: SessionTokenType; sessionClaims: JwtPayload })\n | (BaseSignedInParams & { tokenType: MachineTokenType; machineData: MachineAuthType });\n\nexport function signedIn(params: SignedInParams & { tokenType: T }): AuthenticatedState {\n const { authenticateContext, headers = new Headers(), token } = params;\n\n const toAuth = (({ treatPendingAsSignedOut = true } = {}) => {\n if (params.tokenType === TokenType.SessionToken) {\n const { sessionClaims } = params as { sessionClaims: JwtPayload };\n const authObject = signedInAuthObject(authenticateContext, token, sessionClaims);\n\n if (treatPendingAsSignedOut && authObject.sessionStatus === 'pending') {\n return signedOutAuthObject(undefined, authObject.sessionStatus);\n }\n\n return authObject;\n }\n\n const { machineData } = params as { machineData: MachineAuthType };\n return authenticatedMachineObject(params.tokenType, token, machineData, authenticateContext);\n }) as ToAuth;\n\n return {\n status: AuthStatus.SignedIn,\n reason: null,\n message: null,\n proxyUrl: authenticateContext.proxyUrl || '',\n publishableKey: authenticateContext.publishableKey || '',\n isSatellite: authenticateContext.isSatellite || false,\n domain: authenticateContext.domain || '',\n signInUrl: authenticateContext.signInUrl || '',\n signUpUrl: authenticateContext.signUpUrl || '',\n afterSignInUrl: authenticateContext.afterSignInUrl || '',\n afterSignUpUrl: authenticateContext.afterSignUpUrl || '',\n isSignedIn: true,\n isAuthenticated: true,\n tokenType: params.tokenType,\n toAuth,\n headers,\n token,\n };\n}\n\ntype SignedOutParams = Omit & {\n reason: AuthReason;\n message?: string;\n};\n\nexport function signedOut(params: SignedOutParams & { tokenType: T }): UnauthenticatedState {\n const { authenticateContext, headers = new Headers(), reason, message = '', tokenType } = params;\n\n const toAuth = (() => {\n if (tokenType === TokenType.SessionToken) {\n return signedOutAuthObject({ ...authenticateContext, status: AuthStatus.SignedOut, reason, message });\n }\n\n return unauthenticatedMachineObject(tokenType, { reason, message, headers });\n }) as ToAuth;\n\n return withDebugHeaders({\n status: AuthStatus.SignedOut,\n reason,\n message,\n proxyUrl: authenticateContext.proxyUrl || '',\n publishableKey: authenticateContext.publishableKey || '',\n isSatellite: authenticateContext.isSatellite || false,\n domain: authenticateContext.domain || '',\n signInUrl: authenticateContext.signInUrl || '',\n signUpUrl: authenticateContext.signUpUrl || '',\n afterSignInUrl: authenticateContext.afterSignInUrl || '',\n afterSignUpUrl: authenticateContext.afterSignUpUrl || '',\n isSignedIn: false,\n isAuthenticated: false,\n tokenType,\n toAuth,\n headers,\n token: null,\n });\n}\n\nexport function handshake(\n authenticateContext: AuthenticateContext,\n reason: AuthReason,\n message = '',\n headers: Headers,\n): HandshakeState {\n return withDebugHeaders({\n status: AuthStatus.Handshake,\n reason,\n message,\n publishableKey: authenticateContext.publishableKey || '',\n isSatellite: authenticateContext.isSatellite || false,\n domain: authenticateContext.domain || '',\n proxyUrl: authenticateContext.proxyUrl || '',\n signInUrl: authenticateContext.signInUrl || '',\n signUpUrl: authenticateContext.signUpUrl || '',\n afterSignInUrl: authenticateContext.afterSignInUrl || '',\n afterSignUpUrl: authenticateContext.afterSignUpUrl || '',\n isSignedIn: false,\n isAuthenticated: false,\n tokenType: TokenType.SessionToken,\n toAuth: () => null,\n headers,\n token: null,\n });\n}\n\nexport function signedOutInvalidToken(): UnauthenticatedState {\n const authObject = invalidTokenAuthObject();\n return withDebugHeaders({\n status: AuthStatus.SignedOut,\n reason: AuthErrorReason.TokenTypeMismatch,\n message: '',\n proxyUrl: '',\n publishableKey: '',\n isSatellite: false,\n domain: '',\n signInUrl: '',\n signUpUrl: '',\n afterSignInUrl: '',\n afterSignUpUrl: '',\n isSignedIn: false,\n isAuthenticated: false,\n tokenType: null,\n toAuth: () => authObject,\n headers: new Headers(),\n token: null,\n });\n}\n\nconst withDebugHeaders = (\n requestState: T,\n): T => {\n const headers = new Headers(requestState.headers || {});\n\n if (requestState.message) {\n try {\n headers.set(constants.Headers.AuthMessage, requestState.message);\n } catch {\n // headers.set can throw if unicode strings are passed to it. In this case, simply do nothing\n }\n }\n\n if (requestState.reason) {\n try {\n headers.set(constants.Headers.AuthReason, requestState.reason);\n } catch {\n /* empty */\n }\n }\n\n if (requestState.status) {\n try {\n headers.set(constants.Headers.AuthStatus, requestState.status);\n } catch {\n /* empty */\n }\n }\n\n requestState.headers = headers;\n\n return requestState;\n};\n","export const getCookieName = (cookieDirective: string): string => {\n return cookieDirective.split(';')[0]?.split('=')[0];\n};\n\nexport const getCookieValue = (cookieDirective: string): string => {\n return cookieDirective.split(';')[0]?.split('=')[1];\n};\n","import { constants, SUPPORTED_BAPI_VERSION } from '../constants';\nimport { TokenVerificationError, TokenVerificationErrorAction, TokenVerificationErrorReason } from '../errors';\nimport type { VerifyJwtOptions } from '../jwt';\nimport { assertHeaderAlgorithm, assertHeaderType } from '../jwt/assertions';\nimport { decodeJwt, hasValidSignature } from '../jwt/verifyJwt';\nimport type { AuthenticateContext } from './authenticateContext';\nimport type { SignedInState, SignedOutState } from './authStatus';\nimport { AuthErrorReason, signedIn, signedOut } from './authStatus';\nimport { getCookieName, getCookieValue } from './cookie';\nimport { loadClerkJWKFromLocal, loadClerkJWKFromRemote } from './keys';\nimport type { OrganizationMatcher } from './organizationMatcher';\nimport { TokenType } from './tokenTypes';\nimport type { OrganizationSyncOptions, OrganizationSyncTarget } from './types';\nimport type { VerifyTokenOptions } from './verify';\nimport { verifyToken } from './verify';\n\nasync function verifyHandshakeJwt(token: string, { key }: VerifyJwtOptions): Promise<{ handshake: string[] }> {\n const { data: decoded, errors } = decodeJwt(token);\n if (errors) {\n throw errors[0];\n }\n\n const { header, payload } = decoded;\n\n // Header verifications\n const { typ, alg } = header;\n\n assertHeaderType(typ);\n assertHeaderAlgorithm(alg);\n\n const { data: signatureValid, errors: signatureErrors } = await hasValidSignature(decoded, key);\n if (signatureErrors) {\n throw new TokenVerificationError({\n reason: TokenVerificationErrorReason.TokenVerificationFailed,\n message: `Error verifying handshake token. ${signatureErrors[0]}`,\n });\n }\n\n if (!signatureValid) {\n throw new TokenVerificationError({\n reason: TokenVerificationErrorReason.TokenInvalidSignature,\n message: 'Handshake signature is invalid.',\n });\n }\n\n return payload as unknown as { handshake: string[] };\n}\n\n/**\n * Similar to our verifyToken flow for Clerk-issued JWTs, but this verification flow is for our signed handshake payload.\n * The handshake payload requires fewer verification steps.\n */\nexport async function verifyHandshakeToken(\n token: string,\n options: VerifyTokenOptions,\n): Promise<{ handshake: string[] }> {\n const { secretKey, apiUrl, apiVersion, jwksCacheTtlInMs, jwtKey, skipJwksCache } = options;\n\n const { data, errors } = decodeJwt(token);\n if (errors) {\n throw errors[0];\n }\n\n const { kid } = data.header;\n\n let key;\n\n if (jwtKey) {\n key = loadClerkJWKFromLocal(jwtKey);\n } else if (secretKey) {\n // Fetch JWKS from Backend API using the key\n key = await loadClerkJWKFromRemote({ secretKey, apiUrl, apiVersion, kid, jwksCacheTtlInMs, skipJwksCache });\n } else {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.SetClerkJWTKey,\n message: 'Failed to resolve JWK during handshake verification.',\n reason: TokenVerificationErrorReason.JWKFailedToResolve,\n });\n }\n\n return await verifyHandshakeJwt(token, {\n key,\n });\n}\n\nexport class HandshakeService {\n private readonly authenticateContext: AuthenticateContext;\n private readonly organizationMatcher: OrganizationMatcher;\n private readonly options: { organizationSyncOptions?: OrganizationSyncOptions };\n\n constructor(\n authenticateContext: AuthenticateContext,\n options: { organizationSyncOptions?: OrganizationSyncOptions },\n organizationMatcher: OrganizationMatcher,\n ) {\n this.authenticateContext = authenticateContext;\n this.options = options;\n this.organizationMatcher = organizationMatcher;\n }\n\n /**\n * Determines if a request is eligible for handshake based on its headers\n *\n * Currently, a request is only eligible for a handshake if we can say it's *probably* a request for a document, not a fetch or some other exotic request.\n * This heuristic should give us a reliable enough signal for browsers that support `Sec-Fetch-Dest` and for those that don't.\n *\n * @returns boolean indicating if the request is eligible for handshake\n */\n isRequestEligibleForHandshake(): boolean {\n const { accept, secFetchDest } = this.authenticateContext;\n\n // NOTE: we could also check sec-fetch-mode === navigate here, but according to the spec, sec-fetch-dest: document should indicate that the request is the data of a user navigation.\n // Also, we check for 'iframe' because it's the value set when a doc request is made by an iframe.\n if (secFetchDest === 'document' || secFetchDest === 'iframe') {\n return true;\n }\n\n if (!secFetchDest && accept?.startsWith('text/html')) {\n return true;\n }\n\n return false;\n }\n\n /**\n * Builds the redirect headers for a handshake request\n * @param reason - The reason for the handshake (e.g. 'session-token-expired')\n * @returns Headers object containing the Location header for redirect\n * @throws Error if clerkUrl is missing in authenticateContext\n */\n buildRedirectToHandshake(reason: string): Headers {\n if (!this.authenticateContext?.clerkUrl) {\n throw new Error('Missing clerkUrl in authenticateContext');\n }\n\n const redirectUrl = this.removeDevBrowserFromURL(this.authenticateContext.clerkUrl);\n\n let baseUrl = this.authenticateContext.frontendApi.startsWith('http')\n ? this.authenticateContext.frontendApi\n : `https://${this.authenticateContext.frontendApi}`;\n\n baseUrl = baseUrl.replace(/\\/+$/, '') + '/';\n\n const url = new URL('v1/client/handshake', baseUrl);\n url.searchParams.append('redirect_url', redirectUrl?.href || '');\n url.searchParams.append('__clerk_api_version', SUPPORTED_BAPI_VERSION);\n url.searchParams.append(\n constants.QueryParameters.SuffixedCookies,\n this.authenticateContext.usesSuffixedCookies().toString(),\n );\n url.searchParams.append(constants.QueryParameters.HandshakeReason, reason);\n url.searchParams.append(constants.QueryParameters.HandshakeFormat, 'nonce');\n\n if (this.authenticateContext.instanceType === 'development' && this.authenticateContext.devBrowserToken) {\n url.searchParams.append(constants.QueryParameters.DevBrowser, this.authenticateContext.devBrowserToken);\n }\n\n const toActivate = this.getOrganizationSyncTarget(this.authenticateContext.clerkUrl, this.organizationMatcher);\n if (toActivate) {\n const params = this.getOrganizationSyncQueryParams(toActivate);\n params.forEach((value, key) => {\n url.searchParams.append(key, value);\n });\n }\n\n return new Headers({ [constants.Headers.Location]: url.href });\n }\n\n /**\n * Gets cookies from either a handshake nonce or a handshake token\n * @returns Promise resolving to string array of cookie directives\n */\n public async getCookiesFromHandshake(): Promise {\n const cookiesToSet: string[] = [];\n\n if (this.authenticateContext.handshakeNonce) {\n try {\n const handshakePayload = await this.authenticateContext.apiClient?.clients.getHandshakePayload({\n nonce: this.authenticateContext.handshakeNonce,\n });\n if (handshakePayload) {\n cookiesToSet.push(...handshakePayload.directives);\n }\n } catch (error) {\n console.error('Clerk: HandshakeService: error getting handshake payload:', error);\n }\n } else if (this.authenticateContext.handshakeToken) {\n const handshakePayload = await verifyHandshakeToken(\n this.authenticateContext.handshakeToken,\n this.authenticateContext,\n );\n if (handshakePayload && Array.isArray(handshakePayload.handshake)) {\n cookiesToSet.push(...handshakePayload.handshake);\n }\n }\n\n return cookiesToSet;\n }\n\n /**\n * Resolves a handshake request by verifying the handshake token and setting appropriate cookies\n * @returns Promise resolving to either a SignedInState or SignedOutState\n * @throws Error if handshake verification fails or if there are issues with the session token\n */\n async resolveHandshake(): Promise {\n const headers = new Headers({\n 'Access-Control-Allow-Origin': 'null',\n 'Access-Control-Allow-Credentials': 'true',\n });\n\n const cookiesToSet = await this.getCookiesFromHandshake();\n\n let sessionToken = '';\n cookiesToSet.forEach((x: string) => {\n headers.append('Set-Cookie', x);\n if (getCookieName(x).startsWith(constants.Cookies.Session)) {\n sessionToken = getCookieValue(x);\n }\n });\n\n if (this.authenticateContext.instanceType === 'development') {\n const newUrl = new URL(this.authenticateContext.clerkUrl);\n newUrl.searchParams.delete(constants.QueryParameters.Handshake);\n newUrl.searchParams.delete(constants.QueryParameters.HandshakeHelp);\n newUrl.searchParams.delete(constants.QueryParameters.DevBrowser);\n headers.append(constants.Headers.Location, newUrl.toString());\n headers.set(constants.Headers.CacheControl, 'no-store');\n }\n\n if (sessionToken === '') {\n return signedOut({\n tokenType: TokenType.SessionToken,\n authenticateContext: this.authenticateContext,\n reason: AuthErrorReason.SessionTokenMissing,\n message: '',\n headers,\n });\n }\n\n const { data, errors: [error] = [] } = await verifyToken(sessionToken, this.authenticateContext);\n if (data) {\n return signedIn({\n tokenType: TokenType.SessionToken,\n authenticateContext: this.authenticateContext,\n sessionClaims: data,\n headers,\n token: sessionToken,\n });\n }\n\n if (\n this.authenticateContext.instanceType === 'development' &&\n (error?.reason === TokenVerificationErrorReason.TokenExpired ||\n error?.reason === TokenVerificationErrorReason.TokenNotActiveYet ||\n error?.reason === TokenVerificationErrorReason.TokenIatInTheFuture)\n ) {\n // Create a new error object with the same properties\n const developmentError = new TokenVerificationError({\n action: error.action,\n message: error.message,\n reason: error.reason,\n });\n // Set the tokenCarrier after construction\n developmentError.tokenCarrier = 'cookie';\n\n console.error(\n `Clerk: Clock skew detected. This usually means that your system clock is inaccurate. Clerk will attempt to account for the clock skew in development.\n\nTo resolve this issue, make sure your system's clock is set to the correct time (e.g. turn off and on automatic time synchronization).\n\n---\n\n${developmentError.getFullMessage()}`,\n );\n\n const { data: retryResult, errors: [retryError] = [] } = await verifyToken(sessionToken, {\n ...this.authenticateContext,\n clockSkewInMs: 86_400_000,\n });\n if (retryResult) {\n return signedIn({\n tokenType: TokenType.SessionToken,\n authenticateContext: this.authenticateContext,\n sessionClaims: retryResult,\n headers,\n token: sessionToken,\n });\n }\n\n throw new Error(retryError?.message || 'Clerk: Handshake retry failed.');\n }\n\n throw new Error(error?.message || 'Clerk: Handshake failed.');\n }\n\n /**\n * Handles handshake token verification errors in development mode\n * @param error - The TokenVerificationError that occurred\n * @throws Error with a descriptive message about the verification failure\n */\n handleTokenVerificationErrorInDevelopment(error: TokenVerificationError): void {\n // In development, the handshake token is being transferred in the URL as a query parameter, so there is no\n // possibility of collision with a handshake token of another app running on the same local domain\n // (etc one app on localhost:3000 and one on localhost:3001).\n // Therefore, if the handshake token is invalid, it is likely that the user has switched Clerk keys locally.\n // We make sure to throw a descriptive error message and then stop the handshake flow in every case,\n // to avoid the possibility of an infinite loop.\n if (error.reason === TokenVerificationErrorReason.TokenInvalidSignature) {\n const msg = `Clerk: Handshake token verification failed due to an invalid signature. If you have switched Clerk keys locally, clear your cookies and try again.`;\n throw new Error(msg);\n }\n throw new Error(`Clerk: Handshake token verification failed: ${error.getFullMessage()}.`);\n }\n\n /**\n * Checks if a redirect loop is detected and sets headers to track redirect count\n * @param headers - The Headers object to modify\n * @returns boolean indicating if a redirect loop was detected (true) or if the request can proceed (false)\n */\n checkAndTrackRedirectLoop(headers: Headers): boolean {\n if (this.authenticateContext.handshakeRedirectLoopCounter === 3) {\n return true;\n }\n\n const newCounterValue = this.authenticateContext.handshakeRedirectLoopCounter + 1;\n const cookieName = constants.Cookies.RedirectCount;\n headers.append('Set-Cookie', `${cookieName}=${newCounterValue}; SameSite=Lax; HttpOnly; Max-Age=2`);\n return false;\n }\n\n private removeDevBrowserFromURL(url: URL): URL {\n const updatedURL = new URL(url);\n updatedURL.searchParams.delete(constants.QueryParameters.DevBrowser);\n updatedURL.searchParams.delete(constants.QueryParameters.LegacyDevBrowser);\n return updatedURL;\n }\n\n private getOrganizationSyncTarget(url: URL, matchers: OrganizationMatcher): OrganizationSyncTarget | null {\n return matchers.findTarget(url);\n }\n\n private getOrganizationSyncQueryParams(toActivate: OrganizationSyncTarget): Map {\n const ret = new Map();\n if (toActivate.type === 'personalAccount') {\n ret.set('organization_id', '');\n }\n if (toActivate.type === 'organization') {\n if (toActivate.organizationId) {\n ret.set('organization_id', toActivate.organizationId);\n }\n if (toActivate.organizationSlug) {\n ret.set('organization_id', toActivate.organizationSlug);\n }\n }\n return ret;\n }\n}\n","import type { MatchFunction } from '@clerk/shared/pathToRegexp';\nimport { match } from '@clerk/shared/pathToRegexp';\n\nimport type { OrganizationSyncOptions, OrganizationSyncTarget } from './types';\n\nexport class OrganizationMatcher {\n private readonly organizationPattern: MatchFunction | null;\n private readonly personalAccountPattern: MatchFunction | null;\n\n constructor(options?: OrganizationSyncOptions) {\n this.organizationPattern = this.createMatcher(options?.organizationPatterns);\n this.personalAccountPattern = this.createMatcher(options?.personalAccountPatterns);\n }\n\n private createMatcher(pattern?: string[]): MatchFunction | null {\n if (!pattern) {\n return null;\n }\n try {\n return match(pattern);\n } catch (e) {\n throw new Error(`Invalid pattern \"${pattern}\": ${e}`);\n }\n }\n\n findTarget(url: URL): OrganizationSyncTarget | null {\n const orgTarget = this.findOrganizationTarget(url);\n if (orgTarget) {\n return orgTarget;\n }\n\n return this.findPersonalAccountTarget(url);\n }\n\n private findOrganizationTarget(url: URL): OrganizationSyncTarget | null {\n if (!this.organizationPattern) {\n return null;\n }\n\n try {\n const result = this.organizationPattern(url.pathname);\n if (!result || !('params' in result)) {\n return null;\n }\n\n const params = result.params as { id?: string; slug?: string };\n if (params.id) {\n return { type: 'organization', organizationId: params.id };\n }\n if (params.slug) {\n return { type: 'organization', organizationSlug: params.slug };\n }\n\n return null;\n } catch (e) {\n console.error('Failed to match organization pattern:', e);\n return null;\n }\n }\n\n private findPersonalAccountTarget(url: URL): OrganizationSyncTarget | null {\n if (!this.personalAccountPattern) {\n return null;\n }\n\n try {\n const result = this.personalAccountPattern(url.pathname);\n return result ? { type: 'personalAccount' } : null;\n } catch (e) {\n console.error('Failed to match personal account pattern:', e);\n return null;\n }\n }\n}\n","import type { JwtPayload } from '@clerk/types';\n\nimport { constants } from '../constants';\nimport type { TokenCarrier } from '../errors';\nimport { MachineTokenVerificationError, TokenVerificationError, TokenVerificationErrorReason } from '../errors';\nimport { decodeJwt } from '../jwt/verifyJwt';\nimport { assertValidSecretKey } from '../util/optionsAssertions';\nimport { isDevelopmentFromSecretKey } from '../util/shared';\nimport type { AuthenticateContext } from './authenticateContext';\nimport { createAuthenticateContext } from './authenticateContext';\nimport type { SignedInAuthObject } from './authObjects';\nimport type { HandshakeState, RequestState, SignedInState, SignedOutState, UnauthenticatedState } from './authStatus';\nimport { AuthErrorReason, handshake, signedIn, signedOut, signedOutInvalidToken } from './authStatus';\nimport { createClerkRequest } from './clerkRequest';\nimport { getCookieName, getCookieValue } from './cookie';\nimport { HandshakeService } from './handshake';\nimport { getMachineTokenType, isMachineTokenByPrefix, isTokenTypeAccepted } from './machine';\nimport { OrganizationMatcher } from './organizationMatcher';\nimport type { MachineTokenType, SessionTokenType } from './tokenTypes';\nimport { TokenType } from './tokenTypes';\nimport type { AuthenticateRequestOptions } from './types';\nimport { verifyMachineAuthToken, verifyToken } from './verify';\n\nexport const RefreshTokenErrorReason = {\n NonEligibleNoCookie: 'non-eligible-no-refresh-cookie',\n NonEligibleNonGet: 'non-eligible-non-get',\n InvalidSessionToken: 'invalid-session-token',\n MissingApiClient: 'missing-api-client',\n MissingSessionToken: 'missing-session-token',\n MissingRefreshToken: 'missing-refresh-token',\n ExpiredSessionTokenDecodeFailed: 'expired-session-token-decode-failed',\n ExpiredSessionTokenMissingSidClaim: 'expired-session-token-missing-sid-claim',\n FetchError: 'fetch-error',\n UnexpectedSDKError: 'unexpected-sdk-error',\n UnexpectedBAPIError: 'unexpected-bapi-error',\n} as const;\n\nfunction assertSignInUrlExists(signInUrl: string | undefined, key: string): asserts signInUrl is string {\n if (!signInUrl && isDevelopmentFromSecretKey(key)) {\n throw new Error(`Missing signInUrl. Pass a signInUrl for dev instances if an app is satellite`);\n }\n}\n\nfunction assertProxyUrlOrDomain(proxyUrlOrDomain: string | undefined) {\n if (!proxyUrlOrDomain) {\n throw new Error(`Missing domain and proxyUrl. A satellite application needs to specify a domain or a proxyUrl`);\n }\n}\n\nfunction assertSignInUrlFormatAndOrigin(_signInUrl: string, origin: string) {\n let signInUrl: URL;\n try {\n signInUrl = new URL(_signInUrl);\n } catch {\n throw new Error(`The signInUrl needs to have a absolute url format.`);\n }\n\n if (signInUrl.origin === origin) {\n throw new Error(`The signInUrl needs to be on a different origin than your satellite application.`);\n }\n}\n\nfunction assertMachineSecretOrSecretKey(authenticateContext: AuthenticateContext) {\n if (!authenticateContext.machineSecretKey && !authenticateContext.secretKey) {\n throw new Error(\n 'Machine token authentication requires either a Machine secret key or a Clerk secret key. ' +\n 'Ensure a Clerk secret key or Machine secret key is set.',\n );\n }\n}\n\nfunction isRequestEligibleForRefresh(\n err: TokenVerificationError,\n authenticateContext: { refreshTokenInCookie?: string },\n request: Request,\n) {\n return (\n err.reason === TokenVerificationErrorReason.TokenExpired &&\n !!authenticateContext.refreshTokenInCookie &&\n request.method === 'GET'\n );\n}\n\nfunction checkTokenTypeMismatch(\n parsedTokenType: MachineTokenType,\n acceptsToken: NonNullable,\n authenticateContext: AuthenticateContext,\n): UnauthenticatedState | null {\n const mismatch = !isTokenTypeAccepted(parsedTokenType, acceptsToken);\n if (mismatch) {\n const tokenTypeToReturn = (typeof acceptsToken === 'string' ? acceptsToken : parsedTokenType) as MachineTokenType;\n return signedOut({\n tokenType: tokenTypeToReturn,\n authenticateContext,\n reason: AuthErrorReason.TokenTypeMismatch,\n });\n }\n return null;\n}\n\nfunction isTokenTypeInAcceptedArray(acceptsToken: TokenType[], authenticateContext: AuthenticateContext): boolean {\n let parsedTokenType: TokenType | null = null;\n const { tokenInHeader } = authenticateContext;\n if (tokenInHeader) {\n if (isMachineTokenByPrefix(tokenInHeader)) {\n parsedTokenType = getMachineTokenType(tokenInHeader);\n } else {\n parsedTokenType = TokenType.SessionToken;\n }\n }\n const typeToCheck = parsedTokenType ?? TokenType.SessionToken;\n return isTokenTypeAccepted(typeToCheck, acceptsToken);\n}\n\nexport interface AuthenticateRequest {\n /**\n * @example\n * clerkClient.authenticateRequest(request, { acceptsToken: ['session_token', 'api_key'] });\n */\n (\n request: Request,\n options: AuthenticateRequestOptions & { acceptsToken: T },\n ): Promise>;\n\n /**\n * @example\n * clerkClient.authenticateRequest(request, { acceptsToken: 'session_token' });\n */\n (\n request: Request,\n options: AuthenticateRequestOptions & { acceptsToken: T },\n ): Promise>;\n\n /**\n * @example\n * clerkClient.authenticateRequest(request, { acceptsToken: 'any' });\n */\n (request: Request, options: AuthenticateRequestOptions & { acceptsToken: 'any' }): Promise>;\n\n /**\n * @example\n * clerkClient.authenticateRequest(request);\n */\n (request: Request, options?: AuthenticateRequestOptions): Promise>;\n}\n\nexport const authenticateRequest: AuthenticateRequest = (async (\n request: Request,\n options: AuthenticateRequestOptions,\n): Promise | UnauthenticatedState> => {\n const authenticateContext = await createAuthenticateContext(createClerkRequest(request), options);\n\n // Default tokenType is session_token for backwards compatibility.\n const acceptsToken = options.acceptsToken ?? TokenType.SessionToken;\n\n // machine-to-machine tokens can accept a machine secret or a secret key\n if (acceptsToken !== TokenType.M2MToken) {\n assertValidSecretKey(authenticateContext.secretKey);\n\n if (authenticateContext.isSatellite) {\n assertSignInUrlExists(authenticateContext.signInUrl, authenticateContext.secretKey);\n if (authenticateContext.signInUrl && authenticateContext.origin) {\n assertSignInUrlFormatAndOrigin(authenticateContext.signInUrl, authenticateContext.origin);\n }\n assertProxyUrlOrDomain(authenticateContext.proxyUrl || authenticateContext.domain);\n }\n }\n\n // Make sure a machine secret or instance secret key is provided if acceptsToken is m2m_token\n if (acceptsToken === TokenType.M2MToken) {\n assertMachineSecretOrSecretKey(authenticateContext);\n }\n\n const organizationMatcher = new OrganizationMatcher(options.organizationSyncOptions);\n const handshakeService = new HandshakeService(\n authenticateContext,\n { organizationSyncOptions: options.organizationSyncOptions },\n organizationMatcher,\n );\n\n async function refreshToken(\n authenticateContext: AuthenticateContext,\n ): Promise<{ data: string[]; error: null } | { data: null; error: any }> {\n // To perform a token refresh, apiClient must be defined.\n if (!options.apiClient) {\n return {\n data: null,\n error: {\n message: 'An apiClient is needed to perform token refresh.',\n cause: { reason: RefreshTokenErrorReason.MissingApiClient },\n },\n };\n }\n const { sessionToken: expiredSessionToken, refreshTokenInCookie: refreshToken } = authenticateContext;\n if (!expiredSessionToken) {\n return {\n data: null,\n error: {\n message: 'Session token must be provided.',\n cause: { reason: RefreshTokenErrorReason.MissingSessionToken },\n },\n };\n }\n if (!refreshToken) {\n return {\n data: null,\n error: {\n message: 'Refresh token must be provided.',\n cause: { reason: RefreshTokenErrorReason.MissingRefreshToken },\n },\n };\n }\n // The token refresh endpoint requires a sessionId, so we decode that from the expired token.\n const { data: decodeResult, errors: decodedErrors } = decodeJwt(expiredSessionToken);\n if (!decodeResult || decodedErrors) {\n return {\n data: null,\n error: {\n message: 'Unable to decode the expired session token.',\n cause: { reason: RefreshTokenErrorReason.ExpiredSessionTokenDecodeFailed, errors: decodedErrors },\n },\n };\n }\n\n if (!decodeResult?.payload?.sid) {\n return {\n data: null,\n error: {\n message: 'Expired session token is missing the `sid` claim.',\n cause: { reason: RefreshTokenErrorReason.ExpiredSessionTokenMissingSidClaim },\n },\n };\n }\n\n try {\n // Perform the actual token refresh.\n const response = await options.apiClient.sessions.refreshSession(decodeResult.payload.sid, {\n format: 'cookie',\n suffixed_cookies: authenticateContext.usesSuffixedCookies(),\n expired_token: expiredSessionToken || '',\n refresh_token: refreshToken || '',\n request_origin: authenticateContext.clerkUrl.origin,\n // The refresh endpoint expects headers as Record, so we need to transform it.\n request_headers: Object.fromEntries(Array.from(request.headers.entries()).map(([k, v]) => [k, [v]])),\n });\n return { data: response.cookies, error: null };\n } catch (err: any) {\n if (err?.errors?.length) {\n if (err.errors[0].code === 'unexpected_error') {\n return {\n data: null,\n error: {\n message: `Fetch unexpected error`,\n cause: { reason: RefreshTokenErrorReason.FetchError, errors: err.errors },\n },\n };\n }\n return {\n data: null,\n error: {\n message: err.errors[0].code,\n cause: { reason: err.errors[0].code, errors: err.errors },\n },\n };\n } else {\n return {\n data: null,\n error: {\n message: `Unexpected Server/BAPI error`,\n cause: { reason: RefreshTokenErrorReason.UnexpectedBAPIError, errors: [err] },\n },\n };\n }\n }\n }\n\n async function attemptRefresh(\n authenticateContext: AuthenticateContext,\n ): Promise<\n | { data: { jwtPayload: JwtPayload; sessionToken: string; headers: Headers }; error: null }\n | { data: null; error: any }\n > {\n const { data: cookiesToSet, error } = await refreshToken(authenticateContext);\n if (!cookiesToSet || cookiesToSet.length === 0) {\n return { data: null, error };\n }\n\n const headers = new Headers();\n let sessionToken = '';\n cookiesToSet.forEach((x: string) => {\n headers.append('Set-Cookie', x);\n if (getCookieName(x).startsWith(constants.Cookies.Session)) {\n sessionToken = getCookieValue(x);\n }\n });\n\n // Since we're going to return a signedIn response, we need to decode the data from the new sessionToken.\n const { data: jwtPayload, errors } = await verifyToken(sessionToken, authenticateContext);\n if (errors) {\n return {\n data: null,\n error: {\n message: `Clerk: unable to verify refreshed session token.`,\n cause: { reason: RefreshTokenErrorReason.InvalidSessionToken, errors },\n },\n };\n }\n return { data: { jwtPayload, sessionToken, headers }, error: null };\n }\n\n function handleMaybeHandshakeStatus(\n authenticateContext: AuthenticateContext,\n reason: string,\n message: string,\n headers?: Headers,\n ): SignedInState | SignedOutState | HandshakeState {\n if (!handshakeService.isRequestEligibleForHandshake()) {\n return signedOut({\n tokenType: TokenType.SessionToken,\n authenticateContext,\n reason,\n message,\n });\n }\n\n // Right now the only usage of passing in different headers is for multi-domain sync, which redirects somewhere else.\n // In the future if we want to decorate the handshake redirect with additional headers per call we need to tweak this logic.\n const handshakeHeaders = headers ?? handshakeService.buildRedirectToHandshake(reason);\n\n // Chrome aggressively caches inactive tabs. If we don't set the header here,\n // all 307 redirects will be cached and the handshake will end up in an infinite loop.\n if (handshakeHeaders.get(constants.Headers.Location)) {\n handshakeHeaders.set(constants.Headers.CacheControl, 'no-store');\n }\n\n // Introduce the mechanism to protect for infinite handshake redirect loops\n // using a cookie and returning true if it's infinite redirect loop or false if we can\n // proceed with triggering handshake.\n const isRedirectLoop = handshakeService.checkAndTrackRedirectLoop(handshakeHeaders);\n if (isRedirectLoop) {\n const msg = `Clerk: Refreshing the session token resulted in an infinite redirect loop. This usually means that your Clerk instance keys do not match - make sure to copy the correct publishable and secret keys from the Clerk dashboard.`;\n console.log(msg);\n return signedOut({\n tokenType: TokenType.SessionToken,\n authenticateContext,\n reason,\n message,\n });\n }\n\n return handshake(authenticateContext, reason, message, handshakeHeaders);\n }\n\n /**\n * Determines if a handshake must occur to resolve a mismatch between the organization as specified\n * by the URL (according to the options) and the actual active organization on the session.\n *\n * @returns {HandshakeState | SignedOutState | null} - The function can return the following:\n * - {HandshakeState}: If a handshake is needed to resolve the mismatched organization.\n * - {SignedOutState}: If a handshake is required but cannot be performed.\n * - {null}: If no action is required.\n */\n function handleMaybeOrganizationSyncHandshake(\n authenticateContext: AuthenticateContext,\n auth: SignedInAuthObject,\n ): HandshakeState | SignedOutState | null {\n const organizationSyncTarget = organizationMatcher.findTarget(authenticateContext.clerkUrl);\n if (!organizationSyncTarget) {\n return null;\n }\n let mustActivate = false;\n if (organizationSyncTarget.type === 'organization') {\n // Activate an org by slug?\n if (organizationSyncTarget.organizationSlug && organizationSyncTarget.organizationSlug !== auth.orgSlug) {\n mustActivate = true;\n }\n // Activate an org by ID?\n if (organizationSyncTarget.organizationId && organizationSyncTarget.organizationId !== auth.orgId) {\n mustActivate = true;\n }\n }\n // Activate the personal account?\n if (organizationSyncTarget.type === 'personalAccount' && auth.orgId) {\n mustActivate = true;\n }\n if (!mustActivate) {\n return null;\n }\n if (authenticateContext.handshakeRedirectLoopCounter >= 3) {\n // We have an organization that needs to be activated, but this isn't our first time redirecting.\n // This is because we attempted to activate the organization previously, but the organization\n // must not have been valid (either not found, or not valid for this user), and gave us back\n // a null organization. We won't re-try the handshake, and leave it to the server component to handle.\n console.warn(\n 'Clerk: Organization activation handshake loop detected. This is likely due to an invalid organization ID or slug. Skipping organization activation.',\n );\n return null;\n }\n const handshakeState = handleMaybeHandshakeStatus(\n authenticateContext,\n AuthErrorReason.ActiveOrganizationMismatch,\n '',\n );\n if (handshakeState.status !== 'handshake') {\n // Currently, this is only possible if we're in a redirect loop, but the above check should guard against that.\n return null;\n }\n return handshakeState;\n }\n\n async function authenticateRequestWithTokenInHeader() {\n const { tokenInHeader } = authenticateContext;\n\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const { data, errors } = await verifyToken(tokenInHeader!, authenticateContext);\n if (errors) {\n throw errors[0];\n }\n // use `await` to force this try/catch handle the signedIn invocation\n return signedIn({\n tokenType: TokenType.SessionToken,\n authenticateContext,\n sessionClaims: data,\n headers: new Headers(),\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n token: tokenInHeader!,\n });\n } catch (err) {\n return handleSessionTokenError(err, 'header');\n }\n }\n\n async function authenticateRequestWithTokenInCookie() {\n const hasActiveClient = authenticateContext.clientUat;\n const hasSessionToken = !!authenticateContext.sessionTokenInCookie;\n const hasDevBrowserToken = !!authenticateContext.devBrowserToken;\n\n /**\n * If we have a handshakeToken, resolve the handshake and attempt to return a definitive signed in or signed out state.\n */\n if (authenticateContext.handshakeNonce || authenticateContext.handshakeToken) {\n try {\n return await handshakeService.resolveHandshake();\n } catch (error) {\n // In production, the handshake token is being transferred as a cookie, so there is a possibility of collision\n // with a handshake token of another app running on the same etld+1 domain.\n // For example, if one app is running on sub1.clerk.com and another on sub2.clerk.com, the handshake token\n // cookie for both apps will be set on etld+1 (clerk.com) so there's a possibility that one app will accidentally\n // use the handshake token of a different app during the handshake flow.\n // In this scenario, verification will fail with TokenInvalidSignature. In contrast to the development case,\n // we need to allow the flow to continue so the app eventually retries another handshake with the correct token.\n // We need to make sure, however, that we don't allow the flow to continue indefinitely, so we throw an error after X\n // retries to avoid an infinite loop. An infinite loop can happen if the customer switched Clerk keys for their prod app.\n\n // Check the handleTokenVerificationErrorInDevelopment method for the development case.\n if (error instanceof TokenVerificationError && authenticateContext.instanceType === 'development') {\n handshakeService.handleTokenVerificationErrorInDevelopment(error);\n } else {\n console.error('Clerk: unable to resolve handshake:', error);\n }\n }\n }\n /**\n * Otherwise, check for \"known unknown\" auth states that we can resolve with a handshake.\n */\n if (\n authenticateContext.instanceType === 'development' &&\n authenticateContext.clerkUrl.searchParams.has(constants.QueryParameters.DevBrowser)\n ) {\n return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.DevBrowserSync, '');\n }\n\n const isRequestEligibleForMultiDomainSync =\n authenticateContext.isSatellite && authenticateContext.secFetchDest === 'document';\n\n /**\n * Begin multi-domain sync flows\n */\n if (authenticateContext.instanceType === 'production' && isRequestEligibleForMultiDomainSync) {\n return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.SatelliteCookieNeedsSyncing, '');\n }\n\n // Multi-domain development sync flow\n if (\n authenticateContext.instanceType === 'development' &&\n isRequestEligibleForMultiDomainSync &&\n !authenticateContext.clerkUrl.searchParams.has(constants.QueryParameters.ClerkSynced)\n ) {\n // initiate MD sync\n\n // signInUrl exists, checked at the top of `authenticateRequest`\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const redirectURL = new URL(authenticateContext.signInUrl!);\n redirectURL.searchParams.append(\n constants.QueryParameters.ClerkRedirectUrl,\n authenticateContext.clerkUrl.toString(),\n );\n const headers = new Headers({ [constants.Headers.Location]: redirectURL.toString() });\n return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.SatelliteCookieNeedsSyncing, '', headers);\n }\n\n // Multi-domain development sync flow\n const redirectUrl = new URL(authenticateContext.clerkUrl).searchParams.get(\n constants.QueryParameters.ClerkRedirectUrl,\n );\n\n if (authenticateContext.instanceType === 'development' && !authenticateContext.isSatellite && redirectUrl) {\n // Dev MD sync from primary, redirect back to satellite w/ dev browser query param\n const redirectBackToSatelliteUrl = new URL(redirectUrl);\n\n if (authenticateContext.devBrowserToken) {\n redirectBackToSatelliteUrl.searchParams.append(\n constants.QueryParameters.DevBrowser,\n authenticateContext.devBrowserToken,\n );\n }\n redirectBackToSatelliteUrl.searchParams.append(constants.QueryParameters.ClerkSynced, 'true');\n\n const headers = new Headers({ [constants.Headers.Location]: redirectBackToSatelliteUrl.toString() });\n return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.PrimaryRespondsToSyncing, '', headers);\n }\n /**\n * End multi-domain sync flows\n */\n\n if (authenticateContext.instanceType === 'development' && !hasDevBrowserToken) {\n return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.DevBrowserMissing, '');\n }\n\n if (!hasActiveClient && !hasSessionToken) {\n return signedOut({\n tokenType: TokenType.SessionToken,\n authenticateContext,\n reason: AuthErrorReason.SessionTokenAndUATMissing,\n });\n }\n\n // This can eagerly run handshake since client_uat is SameSite=Strict in dev\n if (!hasActiveClient && hasSessionToken) {\n return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.SessionTokenWithoutClientUAT, '');\n }\n\n if (hasActiveClient && !hasSessionToken) {\n return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.ClientUATWithoutSessionToken, '');\n }\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const { data: decodeResult, errors: decodedErrors } = decodeJwt(authenticateContext.sessionTokenInCookie!);\n\n if (decodedErrors) {\n return handleSessionTokenError(decodedErrors[0], 'cookie');\n }\n\n if (decodeResult.payload.iat < authenticateContext.clientUat) {\n return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.SessionTokenIATBeforeClientUAT, '');\n }\n\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const { data, errors } = await verifyToken(authenticateContext.sessionTokenInCookie!, authenticateContext);\n if (errors) {\n throw errors[0];\n }\n\n const signedInRequestState = signedIn({\n tokenType: TokenType.SessionToken,\n authenticateContext,\n sessionClaims: data,\n headers: new Headers(),\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n token: authenticateContext.sessionTokenInCookie!,\n });\n\n // Check for cross-origin requests from satellite domains to primary domain\n const shouldForceHandshakeForCrossDomain =\n !authenticateContext.isSatellite && // We're on primary\n authenticateContext.secFetchDest === 'document' && // Document navigation\n authenticateContext.isCrossOriginReferrer() && // Came from different domain\n !authenticateContext.isKnownClerkReferrer() && // Not from Clerk accounts portal or FAPI\n authenticateContext.handshakeRedirectLoopCounter === 0; // Not in a redirect loop\n\n if (shouldForceHandshakeForCrossDomain) {\n return handleMaybeHandshakeStatus(\n authenticateContext,\n AuthErrorReason.PrimaryDomainCrossOriginSync,\n 'Cross-origin request from satellite domain requires handshake',\n );\n }\n\n const authObject = signedInRequestState.toAuth();\n // Org sync if necessary\n if (authObject.userId) {\n const handshakeRequestState = handleMaybeOrganizationSyncHandshake(authenticateContext, authObject);\n if (handshakeRequestState) {\n return handshakeRequestState;\n }\n }\n\n return signedInRequestState;\n } catch (err) {\n return handleSessionTokenError(err, 'cookie');\n }\n\n // Unreachable\n return signedOut({\n tokenType: TokenType.SessionToken,\n authenticateContext,\n reason: AuthErrorReason.UnexpectedError,\n });\n }\n\n async function handleSessionTokenError(\n err: unknown,\n tokenCarrier: TokenCarrier,\n ): Promise {\n if (!(err instanceof TokenVerificationError)) {\n return signedOut({\n tokenType: TokenType.SessionToken,\n authenticateContext,\n reason: AuthErrorReason.UnexpectedError,\n });\n }\n\n let refreshError: string | null;\n\n if (isRequestEligibleForRefresh(err, authenticateContext, request)) {\n const { data, error } = await attemptRefresh(authenticateContext);\n if (data) {\n return signedIn({\n tokenType: TokenType.SessionToken,\n authenticateContext,\n sessionClaims: data.jwtPayload,\n headers: data.headers,\n token: data.sessionToken,\n });\n }\n\n // If there's any error, simply fallback to the handshake flow including the reason as a query parameter.\n if (error?.cause?.reason) {\n refreshError = error.cause.reason;\n } else {\n refreshError = RefreshTokenErrorReason.UnexpectedSDKError;\n }\n } else {\n if (request.method !== 'GET') {\n refreshError = RefreshTokenErrorReason.NonEligibleNonGet;\n } else if (!authenticateContext.refreshTokenInCookie) {\n refreshError = RefreshTokenErrorReason.NonEligibleNoCookie;\n } else {\n //refresh error is not applicable if token verification error is not 'session-token-expired'\n refreshError = null;\n }\n }\n\n err.tokenCarrier = tokenCarrier;\n\n const reasonToHandshake = [\n TokenVerificationErrorReason.TokenExpired,\n TokenVerificationErrorReason.TokenNotActiveYet,\n TokenVerificationErrorReason.TokenIatInTheFuture,\n ].includes(err.reason);\n\n if (reasonToHandshake) {\n return handleMaybeHandshakeStatus(\n authenticateContext,\n convertTokenVerificationErrorReasonToAuthErrorReason({ tokenError: err.reason, refreshError }),\n err.getFullMessage(),\n );\n }\n\n return signedOut({\n tokenType: TokenType.SessionToken,\n authenticateContext,\n reason: err.reason,\n message: err.getFullMessage(),\n });\n }\n\n function handleMachineError(tokenType: MachineTokenType, err: unknown): UnauthenticatedState {\n if (!(err instanceof MachineTokenVerificationError)) {\n return signedOut({\n tokenType,\n authenticateContext,\n reason: AuthErrorReason.UnexpectedError,\n });\n }\n\n return signedOut({\n tokenType,\n authenticateContext,\n reason: err.code,\n message: err.getFullMessage(),\n });\n }\n\n async function authenticateMachineRequestWithTokenInHeader() {\n const { tokenInHeader } = authenticateContext;\n // Use session token error handling if no token in header (default behavior)\n if (!tokenInHeader) {\n return handleSessionTokenError(new Error('Missing token in header'), 'header');\n }\n\n // Handle case where tokenType is any and the token is not a machine token\n if (!isMachineTokenByPrefix(tokenInHeader)) {\n return signedOut({\n tokenType: acceptsToken as TokenType,\n authenticateContext,\n reason: AuthErrorReason.TokenTypeMismatch,\n message: '',\n });\n }\n\n const parsedTokenType = getMachineTokenType(tokenInHeader);\n const mismatchState = checkTokenTypeMismatch(parsedTokenType, acceptsToken, authenticateContext);\n if (mismatchState) {\n return mismatchState;\n }\n\n const { data, tokenType, errors } = await verifyMachineAuthToken(tokenInHeader, authenticateContext);\n if (errors) {\n return handleMachineError(tokenType, errors[0]);\n }\n return signedIn({\n tokenType,\n authenticateContext,\n machineData: data,\n token: tokenInHeader,\n });\n }\n\n async function authenticateAnyRequestWithTokenInHeader() {\n const { tokenInHeader } = authenticateContext;\n // Use session token error handling if no token in header (default behavior)\n if (!tokenInHeader) {\n return handleSessionTokenError(new Error('Missing token in header'), 'header');\n }\n\n // Handle as a machine token\n if (isMachineTokenByPrefix(tokenInHeader)) {\n const parsedTokenType = getMachineTokenType(tokenInHeader);\n const mismatchState = checkTokenTypeMismatch(parsedTokenType, acceptsToken, authenticateContext);\n if (mismatchState) {\n return mismatchState;\n }\n\n const { data, tokenType, errors } = await verifyMachineAuthToken(tokenInHeader, authenticateContext);\n if (errors) {\n return handleMachineError(tokenType, errors[0]);\n }\n\n return signedIn({\n tokenType,\n authenticateContext,\n machineData: data,\n token: tokenInHeader,\n });\n }\n\n // Handle as a regular session token\n const { data, errors } = await verifyToken(tokenInHeader, authenticateContext);\n if (errors) {\n return handleSessionTokenError(errors[0], 'header');\n }\n\n return signedIn({\n tokenType: TokenType.SessionToken,\n authenticateContext,\n sessionClaims: data,\n token: tokenInHeader,\n });\n }\n\n // If acceptsToken is an array, early check if the token is in the accepted array\n // to avoid unnecessary verification calls\n if (Array.isArray(acceptsToken)) {\n if (!isTokenTypeInAcceptedArray(acceptsToken, authenticateContext)) {\n return signedOutInvalidToken();\n }\n }\n\n if (authenticateContext.tokenInHeader) {\n if (acceptsToken === 'any') {\n return authenticateAnyRequestWithTokenInHeader();\n }\n if (acceptsToken === TokenType.SessionToken) {\n return authenticateRequestWithTokenInHeader();\n }\n return authenticateMachineRequestWithTokenInHeader();\n }\n\n // Machine requests cannot have the token in the cookie, it must be in header.\n if (\n acceptsToken === TokenType.OAuthToken ||\n acceptsToken === TokenType.ApiKey ||\n acceptsToken === TokenType.M2MToken\n ) {\n return signedOut({\n tokenType: acceptsToken,\n authenticateContext,\n reason: 'No token in header',\n });\n }\n\n return authenticateRequestWithTokenInCookie();\n}) as AuthenticateRequest;\n\n/**\n * @internal\n */\nexport const debugRequestState = (params: RequestState) => {\n const { isSignedIn, isAuthenticated, proxyUrl, reason, message, publishableKey, isSatellite, domain } = params;\n return { isSignedIn, isAuthenticated, proxyUrl, reason, message, publishableKey, isSatellite, domain };\n};\n\nconst convertTokenVerificationErrorReasonToAuthErrorReason = ({\n tokenError,\n refreshError,\n}: {\n tokenError: TokenVerificationErrorReason;\n refreshError: string | null;\n}): string => {\n switch (tokenError) {\n case TokenVerificationErrorReason.TokenExpired:\n return `${AuthErrorReason.SessionTokenExpired}-refresh-${refreshError}`;\n case TokenVerificationErrorReason.TokenNotActiveYet:\n return AuthErrorReason.SessionTokenNBF;\n case TokenVerificationErrorReason.TokenIatInTheFuture:\n return AuthErrorReason.SessionTokenIatInTheFuture;\n default:\n return AuthErrorReason.UnexpectedError;\n }\n};\n","import type { ApiClient } from '../api';\nimport { mergePreDefinedOptions } from '../util/mergePreDefinedOptions';\nimport type { AuthenticateRequest } from './request';\nimport { authenticateRequest as authenticateRequestOriginal, debugRequestState } from './request';\nimport type { AuthenticateRequestOptions } from './types';\n\ntype RunTimeOptions = Omit;\ntype BuildTimeOptions = Partial<\n Pick<\n AuthenticateRequestOptions,\n | 'apiUrl'\n | 'apiVersion'\n | 'audience'\n | 'domain'\n | 'isSatellite'\n | 'jwtKey'\n | 'proxyUrl'\n | 'publishableKey'\n | 'secretKey'\n | 'machineSecretKey'\n >\n>;\n\nconst defaultOptions = {\n secretKey: '',\n machineSecretKey: '',\n jwtKey: '',\n apiUrl: undefined,\n apiVersion: undefined,\n proxyUrl: '',\n publishableKey: '',\n isSatellite: false,\n domain: '',\n audience: '',\n} satisfies BuildTimeOptions;\n\n/**\n * @internal\n */\nexport type CreateAuthenticateRequestOptions = {\n options: BuildTimeOptions;\n apiClient: ApiClient;\n};\n\n/**\n * @internal\n */\nexport function createAuthenticateRequest(params: CreateAuthenticateRequestOptions) {\n const buildTimeOptions = mergePreDefinedOptions(defaultOptions, params.options);\n const apiClient = params.apiClient;\n\n const authenticateRequest: AuthenticateRequest = (request: Request, options: RunTimeOptions = {}) => {\n const { apiUrl, apiVersion } = buildTimeOptions;\n const runTimeOptions = mergePreDefinedOptions(buildTimeOptions, options);\n return authenticateRequestOriginal(request, {\n ...options,\n ...runTimeOptions,\n // We should add all the omitted props from options here (eg apiUrl / apiVersion)\n // to avoid runtime options override them.\n apiUrl,\n apiVersion,\n apiClient,\n });\n };\n\n return {\n authenticateRequest,\n debugRequestState,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA,qBAAAA;AAAA;AAAA;AACA,uBAAmC;;;ACDnC,IAAM,YAAY;AAClB,IAAM,2BAA2B,IAAI,OAAO,WAAW,YAAY,QAAQ,GAAG;AAIvE,SAAS,aAAa,MAA4B;AACvD,SAAO,KACJ,OAAO,OAAK,CAAC,EACb,KAAK,SAAS,EACd,QAAQ,0BAA0B,SAAS;AAChD;;;ACRO,IAAe,cAAf,MAA2B;AAAA,EAChC,YAAsB,SAA0B;AAA1B;AAAA,EAA2B;AAAA,EAEvC,UAAU,IAAY;AAC9B,QAAI,CAAC,IAAI;AACP,YAAM,IAAI,MAAM,kCAAkC;AAAA,IACpD;AAAA,EACF;AACF;;;ACNA,IAAM,WAAW;AAyCV,IAAM,gBAAN,cAA4B,YAAY;AAAA,EAC7C,MAAa,OAAO,QAAgC;AAClD,WAAO,KAAK,QAAoB;AAAA,MAC9B,QAAQ;AAAA,MACR,MA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,aAAa,CAAC;AAAA,EACzB,CAAC;AAED,SAAO;AAAA,IACL,GAAG;AAAA,IACH,GAAG;AAAA,IACH;AAAA,EACF;AACF;","names":["verifyToken","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","crypto","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","import_keys","basePath","basePath","basePath","basePath","import_error","match","convertCase","Headers","Cookies","data","Cookies","import_url","import_buildAccountsBaseUrl","import_error","jwk","sessionId","authenticateContext","refreshToken","data","errors","authenticateRequest","verifyToken"]} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/index.mjs b/backend/node_modules/@clerk/backend/dist/index.mjs new file mode 100644 index 000000000..3945968d1 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/index.mjs @@ -0,0 +1,38 @@ +import { + createAuthenticateRequest, + createBackendApiClient, + verifyToken +} from "./chunk-EEWX6LTS.mjs"; +import "./chunk-LWOXHF4E.mjs"; +import { + withLegacyReturn +} from "./chunk-P263NW7Z.mjs"; +import "./chunk-XJ4RTXJG.mjs"; +import "./chunk-YW6OOOXM.mjs"; +import "./chunk-RPS7XK5K.mjs"; + +// src/index.ts +import { TelemetryCollector } from "@clerk/shared/telemetry"; +var verifyToken2 = withLegacyReturn(verifyToken); +function createClerkClient(options) { + const opts = { ...options }; + const apiClient = createBackendApiClient(opts); + const requestState = createAuthenticateRequest({ options: opts, apiClient }); + const telemetry = new TelemetryCollector({ + publishableKey: opts.publishableKey, + secretKey: opts.secretKey, + samplingRate: 0.1, + ...opts.sdkMetadata ? { sdk: opts.sdkMetadata.name, sdkVersion: opts.sdkMetadata.version } : {}, + ...opts.telemetry || {} + }); + return { + ...apiClient, + ...requestState, + telemetry + }; +} +export { + createClerkClient, + verifyToken2 as verifyToken +}; +//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/index.mjs.map b/backend/node_modules/@clerk/backend/dist/index.mjs.map new file mode 100644 index 000000000..16ed8f82d --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { TelemetryCollectorOptions } from '@clerk/shared/telemetry';\nimport { TelemetryCollector } from '@clerk/shared/telemetry';\nimport type { SDKMetadata } from '@clerk/types';\n\nimport type { ApiClient, CreateBackendApiOptions } from './api';\nimport { createBackendApiClient } from './api';\nimport { withLegacyReturn } from './jwt/legacyReturn';\nimport type { CreateAuthenticateRequestOptions } from './tokens/factory';\nimport { createAuthenticateRequest } from './tokens/factory';\nimport { verifyToken as _verifyToken } from './tokens/verify';\n\nexport const verifyToken = withLegacyReturn(_verifyToken);\n\nexport type ClerkOptions = Omit &\n Partial<\n Pick<\n CreateAuthenticateRequestOptions['options'],\n 'audience' | 'jwtKey' | 'proxyUrl' | 'secretKey' | 'publishableKey' | 'domain' | 'isSatellite'\n >\n > & { sdkMetadata?: SDKMetadata; telemetry?: Pick };\n\n// The current exported type resolves the following issue in packages importing createClerkClient\n// TS4023: Exported variable 'clerkClient' has or is using name 'AuthErrorReason' from external module \"/packages/backend/dist/index\" but cannot be named.\nexport type ClerkClient = {\n telemetry: TelemetryCollector;\n} & ApiClient &\n ReturnType;\n\nexport function createClerkClient(options: ClerkOptions): ClerkClient {\n const opts = { ...options };\n const apiClient = createBackendApiClient(opts);\n const requestState = createAuthenticateRequest({ options: opts, apiClient });\n const telemetry = new TelemetryCollector({\n publishableKey: opts.publishableKey,\n secretKey: opts.secretKey,\n samplingRate: 0.1,\n ...(opts.sdkMetadata ? { sdk: opts.sdkMetadata.name, sdkVersion: opts.sdkMetadata.version } : {}),\n ...(opts.telemetry || {}),\n });\n\n return {\n ...apiClient,\n ...requestState,\n telemetry,\n };\n}\n\n/**\n * General Types\n */\nexport type { OrganizationMembershipRole } from './api/resources';\nexport type { VerifyTokenOptions } from './tokens/verify';\n/**\n * JSON types\n */\nexport type {\n ActorTokenJSON,\n AccountlessApplicationJSON,\n ClerkResourceJSON,\n TokenJSON,\n AllowlistIdentifierJSON,\n BlocklistIdentifierJSON,\n ClientJSON,\n CnameTargetJSON,\n DomainJSON,\n EmailJSON,\n EmailAddressJSON,\n ExternalAccountJSON,\n IdentificationLinkJSON,\n InstanceJSON,\n InstanceRestrictionsJSON,\n InstanceSettingsJSON,\n InvitationJSON,\n JwtTemplateJSON,\n OauthAccessTokenJSON,\n OAuthApplicationJSON,\n OrganizationJSON,\n OrganizationDomainJSON,\n OrganizationDomainVerificationJSON,\n OrganizationInvitationJSON,\n OrganizationSettingsJSON,\n PublicOrganizationDataJSON,\n OrganizationMembershipJSON,\n OrganizationMembershipPublicUserDataJSON,\n PhoneNumberJSON,\n ProxyCheckJSON,\n RedirectUrlJSON,\n SessionJSON,\n SignInJSON,\n SignInTokenJSON,\n SignUpJSON,\n SignUpVerificationJSON,\n SignUpVerificationsJSON,\n SMSMessageJSON,\n UserJSON,\n VerificationJSON,\n WaitlistEntryJSON,\n Web3WalletJSON,\n DeletedObjectJSON,\n PaginatedResponseJSON,\n TestingTokenJSON,\n WebhooksSvixJSON,\n BillingPlanJSON,\n BillingSubscriptionJSON,\n BillingSubscriptionItemJSON,\n} from './api/resources/JSON';\n\n/**\n * Resources\n */\nexport type {\n APIKey,\n ActorToken,\n AccountlessApplication,\n AllowlistIdentifier,\n BlocklistIdentifier,\n Client,\n CnameTarget,\n Domain,\n EmailAddress,\n ExternalAccount,\n Feature,\n Instance,\n InstanceRestrictions,\n InstanceSettings,\n Invitation,\n JwtTemplate,\n Machine,\n M2MToken,\n OauthAccessToken,\n OAuthApplication,\n Organization,\n OrganizationDomain,\n OrganizationDomainVerification,\n OrganizationInvitation,\n OrganizationMembership,\n OrganizationMembershipPublicUserData,\n OrganizationSettings,\n PhoneNumber,\n SamlConnection,\n Session,\n SignInToken,\n SignUpAttempt,\n SMSMessage,\n Token,\n User,\n TestingToken,\n BillingPlan,\n BillingSubscription,\n BillingSubscriptionItem,\n} from './api/resources';\n\n/**\n * Webhooks event types\n */\nexport type {\n EmailWebhookEvent,\n OrganizationWebhookEvent,\n OrganizationDomainWebhookEvent,\n OrganizationInvitationWebhookEvent,\n OrganizationMembershipWebhookEvent,\n RoleWebhookEvent,\n PermissionWebhookEvent,\n SessionWebhookEvent,\n SMSWebhookEvent,\n UserWebhookEvent,\n WaitlistEntryWebhookEvent,\n WebhookEvent,\n WebhookEventType,\n BillingPaymentAttemptWebhookEvent,\n BillingSubscriptionWebhookEvent,\n BillingSubscriptionItemWebhookEvent,\n} from './api/resources/Webhooks';\n\n/**\n * Auth objects\n */\nexport type { AuthObject, InvalidTokenAuthObject } from './tokens/authObjects';\nexport type { SessionAuthObject, MachineAuthObject } from './tokens/types';\n"],"mappings":";;;;;;;;;;;;;;AACA,SAAS,0BAA0B;AAU5B,IAAMA,eAAc,iBAAiB,WAAY;AAiBjD,SAAS,kBAAkB,SAAoC;AACpE,QAAM,OAAO,EAAE,GAAG,QAAQ;AAC1B,QAAM,YAAY,uBAAuB,IAAI;AAC7C,QAAM,eAAe,0BAA0B,EAAE,SAAS,MAAM,UAAU,CAAC;AAC3E,QAAM,YAAY,IAAI,mBAAmB;AAAA,IACvC,gBAAgB,KAAK;AAAA,IACrB,WAAW,KAAK;AAAA,IAChB,cAAc;AAAA,IACd,GAAI,KAAK,cAAc,EAAE,KAAK,KAAK,YAAY,MAAM,YAAY,KAAK,YAAY,QAAQ,IAAI,CAAC;AAAA,IAC/F,GAAI,KAAK,aAAa,CAAC;AAAA,EACzB,CAAC;AAED,SAAO;AAAA,IACL,GAAG;AAAA,IACH,GAAG;AAAA,IACH;AAAA,EACF;AACF;","names":["verifyToken"]} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/internal.d.ts b/backend/node_modules/@clerk/backend/dist/internal.d.ts new file mode 100644 index 000000000..af97b4049 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/internal.d.ts @@ -0,0 +1,20 @@ +export { constants } from './constants'; +export { createRedirect } from './createRedirect'; +export type { RedirectFun } from './createRedirect'; +export type { CreateAuthenticateRequestOptions } from './tokens/factory'; +export { createAuthenticateRequest } from './tokens/factory'; +export { debugRequestState } from './tokens/request'; +export type { AuthenticateRequestOptions, OrganizationSyncOptions, InferAuthObjectFromToken, InferAuthObjectFromTokenArray, GetAuthFn, } from './tokens/types'; +export { TokenType } from './tokens/tokenTypes'; +export type { SessionTokenType, MachineTokenType } from './tokens/tokenTypes'; +export type { SignedInAuthObjectOptions, SignedInAuthObject, SignedOutAuthObject, AuthenticatedMachineObject, UnauthenticatedMachineObject, } from './tokens/authObjects'; +export { makeAuthObjectSerializable, signedOutAuthObject, signedInAuthObject, authenticatedMachineObject, unauthenticatedMachineObject, invalidTokenAuthObject, getAuthObjectFromJwt, getAuthObjectForAcceptedToken, } from './tokens/authObjects'; +export { AuthStatus } from './tokens/authStatus'; +export type { RequestState, SignedInState, SignedOutState, AuthenticatedState, UnauthenticatedState, } from './tokens/authStatus'; +export { decorateObjectWithResources, stripPrivateDataFromObject } from './util/decorateObjectWithResources'; +export { createClerkRequest } from './tokens/clerkRequest'; +export type { ClerkRequest } from './tokens/clerkRequest'; +export { reverificationError, reverificationErrorResponse } from '@clerk/shared/authorization-errors'; +export { verifyMachineAuthToken } from './tokens/verify'; +export { isMachineTokenByPrefix, isMachineTokenType, getMachineTokenType, isTokenTypeAccepted } from './tokens/machine'; +//# sourceMappingURL=internal.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/internal.d.ts.map b/backend/node_modules/@clerk/backend/dist/internal.d.ts.map new file mode 100644 index 000000000..f9eba2b88 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/internal.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"internal.d.ts","sourceRoot":"","sources":["../src/internal.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,cAAc,EAAE,MAAM,k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E,mBAAmB,EAAE,MAAM,kBAAkB,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/internal.js b/backend/node_modules/@clerk/backend/dist/internal.js new file mode 100644 index 000000000..9826506c3 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/internal.js @@ -0,0 +1,6052 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __typeError = (msg) => { + throw TypeError(msg); +}; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg); +var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value); +var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method); + +// src/internal.ts +var internal_exports = {}; +__export(internal_exports, { + AuthStatus: () => AuthStatus, + TokenType: () => TokenType, + authenticatedMachineObject: () => authenticatedMachineObject, + constants: () => constants, + createAuthenticateRequest: () => createAuthenticateRequest, + createClerkRequest: () => createClerkRequest, + createRedirect: () => createRedirect, + debugRequestState: () => debugRequestState, + decorateObjectWithResources: () => decorateObjectWithResources, + getAuthObjectForAcceptedToken: () => getAuthObjectForAcceptedToken, + getAuthObjectFromJwt: () => getAuthObjectFromJwt, + getMachineTokenType: () => getMachineTokenType, + invalidTokenAuthObject: () => invalidTokenAuthObject, + isMachineTokenByPrefix: () => isMachineTokenByPrefix, + isMachineTokenType: () => isMachineTokenType, + isTokenTypeAccepted: () => isTokenTypeAccepted, + makeAuthObjectSerializable: () => makeAuthObjectSerializable, + reverificationError: () => import_authorization_errors.reverificationError, + reverificationErrorResponse: () => import_authorization_errors.reverificationErrorResponse, + signedInAuthObject: () => signedInAuthObject, + signedOutAuthObject: () => signedOutAuthObject, + stripPrivateDataFromObject: () => stripPrivateDataFromObject, + unauthenticatedMachineObject: () => unauthenticatedMachineObject, + verifyMachineAuthToken: () => verifyMachineAuthToken +}); +module.exports = __toCommonJS(internal_exports); + +// src/constants.ts +var API_URL = "https://api.clerk.com"; +var API_VERSION = "v1"; +var USER_AGENT = `${"@clerk/backend"}@${"2.15.0"}`; +var MAX_CACHE_LAST_UPDATED_AT_SECONDS = 5 * 60; +var SUPPORTED_BAPI_VERSION = "2025-04-10"; +var Attributes = { + AuthToken: "__clerkAuthToken", + AuthSignature: "__clerkAuthSignature", + AuthStatus: "__clerkAuthStatus", + AuthReason: "__clerkAuthReason", + AuthMessage: "__clerkAuthMessage", + ClerkUrl: "__clerkUrl" +}; +var Cookies = { + Session: "__session", + Refresh: "__refresh", + ClientUat: "__client_uat", + Handshake: "__clerk_handshake", + DevBrowser: "__clerk_db_jwt", + RedirectCount: "__clerk_redirect_count", + HandshakeNonce: "__clerk_handshake_nonce" +}; +var QueryParameters = { + ClerkSynced: "__clerk_synced", + SuffixedCookies: "suffixed_cookies", + ClerkRedirectUrl: "__clerk_redirect_url", + // use the reference to Cookies to indicate that it's the same value + DevBrowser: Cookies.DevBrowser, + Handshake: Cookies.Handshake, + HandshakeHelp: "__clerk_help", + LegacyDevBrowser: "__dev_session", + HandshakeReason: "__clerk_hs_reason", + HandshakeNonce: Cookies.HandshakeNonce, + HandshakeFormat: "format" +}; +var Headers2 = { + Accept: "accept", + AuthMessage: "x-clerk-auth-message", + Authorization: "authorization", + AuthReason: "x-clerk-auth-reason", + AuthSignature: "x-clerk-auth-signature", + AuthStatus: "x-clerk-auth-status", + AuthToken: "x-clerk-auth-token", + CacheControl: "cache-control", + ClerkRedirectTo: "x-clerk-redirect-to", + ClerkRequestData: "x-clerk-request-data", + ClerkUrl: "x-clerk-clerk-url", + CloudFrontForwardedProto: "cloudfront-forwarded-proto", + ContentType: "content-type", + ContentSecurityPolicy: "content-security-policy", + ContentSecurityPolicyReportOnly: "content-security-policy-report-only", + EnableDebug: "x-clerk-debug", + ForwardedHost: "x-forwarded-host", + ForwardedPort: "x-forwarded-port", + ForwardedProto: "x-forwarded-proto", + Host: "host", + Location: "location", + Nonce: "x-nonce", + Origin: "origin", + Referrer: "referer", + SecFetchDest: "sec-fetch-dest", + SecFetchSite: "sec-fetch-site", + UserAgent: "user-agent", + ReportingEndpoints: "reporting-endpoints" +}; +var ContentTypes = { + Json: "application/json" +}; +var constants = { + Attributes, + Cookies, + Headers: Headers2, + ContentTypes, + QueryParameters +}; + +// src/createRedirect.ts +var import_buildAccountsBaseUrl = require("@clerk/shared/buildAccountsBaseUrl"); + +// src/util/shared.ts +var import_url = require("@clerk/shared/url"); +var import_retry = require("@clerk/shared/retry"); +var import_keys = require("@clerk/shared/keys"); +var import_deprecated = require("@clerk/shared/deprecated"); +var import_error = require("@clerk/shared/error"); +var import_keys2 = require("@clerk/shared/keys"); +var errorThrower = (0, import_error.buildErrorThrower)({ packageName: "@clerk/backend" }); +var { isDevOrStagingUrl } = (0, import_keys2.createDevOrStagingUrlCache)(); + +// src/createRedirect.ts +var buildUrl = (_baseUrl, _targetUrl, _returnBackUrl, _devBrowserToken) => { + if (_baseUrl === "") { + return legacyBuildUrl(_targetUrl.toString(), _returnBackUrl?.toString()); + } + const baseUrl = new URL(_baseUrl); + const returnBackUrl = _returnBackUrl ? new URL(_returnBackUrl, baseUrl) : void 0; + const res = new URL(_targetUrl, baseUrl); + const isCrossOriginRedirect = `${baseUrl.hostname}:${baseUrl.port}` !== `${res.hostname}:${res.port}`; + if (returnBackUrl) { + if (isCrossOriginRedirect) { + returnBackUrl.searchParams.delete(constants.QueryParameters.ClerkSynced); + } + res.searchParams.set("redirect_url", returnBackUrl.toString()); + } + if (isCrossOriginRedirect && _devBrowserToken) { + res.searchParams.set(constants.QueryParameters.DevBrowser, _devBrowserToken); + } + return res.toString(); +}; +var legacyBuildUrl = (targetUrl, redirectUrl) => { + let url; + if (!targetUrl.startsWith("http")) { + if (!redirectUrl || !redirectUrl.startsWith("http")) { + throw new Error("destination url or return back url should be an absolute path url!"); + } + const baseURL = new URL(redirectUrl); + url = new URL(targetUrl, baseURL.origin); + } else { + url = new URL(targetUrl); + } + if (redirectUrl) { + url.searchParams.set("redirect_url", redirectUrl); + } + return url.toString(); +}; +var createRedirect = (params) => { + const { publishableKey, redirectAdapter, signInUrl, signUpUrl, baseUrl, sessionStatus } = params; + const parsedPublishableKey = (0, import_keys.parsePublishableKey)(publishableKey); + const frontendApi = parsedPublishableKey?.frontendApi; + const isDevelopment = parsedPublishableKey?.instanceType === "development"; + const accountsBaseUrl = (0, import_buildAccountsBaseUrl.buildAccountsBaseUrl)(frontendApi); + const hasPendingStatus = sessionStatus === "pending"; + const redirectToTasks = (url, { returnBackUrl }) => { + return redirectAdapter( + buildUrl(baseUrl, `${url}/tasks`, returnBackUrl, isDevelopment ? params.devBrowserToken : null) + ); + }; + const redirectToSignUp = ({ returnBackUrl } = {}) => { + if (!signUpUrl && !accountsBaseUrl) { + errorThrower.throwMissingPublishableKeyError(); + } + const accountsSignUpUrl = `${accountsBaseUrl}/sign-up`; + function buildSignUpUrl(signIn) { + if (!signIn) { + return; + } + const url = new URL(signIn, baseUrl); + url.pathname = `${url.pathname}/create`; + return url.toString(); + } + const targetUrl = signUpUrl || buildSignUpUrl(signInUrl) || accountsSignUpUrl; + if (hasPendingStatus) { + return redirectToTasks(targetUrl, { returnBackUrl }); + } + return redirectAdapter(buildUrl(baseUrl, targetUrl, returnBackUrl, isDevelopment ? params.devBrowserToken : null)); + }; + const redirectToSignIn = ({ returnBackUrl } = {}) => { + if (!signInUrl && !accountsBaseUrl) { + errorThrower.throwMissingPublishableKeyError(); + } + const accountsSignInUrl = `${accountsBaseUrl}/sign-in`; + const targetUrl = signInUrl || accountsSignInUrl; + if (hasPendingStatus) { + return redirectToTasks(targetUrl, { returnBackUrl }); + } + return redirectAdapter(buildUrl(baseUrl, targetUrl, returnBackUrl, isDevelopment ? params.devBrowserToken : null)); + }; + return { redirectToSignUp, redirectToSignIn }; +}; + +// src/util/mergePreDefinedOptions.ts +function mergePreDefinedOptions(preDefinedOptions, options) { + return Object.keys(preDefinedOptions).reduce( + (obj, key) => { + return { ...obj, [key]: options[key] || obj[key] }; + }, + { ...preDefinedOptions } + ); +} + +// src/errors.ts +var TokenVerificationErrorCode = { + InvalidSecretKey: "clerk_key_invalid" +}; +var TokenVerificationErrorReason = { + TokenExpired: "token-expired", + TokenInvalid: "token-invalid", + TokenInvalidAlgorithm: "token-invalid-algorithm", + TokenInvalidAuthorizedParties: "token-invalid-authorized-parties", + TokenInvalidSignature: "token-invalid-signature", + TokenNotActiveYet: "token-not-active-yet", + TokenIatInTheFuture: "token-iat-in-the-future", + TokenVerificationFailed: "token-verification-failed", + InvalidSecretKey: "secret-key-invalid", + LocalJWKMissing: "jwk-local-missing", + RemoteJWKFailedToLoad: "jwk-remote-failed-to-load", + RemoteJWKInvalid: "jwk-remote-invalid", + RemoteJWKMissing: "jwk-remote-missing", + JWKFailedToResolve: "jwk-failed-to-resolve", + JWKKidMismatch: "jwk-kid-mismatch" +}; +var TokenVerificationErrorAction = { + ContactSupport: "Contact support@clerk.com", + EnsureClerkJWT: "Make sure that this is a valid Clerk generate JWT.", + SetClerkJWTKey: "Set the CLERK_JWT_KEY environment variable.", + SetClerkSecretKey: "Set the CLERK_SECRET_KEY environment variable.", + EnsureClockSync: "Make sure your system clock is in sync (e.g. turn off and on automatic time synchronization)." +}; +var TokenVerificationError = class _TokenVerificationError extends Error { + constructor({ + action, + message, + reason + }) { + super(message); + Object.setPrototypeOf(this, _TokenVerificationError.prototype); + this.reason = reason; + this.message = message; + this.action = action; + } + getFullMessage() { + return `${[this.message, this.action].filter((m) => m).join(" ")} (reason=${this.reason}, token-carrier=${this.tokenCarrier})`; + } +}; +var MachineTokenVerificationErrorCode = { + TokenInvalid: "token-invalid", + InvalidSecretKey: "secret-key-invalid", + UnexpectedError: "unexpected-error" +}; +var MachineTokenVerificationError = class _MachineTokenVerificationError extends Error { + constructor({ message, code, status }) { + super(message); + Object.setPrototypeOf(this, _MachineTokenVerificationError.prototype); + this.code = code; + this.status = status; + } + getFullMessage() { + return `${this.message} (code=${this.code}, status=${this.status})`; + } +}; + +// src/runtime.ts +var import_crypto = require("#crypto"); +var globalFetch = fetch.bind(globalThis); +var runtime = { + crypto: import_crypto.webcrypto, + get fetch() { + return process.env.NODE_ENV === "test" ? fetch : globalFetch; + }, + AbortController: globalThis.AbortController, + Blob: globalThis.Blob, + FormData: globalThis.FormData, + Headers: globalThis.Headers, + Request: globalThis.Request, + Response: globalThis.Response +}; + +// src/util/rfc4648.ts +var base64url = { + parse(string, opts) { + return parse(string, base64UrlEncoding, opts); + }, + stringify(data, opts) { + return stringify(data, base64UrlEncoding, opts); + } +}; +var base64UrlEncoding = { + chars: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_", + bits: 6 +}; +function parse(string, encoding, opts = {}) { + if (!encoding.codes) { + encoding.codes = {}; + for (let i = 0; i < encoding.chars.length; ++i) { + encoding.codes[encoding.chars[i]] = i; + } + } + if (!opts.loose && string.length * encoding.bits & 7) { + throw new SyntaxError("Invalid padding"); + } + let end = string.length; + while (string[end - 1] === "=") { + --end; + if (!opts.loose && !((string.length - end) * encoding.bits & 7)) { + throw new SyntaxError("Invalid padding"); + } + } + const out = new (opts.out ?? Uint8Array)(end * encoding.bits / 8 | 0); + let bits = 0; + let buffer = 0; + let written = 0; + for (let i = 0; i < end; ++i) { + const value = encoding.codes[string[i]]; + if (value === void 0) { + throw new SyntaxError("Invalid character " + string[i]); + } + buffer = buffer << encoding.bits | value; + bits += encoding.bits; + if (bits >= 8) { + bits -= 8; + out[written++] = 255 & buffer >> bits; + } + } + if (bits >= encoding.bits || 255 & buffer << 8 - bits) { + throw new SyntaxError("Unexpected end of data"); + } + return out; +} +function stringify(data, encoding, opts = {}) { + const { pad = true } = opts; + const mask = (1 << encoding.bits) - 1; + let out = ""; + let bits = 0; + let buffer = 0; + for (let i = 0; i < data.length; ++i) { + buffer = buffer << 8 | 255 & data[i]; + bits += 8; + while (bits > encoding.bits) { + bits -= encoding.bits; + out += encoding.chars[mask & buffer >> bits]; + } + } + if (bits) { + out += encoding.chars[mask & buffer << encoding.bits - bits]; + } + if (pad) { + while (out.length * encoding.bits & 7) { + out += "="; + } + } + return out; +} + +// src/jwt/algorithms.ts +var algToHash = { + RS256: "SHA-256", + RS384: "SHA-384", + RS512: "SHA-512" +}; +var RSA_ALGORITHM_NAME = "RSASSA-PKCS1-v1_5"; +var jwksAlgToCryptoAlg = { + RS256: RSA_ALGORITHM_NAME, + RS384: RSA_ALGORITHM_NAME, + RS512: RSA_ALGORITHM_NAME +}; +var algs = Object.keys(algToHash); +function getCryptoAlgorithm(algorithmName) { + const hash = algToHash[algorithmName]; + const name = jwksAlgToCryptoAlg[algorithmName]; + if (!hash || !name) { + throw new Error(`Unsupported algorithm ${algorithmName}, expected one of ${algs.join(",")}.`); + } + return { + hash: { name: algToHash[algorithmName] }, + name: jwksAlgToCryptoAlg[algorithmName] + }; +} + +// src/jwt/assertions.ts +var isArrayString = (s) => { + return Array.isArray(s) && s.length > 0 && s.every((a) => typeof a === "string"); +}; +var assertAudienceClaim = (aud, audience) => { + const audienceList = [audience].flat().filter((a) => !!a); + const audList = [aud].flat().filter((a) => !!a); + const shouldVerifyAudience = audienceList.length > 0 && audList.length > 0; + if (!shouldVerifyAudience) { + return; + } + if (typeof aud === "string") { + if (!audienceList.includes(aud)) { + throw new TokenVerificationError({ + action: TokenVerificationErrorAction.EnsureClerkJWT, + reason: TokenVerificationErrorReason.TokenVerificationFailed, + message: `Invalid JWT audience claim (aud) ${JSON.stringify(aud)}. Is not included in "${JSON.stringify( + audienceList + )}".` + }); + } + } else if (isArrayString(aud)) { + if (!aud.some((a) => audienceList.includes(a))) { + throw new TokenVerificationError({ + action: TokenVerificationErrorAction.EnsureClerkJWT, + reason: TokenVerificationErrorReason.TokenVerificationFailed, + message: `Invalid JWT audience claim array (aud) ${JSON.stringify(aud)}. Is not included in "${JSON.stringify( + audienceList + )}".` + }); + } + } +}; +var assertHeaderType = (typ) => { + if (typeof typ === "undefined") { + return; + } + if (typ !== "JWT") { + throw new TokenVerificationError({ + action: TokenVerificationErrorAction.EnsureClerkJWT, + reason: TokenVerificationErrorReason.TokenInvalid, + message: `Invalid JWT type ${JSON.stringify(typ)}. Expected "JWT".` + }); + } +}; +var assertHeaderAlgorithm = (alg) => { + if (!algs.includes(alg)) { + throw new TokenVerificationError({ + action: TokenVerificationErrorAction.EnsureClerkJWT, + reason: TokenVerificationErrorReason.TokenInvalidAlgorithm, + message: `Invalid JWT algorithm ${JSON.stringify(alg)}. Supported: ${algs}.` + }); + } +}; +var assertSubClaim = (sub) => { + if (typeof sub !== "string") { + throw new TokenVerificationError({ + action: TokenVerificationErrorAction.EnsureClerkJWT, + reason: TokenVerificationErrorReason.TokenVerificationFailed, + message: `Subject claim (sub) is required and must be a string. Received ${JSON.stringify(sub)}.` + }); + } +}; +var assertAuthorizedPartiesClaim = (azp, authorizedParties) => { + if (!azp || !authorizedParties || authorizedParties.length === 0) { + return; + } + if (!authorizedParties.includes(azp)) { + throw new TokenVerificationError({ + reason: TokenVerificationErrorReason.TokenInvalidAuthorizedParties, + message: `Invalid JWT Authorized party claim (azp) ${JSON.stringify(azp)}. Expected "${authorizedParties}".` + }); + } +}; +var assertExpirationClaim = (exp, clockSkewInMs) => { + if (typeof exp !== "number") { + throw new TokenVerificationError({ + action: TokenVerificationErrorAction.EnsureClerkJWT, + reason: TokenVerificationErrorReason.TokenVerificationFailed, + message: `Invalid JWT expiry date claim (exp) ${JSON.stringify(exp)}. Expected number.` + }); + } + const currentDate = new Date(Date.now()); + const expiryDate = /* @__PURE__ */ new Date(0); + expiryDate.setUTCSeconds(exp); + const expired = expiryDate.getTime() <= currentDate.getTime() - clockSkewInMs; + if (expired) { + throw new TokenVerificationError({ + reason: TokenVerificationErrorReason.TokenExpired, + message: `JWT is expired. Expiry date: ${expiryDate.toUTCString()}, Current date: ${currentDate.toUTCString()}.` + }); + } +}; +var assertActivationClaim = (nbf, clockSkewInMs) => { + if (typeof nbf === "undefined") { + return; + } + if (typeof nbf !== "number") { + throw new TokenVerificationError({ + action: TokenVerificationErrorAction.EnsureClerkJWT, + reason: TokenVerificationErrorReason.TokenVerificationFailed, + message: `Invalid JWT not before date claim (nbf) ${JSON.stringify(nbf)}. Expected number.` + }); + } + const currentDate = new Date(Date.now()); + const notBeforeDate = /* @__PURE__ */ new Date(0); + notBeforeDate.setUTCSeconds(nbf); + const early = notBeforeDate.getTime() > currentDate.getTime() + clockSkewInMs; + if (early) { + throw new TokenVerificationError({ + reason: TokenVerificationErrorReason.TokenNotActiveYet, + message: `JWT cannot be used prior to not before date claim (nbf). Not before date: ${notBeforeDate.toUTCString()}; Current date: ${currentDate.toUTCString()};` + }); + } +}; +var assertIssuedAtClaim = (iat, clockSkewInMs) => { + if (typeof iat === "undefined") { + return; + } + if (typeof iat !== "number") { + throw new TokenVerificationError({ + action: TokenVerificationErrorAction.EnsureClerkJWT, + reason: TokenVerificationErrorReason.TokenVerificationFailed, + message: `Invalid JWT issued at date claim (iat) ${JSON.stringify(iat)}. Expected number.` + }); + } + const currentDate = new Date(Date.now()); + const issuedAtDate = /* @__PURE__ */ new Date(0); + issuedAtDate.setUTCSeconds(iat); + const postIssued = issuedAtDate.getTime() > currentDate.getTime() + clockSkewInMs; + if (postIssued) { + throw new TokenVerificationError({ + reason: TokenVerificationErrorReason.TokenIatInTheFuture, + message: `JWT issued at date claim (iat) is in the future. Issued at date: ${issuedAtDate.toUTCString()}; Current date: ${currentDate.toUTCString()};` + }); + } +}; + +// src/jwt/cryptoKeys.ts +var import_isomorphicAtob = require("@clerk/shared/isomorphicAtob"); +function pemToBuffer(secret) { + const trimmed = secret.replace(/-----BEGIN.*?-----/g, "").replace(/-----END.*?-----/g, "").replace(/\s/g, ""); + const decoded = (0, import_isomorphicAtob.isomorphicAtob)(trimmed); + const buffer = new ArrayBuffer(decoded.length); + const bufView = new Uint8Array(buffer); + for (let i = 0, strLen = decoded.length; i < strLen; i++) { + bufView[i] = decoded.charCodeAt(i); + } + return bufView; +} +function importKey(key, algorithm, keyUsage) { + if (typeof key === "object") { + return runtime.crypto.subtle.importKey("jwk", key, algorithm, false, [keyUsage]); + } + const keyData = pemToBuffer(key); + const format = keyUsage === "sign" ? "pkcs8" : "spki"; + return runtime.crypto.subtle.importKey(format, keyData, algorithm, false, [keyUsage]); +} + +// src/jwt/verifyJwt.ts +var DEFAULT_CLOCK_SKEW_IN_MS = 5 * 1e3; +async function hasValidSignature(jwt, key) { + const { header, signature, raw } = jwt; + const encoder = new TextEncoder(); + const data = encoder.encode([raw.header, raw.payload].join(".")); + const algorithm = getCryptoAlgorithm(header.alg); + try { + const cryptoKey = await importKey(key, algorithm, "verify"); + const verified = await runtime.crypto.subtle.verify(algorithm.name, cryptoKey, signature, data); + return { data: verified }; + } catch (error) { + return { + errors: [ + new TokenVerificationError({ + reason: TokenVerificationErrorReason.TokenInvalidSignature, + message: error?.message + }) + ] + }; + } +} +function decodeJwt(token) { + const tokenParts = (token || "").toString().split("."); + if (tokenParts.length !== 3) { + return { + errors: [ + new TokenVerificationError({ + reason: TokenVerificationErrorReason.TokenInvalid, + message: `Invalid JWT form. A JWT consists of three parts separated by dots.` + }) + ] + }; + } + const [rawHeader, rawPayload, rawSignature] = tokenParts; + const decoder = new TextDecoder(); + const header = JSON.parse(decoder.decode(base64url.parse(rawHeader, { loose: true }))); + const payload = JSON.parse(decoder.decode(base64url.parse(rawPayload, { loose: true }))); + const signature = base64url.parse(rawSignature, { loose: true }); + const data = { + header, + payload, + signature, + raw: { + header: rawHeader, + payload: rawPayload, + signature: rawSignature, + text: token + } + }; + return { data }; +} +async function verifyJwt(token, options) { + const { audience, authorizedParties, clockSkewInMs, key } = options; + const clockSkew = clockSkewInMs || DEFAULT_CLOCK_SKEW_IN_MS; + const { data: decoded, errors } = decodeJwt(token); + if (errors) { + return { errors }; + } + const { header, payload } = decoded; + try { + const { typ, alg } = header; + assertHeaderType(typ); + assertHeaderAlgorithm(alg); + const { azp, sub, aud, iat, exp, nbf } = payload; + assertSubClaim(sub); + assertAudienceClaim([aud], [audience]); + assertAuthorizedPartiesClaim(azp, authorizedParties); + assertExpirationClaim(exp, clockSkew); + assertActivationClaim(nbf, clockSkew); + assertIssuedAtClaim(iat, clockSkew); + } catch (err) { + return { errors: [err] }; + } + const { data: signatureValid, errors: signatureErrors } = await hasValidSignature(decoded, key); + if (signatureErrors) { + return { + errors: [ + new TokenVerificationError({ + action: TokenVerificationErrorAction.EnsureClerkJWT, + reason: TokenVerificationErrorReason.TokenVerificationFailed, + message: `Error verifying JWT signature. ${signatureErrors[0]}` + }) + ] + }; + } + if (!signatureValid) { + return { + errors: [ + new TokenVerificationError({ + reason: TokenVerificationErrorReason.TokenInvalidSignature, + message: "JWT signature is invalid." + }) + ] + }; + } + return { data: payload }; +} + +// src/util/optionsAssertions.ts +function assertValidSecretKey(val) { + if (!val || typeof val !== "string") { + throw Error("Missing Clerk Secret Key. Go to https://dashboard.clerk.com and get your key for your instance."); + } +} +function assertValidPublishableKey(val) { + (0, import_keys.parsePublishableKey)(val, { fatal: true }); +} + +// src/tokens/authenticateContext.ts +var import_buildAccountsBaseUrl2 = require("@clerk/shared/buildAccountsBaseUrl"); +var import_url2 = require("@clerk/shared/url"); + +// src/tokens/tokenTypes.ts +var TokenType = { + SessionToken: "session_token", + ApiKey: "api_key", + M2MToken: "m2m_token", + OAuthToken: "oauth_token" +}; + +// src/tokens/authenticateContext.ts +var AuthenticateContext = class { + constructor(cookieSuffix, clerkRequest, options) { + this.cookieSuffix = cookieSuffix; + this.clerkRequest = clerkRequest; + /** + * The original Clerk frontend API URL, extracted from publishable key before proxy URL override. + * Used for backend operations like token validation and issuer checking. + */ + this.originalFrontendApi = ""; + if (options.acceptsToken === TokenType.M2MToken || options.acceptsToken === TokenType.ApiKey) { + this.initHeaderValues(); + } else { + this.initPublishableKeyValues(options); + this.initHeaderValues(); + this.initCookieValues(); + this.initHandshakeValues(); + } + Object.assign(this, options); + this.clerkUrl = this.clerkRequest.clerkUrl; + } + /** + * Retrieves the session token from either the cookie or the header. + * + * @returns {string | undefined} The session token if available, otherwise undefined. + */ + get sessionToken() { + return this.sessionTokenInCookie || this.tokenInHeader; + } + usesSuffixedCookies() { + const suffixedClientUat = this.getSuffixedCookie(constants.Cookies.ClientUat); + const clientUat = this.getCookie(constants.Cookies.ClientUat); + const suffixedSession = this.getSuffixedCookie(constants.Cookies.Session) || ""; + const session = this.getCookie(constants.Cookies.Session) || ""; + if (session && !this.tokenHasIssuer(session)) { + return false; + } + if (session && !this.tokenBelongsToInstance(session)) { + return true; + } + if (!suffixedClientUat && !suffixedSession) { + return false; + } + const { data: sessionData } = decodeJwt(session); + const sessionIat = sessionData?.payload.iat || 0; + const { data: suffixedSessionData } = decodeJwt(suffixedSession); + const suffixedSessionIat = suffixedSessionData?.payload.iat || 0; + if (suffixedClientUat !== "0" && clientUat !== "0" && sessionIat > suffixedSessionIat) { + return false; + } + if (suffixedClientUat === "0" && clientUat !== "0") { + return false; + } + if (this.instanceType !== "production") { + const isSuffixedSessionExpired = this.sessionExpired(suffixedSessionData); + if (suffixedClientUat !== "0" && clientUat === "0" && isSuffixedSessionExpired) { + return false; + } + } + if (!suffixedClientUat && suffixedSession) { + return false; + } + return true; + } + /** + * Determines if the request came from a different origin based on the referrer header. + * Used for cross-origin detection in multi-domain authentication flows. + * + * @returns {boolean} True if referrer exists and is from a different origin, false otherwise. + */ + isCrossOriginReferrer() { + if (!this.referrer || !this.clerkUrl.origin) { + return false; + } + try { + const referrerOrigin = new URL(this.referrer).origin; + return referrerOrigin !== this.clerkUrl.origin; + } catch { + return false; + } + } + /** + * Determines if the referrer URL is from a Clerk domain (accounts portal or FAPI). + * This includes both development and production account portal domains, as well as FAPI domains + * used for redirect-based authentication flows. + * + * @returns {boolean} True if the referrer is from a Clerk accounts portal or FAPI domain, false otherwise + */ + isKnownClerkReferrer() { + if (!this.referrer) { + return false; + } + try { + const referrerOrigin = new URL(this.referrer); + const referrerHost = referrerOrigin.hostname; + if (this.frontendApi) { + const fapiHost = this.frontendApi.startsWith("http") ? new URL(this.frontendApi).hostname : this.frontendApi; + if (referrerHost === fapiHost) { + return true; + } + } + if ((0, import_url2.isLegacyDevAccountPortalOrigin)(referrerHost) || (0, import_url2.isCurrentDevAccountPortalOrigin)(referrerHost)) { + return true; + } + const expectedAccountsUrl = (0, import_buildAccountsBaseUrl2.buildAccountsBaseUrl)(this.frontendApi); + if (expectedAccountsUrl) { + const expectedAccountsOrigin = new URL(expectedAccountsUrl).origin; + if (referrerOrigin.origin === expectedAccountsOrigin) { + return true; + } + } + if (referrerHost.startsWith("accounts.")) { + return true; + } + return false; + } catch { + return false; + } + } + initPublishableKeyValues(options) { + assertValidPublishableKey(options.publishableKey); + this.publishableKey = options.publishableKey; + const originalPk = (0, import_keys.parsePublishableKey)(this.publishableKey, { + fatal: true, + domain: options.domain, + isSatellite: options.isSatellite + }); + this.originalFrontendApi = originalPk.frontendApi; + const pk = (0, import_keys.parsePublishableKey)(this.publishableKey, { + fatal: true, + proxyUrl: options.proxyUrl, + domain: options.domain, + isSatellite: options.isSatellite + }); + this.instanceType = pk.instanceType; + this.frontendApi = pk.frontendApi; + } + initHeaderValues() { + this.tokenInHeader = this.parseAuthorizationHeader(this.getHeader(constants.Headers.Authorization)); + this.origin = this.getHeader(constants.Headers.Origin); + this.host = this.getHeader(constants.Headers.Host); + this.forwardedHost = this.getHeader(constants.Headers.ForwardedHost); + this.forwardedProto = this.getHeader(constants.Headers.CloudFrontForwardedProto) || this.getHeader(constants.Headers.ForwardedProto); + this.referrer = this.getHeader(constants.Headers.Referrer); + this.userAgent = this.getHeader(constants.Headers.UserAgent); + this.secFetchDest = this.getHeader(constants.Headers.SecFetchDest); + this.accept = this.getHeader(constants.Headers.Accept); + } + initCookieValues() { + this.sessionTokenInCookie = this.getSuffixedOrUnSuffixedCookie(constants.Cookies.Session); + this.refreshTokenInCookie = this.getSuffixedCookie(constants.Cookies.Refresh); + this.clientUat = Number.parseInt(this.getSuffixedOrUnSuffixedCookie(constants.Cookies.ClientUat) || "") || 0; + } + initHandshakeValues() { + this.devBrowserToken = this.getQueryParam(constants.QueryParameters.DevBrowser) || this.getSuffixedOrUnSuffixedCookie(constants.Cookies.DevBrowser); + this.handshakeToken = this.getQueryParam(constants.QueryParameters.Handshake) || this.getCookie(constants.Cookies.Handshake); + this.handshakeRedirectLoopCounter = Number(this.getCookie(constants.Cookies.RedirectCount)) || 0; + this.handshakeNonce = this.getQueryParam(constants.QueryParameters.HandshakeNonce) || this.getCookie(constants.Cookies.HandshakeNonce); + } + getQueryParam(name) { + return this.clerkRequest.clerkUrl.searchParams.get(name); + } + getHeader(name) { + return this.clerkRequest.headers.get(name) || void 0; + } + getCookie(name) { + return this.clerkRequest.cookies.get(name) || void 0; + } + getSuffixedCookie(name) { + return this.getCookie((0, import_keys.getSuffixedCookieName)(name, this.cookieSuffix)) || void 0; + } + getSuffixedOrUnSuffixedCookie(cookieName) { + if (this.usesSuffixedCookies()) { + return this.getSuffixedCookie(cookieName); + } + return this.getCookie(cookieName); + } + parseAuthorizationHeader(authorizationHeader) { + if (!authorizationHeader) { + return void 0; + } + const [scheme, token] = authorizationHeader.split(" ", 2); + if (!token) { + return scheme; + } + if (scheme === "Bearer") { + return token; + } + return void 0; + } + tokenHasIssuer(token) { + const { data, errors } = decodeJwt(token); + if (errors) { + return false; + } + return !!data.payload.iss; + } + tokenBelongsToInstance(token) { + if (!token) { + return false; + } + const { data, errors } = decodeJwt(token); + if (errors) { + return false; + } + const tokenIssuer = data.payload.iss.replace(/https?:\/\//gi, ""); + return this.originalFrontendApi === tokenIssuer; + } + sessionExpired(jwt) { + return !!jwt && jwt?.payload.exp <= Date.now() / 1e3 >> 0; + } +}; +var createAuthenticateContext = async (clerkRequest, options) => { + const cookieSuffix = options.publishableKey ? await (0, import_keys.getCookieSuffix)(options.publishableKey, runtime.crypto.subtle) : ""; + return new AuthenticateContext(cookieSuffix, clerkRequest, options); +}; + +// src/tokens/authObjects.ts +var import_authorization = require("@clerk/shared/authorization"); +var import_jwtPayloadParser = require("@clerk/shared/jwtPayloadParser"); + +// src/util/path.ts +var SEPARATOR = "/"; +var MULTIPLE_SEPARATOR_REGEX = new RegExp("(? p).join(SEPARATOR).replace(MULTIPLE_SEPARATOR_REGEX, SEPARATOR); +} + +// src/api/endpoints/AbstractApi.ts +var AbstractAPI = class { + constructor(request) { + this.request = request; + } + requireId(id) { + if (!id) { + throw new Error("A valid resource ID is required."); + } + } +}; + +// src/api/endpoints/ActorTokenApi.ts +var basePath = "/actor_tokens"; +var ActorTokenAPI = class extends AbstractAPI { + async create(params) { + return this.request({ + method: "POST", + path: basePath, + bodyParams: params + }); + } + async revoke(actorTokenId) { + this.requireId(actorTokenId); + return this.request({ + method: "POST", + path: joinPaths(basePath, actorTokenId, "revoke") + }); + } +}; + +// src/api/endpoints/AccountlessApplicationsAPI.ts +var basePath2 = "/accountless_applications"; +var AccountlessApplicationAPI = class extends AbstractAPI { + async createAccountlessApplication(params) { + const headerParams = params?.requestHeaders ? Object.fromEntries(params.requestHeaders.entries()) : void 0; + return this.request({ + method: "POST", + path: basePath2, + headerParams + }); + } + async completeAccountlessApplicationOnboarding(params) { + const headerParams = params?.requestHeaders ? Object.fromEntries(params.requestHeaders.entries()) : void 0; + return this.request({ + method: "POST", + path: joinPaths(basePath2, "complete"), + headerParams + }); + } +}; + +// src/api/endpoints/AllowlistIdentifierApi.ts +var basePath3 = "/allowlist_identifiers"; +var AllowlistIdentifierAPI = class extends AbstractAPI { + async getAllowlistIdentifierList(params = {}) { + return this.request({ + method: "GET", + path: basePath3, + queryParams: { ...params, paginated: true } + }); + } + async createAllowlistIdentifier(params) { + return this.request({ + method: "POST", + path: basePath3, + bodyParams: params + }); + } + async deleteAllowlistIdentifier(allowlistIdentifierId) { + this.requireId(allowlistIdentifierId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath3, allowlistIdentifierId) + }); + } +}; + +// src/api/endpoints/APIKeysApi.ts +var basePath4 = "/api_keys"; +var APIKeysAPI = class extends AbstractAPI { + async create(params) { + return this.request({ + method: "POST", + path: basePath4, + bodyParams: params + }); + } + async revoke(params) { + const { apiKeyId, ...bodyParams } = params; + this.requireId(apiKeyId); + return this.request({ + method: "POST", + path: joinPaths(basePath4, apiKeyId, "revoke"), + bodyParams + }); + } + async getSecret(apiKeyId) { + this.requireId(apiKeyId); + return this.request({ + method: "GET", + path: joinPaths(basePath4, apiKeyId, "secret") + }); + } + async verifySecret(secret) { + return this.request({ + method: "POST", + path: joinPaths(basePath4, "verify"), + bodyParams: { secret } + }); + } +}; + +// src/api/endpoints/BetaFeaturesApi.ts +var basePath5 = "/beta_features"; +var BetaFeaturesAPI = class extends AbstractAPI { + /** + * Change the domain of a production instance. + * + * Changing the domain requires updating the DNS records accordingly, deploying new SSL certificates, + * updating your Social Connection's redirect URLs and setting the new keys in your code. + * + * @remarks + * WARNING: Changing your domain will invalidate all current user sessions (i.e. users will be logged out). + * Also, while your application is being deployed, a small downtime is expected to occur. + */ + async changeDomain(params) { + return this.request({ + method: "POST", + path: joinPaths(basePath5, "change_domain"), + bodyParams: params + }); + } +}; + +// src/api/endpoints/BlocklistIdentifierApi.ts +var basePath6 = "/blocklist_identifiers"; +var BlocklistIdentifierAPI = class extends AbstractAPI { + async getBlocklistIdentifierList(params = {}) { + return this.request({ + method: "GET", + path: basePath6, + queryParams: params + }); + } + async createBlocklistIdentifier(params) { + return this.request({ + method: "POST", + path: basePath6, + bodyParams: params + }); + } + async deleteBlocklistIdentifier(blocklistIdentifierId) { + this.requireId(blocklistIdentifierId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath6, blocklistIdentifierId) + }); + } +}; + +// src/api/endpoints/ClientApi.ts +var basePath7 = "/clients"; +var ClientAPI = class extends AbstractAPI { + async getClientList(params = {}) { + return this.request({ + method: "GET", + path: basePath7, + queryParams: { ...params, paginated: true } + }); + } + async getClient(clientId) { + this.requireId(clientId); + return this.request({ + method: "GET", + path: joinPaths(basePath7, clientId) + }); + } + verifyClient(token) { + return this.request({ + method: "POST", + path: joinPaths(basePath7, "verify"), + bodyParams: { token } + }); + } + async getHandshakePayload(queryParams) { + return this.request({ + method: "GET", + path: joinPaths(basePath7, "handshake_payload"), + queryParams + }); + } +}; + +// src/api/endpoints/DomainApi.ts +var basePath8 = "/domains"; +var DomainAPI = class extends AbstractAPI { + async list() { + return this.request({ + method: "GET", + path: basePath8 + }); + } + async add(params) { + return this.request({ + method: "POST", + path: basePath8, + bodyParams: params + }); + } + async update(params) { + const { domainId, ...bodyParams } = params; + this.requireId(domainId); + return this.request({ + method: "PATCH", + path: joinPaths(basePath8, domainId), + bodyParams + }); + } + /** + * Deletes a satellite domain for the instance. + * It is currently not possible to delete the instance's primary domain. + */ + async delete(satelliteDomainId) { + return this.deleteDomain(satelliteDomainId); + } + /** + * @deprecated Use `delete` instead + */ + async deleteDomain(satelliteDomainId) { + this.requireId(satelliteDomainId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath8, satelliteDomainId) + }); + } +}; + +// src/api/endpoints/EmailAddressApi.ts +var basePath9 = "/email_addresses"; +var EmailAddressAPI = class extends AbstractAPI { + async getEmailAddress(emailAddressId) { + this.requireId(emailAddressId); + return this.request({ + method: "GET", + path: joinPaths(basePath9, emailAddressId) + }); + } + async createEmailAddress(params) { + return this.request({ + method: "POST", + path: basePath9, + bodyParams: params + }); + } + async updateEmailAddress(emailAddressId, params = {}) { + this.requireId(emailAddressId); + return this.request({ + method: "PATCH", + path: joinPaths(basePath9, emailAddressId), + bodyParams: params + }); + } + async deleteEmailAddress(emailAddressId) { + this.requireId(emailAddressId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath9, emailAddressId) + }); + } +}; + +// src/api/endpoints/IdPOAuthAccessTokenApi.ts +var basePath10 = "/oauth_applications/access_tokens"; +var IdPOAuthAccessTokenApi = class extends AbstractAPI { + async verifyAccessToken(accessToken) { + return this.request({ + method: "POST", + path: joinPaths(basePath10, "verify"), + bodyParams: { access_token: accessToken } + }); + } +}; + +// src/api/endpoints/InstanceApi.ts +var basePath11 = "/instance"; +var InstanceAPI = class extends AbstractAPI { + async get() { + return this.request({ + method: "GET", + path: basePath11 + }); + } + async update(params) { + return this.request({ + method: "PATCH", + path: basePath11, + bodyParams: params + }); + } + async updateRestrictions(params) { + return this.request({ + method: "PATCH", + path: joinPaths(basePath11, "restrictions"), + bodyParams: params + }); + } + async updateOrganizationSettings(params) { + return this.request({ + method: "PATCH", + path: joinPaths(basePath11, "organization_settings"), + bodyParams: params + }); + } +}; + +// src/api/endpoints/InvitationApi.ts +var basePath12 = "/invitations"; +var InvitationAPI = class extends AbstractAPI { + async getInvitationList(params = {}) { + return this.request({ + method: "GET", + path: basePath12, + queryParams: { ...params, paginated: true } + }); + } + async createInvitation(params) { + return this.request({ + method: "POST", + path: basePath12, + bodyParams: params + }); + } + async createInvitationBulk(params) { + return this.request({ + method: "POST", + path: joinPaths(basePath12, "bulk"), + bodyParams: params + }); + } + async revokeInvitation(invitationId) { + this.requireId(invitationId); + return this.request({ + method: "POST", + path: joinPaths(basePath12, invitationId, "revoke") + }); + } +}; + +// src/api/endpoints/MachineApi.ts +var basePath13 = "/machines"; +var MachineApi = class extends AbstractAPI { + async get(machineId) { + this.requireId(machineId); + return this.request({ + method: "GET", + path: joinPaths(basePath13, machineId) + }); + } + async list(queryParams = {}) { + return this.request({ + method: "GET", + path: basePath13, + queryParams + }); + } + async create(bodyParams) { + return this.request({ + method: "POST", + path: basePath13, + bodyParams + }); + } + async update(params) { + const { machineId, ...bodyParams } = params; + this.requireId(machineId); + return this.request({ + method: "PATCH", + path: joinPaths(basePath13, machineId), + bodyParams + }); + } + async delete(machineId) { + this.requireId(machineId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath13, machineId) + }); + } + async getSecretKey(machineId) { + this.requireId(machineId); + return this.request({ + method: "GET", + path: joinPaths(basePath13, machineId, "secret_key") + }); + } + async rotateSecretKey(params) { + const { machineId, previousTokenTtl } = params; + this.requireId(machineId); + return this.request({ + method: "POST", + path: joinPaths(basePath13, machineId, "secret_key", "rotate"), + bodyParams: { + previousTokenTtl + } + }); + } + /** + * Creates a new machine scope, allowing the specified machine to access another machine. + * + * @param machineId - The ID of the machine that will have access to another machine. + * @param toMachineId - The ID of the machine that will be scoped to the current machine. + */ + async createScope(machineId, toMachineId) { + this.requireId(machineId); + return this.request({ + method: "POST", + path: joinPaths(basePath13, machineId, "scopes"), + bodyParams: { + toMachineId + } + }); + } + /** + * Deletes a machine scope, removing access from one machine to another. + * + * @param machineId - The ID of the machine that has access to another machine. + * @param otherMachineId - The ID of the machine that is being accessed. + */ + async deleteScope(machineId, otherMachineId) { + this.requireId(machineId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath13, machineId, "scopes", otherMachineId) + }); + } +}; + +// src/api/endpoints/M2MTokenApi.ts +var basePath14 = "/m2m_tokens"; +var _M2MTokenApi_instances, createRequestOptions_fn; +var M2MTokenApi = class extends AbstractAPI { + constructor() { + super(...arguments); + __privateAdd(this, _M2MTokenApi_instances); + } + async createToken(params) { + const { claims = null, machineSecretKey, secondsUntilExpiration = null } = params || {}; + const requestOptions = __privateMethod(this, _M2MTokenApi_instances, createRequestOptions_fn).call(this, { + method: "POST", + path: basePath14, + bodyParams: { + secondsUntilExpiration, + claims + } + }, machineSecretKey); + return this.request(requestOptions); + } + async revokeToken(params) { + const { m2mTokenId, revocationReason = null, machineSecretKey } = params; + this.requireId(m2mTokenId); + const requestOptions = __privateMethod(this, _M2MTokenApi_instances, createRequestOptions_fn).call(this, { + method: "POST", + path: joinPaths(basePath14, m2mTokenId, "revoke"), + bodyParams: { + revocationReason + } + }, machineSecretKey); + return this.request(requestOptions); + } + async verifyToken(params) { + const { token, machineSecretKey } = params; + const requestOptions = __privateMethod(this, _M2MTokenApi_instances, createRequestOptions_fn).call(this, { + method: "POST", + path: joinPaths(basePath14, "verify"), + bodyParams: { token } + }, machineSecretKey); + return this.request(requestOptions); + } +}; +_M2MTokenApi_instances = new WeakSet(); +createRequestOptions_fn = function(options, machineSecretKey) { + if (machineSecretKey) { + return { + ...options, + headerParams: { + ...options.headerParams, + Authorization: `Bearer ${machineSecretKey}` + } + }; + } + return options; +}; + +// src/api/endpoints/JwksApi.ts +var basePath15 = "/jwks"; +var JwksAPI = class extends AbstractAPI { + async getJwks() { + return this.request({ + method: "GET", + path: basePath15 + }); + } +}; + +// src/api/endpoints/JwtTemplatesApi.ts +var basePath16 = "/jwt_templates"; +var JwtTemplatesApi = class extends AbstractAPI { + async list(params = {}) { + return this.request({ + method: "GET", + path: basePath16, + queryParams: { ...params, paginated: true } + }); + } + async get(templateId) { + this.requireId(templateId); + return this.request({ + method: "GET", + path: joinPaths(basePath16, templateId) + }); + } + async create(params) { + return this.request({ + method: "POST", + path: basePath16, + bodyParams: params + }); + } + async update(params) { + const { templateId, ...bodyParams } = params; + this.requireId(templateId); + return this.request({ + method: "PATCH", + path: joinPaths(basePath16, templateId), + bodyParams + }); + } + async delete(templateId) { + this.requireId(templateId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath16, templateId) + }); + } +}; + +// src/api/endpoints/OrganizationApi.ts +var basePath17 = "/organizations"; +var OrganizationAPI = class extends AbstractAPI { + async getOrganizationList(params) { + return this.request({ + method: "GET", + path: basePath17, + queryParams: params + }); + } + async createOrganization(params) { + return this.request({ + method: "POST", + path: basePath17, + bodyParams: params + }); + } + async getOrganization(params) { + const { includeMembersCount } = params; + const organizationIdOrSlug = "organizationId" in params ? params.organizationId : params.slug; + this.requireId(organizationIdOrSlug); + return this.request({ + method: "GET", + path: joinPaths(basePath17, organizationIdOrSlug), + queryParams: { + includeMembersCount + } + }); + } + async updateOrganization(organizationId, params) { + this.requireId(organizationId); + return this.request({ + method: "PATCH", + path: joinPaths(basePath17, organizationId), + bodyParams: params + }); + } + async updateOrganizationLogo(organizationId, params) { + this.requireId(organizationId); + const formData = new runtime.FormData(); + formData.append("file", params?.file); + if (params?.uploaderUserId) { + formData.append("uploader_user_id", params?.uploaderUserId); + } + return this.request({ + method: "PUT", + path: joinPaths(basePath17, organizationId, "logo"), + formData + }); + } + async deleteOrganizationLogo(organizationId) { + this.requireId(organizationId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath17, organizationId, "logo") + }); + } + async updateOrganizationMetadata(organizationId, params) { + this.requireId(organizationId); + return this.request({ + method: "PATCH", + path: joinPaths(basePath17, organizationId, "metadata"), + bodyParams: params + }); + } + async deleteOrganization(organizationId) { + return this.request({ + method: "DELETE", + path: joinPaths(basePath17, organizationId) + }); + } + async getOrganizationMembershipList(params) { + const { organizationId, ...queryParams } = params; + this.requireId(organizationId); + return this.request({ + method: "GET", + path: joinPaths(basePath17, organizationId, "memberships"), + queryParams + }); + } + async getInstanceOrganizationMembershipList(params) { + return this.request({ + method: "GET", + path: "/organization_memberships", + queryParams: params + }); + } + async createOrganizationMembership(params) { + const { organizationId, ...bodyParams } = params; + this.requireId(organizationId); + return this.request({ + method: "POST", + path: joinPaths(basePath17, organizationId, "memberships"), + bodyParams + }); + } + async updateOrganizationMembership(params) { + const { organizationId, userId, ...bodyParams } = params; + this.requireId(organizationId); + return this.request({ + method: "PATCH", + path: joinPaths(basePath17, organizationId, "memberships", userId), + bodyParams + }); + } + async updateOrganizationMembershipMetadata(params) { + const { organizationId, userId, ...bodyParams } = params; + return this.request({ + method: "PATCH", + path: joinPaths(basePath17, organizationId, "memberships", userId, "metadata"), + bodyParams + }); + } + async deleteOrganizationMembership(params) { + const { organizationId, userId } = params; + this.requireId(organizationId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath17, organizationId, "memberships", userId) + }); + } + async getOrganizationInvitationList(params) { + const { organizationId, ...queryParams } = params; + this.requireId(organizationId); + return this.request({ + method: "GET", + path: joinPaths(basePath17, organizationId, "invitations"), + queryParams + }); + } + async createOrganizationInvitation(params) { + const { organizationId, ...bodyParams } = params; + this.requireId(organizationId); + return this.request({ + method: "POST", + path: joinPaths(basePath17, organizationId, "invitations"), + bodyParams + }); + } + async createOrganizationInvitationBulk(organizationId, params) { + this.requireId(organizationId); + return this.request({ + method: "POST", + path: joinPaths(basePath17, organizationId, "invitations", "bulk"), + bodyParams: params + }); + } + async getOrganizationInvitation(params) { + const { organizationId, invitationId } = params; + this.requireId(organizationId); + this.requireId(invitationId); + return this.request({ + method: "GET", + path: joinPaths(basePath17, organizationId, "invitations", invitationId) + }); + } + async revokeOrganizationInvitation(params) { + const { organizationId, invitationId, ...bodyParams } = params; + this.requireId(organizationId); + return this.request({ + method: "POST", + path: joinPaths(basePath17, organizationId, "invitations", invitationId, "revoke"), + bodyParams + }); + } + async getOrganizationDomainList(params) { + const { organizationId, ...queryParams } = params; + this.requireId(organizationId); + return this.request({ + method: "GET", + path: joinPaths(basePath17, organizationId, "domains"), + queryParams + }); + } + async createOrganizationDomain(params) { + const { organizationId, ...bodyParams } = params; + this.requireId(organizationId); + return this.request({ + method: "POST", + path: joinPaths(basePath17, organizationId, "domains"), + bodyParams: { + ...bodyParams, + verified: bodyParams.verified ?? true + } + }); + } + async updateOrganizationDomain(params) { + const { organizationId, domainId, ...bodyParams } = params; + this.requireId(organizationId); + this.requireId(domainId); + return this.request({ + method: "PATCH", + path: joinPaths(basePath17, organizationId, "domains", domainId), + bodyParams + }); + } + async deleteOrganizationDomain(params) { + const { organizationId, domainId } = params; + this.requireId(organizationId); + this.requireId(domainId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath17, organizationId, "domains", domainId) + }); + } +}; + +// src/api/endpoints/OAuthApplicationsApi.ts +var basePath18 = "/oauth_applications"; +var OAuthApplicationsApi = class extends AbstractAPI { + async list(params = {}) { + return this.request({ + method: "GET", + path: basePath18, + queryParams: params + }); + } + async get(oauthApplicationId) { + this.requireId(oauthApplicationId); + return this.request({ + method: "GET", + path: joinPaths(basePath18, oauthApplicationId) + }); + } + async create(params) { + return this.request({ + method: "POST", + path: basePath18, + bodyParams: params + }); + } + async update(params) { + const { oauthApplicationId, ...bodyParams } = params; + this.requireId(oauthApplicationId); + return this.request({ + method: "PATCH", + path: joinPaths(basePath18, oauthApplicationId), + bodyParams + }); + } + async delete(oauthApplicationId) { + this.requireId(oauthApplicationId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath18, oauthApplicationId) + }); + } + async rotateSecret(oauthApplicationId) { + this.requireId(oauthApplicationId); + return this.request({ + method: "POST", + path: joinPaths(basePath18, oauthApplicationId, "rotate_secret") + }); + } +}; + +// src/api/endpoints/PhoneNumberApi.ts +var basePath19 = "/phone_numbers"; +var PhoneNumberAPI = class extends AbstractAPI { + async getPhoneNumber(phoneNumberId) { + this.requireId(phoneNumberId); + return this.request({ + method: "GET", + path: joinPaths(basePath19, phoneNumberId) + }); + } + async createPhoneNumber(params) { + return this.request({ + method: "POST", + path: basePath19, + bodyParams: params + }); + } + async updatePhoneNumber(phoneNumberId, params = {}) { + this.requireId(phoneNumberId); + return this.request({ + method: "PATCH", + path: joinPaths(basePath19, phoneNumberId), + bodyParams: params + }); + } + async deletePhoneNumber(phoneNumberId) { + this.requireId(phoneNumberId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath19, phoneNumberId) + }); + } +}; + +// src/api/endpoints/ProxyCheckApi.ts +var basePath20 = "/proxy_checks"; +var ProxyCheckAPI = class extends AbstractAPI { + async verify(params) { + return this.request({ + method: "POST", + path: basePath20, + bodyParams: params + }); + } +}; + +// src/api/endpoints/RedirectUrlApi.ts +var basePath21 = "/redirect_urls"; +var RedirectUrlAPI = class extends AbstractAPI { + async getRedirectUrlList() { + return this.request({ + method: "GET", + path: basePath21, + queryParams: { paginated: true } + }); + } + async getRedirectUrl(redirectUrlId) { + this.requireId(redirectUrlId); + return this.request({ + method: "GET", + path: joinPaths(basePath21, redirectUrlId) + }); + } + async createRedirectUrl(params) { + return this.request({ + method: "POST", + path: basePath21, + bodyParams: params + }); + } + async deleteRedirectUrl(redirectUrlId) { + this.requireId(redirectUrlId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath21, redirectUrlId) + }); + } +}; + +// src/api/endpoints/SamlConnectionApi.ts +var basePath22 = "/saml_connections"; +var SamlConnectionAPI = class extends AbstractAPI { + async getSamlConnectionList(params = {}) { + return this.request({ + method: "GET", + path: basePath22, + queryParams: params + }); + } + async createSamlConnection(params) { + return this.request({ + method: "POST", + path: basePath22, + bodyParams: params, + options: { + deepSnakecaseBodyParamKeys: true + } + }); + } + async getSamlConnection(samlConnectionId) { + this.requireId(samlConnectionId); + return this.request({ + method: "GET", + path: joinPaths(basePath22, samlConnectionId) + }); + } + async updateSamlConnection(samlConnectionId, params = {}) { + this.requireId(samlConnectionId); + return this.request({ + method: "PATCH", + path: joinPaths(basePath22, samlConnectionId), + bodyParams: params, + options: { + deepSnakecaseBodyParamKeys: true + } + }); + } + async deleteSamlConnection(samlConnectionId) { + this.requireId(samlConnectionId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath22, samlConnectionId) + }); + } +}; + +// src/api/endpoints/SessionApi.ts +var basePath23 = "/sessions"; +var SessionAPI = class extends AbstractAPI { + async getSessionList(params = {}) { + return this.request({ + method: "GET", + path: basePath23, + queryParams: { ...params, paginated: true } + }); + } + async getSession(sessionId) { + this.requireId(sessionId); + return this.request({ + method: "GET", + path: joinPaths(basePath23, sessionId) + }); + } + async createSession(params) { + return this.request({ + method: "POST", + path: basePath23, + bodyParams: params + }); + } + async revokeSession(sessionId) { + this.requireId(sessionId); + return this.request({ + method: "POST", + path: joinPaths(basePath23, sessionId, "revoke") + }); + } + async verifySession(sessionId, token) { + this.requireId(sessionId); + return this.request({ + method: "POST", + path: joinPaths(basePath23, sessionId, "verify"), + bodyParams: { token } + }); + } + /** + * Retrieves a session token or generates a JWT using a specified template. + * + * @param sessionId - The ID of the session for which to generate the token + * @param template - Optional name of the JWT template configured in the Clerk Dashboard. + * @param expiresInSeconds - Optional expiration time for the token in seconds. + * If not provided, uses the default expiration. + * + * @returns A promise that resolves to the generated token + * + * @throws {Error} When sessionId is invalid or empty + */ + async getToken(sessionId, template, expiresInSeconds) { + this.requireId(sessionId); + const path = template ? joinPaths(basePath23, sessionId, "tokens", template) : joinPaths(basePath23, sessionId, "tokens"); + const requestOptions = { + method: "POST", + path + }; + if (expiresInSeconds !== void 0) { + requestOptions.bodyParams = { expires_in_seconds: expiresInSeconds }; + } + return this.request(requestOptions); + } + async refreshSession(sessionId, params) { + this.requireId(sessionId); + const { suffixed_cookies, ...restParams } = params; + return this.request({ + method: "POST", + path: joinPaths(basePath23, sessionId, "refresh"), + bodyParams: restParams, + queryParams: { suffixed_cookies } + }); + } +}; + +// src/api/endpoints/SignInTokenApi.ts +var basePath24 = "/sign_in_tokens"; +var SignInTokenAPI = class extends AbstractAPI { + async createSignInToken(params) { + return this.request({ + method: "POST", + path: basePath24, + bodyParams: params + }); + } + async revokeSignInToken(signInTokenId) { + this.requireId(signInTokenId); + return this.request({ + method: "POST", + path: joinPaths(basePath24, signInTokenId, "revoke") + }); + } +}; + +// src/api/endpoints/SignUpApi.ts +var basePath25 = "/sign_ups"; +var SignUpAPI = class extends AbstractAPI { + async get(signUpAttemptId) { + this.requireId(signUpAttemptId); + return this.request({ + method: "GET", + path: joinPaths(basePath25, signUpAttemptId) + }); + } + async update(params) { + const { signUpAttemptId, ...bodyParams } = params; + return this.request({ + method: "PATCH", + path: joinPaths(basePath25, signUpAttemptId), + bodyParams + }); + } +}; + +// src/api/endpoints/TestingTokenApi.ts +var basePath26 = "/testing_tokens"; +var TestingTokenAPI = class extends AbstractAPI { + async createTestingToken() { + return this.request({ + method: "POST", + path: basePath26 + }); + } +}; + +// src/api/endpoints/UserApi.ts +var basePath27 = "/users"; +var UserAPI = class extends AbstractAPI { + async getUserList(params = {}) { + const { limit, offset, orderBy, ...userCountParams } = params; + const [data, totalCount] = await Promise.all([ + this.request({ + method: "GET", + path: basePath27, + queryParams: params + }), + this.getCount(userCountParams) + ]); + return { data, totalCount }; + } + async getUser(userId) { + this.requireId(userId); + return this.request({ + method: "GET", + path: joinPaths(basePath27, userId) + }); + } + async createUser(params) { + return this.request({ + method: "POST", + path: basePath27, + bodyParams: params + }); + } + async updateUser(userId, params = {}) { + this.requireId(userId); + return this.request({ + method: "PATCH", + path: joinPaths(basePath27, userId), + bodyParams: params + }); + } + async updateUserProfileImage(userId, params) { + this.requireId(userId); + const formData = new runtime.FormData(); + formData.append("file", params?.file); + return this.request({ + method: "POST", + path: joinPaths(basePath27, userId, "profile_image"), + formData + }); + } + async updateUserMetadata(userId, params) { + this.requireId(userId); + return this.request({ + method: "PATCH", + path: joinPaths(basePath27, userId, "metadata"), + bodyParams: params + }); + } + async deleteUser(userId) { + this.requireId(userId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath27, userId) + }); + } + async getCount(params = {}) { + return this.request({ + method: "GET", + path: joinPaths(basePath27, "count"), + queryParams: params + }); + } + async getUserOauthAccessToken(userId, provider) { + this.requireId(userId); + const hasPrefix = provider.startsWith("oauth_"); + const _provider = hasPrefix ? provider : `oauth_${provider}`; + if (hasPrefix) { + (0, import_deprecated.deprecated)( + "getUserOauthAccessToken(userId, provider)", + "Remove the `oauth_` prefix from the `provider` argument." + ); + } + return this.request({ + method: "GET", + path: joinPaths(basePath27, userId, "oauth_access_tokens", _provider), + queryParams: { paginated: true } + }); + } + async disableUserMFA(userId) { + this.requireId(userId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath27, userId, "mfa") + }); + } + async getOrganizationMembershipList(params) { + const { userId, limit, offset } = params; + this.requireId(userId); + return this.request({ + method: "GET", + path: joinPaths(basePath27, userId, "organization_memberships"), + queryParams: { limit, offset } + }); + } + async getOrganizationInvitationList(params) { + const { userId, ...queryParams } = params; + this.requireId(userId); + return this.request({ + method: "GET", + path: joinPaths(basePath27, userId, "organization_invitations"), + queryParams + }); + } + async verifyPassword(params) { + const { userId, password } = params; + this.requireId(userId); + return this.request({ + method: "POST", + path: joinPaths(basePath27, userId, "verify_password"), + bodyParams: { password } + }); + } + async verifyTOTP(params) { + const { userId, code } = params; + this.requireId(userId); + return this.request({ + method: "POST", + path: joinPaths(basePath27, userId, "verify_totp"), + bodyParams: { code } + }); + } + async banUser(userId) { + this.requireId(userId); + return this.request({ + method: "POST", + path: joinPaths(basePath27, userId, "ban") + }); + } + async unbanUser(userId) { + this.requireId(userId); + return this.request({ + method: "POST", + path: joinPaths(basePath27, userId, "unban") + }); + } + async lockUser(userId) { + this.requireId(userId); + return this.request({ + method: "POST", + path: joinPaths(basePath27, userId, "lock") + }); + } + async unlockUser(userId) { + this.requireId(userId); + return this.request({ + method: "POST", + path: joinPaths(basePath27, userId, "unlock") + }); + } + async deleteUserProfileImage(userId) { + this.requireId(userId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath27, userId, "profile_image") + }); + } + async deleteUserPasskey(params) { + this.requireId(params.userId); + this.requireId(params.passkeyIdentificationId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath27, params.userId, "passkeys", params.passkeyIdentificationId) + }); + } + async deleteUserWeb3Wallet(params) { + this.requireId(params.userId); + this.requireId(params.web3WalletIdentificationId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath27, params.userId, "web3_wallets", params.web3WalletIdentificationId) + }); + } + async deleteUserExternalAccount(params) { + this.requireId(params.userId); + this.requireId(params.externalAccountId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath27, params.userId, "external_accounts", params.externalAccountId) + }); + } + async deleteUserBackupCodes(userId) { + this.requireId(userId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath27, userId, "backup_code") + }); + } + async deleteUserTOTP(userId) { + this.requireId(userId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath27, userId, "totp") + }); + } +}; + +// src/api/endpoints/WaitlistEntryApi.ts +var basePath28 = "/waitlist_entries"; +var WaitlistEntryAPI = class extends AbstractAPI { + /** + * List waitlist entries. + * @param params Optional parameters (e.g., `query`, `status`, `orderBy`). + */ + async list(params = {}) { + return this.request({ + method: "GET", + path: basePath28, + queryParams: params + }); + } + /** + * Create a waitlist entry. + * @param params The parameters for creating a waitlist entry. + */ + async create(params) { + return this.request({ + method: "POST", + path: basePath28, + bodyParams: params + }); + } + /** + * Invite a waitlist entry. + * @param id The waitlist entry ID. + * @param params Optional parameters (e.g., `ignoreExisting`). + */ + async invite(id, params = {}) { + this.requireId(id); + return this.request({ + method: "POST", + path: joinPaths(basePath28, id, "invite"), + bodyParams: params + }); + } + /** + * Reject a waitlist entry. + * @param id The waitlist entry ID. + */ + async reject(id) { + this.requireId(id); + return this.request({ + method: "POST", + path: joinPaths(basePath28, id, "reject") + }); + } + /** + * Delete a waitlist entry. + * @param id The waitlist entry ID. + */ + async delete(id) { + this.requireId(id); + return this.request({ + method: "DELETE", + path: joinPaths(basePath28, id) + }); + } +}; + +// src/api/endpoints/WebhookApi.ts +var basePath29 = "/webhooks"; +var WebhookAPI = class extends AbstractAPI { + async createSvixApp() { + return this.request({ + method: "POST", + path: joinPaths(basePath29, "svix") + }); + } + async generateSvixAuthURL() { + return this.request({ + method: "POST", + path: joinPaths(basePath29, "svix_url") + }); + } + async deleteSvixApp() { + return this.request({ + method: "DELETE", + path: joinPaths(basePath29, "svix") + }); + } +}; + +// src/api/endpoints/BillingApi.ts +var basePath30 = "/commerce"; +var organizationBasePath = "/organizations"; +var userBasePath = "/users"; +var BillingAPI = class extends AbstractAPI { + /** + * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. + */ + async getPlanList(params) { + return this.request({ + method: "GET", + path: joinPaths(basePath30, "plans"), + queryParams: params + }); + } + /** + * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. + */ + async cancelSubscriptionItem(subscriptionItemId, params) { + this.requireId(subscriptionItemId); + return this.request({ + method: "DELETE", + path: joinPaths(basePath30, "subscription_items", subscriptionItemId), + queryParams: params + }); + } + /** + * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. + */ + async extendSubscriptionItemFreeTrial(subscriptionItemId, params) { + this.requireId(subscriptionItemId); + return this.request({ + method: "POST", + path: joinPaths("/billing", "subscription_items", subscriptionItemId, "extend_free_trial"), + bodyParams: params + }); + } + /** + * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. + */ + async getOrganizationBillingSubscription(organizationId) { + this.requireId(organizationId); + return this.request({ + method: "GET", + path: joinPaths(organizationBasePath, organizationId, "billing", "subscription") + }); + } + /** + * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. + */ + async getUserBillingSubscription(userId) { + this.requireId(userId); + return this.request({ + method: "GET", + path: joinPaths(userBasePath, userId, "billing", "subscription") + }); + } +}; + +// src/api/request.ts +var import_error2 = require("@clerk/shared/error"); + +// ../../node_modules/.pnpm/map-obj@5.0.2/node_modules/map-obj/index.js +var isObject = (value) => typeof value === "object" && value !== null; +var isObjectCustom = (value) => isObject(value) && !(value instanceof RegExp) && !(value instanceof Error) && !(value instanceof Date) && !(globalThis.Blob && value instanceof globalThis.Blob); +var mapObjectSkip = Symbol("mapObjectSkip"); +var _mapObject = (object, mapper, options, isSeen = /* @__PURE__ */ new WeakMap()) => { + options = { + deep: false, + target: {}, + ...options + }; + if (isSeen.has(object)) { + return isSeen.get(object); + } + isSeen.set(object, options.target); + const { target } = options; + delete options.target; + const mapArray = (array) => array.map((element) => isObjectCustom(element) ? _mapObject(element, mapper, options, isSeen) : element); + if (Array.isArray(object)) { + return mapArray(object); + } + for (const [key, value] of Object.entries(object)) { + const mapResult = mapper(key, value, object); + if (mapResult === mapObjectSkip) { + continue; + } + let [newKey, newValue, { shouldRecurse = true } = {}] = mapResult; + if (newKey === "__proto__") { + continue; + } + if (options.deep && shouldRecurse && isObjectCustom(newValue)) { + newValue = Array.isArray(newValue) ? mapArray(newValue) : _mapObject(newValue, mapper, options, isSeen); + } + target[newKey] = newValue; + } + return target; +}; +function mapObject(object, mapper, options) { + if (!isObject(object)) { + throw new TypeError(`Expected an object, got \`${object}\` (${typeof object})`); + } + if (Array.isArray(object)) { + throw new TypeError("Expected an object, got an array"); + } + return _mapObject(object, mapper, options); +} + +// ../../node_modules/.pnpm/change-case@5.4.4/node_modules/change-case/dist/index.js +var SPLIT_LOWER_UPPER_RE = /([\p{Ll}\d])(\p{Lu})/gu; +var SPLIT_UPPER_UPPER_RE = /(\p{Lu})([\p{Lu}][\p{Ll}])/gu; +var SPLIT_SEPARATE_NUMBER_RE = /(\d)\p{Ll}|(\p{L})\d/u; +var DEFAULT_STRIP_REGEXP = /[^\p{L}\d]+/giu; +var SPLIT_REPLACE_VALUE = "$1\0$2"; +var DEFAULT_PREFIX_SUFFIX_CHARACTERS = ""; +function split(value) { + let result = value.trim(); + result = result.replace(SPLIT_LOWER_UPPER_RE, SPLIT_REPLACE_VALUE).replace(SPLIT_UPPER_UPPER_RE, SPLIT_REPLACE_VALUE); + result = result.replace(DEFAULT_STRIP_REGEXP, "\0"); + let start = 0; + let end = result.length; + while (result.charAt(start) === "\0") + start++; + if (start === end) + return []; + while (result.charAt(end - 1) === "\0") + end--; + return result.slice(start, end).split(/\0/g); +} +function splitSeparateNumbers(value) { + const words = split(value); + for (let i = 0; i < words.length; i++) { + const word = words[i]; + const match2 = SPLIT_SEPARATE_NUMBER_RE.exec(word); + if (match2) { + const offset = match2.index + (match2[1] ?? match2[2]).length; + words.splice(i, 1, word.slice(0, offset), word.slice(offset)); + } + } + return words; +} +function noCase(input, options) { + const [prefix, words, suffix] = splitPrefixSuffix(input, options); + return prefix + words.map(lowerFactory(options?.locale)).join(options?.delimiter ?? " ") + suffix; +} +function snakeCase(input, options) { + return noCase(input, { delimiter: "_", ...options }); +} +function lowerFactory(locale) { + return locale === false ? (input) => input.toLowerCase() : (input) => input.toLocaleLowerCase(locale); +} +function splitPrefixSuffix(input, options = {}) { + const splitFn = options.split ?? (options.separateNumbers ? splitSeparateNumbers : split); + const prefixCharacters = options.prefixCharacters ?? DEFAULT_PREFIX_SUFFIX_CHARACTERS; + const suffixCharacters = options.suffixCharacters ?? DEFAULT_PREFIX_SUFFIX_CHARACTERS; + let prefixIndex = 0; + let suffixIndex = input.length; + while (prefixIndex < input.length) { + const char = input.charAt(prefixIndex); + if (!prefixCharacters.includes(char)) + break; + prefixIndex++; + } + while (suffixIndex > prefixIndex) { + const index = suffixIndex - 1; + const char = input.charAt(index); + if (!suffixCharacters.includes(char)) + break; + suffixIndex = index; + } + return [ + input.slice(0, prefixIndex), + splitFn(input.slice(prefixIndex, suffixIndex)), + input.slice(suffixIndex) + ]; +} + +// ../../node_modules/.pnpm/snakecase-keys@9.0.2/node_modules/snakecase-keys/index.js +var PlainObjectConstructor = {}.constructor; +function snakecaseKeys(obj, options) { + if (Array.isArray(obj)) { + if (obj.some((item) => item.constructor !== PlainObjectConstructor)) { + throw new Error("obj must be array of plain objects"); + } + options = { deep: true, exclude: [], parsingOptions: {}, ...options }; + const convertCase2 = options.snakeCase || ((key) => snakeCase(key, options.parsingOptions)); + return obj.map((item) => { + return mapObject(item, (key, val) => { + return [ + matches(options.exclude, key) ? key : convertCase2(key), + val, + mapperOptions(key, val, options) + ]; + }, options); + }); + } else { + if (obj.constructor !== PlainObjectConstructor) { + throw new Error("obj must be an plain object"); + } + } + options = { deep: true, exclude: [], parsingOptions: {}, ...options }; + const convertCase = options.snakeCase || ((key) => snakeCase(key, options.parsingOptions)); + return mapObject(obj, (key, val) => { + return [ + matches(options.exclude, key) ? key : convertCase(key), + val, + mapperOptions(key, val, options) + ]; + }, options); +} +function matches(patterns, value) { + return patterns.some((pattern) => { + return typeof pattern === "string" ? pattern === value : pattern.test(value); + }); +} +function mapperOptions(key, val, options) { + return options.shouldRecurse ? { shouldRecurse: options.shouldRecurse(key, val) } : void 0; +} +var snakecase_keys_default = snakecaseKeys; + +// src/api/resources/AccountlessApplication.ts +var AccountlessApplication = class _AccountlessApplication { + constructor(publishableKey, secretKey, claimUrl, apiKeysUrl) { + this.publishableKey = publishableKey; + this.secretKey = secretKey; + this.claimUrl = claimUrl; + this.apiKeysUrl = apiKeysUrl; + } + static fromJSON(data) { + return new _AccountlessApplication(data.publishable_key, data.secret_key, data.claim_url, data.api_keys_url); + } +}; + +// src/api/resources/ActorToken.ts +var ActorToken = class _ActorToken { + constructor(id, status, userId, actor, token, url, createdAt, updatedAt) { + this.id = id; + this.status = status; + this.userId = userId; + this.actor = actor; + this.token = token; + this.url = url; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + } + static fromJSON(data) { + return new _ActorToken( + data.id, + data.status, + data.user_id, + data.actor, + data.token, + data.url, + data.created_at, + data.updated_at + ); + } +}; + +// src/api/resources/AllowlistIdentifier.ts +var AllowlistIdentifier = class _AllowlistIdentifier { + constructor(id, identifier, identifierType, createdAt, updatedAt, instanceId, invitationId) { + this.id = id; + this.identifier = identifier; + this.identifierType = identifierType; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + this.instanceId = instanceId; + this.invitationId = invitationId; + } + static fromJSON(data) { + return new _AllowlistIdentifier( + data.id, + data.identifier, + data.identifier_type, + data.created_at, + data.updated_at, + data.instance_id, + data.invitation_id + ); + } +}; + +// src/api/resources/APIKey.ts +var APIKey = class _APIKey { + constructor(id, type, name, subject, scopes, claims, revoked, revocationReason, expired, expiration, createdBy, description, lastUsedAt, createdAt, updatedAt, secret) { + this.id = id; + this.type = type; + this.name = name; + this.subject = subject; + this.scopes = scopes; + this.claims = claims; + this.revoked = revoked; + this.revocationReason = revocationReason; + this.expired = expired; + this.expiration = expiration; + this.createdBy = createdBy; + this.description = description; + this.lastUsedAt = lastUsedAt; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + this.secret = secret; + } + static fromJSON(data) { + return new _APIKey( + data.id, + data.type, + data.name, + data.subject, + data.scopes, + data.claims, + data.revoked, + data.revocation_reason, + data.expired, + data.expiration, + data.created_by, + data.description, + data.last_used_at, + data.created_at, + data.updated_at, + data.secret + ); + } +}; + +// src/api/resources/BlocklistIdentifier.ts +var BlocklistIdentifier = class _BlocklistIdentifier { + constructor(id, identifier, identifierType, createdAt, updatedAt, instanceId) { + this.id = id; + this.identifier = identifier; + this.identifierType = identifierType; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + this.instanceId = instanceId; + } + static fromJSON(data) { + return new _BlocklistIdentifier( + data.id, + data.identifier, + data.identifier_type, + data.created_at, + data.updated_at, + data.instance_id + ); + } +}; + +// src/api/resources/Session.ts +var SessionActivity = class _SessionActivity { + constructor(id, isMobile, ipAddress, city, country, browserVersion, browserName, deviceType) { + this.id = id; + this.isMobile = isMobile; + this.ipAddress = ipAddress; + this.city = city; + this.country = country; + this.browserVersion = browserVersion; + this.browserName = browserName; + this.deviceType = deviceType; + } + static fromJSON(data) { + return new _SessionActivity( + data.id, + data.is_mobile, + data.ip_address, + data.city, + data.country, + data.browser_version, + data.browser_name, + data.device_type + ); + } +}; +var Session = class _Session { + constructor(id, clientId, userId, status, lastActiveAt, expireAt, abandonAt, createdAt, updatedAt, lastActiveOrganizationId, latestActivity, actor = null) { + this.id = id; + this.clientId = clientId; + this.userId = userId; + this.status = status; + this.lastActiveAt = lastActiveAt; + this.expireAt = expireAt; + this.abandonAt = abandonAt; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + this.lastActiveOrganizationId = lastActiveOrganizationId; + this.latestActivity = latestActivity; + this.actor = actor; + } + static fromJSON(data) { + return new _Session( + data.id, + data.client_id, + data.user_id, + data.status, + data.last_active_at, + data.expire_at, + data.abandon_at, + data.created_at, + data.updated_at, + data.last_active_organization_id, + data.latest_activity && SessionActivity.fromJSON(data.latest_activity), + data.actor + ); + } +}; + +// src/api/resources/Client.ts +var Client = class _Client { + constructor(id, sessionIds, sessions, signInId, signUpId, lastActiveSessionId, lastAuthenticationStrategy, createdAt, updatedAt) { + this.id = id; + this.sessionIds = sessionIds; + this.sessions = sessions; + this.signInId = signInId; + this.signUpId = signUpId; + this.lastActiveSessionId = lastActiveSessionId; + this.lastAuthenticationStrategy = lastAuthenticationStrategy; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + } + static fromJSON(data) { + return new _Client( + data.id, + data.session_ids, + data.sessions.map((x) => Session.fromJSON(x)), + data.sign_in_id, + data.sign_up_id, + data.last_active_session_id, + data.last_authentication_strategy, + data.created_at, + data.updated_at + ); + } +}; + +// src/api/resources/CnameTarget.ts +var CnameTarget = class _CnameTarget { + constructor(host, value, required) { + this.host = host; + this.value = value; + this.required = required; + } + static fromJSON(data) { + return new _CnameTarget(data.host, data.value, data.required); + } +}; + +// src/api/resources/Cookies.ts +var Cookies2 = class _Cookies { + constructor(cookies) { + this.cookies = cookies; + } + static fromJSON(data) { + return new _Cookies(data.cookies); + } +}; + +// src/api/resources/DeletedObject.ts +var DeletedObject = class _DeletedObject { + constructor(object, id, slug, deleted) { + this.object = object; + this.id = id; + this.slug = slug; + this.deleted = deleted; + } + static fromJSON(data) { + return new _DeletedObject(data.object, data.id || null, data.slug || null, data.deleted); + } +}; + +// src/api/resources/Domain.ts +var Domain = class _Domain { + constructor(id, name, isSatellite, frontendApiUrl, developmentOrigin, cnameTargets, accountsPortalUrl, proxyUrl) { + this.id = id; + this.name = name; + this.isSatellite = isSatellite; + this.frontendApiUrl = frontendApiUrl; + this.developmentOrigin = developmentOrigin; + this.cnameTargets = cnameTargets; + this.accountsPortalUrl = accountsPortalUrl; + this.proxyUrl = proxyUrl; + } + static fromJSON(data) { + return new _Domain( + data.id, + data.name, + data.is_satellite, + data.frontend_api_url, + data.development_origin, + data.cname_targets && data.cname_targets.map((x) => CnameTarget.fromJSON(x)), + data.accounts_portal_url, + data.proxy_url + ); + } +}; + +// src/api/resources/Email.ts +var Email = class _Email { + constructor(id, fromEmailName, emailAddressId, toEmailAddress, subject, body, bodyPlain, status, slug, data, deliveredByClerk) { + this.id = id; + this.fromEmailName = fromEmailName; + this.emailAddressId = emailAddressId; + this.toEmailAddress = toEmailAddress; + this.subject = subject; + this.body = body; + this.bodyPlain = bodyPlain; + this.status = status; + this.slug = slug; + this.data = data; + this.deliveredByClerk = deliveredByClerk; + } + static fromJSON(data) { + return new _Email( + data.id, + data.from_email_name, + data.email_address_id, + data.to_email_address, + data.subject, + data.body, + data.body_plain, + data.status, + data.slug, + data.data, + data.delivered_by_clerk + ); + } +}; + +// src/api/resources/IdentificationLink.ts +var IdentificationLink = class _IdentificationLink { + constructor(id, type) { + this.id = id; + this.type = type; + } + static fromJSON(data) { + return new _IdentificationLink(data.id, data.type); + } +}; + +// src/api/resources/Verification.ts +var Verification = class _Verification { + constructor(status, strategy, externalVerificationRedirectURL = null, attempts = null, expireAt = null, nonce = null, message = null) { + this.status = status; + this.strategy = strategy; + this.externalVerificationRedirectURL = externalVerificationRedirectURL; + this.attempts = attempts; + this.expireAt = expireAt; + this.nonce = nonce; + this.message = message; + } + static fromJSON(data) { + return new _Verification( + data.status, + data.strategy, + data.external_verification_redirect_url ? new URL(data.external_verification_redirect_url) : null, + data.attempts, + data.expire_at, + data.nonce + ); + } +}; + +// src/api/resources/EmailAddress.ts +var EmailAddress = class _EmailAddress { + constructor(id, emailAddress, verification, linkedTo) { + this.id = id; + this.emailAddress = emailAddress; + this.verification = verification; + this.linkedTo = linkedTo; + } + static fromJSON(data) { + return new _EmailAddress( + data.id, + data.email_address, + data.verification && Verification.fromJSON(data.verification), + data.linked_to.map((link) => IdentificationLink.fromJSON(link)) + ); + } +}; + +// src/api/resources/ExternalAccount.ts +var ExternalAccount = class _ExternalAccount { + constructor(id, provider, identificationId, externalId, approvedScopes, emailAddress, firstName, lastName, imageUrl, username, phoneNumber, publicMetadata = {}, label, verification) { + this.id = id; + this.provider = provider; + this.identificationId = identificationId; + this.externalId = externalId; + this.approvedScopes = approvedScopes; + this.emailAddress = emailAddress; + this.firstName = firstName; + this.lastName = lastName; + this.imageUrl = imageUrl; + this.username = username; + this.phoneNumber = phoneNumber; + this.publicMetadata = publicMetadata; + this.label = label; + this.verification = verification; + } + static fromJSON(data) { + return new _ExternalAccount( + data.id, + data.provider, + data.identification_id, + data.provider_user_id, + data.approved_scopes, + data.email_address, + data.first_name, + data.last_name, + data.image_url || "", + data.username, + data.phone_number, + data.public_metadata, + data.label, + data.verification && Verification.fromJSON(data.verification) + ); + } +}; + +// src/api/resources/IdPOAuthAccessToken.ts +var IdPOAuthAccessToken = class _IdPOAuthAccessToken { + constructor(id, clientId, type, subject, scopes, revoked, revocationReason, expired, expiration, createdAt, updatedAt) { + this.id = id; + this.clientId = clientId; + this.type = type; + this.subject = subject; + this.scopes = scopes; + this.revoked = revoked; + this.revocationReason = revocationReason; + this.expired = expired; + this.expiration = expiration; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + } + static fromJSON(data) { + return new _IdPOAuthAccessToken( + data.id, + data.client_id, + data.type, + data.subject, + data.scopes, + data.revoked, + data.revocation_reason, + data.expired, + data.expiration, + data.created_at, + data.updated_at + ); + } +}; + +// src/api/resources/Instance.ts +var Instance = class _Instance { + constructor(id, environmentType, allowedOrigins) { + this.id = id; + this.environmentType = environmentType; + this.allowedOrigins = allowedOrigins; + } + static fromJSON(data) { + return new _Instance(data.id, data.environment_type, data.allowed_origins); + } +}; + +// src/api/resources/InstanceRestrictions.ts +var InstanceRestrictions = class _InstanceRestrictions { + constructor(allowlist, blocklist, blockEmailSubaddresses, blockDisposableEmailDomains, ignoreDotsForGmailAddresses) { + this.allowlist = allowlist; + this.blocklist = blocklist; + this.blockEmailSubaddresses = blockEmailSubaddresses; + this.blockDisposableEmailDomains = blockDisposableEmailDomains; + this.ignoreDotsForGmailAddresses = ignoreDotsForGmailAddresses; + } + static fromJSON(data) { + return new _InstanceRestrictions( + data.allowlist, + data.blocklist, + data.block_email_subaddresses, + data.block_disposable_email_domains, + data.ignore_dots_for_gmail_addresses + ); + } +}; + +// src/api/resources/InstanceSettings.ts +var InstanceSettings = class _InstanceSettings { + constructor(id, restrictedToAllowlist, fromEmailAddress, progressiveSignUp, enhancedEmailDeliverability) { + this.id = id; + this.restrictedToAllowlist = restrictedToAllowlist; + this.fromEmailAddress = fromEmailAddress; + this.progressiveSignUp = progressiveSignUp; + this.enhancedEmailDeliverability = enhancedEmailDeliverability; + } + static fromJSON(data) { + return new _InstanceSettings( + data.id, + data.restricted_to_allowlist, + data.from_email_address, + data.progressive_sign_up, + data.enhanced_email_deliverability + ); + } +}; + +// src/api/resources/Invitation.ts +var Invitation = class _Invitation { + constructor(id, emailAddress, publicMetadata, createdAt, updatedAt, status, url, revoked) { + this.id = id; + this.emailAddress = emailAddress; + this.publicMetadata = publicMetadata; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + this.status = status; + this.url = url; + this.revoked = revoked; + this._raw = null; + } + get raw() { + return this._raw; + } + static fromJSON(data) { + const res = new _Invitation( + data.id, + data.email_address, + data.public_metadata, + data.created_at, + data.updated_at, + data.status, + data.url, + data.revoked + ); + res._raw = data; + return res; + } +}; + +// src/api/resources/JSON.ts +var ObjectType = { + AccountlessApplication: "accountless_application", + ActorToken: "actor_token", + AllowlistIdentifier: "allowlist_identifier", + ApiKey: "api_key", + BlocklistIdentifier: "blocklist_identifier", + Client: "client", + Cookies: "cookies", + Domain: "domain", + Email: "email", + EmailAddress: "email_address", + ExternalAccount: "external_account", + FacebookAccount: "facebook_account", + GoogleAccount: "google_account", + Instance: "instance", + InstanceRestrictions: "instance_restrictions", + InstanceSettings: "instance_settings", + Invitation: "invitation", + Machine: "machine", + MachineScope: "machine_scope", + MachineSecretKey: "machine_secret_key", + M2MToken: "machine_to_machine_token", + JwtTemplate: "jwt_template", + OauthAccessToken: "oauth_access_token", + IdpOAuthAccessToken: "clerk_idp_oauth_access_token", + OAuthApplication: "oauth_application", + Organization: "organization", + OrganizationDomain: "organization_domain", + OrganizationInvitation: "organization_invitation", + OrganizationMembership: "organization_membership", + OrganizationSettings: "organization_settings", + PhoneNumber: "phone_number", + ProxyCheck: "proxy_check", + RedirectUrl: "redirect_url", + SamlAccount: "saml_account", + SamlConnection: "saml_connection", + Session: "session", + SignInAttempt: "sign_in_attempt", + SignInToken: "sign_in_token", + SignUpAttempt: "sign_up_attempt", + SmsMessage: "sms_message", + User: "user", + WaitlistEntry: "waitlist_entry", + Web3Wallet: "web3_wallet", + Token: "token", + TotalCount: "total_count", + TestingToken: "testing_token", + Role: "role", + Permission: "permission", + BillingPayer: "commerce_payer", + BillingPaymentAttempt: "commerce_payment_attempt", + BillingSubscription: "commerce_subscription", + BillingSubscriptionItem: "commerce_subscription_item", + BillingPlan: "commerce_plan", + Feature: "feature" +}; + +// src/api/resources/Machine.ts +var Machine = class _Machine { + constructor(id, name, instanceId, createdAt, updatedAt, scopedMachines, defaultTokenTtl, secretKey) { + this.id = id; + this.name = name; + this.instanceId = instanceId; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + this.scopedMachines = scopedMachines; + this.defaultTokenTtl = defaultTokenTtl; + this.secretKey = secretKey; + } + static fromJSON(data) { + return new _Machine( + data.id, + data.name, + data.instance_id, + data.created_at, + data.updated_at, + data.scoped_machines.map( + (m) => new _Machine( + m.id, + m.name, + m.instance_id, + m.created_at, + m.updated_at, + [], + // Nested machines don't have scoped_machines + m.default_token_ttl + ) + ), + data.default_token_ttl, + data.secret_key + ); + } +}; + +// src/api/resources/MachineScope.ts +var MachineScope = class _MachineScope { + constructor(fromMachineId, toMachineId, createdAt, deleted) { + this.fromMachineId = fromMachineId; + this.toMachineId = toMachineId; + this.createdAt = createdAt; + this.deleted = deleted; + } + static fromJSON(data) { + return new _MachineScope(data.from_machine_id, data.to_machine_id, data.created_at, data.deleted); + } +}; + +// src/api/resources/MachineSecretKey.ts +var MachineSecretKey = class _MachineSecretKey { + constructor(secret) { + this.secret = secret; + } + static fromJSON(data) { + return new _MachineSecretKey(data.secret); + } +}; + +// src/api/resources/M2MToken.ts +var M2MToken = class _M2MToken { + constructor(id, subject, scopes, claims, revoked, revocationReason, expired, expiration, createdAt, updatedAt, token) { + this.id = id; + this.subject = subject; + this.scopes = scopes; + this.claims = claims; + this.revoked = revoked; + this.revocationReason = revocationReason; + this.expired = expired; + this.expiration = expiration; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + this.token = token; + } + static fromJSON(data) { + return new _M2MToken( + data.id, + data.subject, + data.scopes, + data.claims, + data.revoked, + data.revocation_reason, + data.expired, + data.expiration, + data.created_at, + data.updated_at, + data.token + ); + } +}; + +// src/api/resources/JwtTemplate.ts +var JwtTemplate = class _JwtTemplate { + constructor(id, name, claims, lifetime, allowedClockSkew, customSigningKey, signingAlgorithm, createdAt, updatedAt) { + this.id = id; + this.name = name; + this.claims = claims; + this.lifetime = lifetime; + this.allowedClockSkew = allowedClockSkew; + this.customSigningKey = customSigningKey; + this.signingAlgorithm = signingAlgorithm; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + } + static fromJSON(data) { + return new _JwtTemplate( + data.id, + data.name, + data.claims, + data.lifetime, + data.allowed_clock_skew, + data.custom_signing_key, + data.signing_algorithm, + data.created_at, + data.updated_at + ); + } +}; + +// src/api/resources/OauthAccessToken.ts +var OauthAccessToken = class _OauthAccessToken { + constructor(externalAccountId, provider, token, publicMetadata = {}, label, scopes, tokenSecret, expiresAt) { + this.externalAccountId = externalAccountId; + this.provider = provider; + this.token = token; + this.publicMetadata = publicMetadata; + this.label = label; + this.scopes = scopes; + this.tokenSecret = tokenSecret; + this.expiresAt = expiresAt; + } + static fromJSON(data) { + return new _OauthAccessToken( + data.external_account_id, + data.provider, + data.token, + data.public_metadata, + data.label || "", + data.scopes, + data.token_secret, + data.expires_at + ); + } +}; + +// src/api/resources/OAuthApplication.ts +var OAuthApplication = class _OAuthApplication { + constructor(id, instanceId, name, clientId, clientUri, clientImageUrl, dynamicallyRegistered, consentScreenEnabled, pkceRequired, isPublic, scopes, redirectUris, authorizeUrl, tokenFetchUrl, userInfoUrl, discoveryUrl, tokenIntrospectionUrl, createdAt, updatedAt, clientSecret) { + this.id = id; + this.instanceId = instanceId; + this.name = name; + this.clientId = clientId; + this.clientUri = clientUri; + this.clientImageUrl = clientImageUrl; + this.dynamicallyRegistered = dynamicallyRegistered; + this.consentScreenEnabled = consentScreenEnabled; + this.pkceRequired = pkceRequired; + this.isPublic = isPublic; + this.scopes = scopes; + this.redirectUris = redirectUris; + this.authorizeUrl = authorizeUrl; + this.tokenFetchUrl = tokenFetchUrl; + this.userInfoUrl = userInfoUrl; + this.discoveryUrl = discoveryUrl; + this.tokenIntrospectionUrl = tokenIntrospectionUrl; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + this.clientSecret = clientSecret; + } + static fromJSON(data) { + return new _OAuthApplication( + data.id, + data.instance_id, + data.name, + data.client_id, + data.client_uri, + data.client_image_url, + data.dynamically_registered, + data.consent_screen_enabled, + data.pkce_required, + data.public, + data.scopes, + data.redirect_uris, + data.authorize_url, + data.token_fetch_url, + data.user_info_url, + data.discovery_url, + data.token_introspection_url, + data.created_at, + data.updated_at, + data.client_secret + ); + } +}; + +// src/api/resources/Organization.ts +var Organization = class _Organization { + constructor(id, name, slug, imageUrl, hasImage, createdAt, updatedAt, publicMetadata = {}, privateMetadata = {}, maxAllowedMemberships, adminDeleteEnabled, membersCount, createdBy) { + this.id = id; + this.name = name; + this.slug = slug; + this.imageUrl = imageUrl; + this.hasImage = hasImage; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + this.publicMetadata = publicMetadata; + this.privateMetadata = privateMetadata; + this.maxAllowedMemberships = maxAllowedMemberships; + this.adminDeleteEnabled = adminDeleteEnabled; + this.membersCount = membersCount; + this.createdBy = createdBy; + this._raw = null; + } + get raw() { + return this._raw; + } + static fromJSON(data) { + const res = new _Organization( + data.id, + data.name, + data.slug, + data.image_url || "", + data.has_image, + data.created_at, + data.updated_at, + data.public_metadata, + data.private_metadata, + data.max_allowed_memberships, + data.admin_delete_enabled, + data.members_count, + data.created_by + ); + res._raw = data; + return res; + } +}; + +// src/api/resources/OrganizationInvitation.ts +var OrganizationInvitation = class _OrganizationInvitation { + constructor(id, emailAddress, role, roleName, organizationId, createdAt, updatedAt, expiresAt, url, status, publicMetadata = {}, privateMetadata = {}, publicOrganizationData) { + this.id = id; + this.emailAddress = emailAddress; + this.role = role; + this.roleName = roleName; + this.organizationId = organizationId; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + this.expiresAt = expiresAt; + this.url = url; + this.status = status; + this.publicMetadata = publicMetadata; + this.privateMetadata = privateMetadata; + this.publicOrganizationData = publicOrganizationData; + this._raw = null; + } + get raw() { + return this._raw; + } + static fromJSON(data) { + const res = new _OrganizationInvitation( + data.id, + data.email_address, + data.role, + data.role_name, + data.organization_id, + data.created_at, + data.updated_at, + data.expires_at, + data.url, + data.status, + data.public_metadata, + data.private_metadata, + data.public_organization_data + ); + res._raw = data; + return res; + } +}; + +// src/api/resources/OrganizationMembership.ts +var OrganizationMembership = class _OrganizationMembership { + constructor(id, role, permissions, publicMetadata = {}, privateMetadata = {}, createdAt, updatedAt, organization, publicUserData) { + this.id = id; + this.role = role; + this.permissions = permissions; + this.publicMetadata = publicMetadata; + this.privateMetadata = privateMetadata; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + this.organization = organization; + this.publicUserData = publicUserData; + this._raw = null; + } + get raw() { + return this._raw; + } + static fromJSON(data) { + const res = new _OrganizationMembership( + data.id, + data.role, + data.permissions, + data.public_metadata, + data.private_metadata, + data.created_at, + data.updated_at, + Organization.fromJSON(data.organization), + OrganizationMembershipPublicUserData.fromJSON(data.public_user_data) + ); + res._raw = data; + return res; + } +}; +var OrganizationMembershipPublicUserData = class _OrganizationMembershipPublicUserData { + constructor(identifier, firstName, lastName, imageUrl, hasImage, userId) { + this.identifier = identifier; + this.firstName = firstName; + this.lastName = lastName; + this.imageUrl = imageUrl; + this.hasImage = hasImage; + this.userId = userId; + } + static fromJSON(data) { + return new _OrganizationMembershipPublicUserData( + data.identifier, + data.first_name, + data.last_name, + data.image_url, + data.has_image, + data.user_id + ); + } +}; + +// src/api/resources/OrganizationSettings.ts +var OrganizationSettings = class _OrganizationSettings { + constructor(enabled, maxAllowedMemberships, maxAllowedRoles, maxAllowedPermissions, creatorRole, adminDeleteEnabled, domainsEnabled, domainsEnrollmentModes, domainsDefaultRole) { + this.enabled = enabled; + this.maxAllowedMemberships = maxAllowedMemberships; + this.maxAllowedRoles = maxAllowedRoles; + this.maxAllowedPermissions = maxAllowedPermissions; + this.creatorRole = creatorRole; + this.adminDeleteEnabled = adminDeleteEnabled; + this.domainsEnabled = domainsEnabled; + this.domainsEnrollmentModes = domainsEnrollmentModes; + this.domainsDefaultRole = domainsDefaultRole; + } + static fromJSON(data) { + return new _OrganizationSettings( + data.enabled, + data.max_allowed_memberships, + data.max_allowed_roles, + data.max_allowed_permissions, + data.creator_role, + data.admin_delete_enabled, + data.domains_enabled, + data.domains_enrollment_modes, + data.domains_default_role + ); + } +}; + +// src/api/resources/PhoneNumber.ts +var PhoneNumber = class _PhoneNumber { + constructor(id, phoneNumber, reservedForSecondFactor, defaultSecondFactor, verification, linkedTo) { + this.id = id; + this.phoneNumber = phoneNumber; + this.reservedForSecondFactor = reservedForSecondFactor; + this.defaultSecondFactor = defaultSecondFactor; + this.verification = verification; + this.linkedTo = linkedTo; + } + static fromJSON(data) { + return new _PhoneNumber( + data.id, + data.phone_number, + data.reserved_for_second_factor, + data.default_second_factor, + data.verification && Verification.fromJSON(data.verification), + data.linked_to.map((link) => IdentificationLink.fromJSON(link)) + ); + } +}; + +// src/api/resources/ProxyCheck.ts +var ProxyCheck = class _ProxyCheck { + constructor(id, domainId, lastRunAt, proxyUrl, successful, createdAt, updatedAt) { + this.id = id; + this.domainId = domainId; + this.lastRunAt = lastRunAt; + this.proxyUrl = proxyUrl; + this.successful = successful; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + } + static fromJSON(data) { + return new _ProxyCheck( + data.id, + data.domain_id, + data.last_run_at, + data.proxy_url, + data.successful, + data.created_at, + data.updated_at + ); + } +}; + +// src/api/resources/RedirectUrl.ts +var RedirectUrl = class _RedirectUrl { + constructor(id, url, createdAt, updatedAt) { + this.id = id; + this.url = url; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + } + static fromJSON(data) { + return new _RedirectUrl(data.id, data.url, data.created_at, data.updated_at); + } +}; + +// src/api/resources/SamlConnection.ts +var SamlConnection = class _SamlConnection { + constructor(id, name, domain, organizationId, idpEntityId, idpSsoUrl, idpCertificate, idpMetadataUrl, idpMetadata, acsUrl, spEntityId, spMetadataUrl, active, provider, userCount, syncUserAttributes, allowSubdomains, allowIdpInitiated, createdAt, updatedAt, attributeMapping) { + this.id = id; + this.name = name; + this.domain = domain; + this.organizationId = organizationId; + this.idpEntityId = idpEntityId; + this.idpSsoUrl = idpSsoUrl; + this.idpCertificate = idpCertificate; + this.idpMetadataUrl = idpMetadataUrl; + this.idpMetadata = idpMetadata; + this.acsUrl = acsUrl; + this.spEntityId = spEntityId; + this.spMetadataUrl = spMetadataUrl; + this.active = active; + this.provider = provider; + this.userCount = userCount; + this.syncUserAttributes = syncUserAttributes; + this.allowSubdomains = allowSubdomains; + this.allowIdpInitiated = allowIdpInitiated; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + this.attributeMapping = attributeMapping; + } + static fromJSON(data) { + return new _SamlConnection( + data.id, + data.name, + data.domain, + data.organization_id, + data.idp_entity_id, + data.idp_sso_url, + data.idp_certificate, + data.idp_metadata_url, + data.idp_metadata, + data.acs_url, + data.sp_entity_id, + data.sp_metadata_url, + data.active, + data.provider, + data.user_count, + data.sync_user_attributes, + data.allow_subdomains, + data.allow_idp_initiated, + data.created_at, + data.updated_at, + data.attribute_mapping && AttributeMapping.fromJSON(data.attribute_mapping) + ); + } +}; +var SamlAccountConnection = class _SamlAccountConnection { + constructor(id, name, domain, active, provider, syncUserAttributes, allowSubdomains, allowIdpInitiated, createdAt, updatedAt) { + this.id = id; + this.name = name; + this.domain = domain; + this.active = active; + this.provider = provider; + this.syncUserAttributes = syncUserAttributes; + this.allowSubdomains = allowSubdomains; + this.allowIdpInitiated = allowIdpInitiated; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + } + static fromJSON(data) { + return new _SamlAccountConnection( + data.id, + data.name, + data.domain, + data.active, + data.provider, + data.sync_user_attributes, + data.allow_subdomains, + data.allow_idp_initiated, + data.created_at, + data.updated_at + ); + } +}; +var AttributeMapping = class _AttributeMapping { + constructor(userId, emailAddress, firstName, lastName) { + this.userId = userId; + this.emailAddress = emailAddress; + this.firstName = firstName; + this.lastName = lastName; + } + static fromJSON(data) { + return new _AttributeMapping(data.user_id, data.email_address, data.first_name, data.last_name); + } +}; + +// src/api/resources/SamlAccount.ts +var SamlAccount = class _SamlAccount { + constructor(id, provider, providerUserId, active, emailAddress, firstName, lastName, verification, samlConnection) { + this.id = id; + this.provider = provider; + this.providerUserId = providerUserId; + this.active = active; + this.emailAddress = emailAddress; + this.firstName = firstName; + this.lastName = lastName; + this.verification = verification; + this.samlConnection = samlConnection; + } + static fromJSON(data) { + return new _SamlAccount( + data.id, + data.provider, + data.provider_user_id, + data.active, + data.email_address, + data.first_name, + data.last_name, + data.verification && Verification.fromJSON(data.verification), + data.saml_connection && SamlAccountConnection.fromJSON(data.saml_connection) + ); + } +}; + +// src/api/resources/SignInTokens.ts +var SignInToken = class _SignInToken { + constructor(id, userId, token, status, url, createdAt, updatedAt) { + this.id = id; + this.userId = userId; + this.token = token; + this.status = status; + this.url = url; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + } + static fromJSON(data) { + return new _SignInToken(data.id, data.user_id, data.token, data.status, data.url, data.created_at, data.updated_at); + } +}; + +// src/api/resources/SignUpAttempt.ts +var SignUpAttemptVerification = class _SignUpAttemptVerification { + constructor(nextAction, supportedStrategies) { + this.nextAction = nextAction; + this.supportedStrategies = supportedStrategies; + } + static fromJSON(data) { + return new _SignUpAttemptVerification(data.next_action, data.supported_strategies); + } +}; +var SignUpAttemptVerifications = class _SignUpAttemptVerifications { + constructor(emailAddress, phoneNumber, web3Wallet, externalAccount) { + this.emailAddress = emailAddress; + this.phoneNumber = phoneNumber; + this.web3Wallet = web3Wallet; + this.externalAccount = externalAccount; + } + static fromJSON(data) { + return new _SignUpAttemptVerifications( + data.email_address && SignUpAttemptVerification.fromJSON(data.email_address), + data.phone_number && SignUpAttemptVerification.fromJSON(data.phone_number), + data.web3_wallet && SignUpAttemptVerification.fromJSON(data.web3_wallet), + data.external_account + ); + } +}; +var SignUpAttempt = class _SignUpAttempt { + constructor(id, status, requiredFields, optionalFields, missingFields, unverifiedFields, verifications, username, emailAddress, phoneNumber, web3Wallet, passwordEnabled, firstName, lastName, customAction, externalId, createdSessionId, createdUserId, abandonAt, legalAcceptedAt, publicMetadata, unsafeMetadata) { + this.id = id; + this.status = status; + this.requiredFields = requiredFields; + this.optionalFields = optionalFields; + this.missingFields = missingFields; + this.unverifiedFields = unverifiedFields; + this.verifications = verifications; + this.username = username; + this.emailAddress = emailAddress; + this.phoneNumber = phoneNumber; + this.web3Wallet = web3Wallet; + this.passwordEnabled = passwordEnabled; + this.firstName = firstName; + this.lastName = lastName; + this.customAction = customAction; + this.externalId = externalId; + this.createdSessionId = createdSessionId; + this.createdUserId = createdUserId; + this.abandonAt = abandonAt; + this.legalAcceptedAt = legalAcceptedAt; + this.publicMetadata = publicMetadata; + this.unsafeMetadata = unsafeMetadata; + } + static fromJSON(data) { + return new _SignUpAttempt( + data.id, + data.status, + data.required_fields, + data.optional_fields, + data.missing_fields, + data.unverified_fields, + data.verifications ? SignUpAttemptVerifications.fromJSON(data.verifications) : null, + data.username, + data.email_address, + data.phone_number, + data.web3_wallet, + data.password_enabled, + data.first_name, + data.last_name, + data.custom_action, + data.external_id, + data.created_session_id, + data.created_user_id, + data.abandon_at, + data.legal_accepted_at, + data.public_metadata, + data.unsafe_metadata + ); + } +}; + +// src/api/resources/SMSMessage.ts +var SMSMessage = class _SMSMessage { + constructor(id, fromPhoneNumber, toPhoneNumber, message, status, phoneNumberId, data) { + this.id = id; + this.fromPhoneNumber = fromPhoneNumber; + this.toPhoneNumber = toPhoneNumber; + this.message = message; + this.status = status; + this.phoneNumberId = phoneNumberId; + this.data = data; + } + static fromJSON(data) { + return new _SMSMessage( + data.id, + data.from_phone_number, + data.to_phone_number, + data.message, + data.status, + data.phone_number_id, + data.data + ); + } +}; + +// src/api/resources/Token.ts +var Token = class _Token { + constructor(jwt) { + this.jwt = jwt; + } + static fromJSON(data) { + return new _Token(data.jwt); + } +}; + +// src/api/resources/Web3Wallet.ts +var Web3Wallet = class _Web3Wallet { + constructor(id, web3Wallet, verification) { + this.id = id; + this.web3Wallet = web3Wallet; + this.verification = verification; + } + static fromJSON(data) { + return new _Web3Wallet(data.id, data.web3_wallet, data.verification && Verification.fromJSON(data.verification)); + } +}; + +// src/api/resources/User.ts +var User = class _User { + constructor(id, passwordEnabled, totpEnabled, backupCodeEnabled, twoFactorEnabled, banned, locked, createdAt, updatedAt, imageUrl, hasImage, primaryEmailAddressId, primaryPhoneNumberId, primaryWeb3WalletId, lastSignInAt, externalId, username, firstName, lastName, publicMetadata = {}, privateMetadata = {}, unsafeMetadata = {}, emailAddresses = [], phoneNumbers = [], web3Wallets = [], externalAccounts = [], samlAccounts = [], lastActiveAt, createOrganizationEnabled, createOrganizationsLimit = null, deleteSelfEnabled, legalAcceptedAt) { + this.id = id; + this.passwordEnabled = passwordEnabled; + this.totpEnabled = totpEnabled; + this.backupCodeEnabled = backupCodeEnabled; + this.twoFactorEnabled = twoFactorEnabled; + this.banned = banned; + this.locked = locked; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + this.imageUrl = imageUrl; + this.hasImage = hasImage; + this.primaryEmailAddressId = primaryEmailAddressId; + this.primaryPhoneNumberId = primaryPhoneNumberId; + this.primaryWeb3WalletId = primaryWeb3WalletId; + this.lastSignInAt = lastSignInAt; + this.externalId = externalId; + this.username = username; + this.firstName = firstName; + this.lastName = lastName; + this.publicMetadata = publicMetadata; + this.privateMetadata = privateMetadata; + this.unsafeMetadata = unsafeMetadata; + this.emailAddresses = emailAddresses; + this.phoneNumbers = phoneNumbers; + this.web3Wallets = web3Wallets; + this.externalAccounts = externalAccounts; + this.samlAccounts = samlAccounts; + this.lastActiveAt = lastActiveAt; + this.createOrganizationEnabled = createOrganizationEnabled; + this.createOrganizationsLimit = createOrganizationsLimit; + this.deleteSelfEnabled = deleteSelfEnabled; + this.legalAcceptedAt = legalAcceptedAt; + this._raw = null; + } + get raw() { + return this._raw; + } + static fromJSON(data) { + const res = new _User( + data.id, + data.password_enabled, + data.totp_enabled, + data.backup_code_enabled, + data.two_factor_enabled, + data.banned, + data.locked, + data.created_at, + data.updated_at, + data.image_url, + data.has_image, + data.primary_email_address_id, + data.primary_phone_number_id, + data.primary_web3_wallet_id, + data.last_sign_in_at, + data.external_id, + data.username, + data.first_name, + data.last_name, + data.public_metadata, + data.private_metadata, + data.unsafe_metadata, + (data.email_addresses || []).map((x) => EmailAddress.fromJSON(x)), + (data.phone_numbers || []).map((x) => PhoneNumber.fromJSON(x)), + (data.web3_wallets || []).map((x) => Web3Wallet.fromJSON(x)), + (data.external_accounts || []).map((x) => ExternalAccount.fromJSON(x)), + (data.saml_accounts || []).map((x) => SamlAccount.fromJSON(x)), + data.last_active_at, + data.create_organization_enabled, + data.create_organizations_limit, + data.delete_self_enabled, + data.legal_accepted_at + ); + res._raw = data; + return res; + } + /** + * The primary email address of the user. + */ + get primaryEmailAddress() { + return this.emailAddresses.find(({ id }) => id === this.primaryEmailAddressId) ?? null; + } + /** + * The primary phone number of the user. + */ + get primaryPhoneNumber() { + return this.phoneNumbers.find(({ id }) => id === this.primaryPhoneNumberId) ?? null; + } + /** + * The primary web3 wallet of the user. + */ + get primaryWeb3Wallet() { + return this.web3Wallets.find(({ id }) => id === this.primaryWeb3WalletId) ?? null; + } + /** + * The full name of the user. + */ + get fullName() { + return [this.firstName, this.lastName].join(" ").trim() || null; + } +}; + +// src/api/resources/WaitlistEntry.ts +var WaitlistEntry = class _WaitlistEntry { + constructor(id, emailAddress, status, invitation, createdAt, updatedAt, isLocked) { + this.id = id; + this.emailAddress = emailAddress; + this.status = status; + this.invitation = invitation; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + this.isLocked = isLocked; + } + static fromJSON(data) { + return new _WaitlistEntry( + data.id, + data.email_address, + data.status, + data.invitation && Invitation.fromJSON(data.invitation), + data.created_at, + data.updated_at, + data.is_locked + ); + } +}; + +// src/api/resources/Feature.ts +var Feature = class _Feature { + constructor(id, name, description, slug, avatarUrl) { + this.id = id; + this.name = name; + this.description = description; + this.slug = slug; + this.avatarUrl = avatarUrl; + } + static fromJSON(data) { + return new _Feature(data.id, data.name, data.description, data.slug, data.avatar_url); + } +}; + +// src/api/resources/CommercePlan.ts +var BillingPlan = class _BillingPlan { + constructor(id, productId, name, slug, description, isDefault, isRecurring, hasBaseFee, publiclyVisible, fee, annualFee, annualMonthlyFee, forPayerType, features) { + this.id = id; + this.productId = productId; + this.name = name; + this.slug = slug; + this.description = description; + this.isDefault = isDefault; + this.isRecurring = isRecurring; + this.hasBaseFee = hasBaseFee; + this.publiclyVisible = publiclyVisible; + this.fee = fee; + this.annualFee = annualFee; + this.annualMonthlyFee = annualMonthlyFee; + this.forPayerType = forPayerType; + this.features = features; + } + static fromJSON(data) { + const formatAmountJSON = (fee) => { + return { + amount: fee.amount, + amountFormatted: fee.amount_formatted, + currency: fee.currency, + currencySymbol: fee.currency_symbol + }; + }; + return new _BillingPlan( + data.id, + data.product_id, + data.name, + data.slug, + data.description, + data.is_default, + data.is_recurring, + data.has_base_fee, + data.publicly_visible, + formatAmountJSON(data.fee), + formatAmountJSON(data.annual_fee), + formatAmountJSON(data.annual_monthly_fee), + data.for_payer_type, + data.features.map((feature) => Feature.fromJSON(feature)) + ); + } +}; + +// src/api/resources/CommerceSubscriptionItem.ts +var BillingSubscriptionItem = class _BillingSubscriptionItem { + constructor(id, status, planPeriod, periodStart, nextPayment, amount, plan, planId, createdAt, updatedAt, periodEnd, canceledAt, pastDueAt, endedAt, payerId, isFreeTrial, lifetimePaid) { + this.id = id; + this.status = status; + this.planPeriod = planPeriod; + this.periodStart = periodStart; + this.nextPayment = nextPayment; + this.amount = amount; + this.plan = plan; + this.planId = planId; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + this.periodEnd = periodEnd; + this.canceledAt = canceledAt; + this.pastDueAt = pastDueAt; + this.endedAt = endedAt; + this.payerId = payerId; + this.isFreeTrial = isFreeTrial; + this.lifetimePaid = lifetimePaid; + } + static fromJSON(data) { + function formatAmountJSON(amount) { + if (!amount) { + return amount; + } + return { + amount: amount.amount, + amountFormatted: amount.amount_formatted, + currency: amount.currency, + currencySymbol: amount.currency_symbol + }; + } + return new _BillingSubscriptionItem( + data.id, + data.status, + data.plan_period, + data.period_start, + data.next_payment, + formatAmountJSON(data.amount), + BillingPlan.fromJSON(data.plan), + data.plan_id, + data.created_at, + data.updated_at, + data.period_end, + data.canceled_at, + data.past_due_at, + data.ended_at, + data.payer_id, + data.is_free_trial, + formatAmountJSON(data.lifetime_paid) + ); + } +}; + +// src/api/resources/CommerceSubscription.ts +var BillingSubscription = class _BillingSubscription { + constructor(id, status, payerId, createdAt, updatedAt, activeAt, pastDueAt, subscriptionItems, nextPayment, eligibleForFreeTrial) { + this.id = id; + this.status = status; + this.payerId = payerId; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + this.activeAt = activeAt; + this.pastDueAt = pastDueAt; + this.subscriptionItems = subscriptionItems; + this.nextPayment = nextPayment; + this.eligibleForFreeTrial = eligibleForFreeTrial; + } + static fromJSON(data) { + const nextPayment = data.next_payment ? { + date: data.next_payment.date, + amount: { + amount: data.next_payment.amount.amount, + amountFormatted: data.next_payment.amount.amount_formatted, + currency: data.next_payment.amount.currency, + currencySymbol: data.next_payment.amount.currency_symbol + } + } : null; + return new _BillingSubscription( + data.id, + data.status, + data.payer_id, + data.created_at, + data.updated_at, + data.active_at ?? null, + data.past_due_at ?? null, + data.subscription_items.map((item) => BillingSubscriptionItem.fromJSON(item)), + nextPayment, + data.eligible_for_free_trial ?? false + ); + } +}; + +// src/api/resources/Deserializer.ts +function deserialize(payload) { + let data, totalCount; + if (Array.isArray(payload)) { + const data2 = payload.map((item) => jsonToObject(item)); + return { data: data2 }; + } else if (isPaginated(payload)) { + data = payload.data.map((item) => jsonToObject(item)); + totalCount = payload.total_count; + return { data, totalCount }; + } else { + return { data: jsonToObject(payload) }; + } +} +function isPaginated(payload) { + if (!payload || typeof payload !== "object" || !("data" in payload)) { + return false; + } + return Array.isArray(payload.data) && payload.data !== void 0; +} +function getCount(item) { + return item.total_count; +} +function jsonToObject(item) { + if (typeof item !== "string" && "object" in item && "deleted" in item) { + return DeletedObject.fromJSON(item); + } + switch (item.object) { + case ObjectType.AccountlessApplication: + return AccountlessApplication.fromJSON(item); + case ObjectType.ActorToken: + return ActorToken.fromJSON(item); + case ObjectType.AllowlistIdentifier: + return AllowlistIdentifier.fromJSON(item); + case ObjectType.ApiKey: + return APIKey.fromJSON(item); + case ObjectType.BlocklistIdentifier: + return BlocklistIdentifier.fromJSON(item); + case ObjectType.Client: + return Client.fromJSON(item); + case ObjectType.Cookies: + return Cookies2.fromJSON(item); + case ObjectType.Domain: + return Domain.fromJSON(item); + case ObjectType.EmailAddress: + return EmailAddress.fromJSON(item); + case ObjectType.Email: + return Email.fromJSON(item); + case ObjectType.IdpOAuthAccessToken: + return IdPOAuthAccessToken.fromJSON(item); + case ObjectType.Instance: + return Instance.fromJSON(item); + case ObjectType.InstanceRestrictions: + return InstanceRestrictions.fromJSON(item); + case ObjectType.InstanceSettings: + return InstanceSettings.fromJSON(item); + case ObjectType.Invitation: + return Invitation.fromJSON(item); + case ObjectType.JwtTemplate: + return JwtTemplate.fromJSON(item); + case ObjectType.Machine: + return Machine.fromJSON(item); + case ObjectType.MachineScope: + return MachineScope.fromJSON(item); + case ObjectType.MachineSecretKey: + return MachineSecretKey.fromJSON(item); + case ObjectType.M2MToken: + return M2MToken.fromJSON(item); + case ObjectType.OauthAccessToken: + return OauthAccessToken.fromJSON(item); + case ObjectType.OAuthApplication: + return OAuthApplication.fromJSON(item); + case ObjectType.Organization: + return Organization.fromJSON(item); + case ObjectType.OrganizationInvitation: + return OrganizationInvitation.fromJSON(item); + case ObjectType.OrganizationMembership: + return OrganizationMembership.fromJSON(item); + case ObjectType.OrganizationSettings: + return OrganizationSettings.fromJSON(item); + case ObjectType.PhoneNumber: + return PhoneNumber.fromJSON(item); + case ObjectType.ProxyCheck: + return ProxyCheck.fromJSON(item); + case ObjectType.RedirectUrl: + return RedirectUrl.fromJSON(item); + case ObjectType.SamlConnection: + return SamlConnection.fromJSON(item); + case ObjectType.SignInToken: + return SignInToken.fromJSON(item); + case ObjectType.SignUpAttempt: + return SignUpAttempt.fromJSON(item); + case ObjectType.Session: + return Session.fromJSON(item); + case ObjectType.SmsMessage: + return SMSMessage.fromJSON(item); + case ObjectType.Token: + return Token.fromJSON(item); + case ObjectType.TotalCount: + return getCount(item); + case ObjectType.User: + return User.fromJSON(item); + case ObjectType.WaitlistEntry: + return WaitlistEntry.fromJSON(item); + case ObjectType.BillingPlan: + return BillingPlan.fromJSON(item); + case ObjectType.BillingSubscription: + return BillingSubscription.fromJSON(item); + case ObjectType.BillingSubscriptionItem: + return BillingSubscriptionItem.fromJSON(item); + case ObjectType.Feature: + return Feature.fromJSON(item); + default: + return item; + } +} + +// src/api/request.ts +function buildRequest(options) { + const requestFn = async (requestOptions) => { + const { + secretKey, + machineSecretKey, + useMachineSecretKey = false, + requireSecretKey = true, + apiUrl = API_URL, + apiVersion = API_VERSION, + userAgent = USER_AGENT, + skipApiVersionInUrl = false + } = options; + const { path, method, queryParams, headerParams, bodyParams, formData, options: opts } = requestOptions; + const { deepSnakecaseBodyParamKeys = false } = opts || {}; + if (requireSecretKey) { + assertValidSecretKey(secretKey); + } + const url = skipApiVersionInUrl ? joinPaths(apiUrl, path) : joinPaths(apiUrl, apiVersion, path); + const finalUrl = new URL(url); + if (queryParams) { + const snakecasedQueryParams = snakecase_keys_default({ ...queryParams }); + for (const [key, val] of Object.entries(snakecasedQueryParams)) { + if (val) { + [val].flat().forEach((v) => finalUrl.searchParams.append(key, v)); + } + } + } + const headers = new Headers({ + "Clerk-API-Version": SUPPORTED_BAPI_VERSION, + [constants.Headers.UserAgent]: userAgent, + ...headerParams + }); + const authorizationHeader = constants.Headers.Authorization; + if (!headers.has(authorizationHeader)) { + if (useMachineSecretKey && machineSecretKey) { + headers.set(authorizationHeader, `Bearer ${machineSecretKey}`); + } else if (secretKey) { + headers.set(authorizationHeader, `Bearer ${secretKey}`); + } + } + let res; + try { + if (formData) { + res = await runtime.fetch(finalUrl.href, { + method, + headers, + body: formData + }); + } else { + headers.set("Content-Type", "application/json"); + const buildBody = () => { + const hasBody = method !== "GET" && bodyParams && Object.keys(bodyParams).length > 0; + if (!hasBody) { + return null; + } + const formatKeys = (object) => snakecase_keys_default(object, { deep: deepSnakecaseBodyParamKeys }); + return { + body: JSON.stringify(Array.isArray(bodyParams) ? bodyParams.map(formatKeys) : formatKeys(bodyParams)) + }; + }; + res = await runtime.fetch(finalUrl.href, { + method, + headers, + ...buildBody() + }); + } + const isJSONResponse = res?.headers && res.headers?.get(constants.Headers.ContentType) === constants.ContentTypes.Json; + const responseBody = await (isJSONResponse ? res.json() : res.text()); + if (!res.ok) { + return { + data: null, + errors: parseErrors(responseBody), + status: res?.status, + statusText: res?.statusText, + clerkTraceId: getTraceId(responseBody, res?.headers), + retryAfter: getRetryAfter(res?.headers) + }; + } + return { + ...deserialize(responseBody), + errors: null + }; + } catch (err) { + if (err instanceof Error) { + return { + data: null, + errors: [ + { + code: "unexpected_error", + message: err.message || "Unexpected error" + } + ], + clerkTraceId: getTraceId(err, res?.headers) + }; + } + return { + data: null, + errors: parseErrors(err), + status: res?.status, + statusText: res?.statusText, + clerkTraceId: getTraceId(err, res?.headers), + retryAfter: getRetryAfter(res?.headers) + }; + } + }; + return withLegacyRequestReturn(requestFn); +} +function getTraceId(data, headers) { + if (data && typeof data === "object" && "clerk_trace_id" in data && typeof data.clerk_trace_id === "string") { + return data.clerk_trace_id; + } + const cfRay = headers?.get("cf-ray"); + return cfRay || ""; +} +function getRetryAfter(headers) { + const retryAfter = headers?.get("Retry-After"); + if (!retryAfter) { + return; + } + const value = parseInt(retryAfter, 10); + if (isNaN(value)) { + return; + } + return value; +} +function parseErrors(data) { + if (!!data && typeof data === "object" && "errors" in data) { + const errors = data.errors; + return errors.length > 0 ? errors.map(import_error2.parseError) : []; + } + return []; +} +function withLegacyRequestReturn(cb) { + return async (...args) => { + const { data, errors, totalCount, status, statusText, clerkTraceId, retryAfter } = await cb(...args); + if (errors) { + const error = new import_error2.ClerkAPIResponseError(statusText || "", { + data: [], + status, + clerkTraceId, + retryAfter + }); + error.errors = errors; + throw error; + } + if (typeof totalCount !== "undefined") { + return { data, totalCount }; + } + return data; + }; +} + +// src/api/factory.ts +function createBackendApiClient(options) { + const request = buildRequest(options); + return { + __experimental_accountlessApplications: new AccountlessApplicationAPI( + buildRequest({ ...options, requireSecretKey: false }) + ), + actorTokens: new ActorTokenAPI(request), + allowlistIdentifiers: new AllowlistIdentifierAPI(request), + apiKeys: new APIKeysAPI( + buildRequest({ + ...options, + skipApiVersionInUrl: true + }) + ), + betaFeatures: new BetaFeaturesAPI(request), + blocklistIdentifiers: new BlocklistIdentifierAPI(request), + /** + * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. + */ + billing: new BillingAPI(request), + clients: new ClientAPI(request), + domains: new DomainAPI(request), + emailAddresses: new EmailAddressAPI(request), + idPOAuthAccessToken: new IdPOAuthAccessTokenApi( + buildRequest({ + ...options, + skipApiVersionInUrl: true + }) + ), + instance: new InstanceAPI(request), + invitations: new InvitationAPI(request), + jwks: new JwksAPI(request), + jwtTemplates: new JwtTemplatesApi(request), + machines: new MachineApi(request), + m2m: new M2MTokenApi( + buildRequest({ + ...options, + skipApiVersionInUrl: true, + requireSecretKey: false, + useMachineSecretKey: true + }) + ), + oauthApplications: new OAuthApplicationsApi(request), + organizations: new OrganizationAPI(request), + phoneNumbers: new PhoneNumberAPI(request), + proxyChecks: new ProxyCheckAPI(request), + redirectUrls: new RedirectUrlAPI(request), + samlConnections: new SamlConnectionAPI(request), + sessions: new SessionAPI(request), + signInTokens: new SignInTokenAPI(request), + signUps: new SignUpAPI(request), + testingTokens: new TestingTokenAPI(request), + users: new UserAPI(request), + waitlistEntries: new WaitlistEntryAPI(request), + webhooks: new WebhookAPI(request) + }; +} + +// src/tokens/machine.ts +var M2M_TOKEN_PREFIX = "mt_"; +var OAUTH_TOKEN_PREFIX = "oat_"; +var API_KEY_PREFIX = "ak_"; +var MACHINE_TOKEN_PREFIXES = [M2M_TOKEN_PREFIX, OAUTH_TOKEN_PREFIX, API_KEY_PREFIX]; +function isMachineTokenByPrefix(token) { + return MACHINE_TOKEN_PREFIXES.some((prefix) => token.startsWith(prefix)); +} +function getMachineTokenType(token) { + if (token.startsWith(M2M_TOKEN_PREFIX)) { + return TokenType.M2MToken; + } + if (token.startsWith(OAUTH_TOKEN_PREFIX)) { + return TokenType.OAuthToken; + } + if (token.startsWith(API_KEY_PREFIX)) { + return TokenType.ApiKey; + } + throw new Error("Unknown machine token type"); +} +var isTokenTypeAccepted = (tokenType, acceptsToken) => { + if (!tokenType) { + return false; + } + if (acceptsToken === "any") { + return true; + } + const tokenTypes = Array.isArray(acceptsToken) ? acceptsToken : [acceptsToken]; + return tokenTypes.includes(tokenType); +}; +function isMachineTokenType(type) { + return type === TokenType.ApiKey || type === TokenType.M2MToken || type === TokenType.OAuthToken; +} + +// src/tokens/authObjects.ts +var createDebug = (data) => { + return () => { + const res = { ...data }; + res.secretKey = (res.secretKey || "").substring(0, 7); + res.jwtKey = (res.jwtKey || "").substring(0, 7); + return { ...res }; + }; +}; +function signedInAuthObject(authenticateContext, sessionToken, sessionClaims) { + const { actor, sessionId, sessionStatus, userId, orgId, orgRole, orgSlug, orgPermissions, factorVerificationAge } = (0, import_jwtPayloadParser.__experimental_JWTPayloadToAuthObjectProperties)(sessionClaims); + const apiClient = createBackendApiClient(authenticateContext); + const getToken = createGetToken({ + sessionId, + sessionToken, + fetcher: async (sessionId2, template, expiresInSeconds) => (await apiClient.sessions.getToken(sessionId2, template || "", expiresInSeconds)).jwt + }); + return { + tokenType: TokenType.SessionToken, + actor, + sessionClaims, + sessionId, + sessionStatus, + userId, + orgId, + orgRole, + orgSlug, + orgPermissions, + factorVerificationAge, + getToken, + has: (0, import_authorization.createCheckAuthorization)({ + orgId, + orgRole, + orgPermissions, + userId, + factorVerificationAge, + features: sessionClaims.fea || "", + plans: sessionClaims.pla || "" + }), + debug: createDebug({ ...authenticateContext, sessionToken }), + isAuthenticated: true + }; +} +function signedOutAuthObject(debugData, initialSessionStatus) { + return { + tokenType: TokenType.SessionToken, + sessionClaims: null, + sessionId: null, + sessionStatus: initialSessionStatus ?? null, + userId: null, + actor: null, + orgId: null, + orgRole: null, + orgSlug: null, + orgPermissions: null, + factorVerificationAge: null, + getToken: () => Promise.resolve(null), + has: () => false, + debug: createDebug(debugData), + isAuthenticated: false + }; +} +function authenticatedMachineObject(tokenType, token, verificationResult, debugData) { + const baseObject = { + id: verificationResult.id, + subject: verificationResult.subject, + getToken: () => Promise.resolve(token), + has: () => false, + debug: createDebug(debugData), + isAuthenticated: true + }; + switch (tokenType) { + case TokenType.ApiKey: { + const result = verificationResult; + return { + ...baseObject, + tokenType, + name: result.name, + claims: result.claims, + scopes: result.scopes, + userId: result.subject.startsWith("user_") ? result.subject : null, + orgId: result.subject.startsWith("org_") ? result.subject : null + }; + } + case TokenType.M2MToken: { + const result = verificationResult; + return { + ...baseObject, + tokenType, + claims: result.claims, + scopes: result.scopes, + machineId: result.subject + }; + } + case TokenType.OAuthToken: { + const result = verificationResult; + return { + ...baseObject, + tokenType, + scopes: result.scopes, + userId: result.subject, + clientId: result.clientId + }; + } + default: + throw new Error(`Invalid token type: ${tokenType}`); + } +} +function unauthenticatedMachineObject(tokenType, debugData) { + const baseObject = { + id: null, + subject: null, + scopes: null, + has: () => false, + getToken: () => Promise.resolve(null), + debug: createDebug(debugData), + isAuthenticated: false + }; + switch (tokenType) { + case TokenType.ApiKey: { + return { + ...baseObject, + tokenType, + name: null, + claims: null, + scopes: null, + userId: null, + orgId: null + }; + } + case TokenType.M2MToken: { + return { + ...baseObject, + tokenType, + claims: null, + scopes: null, + machineId: null + }; + } + case TokenType.OAuthToken: { + return { + ...baseObject, + tokenType, + scopes: null, + userId: null, + clientId: null + }; + } + default: + throw new Error(`Invalid token type: ${tokenType}`); + } +} +function invalidTokenAuthObject() { + return { + isAuthenticated: false, + tokenType: null, + getToken: () => Promise.resolve(null), + has: () => false, + debug: () => ({}) + }; +} +var makeAuthObjectSerializable = (obj) => { + const { debug, getToken, has, ...rest } = obj; + return rest; +}; +var createGetToken = (params) => { + const { fetcher, sessionToken, sessionId } = params || {}; + return async (options = {}) => { + if (!sessionId) { + return null; + } + if (options.template || options.expiresInSeconds !== void 0) { + return fetcher(sessionId, options.template, options.expiresInSeconds); + } + return sessionToken; + }; +}; +var getAuthObjectFromJwt = (jwt, { treatPendingAsSignedOut = true, ...options }) => { + const authObject = signedInAuthObject(options, jwt.raw.text, jwt.payload); + if (treatPendingAsSignedOut && authObject.sessionStatus === "pending") { + return signedOutAuthObject(options, authObject.sessionStatus); + } + return authObject; +}; +var getAuthObjectForAcceptedToken = ({ + authObject, + acceptsToken = TokenType.SessionToken +}) => { + if (acceptsToken === "any") { + return authObject; + } + if (Array.isArray(acceptsToken)) { + if (!isTokenTypeAccepted(authObject.tokenType, acceptsToken)) { + return invalidTokenAuthObject(); + } + return authObject; + } + if (!isTokenTypeAccepted(authObject.tokenType, acceptsToken)) { + if (isMachineTokenType(acceptsToken)) { + return unauthenticatedMachineObject(acceptsToken, authObject.debug); + } + return signedOutAuthObject(authObject.debug); + } + return authObject; +}; + +// src/tokens/authStatus.ts +var AuthStatus = { + SignedIn: "signed-in", + SignedOut: "signed-out", + Handshake: "handshake" +}; +var AuthErrorReason = { + ClientUATWithoutSessionToken: "client-uat-but-no-session-token", + DevBrowserMissing: "dev-browser-missing", + DevBrowserSync: "dev-browser-sync", + PrimaryRespondsToSyncing: "primary-responds-to-syncing", + PrimaryDomainCrossOriginSync: "primary-domain-cross-origin-sync", + SatelliteCookieNeedsSyncing: "satellite-needs-syncing", + SessionTokenAndUATMissing: "session-token-and-uat-missing", + SessionTokenMissing: "session-token-missing", + SessionTokenExpired: "session-token-expired", + SessionTokenIATBeforeClientUAT: "session-token-iat-before-client-uat", + SessionTokenNBF: "session-token-nbf", + SessionTokenIatInTheFuture: "session-token-iat-in-the-future", + SessionTokenWithoutClientUAT: "session-token-but-no-client-uat", + ActiveOrganizationMismatch: "active-organization-mismatch", + TokenTypeMismatch: "token-type-mismatch", + UnexpectedError: "unexpected-error" +}; +function signedIn(params) { + const { authenticateContext, headers = new Headers(), token } = params; + const toAuth = ({ treatPendingAsSignedOut = true } = {}) => { + if (params.tokenType === TokenType.SessionToken) { + const { sessionClaims } = params; + const authObject = signedInAuthObject(authenticateContext, token, sessionClaims); + if (treatPendingAsSignedOut && authObject.sessionStatus === "pending") { + return signedOutAuthObject(void 0, authObject.sessionStatus); + } + return authObject; + } + const { machineData } = params; + return authenticatedMachineObject(params.tokenType, token, machineData, authenticateContext); + }; + return { + status: AuthStatus.SignedIn, + reason: null, + message: null, + proxyUrl: authenticateContext.proxyUrl || "", + publishableKey: authenticateContext.publishableKey || "", + isSatellite: authenticateContext.isSatellite || false, + domain: authenticateContext.domain || "", + signInUrl: authenticateContext.signInUrl || "", + signUpUrl: authenticateContext.signUpUrl || "", + afterSignInUrl: authenticateContext.afterSignInUrl || "", + afterSignUpUrl: authenticateContext.afterSignUpUrl || "", + isSignedIn: true, + isAuthenticated: true, + tokenType: params.tokenType, + toAuth, + headers, + token + }; +} +function signedOut(params) { + const { authenticateContext, headers = new Headers(), reason, message = "", tokenType } = params; + const toAuth = () => { + if (tokenType === TokenType.SessionToken) { + return signedOutAuthObject({ ...authenticateContext, status: AuthStatus.SignedOut, reason, message }); + } + return unauthenticatedMachineObject(tokenType, { reason, message, headers }); + }; + return withDebugHeaders({ + status: AuthStatus.SignedOut, + reason, + message, + proxyUrl: authenticateContext.proxyUrl || "", + publishableKey: authenticateContext.publishableKey || "", + isSatellite: authenticateContext.isSatellite || false, + domain: authenticateContext.domain || "", + signInUrl: authenticateContext.signInUrl || "", + signUpUrl: authenticateContext.signUpUrl || "", + afterSignInUrl: authenticateContext.afterSignInUrl || "", + afterSignUpUrl: authenticateContext.afterSignUpUrl || "", + isSignedIn: false, + isAuthenticated: false, + tokenType, + toAuth, + headers, + token: null + }); +} +function handshake(authenticateContext, reason, message = "", headers) { + return withDebugHeaders({ + status: AuthStatus.Handshake, + reason, + message, + publishableKey: authenticateContext.publishableKey || "", + isSatellite: authenticateContext.isSatellite || false, + domain: authenticateContext.domain || "", + proxyUrl: authenticateContext.proxyUrl || "", + signInUrl: authenticateContext.signInUrl || "", + signUpUrl: authenticateContext.signUpUrl || "", + afterSignInUrl: authenticateContext.afterSignInUrl || "", + afterSignUpUrl: authenticateContext.afterSignUpUrl || "", + isSignedIn: false, + isAuthenticated: false, + tokenType: TokenType.SessionToken, + toAuth: () => null, + headers, + token: null + }); +} +function signedOutInvalidToken() { + const authObject = invalidTokenAuthObject(); + return withDebugHeaders({ + status: AuthStatus.SignedOut, + reason: AuthErrorReason.TokenTypeMismatch, + message: "", + proxyUrl: "", + publishableKey: "", + isSatellite: false, + domain: "", + signInUrl: "", + signUpUrl: "", + afterSignInUrl: "", + afterSignUpUrl: "", + isSignedIn: false, + isAuthenticated: false, + tokenType: null, + toAuth: () => authObject, + headers: new Headers(), + token: null + }); +} +var withDebugHeaders = (requestState) => { + const headers = new Headers(requestState.headers || {}); + if (requestState.message) { + try { + headers.set(constants.Headers.AuthMessage, requestState.message); + } catch { + } + } + if (requestState.reason) { + try { + headers.set(constants.Headers.AuthReason, requestState.reason); + } catch { + } + } + if (requestState.status) { + try { + headers.set(constants.Headers.AuthStatus, requestState.status); + } catch { + } + } + requestState.headers = headers; + return requestState; +}; + +// src/tokens/clerkRequest.ts +var import_cookie = require("cookie"); + +// src/tokens/clerkUrl.ts +var ClerkUrl = class extends URL { + isCrossOrigin(other) { + return this.origin !== new URL(other.toString()).origin; + } +}; +var createClerkUrl = (...args) => { + return new ClerkUrl(...args); +}; + +// src/tokens/clerkRequest.ts +var ClerkRequest = class extends Request { + constructor(input, init) { + const url = typeof input !== "string" && "url" in input ? input.url : String(input); + super(url, init || typeof input === "string" ? void 0 : input); + this.clerkUrl = this.deriveUrlFromHeaders(this); + this.cookies = this.parseCookies(this); + } + toJSON() { + return { + url: this.clerkUrl.href, + method: this.method, + headers: JSON.stringify(Object.fromEntries(this.headers)), + clerkUrl: this.clerkUrl.toString(), + cookies: JSON.stringify(Object.fromEntries(this.cookies)) + }; + } + /** + * Used to fix request.url using the x-forwarded-* headers + * TODO add detailed description of the issues this solves + */ + deriveUrlFromHeaders(req) { + const initialUrl = new URL(req.url); + const forwardedProto = req.headers.get(constants.Headers.ForwardedProto); + const forwardedHost = req.headers.get(constants.Headers.ForwardedHost); + const host = req.headers.get(constants.Headers.Host); + const protocol = initialUrl.protocol; + const resolvedHost = this.getFirstValueFromHeader(forwardedHost) ?? host; + const resolvedProtocol = this.getFirstValueFromHeader(forwardedProto) ?? protocol?.replace(/[:/]/, ""); + const origin = resolvedHost && resolvedProtocol ? `${resolvedProtocol}://${resolvedHost}` : initialUrl.origin; + if (origin === initialUrl.origin) { + return createClerkUrl(initialUrl); + } + return createClerkUrl(initialUrl.pathname + initialUrl.search, origin); + } + getFirstValueFromHeader(value) { + return value?.split(",")[0]; + } + parseCookies(req) { + const cookiesRecord = (0, import_cookie.parse)(this.decodeCookieValue(req.headers.get("cookie") || "")); + return new Map(Object.entries(cookiesRecord)); + } + decodeCookieValue(str) { + return str ? str.replace(/(%[0-9A-Z]{2})+/g, decodeURIComponent) : str; + } +}; +var createClerkRequest = (...args) => { + return args[0] instanceof ClerkRequest ? args[0] : new ClerkRequest(...args); +}; + +// src/tokens/cookie.ts +var getCookieName = (cookieDirective) => { + return cookieDirective.split(";")[0]?.split("=")[0]; +}; +var getCookieValue = (cookieDirective) => { + return cookieDirective.split(";")[0]?.split("=")[1]; +}; + +// src/tokens/keys.ts +var cache = {}; +var lastUpdatedAt = 0; +function getFromCache(kid) { + return cache[kid]; +} +function getCacheValues() { + return Object.values(cache); +} +function setInCache(jwk, shouldExpire = true) { + cache[jwk.kid] = jwk; + lastUpdatedAt = shouldExpire ? Date.now() : -1; +} +var LocalJwkKid = "local"; +var PEM_HEADER = "-----BEGIN PUBLIC KEY-----"; +var PEM_TRAILER = "-----END PUBLIC KEY-----"; +var RSA_PREFIX = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA"; +var RSA_SUFFIX = "IDAQAB"; +function loadClerkJWKFromLocal(localKey) { + if (!getFromCache(LocalJwkKid)) { + if (!localKey) { + throw new TokenVerificationError({ + action: TokenVerificationErrorAction.SetClerkJWTKey, + message: "Missing local JWK.", + reason: TokenVerificationErrorReason.LocalJWKMissing + }); + } + const modulus = localKey.replace(/\r\n|\n|\r/g, "").replace(PEM_HEADER, "").replace(PEM_TRAILER, "").replace(RSA_PREFIX, "").replace(RSA_SUFFIX, "").replace(/\+/g, "-").replace(/\//g, "_"); + setInCache( + { + kid: "local", + kty: "RSA", + alg: "RS256", + n: modulus, + e: "AQAB" + }, + false + // local key never expires in cache + ); + } + return getFromCache(LocalJwkKid); +} +async function loadClerkJWKFromRemote({ + secretKey, + apiUrl = API_URL, + apiVersion = API_VERSION, + kid, + skipJwksCache +}) { + if (skipJwksCache || cacheHasExpired() || !getFromCache(kid)) { + if (!secretKey) { + throw new TokenVerificationError({ + action: TokenVerificationErrorAction.ContactSupport, + message: "Failed to load JWKS from Clerk Backend or Frontend API.", + reason: TokenVerificationErrorReason.RemoteJWKFailedToLoad + }); + } + const fetcher = () => fetchJWKSFromBAPI(apiUrl, secretKey, apiVersion); + const { keys } = await (0, import_retry.retry)(fetcher); + if (!keys || !keys.length) { + throw new TokenVerificationError({ + action: TokenVerificationErrorAction.ContactSupport, + message: "The JWKS endpoint did not contain any signing keys. Contact support@clerk.com.", + reason: TokenVerificationErrorReason.RemoteJWKFailedToLoad + }); + } + keys.forEach((key) => setInCache(key)); + } + const jwk = getFromCache(kid); + if (!jwk) { + const cacheValues = getCacheValues(); + const jwkKeys = cacheValues.map((jwk2) => jwk2.kid).sort().join(", "); + throw new TokenVerificationError({ + action: `Go to your Dashboard and validate your secret and public keys are correct. ${TokenVerificationErrorAction.ContactSupport} if the issue persists.`, + message: `Unable to find a signing key in JWKS that matches the kid='${kid}' of the provided session token. Please make sure that the __session cookie or the HTTP authorization header contain a Clerk-generated session JWT. The following kid is available: ${jwkKeys}`, + reason: TokenVerificationErrorReason.JWKKidMismatch + }); + } + return jwk; +} +async function fetchJWKSFromBAPI(apiUrl, key, apiVersion) { + if (!key) { + throw new TokenVerificationError({ + action: TokenVerificationErrorAction.SetClerkSecretKey, + message: "Missing Clerk Secret Key or API Key. Go to https://dashboard.clerk.com and get your key for your instance.", + reason: TokenVerificationErrorReason.RemoteJWKFailedToLoad + }); + } + const url = new URL(apiUrl); + url.pathname = joinPaths(url.pathname, apiVersion, "/jwks"); + const response = await runtime.fetch(url.href, { + headers: { + Authorization: `Bearer ${key}`, + "Clerk-API-Version": SUPPORTED_BAPI_VERSION, + "Content-Type": "application/json", + "User-Agent": USER_AGENT + } + }); + if (!response.ok) { + const json = await response.json(); + const invalidSecretKeyError = getErrorObjectByCode(json?.errors, TokenVerificationErrorCode.InvalidSecretKey); + if (invalidSecretKeyError) { + const reason = TokenVerificationErrorReason.InvalidSecretKey; + throw new TokenVerificationError({ + action: TokenVerificationErrorAction.ContactSupport, + message: invalidSecretKeyError.message, + reason + }); + } + throw new TokenVerificationError({ + action: TokenVerificationErrorAction.ContactSupport, + message: `Error loading Clerk JWKS from ${url.href} with code=${response.status}`, + reason: TokenVerificationErrorReason.RemoteJWKFailedToLoad + }); + } + return response.json(); +} +function cacheHasExpired() { + if (lastUpdatedAt === -1) { + return false; + } + const isExpired = Date.now() - lastUpdatedAt >= MAX_CACHE_LAST_UPDATED_AT_SECONDS * 1e3; + if (isExpired) { + cache = {}; + } + return isExpired; +} +var getErrorObjectByCode = (errors, code) => { + if (!errors) { + return null; + } + return errors.find((err) => err.code === code); +}; + +// src/tokens/verify.ts +var import_error3 = require("@clerk/shared/error"); +async function verifyToken(token, options) { + const { data: decodedResult, errors } = decodeJwt(token); + if (errors) { + return { errors }; + } + const { header } = decodedResult; + const { kid } = header; + try { + let key; + if (options.jwtKey) { + key = loadClerkJWKFromLocal(options.jwtKey); + } else if (options.secretKey) { + key = await loadClerkJWKFromRemote({ ...options, kid }); + } else { + return { + errors: [ + new TokenVerificationError({ + action: TokenVerificationErrorAction.SetClerkJWTKey, + message: "Failed to resolve JWK during verification.", + reason: TokenVerificationErrorReason.JWKFailedToResolve + }) + ] + }; + } + return await verifyJwt(token, { ...options, key }); + } catch (error) { + return { errors: [error] }; + } +} +function handleClerkAPIError(tokenType, err, notFoundMessage) { + if ((0, import_error3.isClerkAPIResponseError)(err)) { + let code; + let message; + switch (err.status) { + case 401: + code = MachineTokenVerificationErrorCode.InvalidSecretKey; + message = err.errors[0]?.message || "Invalid secret key"; + break; + case 404: + code = MachineTokenVerificationErrorCode.TokenInvalid; + message = notFoundMessage; + break; + default: + code = MachineTokenVerificationErrorCode.UnexpectedError; + message = "Unexpected error"; + } + return { + data: void 0, + tokenType, + errors: [ + new MachineTokenVerificationError({ + message, + code, + status: err.status + }) + ] + }; + } + return { + data: void 0, + tokenType, + errors: [ + new MachineTokenVerificationError({ + message: "Unexpected error", + code: MachineTokenVerificationErrorCode.UnexpectedError, + status: err.status + }) + ] + }; +} +async function verifyM2MToken(token, options) { + try { + const client = createBackendApiClient(options); + const verifiedToken = await client.m2m.verifyToken({ token }); + return { data: verifiedToken, tokenType: TokenType.M2MToken, errors: void 0 }; + } catch (err) { + return handleClerkAPIError(TokenType.M2MToken, err, "Machine token not found"); + } +} +async function verifyOAuthToken(accessToken, options) { + try { + const client = createBackendApiClient(options); + const verifiedToken = await client.idPOAuthAccessToken.verifyAccessToken(accessToken); + return { data: verifiedToken, tokenType: TokenType.OAuthToken, errors: void 0 }; + } catch (err) { + return handleClerkAPIError(TokenType.OAuthToken, err, "OAuth token not found"); + } +} +async function verifyAPIKey(secret, options) { + try { + const client = createBackendApiClient(options); + const verifiedToken = await client.apiKeys.verifySecret(secret); + return { data: verifiedToken, tokenType: TokenType.ApiKey, errors: void 0 }; + } catch (err) { + return handleClerkAPIError(TokenType.ApiKey, err, "API key not found"); + } +} +async function verifyMachineAuthToken(token, options) { + if (token.startsWith(M2M_TOKEN_PREFIX)) { + return verifyM2MToken(token, options); + } + if (token.startsWith(OAUTH_TOKEN_PREFIX)) { + return verifyOAuthToken(token, options); + } + if (token.startsWith(API_KEY_PREFIX)) { + return verifyAPIKey(token, options); + } + throw new Error("Unknown machine token type"); +} + +// src/tokens/handshake.ts +async function verifyHandshakeJwt(token, { key }) { + const { data: decoded, errors } = decodeJwt(token); + if (errors) { + throw errors[0]; + } + const { header, payload } = decoded; + const { typ, alg } = header; + assertHeaderType(typ); + assertHeaderAlgorithm(alg); + const { data: signatureValid, errors: signatureErrors } = await hasValidSignature(decoded, key); + if (signatureErrors) { + throw new TokenVerificationError({ + reason: TokenVerificationErrorReason.TokenVerificationFailed, + message: `Error verifying handshake token. ${signatureErrors[0]}` + }); + } + if (!signatureValid) { + throw new TokenVerificationError({ + reason: TokenVerificationErrorReason.TokenInvalidSignature, + message: "Handshake signature is invalid." + }); + } + return payload; +} +async function verifyHandshakeToken(token, options) { + const { secretKey, apiUrl, apiVersion, jwksCacheTtlInMs, jwtKey, skipJwksCache } = options; + const { data, errors } = decodeJwt(token); + if (errors) { + throw errors[0]; + } + const { kid } = data.header; + let key; + if (jwtKey) { + key = loadClerkJWKFromLocal(jwtKey); + } else if (secretKey) { + key = await loadClerkJWKFromRemote({ secretKey, apiUrl, apiVersion, kid, jwksCacheTtlInMs, skipJwksCache }); + } else { + throw new TokenVerificationError({ + action: TokenVerificationErrorAction.SetClerkJWTKey, + message: "Failed to resolve JWK during handshake verification.", + reason: TokenVerificationErrorReason.JWKFailedToResolve + }); + } + return await verifyHandshakeJwt(token, { + key + }); +} +var HandshakeService = class { + constructor(authenticateContext, options, organizationMatcher) { + this.authenticateContext = authenticateContext; + this.options = options; + this.organizationMatcher = organizationMatcher; + } + /** + * Determines if a request is eligible for handshake based on its headers + * + * Currently, a request is only eligible for a handshake if we can say it's *probably* a request for a document, not a fetch or some other exotic request. + * This heuristic should give us a reliable enough signal for browsers that support `Sec-Fetch-Dest` and for those that don't. + * + * @returns boolean indicating if the request is eligible for handshake + */ + isRequestEligibleForHandshake() { + const { accept, secFetchDest } = this.authenticateContext; + if (secFetchDest === "document" || secFetchDest === "iframe") { + return true; + } + if (!secFetchDest && accept?.startsWith("text/html")) { + return true; + } + return false; + } + /** + * Builds the redirect headers for a handshake request + * @param reason - The reason for the handshake (e.g. 'session-token-expired') + * @returns Headers object containing the Location header for redirect + * @throws Error if clerkUrl is missing in authenticateContext + */ + buildRedirectToHandshake(reason) { + if (!this.authenticateContext?.clerkUrl) { + throw new Error("Missing clerkUrl in authenticateContext"); + } + const redirectUrl = this.removeDevBrowserFromURL(this.authenticateContext.clerkUrl); + let baseUrl = this.authenticateContext.frontendApi.startsWith("http") ? this.authenticateContext.frontendApi : `https://${this.authenticateContext.frontendApi}`; + baseUrl = baseUrl.replace(/\/+$/, "") + "/"; + const url = new URL("v1/client/handshake", baseUrl); + url.searchParams.append("redirect_url", redirectUrl?.href || ""); + url.searchParams.append("__clerk_api_version", SUPPORTED_BAPI_VERSION); + url.searchParams.append( + constants.QueryParameters.SuffixedCookies, + this.authenticateContext.usesSuffixedCookies().toString() + ); + url.searchParams.append(constants.QueryParameters.HandshakeReason, reason); + url.searchParams.append(constants.QueryParameters.HandshakeFormat, "nonce"); + if (this.authenticateContext.instanceType === "development" && this.authenticateContext.devBrowserToken) { + url.searchParams.append(constants.QueryParameters.DevBrowser, this.authenticateContext.devBrowserToken); + } + const toActivate = this.getOrganizationSyncTarget(this.authenticateContext.clerkUrl, this.organizationMatcher); + if (toActivate) { + const params = this.getOrganizationSyncQueryParams(toActivate); + params.forEach((value, key) => { + url.searchParams.append(key, value); + }); + } + return new Headers({ [constants.Headers.Location]: url.href }); + } + /** + * Gets cookies from either a handshake nonce or a handshake token + * @returns Promise resolving to string array of cookie directives + */ + async getCookiesFromHandshake() { + const cookiesToSet = []; + if (this.authenticateContext.handshakeNonce) { + try { + const handshakePayload = await this.authenticateContext.apiClient?.clients.getHandshakePayload({ + nonce: this.authenticateContext.handshakeNonce + }); + if (handshakePayload) { + cookiesToSet.push(...handshakePayload.directives); + } + } catch (error) { + console.error("Clerk: HandshakeService: error getting handshake payload:", error); + } + } else if (this.authenticateContext.handshakeToken) { + const handshakePayload = await verifyHandshakeToken( + this.authenticateContext.handshakeToken, + this.authenticateContext + ); + if (handshakePayload && Array.isArray(handshakePayload.handshake)) { + cookiesToSet.push(...handshakePayload.handshake); + } + } + return cookiesToSet; + } + /** + * Resolves a handshake request by verifying the handshake token and setting appropriate cookies + * @returns Promise resolving to either a SignedInState or SignedOutState + * @throws Error if handshake verification fails or if there are issues with the session token + */ + async resolveHandshake() { + const headers = new Headers({ + "Access-Control-Allow-Origin": "null", + "Access-Control-Allow-Credentials": "true" + }); + const cookiesToSet = await this.getCookiesFromHandshake(); + let sessionToken = ""; + cookiesToSet.forEach((x) => { + headers.append("Set-Cookie", x); + if (getCookieName(x).startsWith(constants.Cookies.Session)) { + sessionToken = getCookieValue(x); + } + }); + if (this.authenticateContext.instanceType === "development") { + const newUrl = new URL(this.authenticateContext.clerkUrl); + newUrl.searchParams.delete(constants.QueryParameters.Handshake); + newUrl.searchParams.delete(constants.QueryParameters.HandshakeHelp); + newUrl.searchParams.delete(constants.QueryParameters.DevBrowser); + headers.append(constants.Headers.Location, newUrl.toString()); + headers.set(constants.Headers.CacheControl, "no-store"); + } + if (sessionToken === "") { + return signedOut({ + tokenType: TokenType.SessionToken, + authenticateContext: this.authenticateContext, + reason: AuthErrorReason.SessionTokenMissing, + message: "", + headers + }); + } + const { data, errors: [error] = [] } = await verifyToken(sessionToken, this.authenticateContext); + if (data) { + return signedIn({ + tokenType: TokenType.SessionToken, + authenticateContext: this.authenticateContext, + sessionClaims: data, + headers, + token: sessionToken + }); + } + if (this.authenticateContext.instanceType === "development" && (error?.reason === TokenVerificationErrorReason.TokenExpired || error?.reason === TokenVerificationErrorReason.TokenNotActiveYet || error?.reason === TokenVerificationErrorReason.TokenIatInTheFuture)) { + const developmentError = new TokenVerificationError({ + action: error.action, + message: error.message, + reason: error.reason + }); + developmentError.tokenCarrier = "cookie"; + console.error( + `Clerk: Clock skew detected. This usually means that your system clock is inaccurate. Clerk will attempt to account for the clock skew in development. + +To resolve this issue, make sure your system's clock is set to the correct time (e.g. turn off and on automatic time synchronization). + +--- + +${developmentError.getFullMessage()}` + ); + const { data: retryResult, errors: [retryError] = [] } = await verifyToken(sessionToken, { + ...this.authenticateContext, + clockSkewInMs: 864e5 + }); + if (retryResult) { + return signedIn({ + tokenType: TokenType.SessionToken, + authenticateContext: this.authenticateContext, + sessionClaims: retryResult, + headers, + token: sessionToken + }); + } + throw new Error(retryError?.message || "Clerk: Handshake retry failed."); + } + throw new Error(error?.message || "Clerk: Handshake failed."); + } + /** + * Handles handshake token verification errors in development mode + * @param error - The TokenVerificationError that occurred + * @throws Error with a descriptive message about the verification failure + */ + handleTokenVerificationErrorInDevelopment(error) { + if (error.reason === TokenVerificationErrorReason.TokenInvalidSignature) { + const msg = `Clerk: Handshake token verification failed due to an invalid signature. If you have switched Clerk keys locally, clear your cookies and try again.`; + throw new Error(msg); + } + throw new Error(`Clerk: Handshake token verification failed: ${error.getFullMessage()}.`); + } + /** + * Checks if a redirect loop is detected and sets headers to track redirect count + * @param headers - The Headers object to modify + * @returns boolean indicating if a redirect loop was detected (true) or if the request can proceed (false) + */ + checkAndTrackRedirectLoop(headers) { + if (this.authenticateContext.handshakeRedirectLoopCounter === 3) { + return true; + } + const newCounterValue = this.authenticateContext.handshakeRedirectLoopCounter + 1; + const cookieName = constants.Cookies.RedirectCount; + headers.append("Set-Cookie", `${cookieName}=${newCounterValue}; SameSite=Lax; HttpOnly; Max-Age=2`); + return false; + } + removeDevBrowserFromURL(url) { + const updatedURL = new URL(url); + updatedURL.searchParams.delete(constants.QueryParameters.DevBrowser); + updatedURL.searchParams.delete(constants.QueryParameters.LegacyDevBrowser); + return updatedURL; + } + getOrganizationSyncTarget(url, matchers) { + return matchers.findTarget(url); + } + getOrganizationSyncQueryParams(toActivate) { + const ret = /* @__PURE__ */ new Map(); + if (toActivate.type === "personalAccount") { + ret.set("organization_id", ""); + } + if (toActivate.type === "organization") { + if (toActivate.organizationId) { + ret.set("organization_id", toActivate.organizationId); + } + if (toActivate.organizationSlug) { + ret.set("organization_id", toActivate.organizationSlug); + } + } + return ret; + } +}; + +// src/tokens/organizationMatcher.ts +var import_pathToRegexp = require("@clerk/shared/pathToRegexp"); +var OrganizationMatcher = class { + constructor(options) { + this.organizationPattern = this.createMatcher(options?.organizationPatterns); + this.personalAccountPattern = this.createMatcher(options?.personalAccountPatterns); + } + createMatcher(pattern) { + if (!pattern) { + return null; + } + try { + return (0, import_pathToRegexp.match)(pattern); + } catch (e) { + throw new Error(`Invalid pattern "${pattern}": ${e}`); + } + } + findTarget(url) { + const orgTarget = this.findOrganizationTarget(url); + if (orgTarget) { + return orgTarget; + } + return this.findPersonalAccountTarget(url); + } + findOrganizationTarget(url) { + if (!this.organizationPattern) { + return null; + } + try { + const result = this.organizationPattern(url.pathname); + if (!result || !("params" in result)) { + return null; + } + const params = result.params; + if (params.id) { + return { type: "organization", organizationId: params.id }; + } + if (params.slug) { + return { type: "organization", organizationSlug: params.slug }; + } + return null; + } catch (e) { + console.error("Failed to match organization pattern:", e); + return null; + } + } + findPersonalAccountTarget(url) { + if (!this.personalAccountPattern) { + return null; + } + try { + const result = this.personalAccountPattern(url.pathname); + return result ? { type: "personalAccount" } : null; + } catch (e) { + console.error("Failed to match personal account pattern:", e); + return null; + } + } +}; + +// src/tokens/request.ts +var RefreshTokenErrorReason = { + NonEligibleNoCookie: "non-eligible-no-refresh-cookie", + NonEligibleNonGet: "non-eligible-non-get", + InvalidSessionToken: "invalid-session-token", + MissingApiClient: "missing-api-client", + MissingSessionToken: "missing-session-token", + MissingRefreshToken: "missing-refresh-token", + ExpiredSessionTokenDecodeFailed: "expired-session-token-decode-failed", + ExpiredSessionTokenMissingSidClaim: "expired-session-token-missing-sid-claim", + FetchError: "fetch-error", + UnexpectedSDKError: "unexpected-sdk-error", + UnexpectedBAPIError: "unexpected-bapi-error" +}; +function assertSignInUrlExists(signInUrl, key) { + if (!signInUrl && (0, import_keys.isDevelopmentFromSecretKey)(key)) { + throw new Error(`Missing signInUrl. Pass a signInUrl for dev instances if an app is satellite`); + } +} +function assertProxyUrlOrDomain(proxyUrlOrDomain) { + if (!proxyUrlOrDomain) { + throw new Error(`Missing domain and proxyUrl. A satellite application needs to specify a domain or a proxyUrl`); + } +} +function assertSignInUrlFormatAndOrigin(_signInUrl, origin) { + let signInUrl; + try { + signInUrl = new URL(_signInUrl); + } catch { + throw new Error(`The signInUrl needs to have a absolute url format.`); + } + if (signInUrl.origin === origin) { + throw new Error(`The signInUrl needs to be on a different origin than your satellite application.`); + } +} +function assertMachineSecretOrSecretKey(authenticateContext) { + if (!authenticateContext.machineSecretKey && !authenticateContext.secretKey) { + throw new Error( + "Machine token authentication requires either a Machine secret key or a Clerk secret key. Ensure a Clerk secret key or Machine secret key is set." + ); + } +} +function isRequestEligibleForRefresh(err, authenticateContext, request) { + return err.reason === TokenVerificationErrorReason.TokenExpired && !!authenticateContext.refreshTokenInCookie && request.method === "GET"; +} +function checkTokenTypeMismatch(parsedTokenType, acceptsToken, authenticateContext) { + const mismatch = !isTokenTypeAccepted(parsedTokenType, acceptsToken); + if (mismatch) { + const tokenTypeToReturn = typeof acceptsToken === "string" ? acceptsToken : parsedTokenType; + return signedOut({ + tokenType: tokenTypeToReturn, + authenticateContext, + reason: AuthErrorReason.TokenTypeMismatch + }); + } + return null; +} +function isTokenTypeInAcceptedArray(acceptsToken, authenticateContext) { + let parsedTokenType = null; + const { tokenInHeader } = authenticateContext; + if (tokenInHeader) { + if (isMachineTokenByPrefix(tokenInHeader)) { + parsedTokenType = getMachineTokenType(tokenInHeader); + } else { + parsedTokenType = TokenType.SessionToken; + } + } + const typeToCheck = parsedTokenType ?? TokenType.SessionToken; + return isTokenTypeAccepted(typeToCheck, acceptsToken); +} +var authenticateRequest = async (request, options) => { + const authenticateContext = await createAuthenticateContext(createClerkRequest(request), options); + const acceptsToken = options.acceptsToken ?? TokenType.SessionToken; + if (acceptsToken !== TokenType.M2MToken) { + assertValidSecretKey(authenticateContext.secretKey); + if (authenticateContext.isSatellite) { + assertSignInUrlExists(authenticateContext.signInUrl, authenticateContext.secretKey); + if (authenticateContext.signInUrl && authenticateContext.origin) { + assertSignInUrlFormatAndOrigin(authenticateContext.signInUrl, authenticateContext.origin); + } + assertProxyUrlOrDomain(authenticateContext.proxyUrl || authenticateContext.domain); + } + } + if (acceptsToken === TokenType.M2MToken) { + assertMachineSecretOrSecretKey(authenticateContext); + } + const organizationMatcher = new OrganizationMatcher(options.organizationSyncOptions); + const handshakeService = new HandshakeService( + authenticateContext, + { organizationSyncOptions: options.organizationSyncOptions }, + organizationMatcher + ); + async function refreshToken(authenticateContext2) { + if (!options.apiClient) { + return { + data: null, + error: { + message: "An apiClient is needed to perform token refresh.", + cause: { reason: RefreshTokenErrorReason.MissingApiClient } + } + }; + } + const { sessionToken: expiredSessionToken, refreshTokenInCookie: refreshToken2 } = authenticateContext2; + if (!expiredSessionToken) { + return { + data: null, + error: { + message: "Session token must be provided.", + cause: { reason: RefreshTokenErrorReason.MissingSessionToken } + } + }; + } + if (!refreshToken2) { + return { + data: null, + error: { + message: "Refresh token must be provided.", + cause: { reason: RefreshTokenErrorReason.MissingRefreshToken } + } + }; + } + const { data: decodeResult, errors: decodedErrors } = decodeJwt(expiredSessionToken); + if (!decodeResult || decodedErrors) { + return { + data: null, + error: { + message: "Unable to decode the expired session token.", + cause: { reason: RefreshTokenErrorReason.ExpiredSessionTokenDecodeFailed, errors: decodedErrors } + } + }; + } + if (!decodeResult?.payload?.sid) { + return { + data: null, + error: { + message: "Expired session token is missing the `sid` claim.", + cause: { reason: RefreshTokenErrorReason.ExpiredSessionTokenMissingSidClaim } + } + }; + } + try { + const response = await options.apiClient.sessions.refreshSession(decodeResult.payload.sid, { + format: "cookie", + suffixed_cookies: authenticateContext2.usesSuffixedCookies(), + expired_token: expiredSessionToken || "", + refresh_token: refreshToken2 || "", + request_origin: authenticateContext2.clerkUrl.origin, + // The refresh endpoint expects headers as Record, so we need to transform it. + request_headers: Object.fromEntries(Array.from(request.headers.entries()).map(([k, v]) => [k, [v]])) + }); + return { data: response.cookies, error: null }; + } catch (err) { + if (err?.errors?.length) { + if (err.errors[0].code === "unexpected_error") { + return { + data: null, + error: { + message: `Fetch unexpected error`, + cause: { reason: RefreshTokenErrorReason.FetchError, errors: err.errors } + } + }; + } + return { + data: null, + error: { + message: err.errors[0].code, + cause: { reason: err.errors[0].code, errors: err.errors } + } + }; + } else { + return { + data: null, + error: { + message: `Unexpected Server/BAPI error`, + cause: { reason: RefreshTokenErrorReason.UnexpectedBAPIError, errors: [err] } + } + }; + } + } + } + async function attemptRefresh(authenticateContext2) { + const { data: cookiesToSet, error } = await refreshToken(authenticateContext2); + if (!cookiesToSet || cookiesToSet.length === 0) { + return { data: null, error }; + } + const headers = new Headers(); + let sessionToken = ""; + cookiesToSet.forEach((x) => { + headers.append("Set-Cookie", x); + if (getCookieName(x).startsWith(constants.Cookies.Session)) { + sessionToken = getCookieValue(x); + } + }); + const { data: jwtPayload, errors } = await verifyToken(sessionToken, authenticateContext2); + if (errors) { + return { + data: null, + error: { + message: `Clerk: unable to verify refreshed session token.`, + cause: { reason: RefreshTokenErrorReason.InvalidSessionToken, errors } + } + }; + } + return { data: { jwtPayload, sessionToken, headers }, error: null }; + } + function handleMaybeHandshakeStatus(authenticateContext2, reason, message, headers) { + if (!handshakeService.isRequestEligibleForHandshake()) { + return signedOut({ + tokenType: TokenType.SessionToken, + authenticateContext: authenticateContext2, + reason, + message + }); + } + const handshakeHeaders = headers ?? handshakeService.buildRedirectToHandshake(reason); + if (handshakeHeaders.get(constants.Headers.Location)) { + handshakeHeaders.set(constants.Headers.CacheControl, "no-store"); + } + const isRedirectLoop = handshakeService.checkAndTrackRedirectLoop(handshakeHeaders); + if (isRedirectLoop) { + const msg = `Clerk: Refreshing the session token resulted in an infinite redirect loop. This usually means that your Clerk instance keys do not match - make sure to copy the correct publishable and secret keys from the Clerk dashboard.`; + console.log(msg); + return signedOut({ + tokenType: TokenType.SessionToken, + authenticateContext: authenticateContext2, + reason, + message + }); + } + return handshake(authenticateContext2, reason, message, handshakeHeaders); + } + function handleMaybeOrganizationSyncHandshake(authenticateContext2, auth) { + const organizationSyncTarget = organizationMatcher.findTarget(authenticateContext2.clerkUrl); + if (!organizationSyncTarget) { + return null; + } + let mustActivate = false; + if (organizationSyncTarget.type === "organization") { + if (organizationSyncTarget.organizationSlug && organizationSyncTarget.organizationSlug !== auth.orgSlug) { + mustActivate = true; + } + if (organizationSyncTarget.organizationId && organizationSyncTarget.organizationId !== auth.orgId) { + mustActivate = true; + } + } + if (organizationSyncTarget.type === "personalAccount" && auth.orgId) { + mustActivate = true; + } + if (!mustActivate) { + return null; + } + if (authenticateContext2.handshakeRedirectLoopCounter >= 3) { + console.warn( + "Clerk: Organization activation handshake loop detected. This is likely due to an invalid organization ID or slug. Skipping organization activation." + ); + return null; + } + const handshakeState = handleMaybeHandshakeStatus( + authenticateContext2, + AuthErrorReason.ActiveOrganizationMismatch, + "" + ); + if (handshakeState.status !== "handshake") { + return null; + } + return handshakeState; + } + async function authenticateRequestWithTokenInHeader() { + const { tokenInHeader } = authenticateContext; + try { + const { data, errors } = await verifyToken(tokenInHeader, authenticateContext); + if (errors) { + throw errors[0]; + } + return signedIn({ + tokenType: TokenType.SessionToken, + authenticateContext, + sessionClaims: data, + headers: new Headers(), + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + token: tokenInHeader + }); + } catch (err) { + return handleSessionTokenError(err, "header"); + } + } + async function authenticateRequestWithTokenInCookie() { + const hasActiveClient = authenticateContext.clientUat; + const hasSessionToken = !!authenticateContext.sessionTokenInCookie; + const hasDevBrowserToken = !!authenticateContext.devBrowserToken; + if (authenticateContext.handshakeNonce || authenticateContext.handshakeToken) { + try { + return await handshakeService.resolveHandshake(); + } catch (error) { + if (error instanceof TokenVerificationError && authenticateContext.instanceType === "development") { + handshakeService.handleTokenVerificationErrorInDevelopment(error); + } else { + console.error("Clerk: unable to resolve handshake:", error); + } + } + } + if (authenticateContext.instanceType === "development" && authenticateContext.clerkUrl.searchParams.has(constants.QueryParameters.DevBrowser)) { + return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.DevBrowserSync, ""); + } + const isRequestEligibleForMultiDomainSync = authenticateContext.isSatellite && authenticateContext.secFetchDest === "document"; + if (authenticateContext.instanceType === "production" && isRequestEligibleForMultiDomainSync) { + return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.SatelliteCookieNeedsSyncing, ""); + } + if (authenticateContext.instanceType === "development" && isRequestEligibleForMultiDomainSync && !authenticateContext.clerkUrl.searchParams.has(constants.QueryParameters.ClerkSynced)) { + const redirectURL = new URL(authenticateContext.signInUrl); + redirectURL.searchParams.append( + constants.QueryParameters.ClerkRedirectUrl, + authenticateContext.clerkUrl.toString() + ); + const headers = new Headers({ [constants.Headers.Location]: redirectURL.toString() }); + return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.SatelliteCookieNeedsSyncing, "", headers); + } + const redirectUrl = new URL(authenticateContext.clerkUrl).searchParams.get( + constants.QueryParameters.ClerkRedirectUrl + ); + if (authenticateContext.instanceType === "development" && !authenticateContext.isSatellite && redirectUrl) { + const redirectBackToSatelliteUrl = new URL(redirectUrl); + if (authenticateContext.devBrowserToken) { + redirectBackToSatelliteUrl.searchParams.append( + constants.QueryParameters.DevBrowser, + authenticateContext.devBrowserToken + ); + } + redirectBackToSatelliteUrl.searchParams.append(constants.QueryParameters.ClerkSynced, "true"); + const headers = new Headers({ [constants.Headers.Location]: redirectBackToSatelliteUrl.toString() }); + return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.PrimaryRespondsToSyncing, "", headers); + } + if (authenticateContext.instanceType === "development" && !hasDevBrowserToken) { + return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.DevBrowserMissing, ""); + } + if (!hasActiveClient && !hasSessionToken) { + return signedOut({ + tokenType: TokenType.SessionToken, + authenticateContext, + reason: AuthErrorReason.SessionTokenAndUATMissing + }); + } + if (!hasActiveClient && hasSessionToken) { + return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.SessionTokenWithoutClientUAT, ""); + } + if (hasActiveClient && !hasSessionToken) { + return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.ClientUATWithoutSessionToken, ""); + } + const { data: decodeResult, errors: decodedErrors } = decodeJwt(authenticateContext.sessionTokenInCookie); + if (decodedErrors) { + return handleSessionTokenError(decodedErrors[0], "cookie"); + } + if (decodeResult.payload.iat < authenticateContext.clientUat) { + return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.SessionTokenIATBeforeClientUAT, ""); + } + try { + const { data, errors } = await verifyToken(authenticateContext.sessionTokenInCookie, authenticateContext); + if (errors) { + throw errors[0]; + } + const signedInRequestState = signedIn({ + tokenType: TokenType.SessionToken, + authenticateContext, + sessionClaims: data, + headers: new Headers(), + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + token: authenticateContext.sessionTokenInCookie + }); + const shouldForceHandshakeForCrossDomain = !authenticateContext.isSatellite && // We're on primary + authenticateContext.secFetchDest === "document" && // Document navigation + authenticateContext.isCrossOriginReferrer() && // Came from different domain + !authenticateContext.isKnownClerkReferrer() && // Not from Clerk accounts portal or FAPI + authenticateContext.handshakeRedirectLoopCounter === 0; + if (shouldForceHandshakeForCrossDomain) { + return handleMaybeHandshakeStatus( + authenticateContext, + AuthErrorReason.PrimaryDomainCrossOriginSync, + "Cross-origin request from satellite domain requires handshake" + ); + } + const authObject = signedInRequestState.toAuth(); + if (authObject.userId) { + const handshakeRequestState = handleMaybeOrganizationSyncHandshake(authenticateContext, authObject); + if (handshakeRequestState) { + return handshakeRequestState; + } + } + return signedInRequestState; + } catch (err) { + return handleSessionTokenError(err, "cookie"); + } + return signedOut({ + tokenType: TokenType.SessionToken, + authenticateContext, + reason: AuthErrorReason.UnexpectedError + }); + } + async function handleSessionTokenError(err, tokenCarrier) { + if (!(err instanceof TokenVerificationError)) { + return signedOut({ + tokenType: TokenType.SessionToken, + authenticateContext, + reason: AuthErrorReason.UnexpectedError + }); + } + let refreshError; + if (isRequestEligibleForRefresh(err, authenticateContext, request)) { + const { data, error } = await attemptRefresh(authenticateContext); + if (data) { + return signedIn({ + tokenType: TokenType.SessionToken, + authenticateContext, + sessionClaims: data.jwtPayload, + headers: data.headers, + token: data.sessionToken + }); + } + if (error?.cause?.reason) { + refreshError = error.cause.reason; + } else { + refreshError = RefreshTokenErrorReason.UnexpectedSDKError; + } + } else { + if (request.method !== "GET") { + refreshError = RefreshTokenErrorReason.NonEligibleNonGet; + } else if (!authenticateContext.refreshTokenInCookie) { + refreshError = RefreshTokenErrorReason.NonEligibleNoCookie; + } else { + refreshError = null; + } + } + err.tokenCarrier = tokenCarrier; + const reasonToHandshake = [ + TokenVerificationErrorReason.TokenExpired, + TokenVerificationErrorReason.TokenNotActiveYet, + TokenVerificationErrorReason.TokenIatInTheFuture + ].includes(err.reason); + if (reasonToHandshake) { + return handleMaybeHandshakeStatus( + authenticateContext, + convertTokenVerificationErrorReasonToAuthErrorReason({ tokenError: err.reason, refreshError }), + err.getFullMessage() + ); + } + return signedOut({ + tokenType: TokenType.SessionToken, + authenticateContext, + reason: err.reason, + message: err.getFullMessage() + }); + } + function handleMachineError(tokenType, err) { + if (!(err instanceof MachineTokenVerificationError)) { + return signedOut({ + tokenType, + authenticateContext, + reason: AuthErrorReason.UnexpectedError + }); + } + return signedOut({ + tokenType, + authenticateContext, + reason: err.code, + message: err.getFullMessage() + }); + } + async function authenticateMachineRequestWithTokenInHeader() { + const { tokenInHeader } = authenticateContext; + if (!tokenInHeader) { + return handleSessionTokenError(new Error("Missing token in header"), "header"); + } + if (!isMachineTokenByPrefix(tokenInHeader)) { + return signedOut({ + tokenType: acceptsToken, + authenticateContext, + reason: AuthErrorReason.TokenTypeMismatch, + message: "" + }); + } + const parsedTokenType = getMachineTokenType(tokenInHeader); + const mismatchState = checkTokenTypeMismatch(parsedTokenType, acceptsToken, authenticateContext); + if (mismatchState) { + return mismatchState; + } + const { data, tokenType, errors } = await verifyMachineAuthToken(tokenInHeader, authenticateContext); + if (errors) { + return handleMachineError(tokenType, errors[0]); + } + return signedIn({ + tokenType, + authenticateContext, + machineData: data, + token: tokenInHeader + }); + } + async function authenticateAnyRequestWithTokenInHeader() { + const { tokenInHeader } = authenticateContext; + if (!tokenInHeader) { + return handleSessionTokenError(new Error("Missing token in header"), "header"); + } + if (isMachineTokenByPrefix(tokenInHeader)) { + const parsedTokenType = getMachineTokenType(tokenInHeader); + const mismatchState = checkTokenTypeMismatch(parsedTokenType, acceptsToken, authenticateContext); + if (mismatchState) { + return mismatchState; + } + const { data: data2, tokenType, errors: errors2 } = await verifyMachineAuthToken(tokenInHeader, authenticateContext); + if (errors2) { + return handleMachineError(tokenType, errors2[0]); + } + return signedIn({ + tokenType, + authenticateContext, + machineData: data2, + token: tokenInHeader + }); + } + const { data, errors } = await verifyToken(tokenInHeader, authenticateContext); + if (errors) { + return handleSessionTokenError(errors[0], "header"); + } + return signedIn({ + tokenType: TokenType.SessionToken, + authenticateContext, + sessionClaims: data, + token: tokenInHeader + }); + } + if (Array.isArray(acceptsToken)) { + if (!isTokenTypeInAcceptedArray(acceptsToken, authenticateContext)) { + return signedOutInvalidToken(); + } + } + if (authenticateContext.tokenInHeader) { + if (acceptsToken === "any") { + return authenticateAnyRequestWithTokenInHeader(); + } + if (acceptsToken === TokenType.SessionToken) { + return authenticateRequestWithTokenInHeader(); + } + return authenticateMachineRequestWithTokenInHeader(); + } + if (acceptsToken === TokenType.OAuthToken || acceptsToken === TokenType.ApiKey || acceptsToken === TokenType.M2MToken) { + return signedOut({ + tokenType: acceptsToken, + authenticateContext, + reason: "No token in header" + }); + } + return authenticateRequestWithTokenInCookie(); +}; +var debugRequestState = (params) => { + const { isSignedIn, isAuthenticated, proxyUrl, reason, message, publishableKey, isSatellite, domain } = params; + return { isSignedIn, isAuthenticated, proxyUrl, reason, message, publishableKey, isSatellite, domain }; +}; +var convertTokenVerificationErrorReasonToAuthErrorReason = ({ + tokenError, + refreshError +}) => { + switch (tokenError) { + case TokenVerificationErrorReason.TokenExpired: + return `${AuthErrorReason.SessionTokenExpired}-refresh-${refreshError}`; + case TokenVerificationErrorReason.TokenNotActiveYet: + return AuthErrorReason.SessionTokenNBF; + case TokenVerificationErrorReason.TokenIatInTheFuture: + return AuthErrorReason.SessionTokenIatInTheFuture; + default: + return AuthErrorReason.UnexpectedError; + } +}; + +// src/tokens/factory.ts +var defaultOptions = { + secretKey: "", + machineSecretKey: "", + jwtKey: "", + apiUrl: void 0, + apiVersion: void 0, + proxyUrl: "", + publishableKey: "", + isSatellite: false, + domain: "", + audience: "" +}; +function createAuthenticateRequest(params) { + const buildTimeOptions = mergePreDefinedOptions(defaultOptions, params.options); + const apiClient = params.apiClient; + const authenticateRequest2 = (request, options = {}) => { + const { apiUrl, apiVersion } = buildTimeOptions; + const runTimeOptions = mergePreDefinedOptions(buildTimeOptions, options); + return authenticateRequest(request, { + ...options, + ...runTimeOptions, + // We should add all the omitted props from options here (eg apiUrl / apiVersion) + // to avoid runtime options override them. + apiUrl, + apiVersion, + apiClient + }); + }; + return { + authenticateRequest: authenticateRequest2, + debugRequestState + }; +} + +// src/util/decorateObjectWithResources.ts +var decorateObjectWithResources = async (obj, authObj, opts) => { + const { loadSession, loadUser, loadOrganization } = opts || {}; + const { userId, sessionId, orgId } = authObj; + const { sessions, users, organizations } = createBackendApiClient({ ...opts }); + const [sessionResp, userResp, organizationResp] = await Promise.all([ + loadSession && sessionId ? sessions.getSession(sessionId) : Promise.resolve(void 0), + loadUser && userId ? users.getUser(userId) : Promise.resolve(void 0), + loadOrganization && orgId ? organizations.getOrganization({ organizationId: orgId }) : Promise.resolve(void 0) + ]); + const resources = stripPrivateDataFromObject({ + session: sessionResp, + user: userResp, + organization: organizationResp + }); + return Object.assign(obj, resources); +}; +function stripPrivateDataFromObject(authObject) { + const user = authObject.user ? { ...authObject.user } : authObject.user; + const organization = authObject.organization ? { ...authObject.organization } : authObject.organization; + prunePrivateMetadata(user); + prunePrivateMetadata(organization); + return { ...authObject, user, organization }; +} +function prunePrivateMetadata(resource) { + if (resource) { + if ("privateMetadata" in resource) { + delete resource["privateMetadata"]; + } + if ("private_metadata" in resource) { + delete resource["private_metadata"]; + } + } + return resource; +} + +// src/internal.ts +var import_authorization_errors = require("@clerk/shared/authorization-errors"); +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + AuthStatus, + TokenType, + authenticatedMachineObject, + constants, + createAuthenticateRequest, + createClerkRequest, + createRedirect, + debugRequestState, + decorateObjectWithResources, + getAuthObjectForAcceptedToken, + getAuthObjectFromJwt, + getMachineTokenType, + invalidTokenAuthObject, + isMachineTokenByPrefix, + isMachineTokenType, + isTokenTypeAccepted, + makeAuthObjectSerializable, + reverificationError, + reverificationErrorResponse, + signedInAuthObject, + signedOutAuthObject, + stripPrivateDataFromObject, + unauthenticatedMachineObject, + verifyMachineAuthToken +}); +//# sourceMappingURL=internal.js.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/internal.js.map b/backend/node_modules/@clerk/backend/dist/internal.js.map new file mode 100644 index 000000000..ffaf0d28f --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/internal.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../src/internal.ts","../src/constants.ts","../src/createRedirect.ts","../src/util/shared.ts","../src/util/mergePreDefinedOptions.ts","../src/errors.ts","../src/runtime.ts","../src/util/rfc4648.ts","../src/jwt/algorithms.ts","../src/jwt/assertions.ts","../src/jwt/cryptoKeys.ts","../src/jwt/verifyJwt.ts","../src/util/optionsAssertions.ts","../src/tokens/authenticateContext.ts","../src/tokens/tokenTypes.ts","../src/tokens/authObjects.ts","../src/util/path.ts","../src/api/endpoints/AbstractApi.ts","../src/api/endpoints/ActorTokenApi.ts","../src/api/endpoints/AccountlessApplicationsAPI.ts","../src/api/endpoints/AllowlistIdentifierApi.ts","../src/api/endpoints/APIKeysApi.ts","../src/api/endpoints/BetaFeaturesApi.ts","../src/api/endpoints/BlocklistIdentifierApi.ts","../src/api/endpoints/ClientApi.ts","../src/api/endpoints/DomainApi.ts","../src/api/endpoints/EmailAddressApi.ts","../src/api/endpoints/IdPOAuthAccessTokenApi.ts","../src/api/endpoints/InstanceApi.ts","../src/api/endpoints/InvitationApi.ts","../src/api/endpoints/MachineApi.ts","../src/api/endpoints/M2MTokenApi.ts","../src/api/endpoints/JwksApi.ts","../src/api/endpoints/JwtTemplatesApi.ts","../src/api/endpoints/OrganizationApi.ts","../src/api/endpoints/OAuthApplicationsApi.ts","../src/api/endpoints/PhoneNumberApi.ts","../src/api/endpoints/ProxyCheckApi.ts","../src/api/endpoints/RedirectUrlApi.ts","../src/api/endpoints/SamlConnectionApi.ts","../src/api/endpoints/SessionApi.ts","../src/api/endpoints/SignInTokenApi.ts","../src/api/endpoints/SignUpApi.ts","../src/api/endpoints/TestingTokenApi.ts","../src/api/endpoints/UserApi.ts","../src/api/endpoints/WaitlistEntryApi.ts","../src/api/endpoints/WebhookApi.ts","../src/api/endpoints/BillingApi.ts","../src/api/request.ts","../../../node_modules/.pnpm/map-obj@5.0.2/node_modules/map-obj/index.js","../../../node_modules/.pnpm/change-case@5.4.4/node_modules/change-case/src/index.ts","../../../node_modules/.pnpm/snakecase-keys@9.0.2/node_modules/snakecase-keys/index.js","../src/api/resources/AccountlessApplication.ts","../src/api/resources/ActorToken.ts","../src/api/resources/AllowlistIdentifier.ts","../src/api/resources/APIKey.ts","../src/api/resources/BlocklistIdentifier.ts","../src/api/resources/Session.ts","../src/api/resources/Client.ts","../src/api/resources/CnameTarget.ts","../src/api/resources/Cookies.ts","../src/api/resources/DeletedObject.ts","../src/api/resources/Domain.ts","../src/api/resources/Email.ts","../src/api/resources/IdentificationLink.ts","../src/api/resources/Verification.ts","../src/api/resources/EmailAddress.ts","../src/api/resources/ExternalAccount.ts","../src/api/resources/IdPOAuthAccessToken.ts","../src/api/resources/Instance.ts","../src/api/resources/InstanceRestrictions.ts","../src/api/resources/InstanceSettings.ts","../src/api/resources/Invitation.ts","../src/api/resources/JSON.ts","../src/api/resources/Machine.ts","../src/api/resources/MachineScope.ts","../src/api/resources/MachineSecretKey.ts","../src/api/resources/M2MToken.ts","../src/api/resources/JwtTemplate.ts","../src/api/resources/OauthAccessToken.ts","../src/api/resources/OAuthApplication.ts","../src/api/resources/Organization.ts","../src/api/resources/OrganizationInvitation.ts","../src/api/resources/OrganizationMembership.ts","../src/api/resources/OrganizationSettings.ts","../src/api/resources/PhoneNumber.ts","../src/api/resources/ProxyCheck.ts","../src/api/resources/RedirectUrl.ts","../src/api/resources/SamlConnection.ts","../src/api/resources/SamlAccount.ts","../src/api/resources/SignInTokens.ts","../src/api/resources/SignUpAttempt.ts","../src/api/resources/SMSMessage.ts","../src/api/resources/Token.ts","../src/api/resources/Web3Wallet.ts","../src/api/resources/User.ts","../src/api/resources/WaitlistEntry.ts","../src/api/resources/Feature.ts","../src/api/resources/CommercePlan.ts","../src/api/resources/CommerceSubscriptionItem.ts","../src/api/resources/CommerceSubscription.ts","../src/api/resources/Deserializer.ts","../src/api/factory.ts","../src/tokens/machine.ts","../src/tokens/authStatus.ts","../src/tokens/clerkRequest.ts","../src/tokens/clerkUrl.ts","../src/tokens/cookie.ts","../src/tokens/keys.ts","../src/tokens/verify.ts","../src/tokens/handshake.ts","../src/tokens/organizationMatcher.ts","../src/tokens/request.ts","../src/tokens/factory.ts","../src/util/decorateObjectWithResources.ts"],"sourcesContent":["export { constants } from './constants';\nexport { createRedirect } from './createRedirect';\nexport type { RedirectFun } from './createRedirect';\n\nexport type { CreateAuthenticateRequestOptions } from './tokens/factory';\nexport { createAuthenticateRequest } from './tokens/factory';\n\nexport { debugRequestState } from './tokens/request';\n\nexport type {\n AuthenticateRequestOptions,\n OrganizationSyncOptions,\n InferAuthObjectFromToken,\n InferAuthObjectFromTokenArray,\n GetAuthFn,\n} from './tokens/types';\n\nexport { TokenType } from './tokens/tokenTypes';\nexport type { SessionTokenType, MachineTokenType } from './tokens/tokenTypes';\n\nexport type {\n SignedInAuthObjectOptions,\n SignedInAuthObject,\n SignedOutAuthObject,\n AuthenticatedMachineObject,\n UnauthenticatedMachineObject,\n} from './tokens/authObjects';\nexport {\n makeAuthObjectSerializable,\n signedOutAuthObject,\n signedInAuthObject,\n authenticatedMachineObject,\n unauthenticatedMachineObject,\n invalidTokenAuthObject,\n getAuthObjectFromJwt,\n getAuthObjectForAcceptedToken,\n} from './tokens/authObjects';\n\nexport { AuthStatus } from './tokens/authStatus';\nexport type {\n RequestState,\n SignedInState,\n SignedOutState,\n AuthenticatedState,\n UnauthenticatedState,\n} from './tokens/authStatus';\n\nexport { decorateObjectWithResources, stripPrivateDataFromObject } from './util/decorateObjectWithResources';\n\nexport { createClerkRequest } from './tokens/clerkRequest';\nexport type { ClerkRequest } from './tokens/clerkRequest';\n\nexport { reverificationError, reverificationErrorResponse } from '@clerk/shared/authorization-errors';\n\nexport { verifyMachineAuthToken } from './tokens/verify';\n\nexport { isMachineTokenByPrefix, isMachineTokenType, getMachineTokenType, isTokenTypeAccepted } from './tokens/machine';\n","export const API_URL = 'https://api.clerk.com';\nexport const API_VERSION = 'v1';\n\nexport const USER_AGENT = `${PACKAGE_NAME}@${PACKAGE_VERSION}`;\nexport const MAX_CACHE_LAST_UPDATED_AT_SECONDS = 5 * 60;\nexport const SUPPORTED_BAPI_VERSION = '2025-04-10';\n\nconst Attributes = {\n AuthToken: '__clerkAuthToken',\n AuthSignature: '__clerkAuthSignature',\n AuthStatus: '__clerkAuthStatus',\n AuthReason: '__clerkAuthReason',\n AuthMessage: '__clerkAuthMessage',\n ClerkUrl: '__clerkUrl',\n} as const;\n\nconst Cookies = {\n Session: '__session',\n Refresh: '__refresh',\n ClientUat: '__client_uat',\n Handshake: '__clerk_handshake',\n DevBrowser: '__clerk_db_jwt',\n RedirectCount: '__clerk_redirect_count',\n HandshakeNonce: '__clerk_handshake_nonce',\n} as const;\n\nconst QueryParameters = {\n ClerkSynced: '__clerk_synced',\n SuffixedCookies: 'suffixed_cookies',\n ClerkRedirectUrl: '__clerk_redirect_url',\n // use the reference to Cookies to indicate that it's the same value\n DevBrowser: Cookies.DevBrowser,\n Handshake: Cookies.Handshake,\n HandshakeHelp: '__clerk_help',\n LegacyDevBrowser: '__dev_session',\n HandshakeReason: '__clerk_hs_reason',\n HandshakeNonce: Cookies.HandshakeNonce,\n HandshakeFormat: 'format',\n} as const;\n\nconst Headers = {\n Accept: 'accept',\n AuthMessage: 'x-clerk-auth-message',\n Authorization: 'authorization',\n AuthReason: 'x-clerk-auth-reason',\n AuthSignature: 'x-clerk-auth-signature',\n AuthStatus: 'x-clerk-auth-status',\n AuthToken: 'x-clerk-auth-token',\n CacheControl: 'cache-control',\n ClerkRedirectTo: 'x-clerk-redirect-to',\n ClerkRequestData: 'x-clerk-request-data',\n ClerkUrl: 'x-clerk-clerk-url',\n CloudFrontForwardedProto: 'cloudfront-forwarded-proto',\n ContentType: 'content-type',\n ContentSecurityPolicy: 'content-security-policy',\n ContentSecurityPolicyReportOnly: 'content-security-policy-report-only',\n EnableDebug: 'x-clerk-debug',\n ForwardedHost: 'x-forwarded-host',\n ForwardedPort: 'x-forwarded-port',\n ForwardedProto: 'x-forwarded-proto',\n Host: 'host',\n Location: 'location',\n Nonce: 'x-nonce',\n Origin: 'origin',\n Referrer: 'referer',\n SecFetchDest: 'sec-fetch-dest',\n SecFetchSite: 'sec-fetch-site',\n UserAgent: 'user-agent',\n ReportingEndpoints: 'reporting-endpoints',\n} as const;\n\nconst ContentTypes = {\n Json: 'application/json',\n} as const;\n\n/**\n * @internal\n */\nexport const constants = {\n Attributes,\n Cookies,\n Headers,\n ContentTypes,\n QueryParameters,\n} as const;\n\nexport type Constants = typeof constants;\n","import { buildAccountsBaseUrl } from '@clerk/shared/buildAccountsBaseUrl';\nimport type { SessionStatusClaim } from '@clerk/types';\n\nimport { constants } from './constants';\nimport { errorThrower, parsePublishableKey } from './util/shared';\n\nconst buildUrl = (\n _baseUrl: string | URL,\n _targetUrl: string | URL,\n _returnBackUrl?: string | URL | null,\n _devBrowserToken?: string | null,\n) => {\n if (_baseUrl === '') {\n return legacyBuildUrl(_targetUrl.toString(), _returnBackUrl?.toString());\n }\n\n const baseUrl = new URL(_baseUrl);\n const returnBackUrl = _returnBackUrl ? new URL(_returnBackUrl, baseUrl) : undefined;\n const res = new URL(_targetUrl, baseUrl);\n const isCrossOriginRedirect = `${baseUrl.hostname}:${baseUrl.port}` !== `${res.hostname}:${res.port}`;\n\n if (returnBackUrl) {\n if (isCrossOriginRedirect) {\n returnBackUrl.searchParams.delete(constants.QueryParameters.ClerkSynced);\n }\n\n res.searchParams.set('redirect_url', returnBackUrl.toString());\n }\n // For cross-origin redirects, we need to pass the dev browser token for URL session syncing\n if (isCrossOriginRedirect && _devBrowserToken) {\n res.searchParams.set(constants.QueryParameters.DevBrowser, _devBrowserToken);\n }\n return res.toString();\n};\n\n/**\n * In v5, we deprecated the top-level redirectToSignIn and redirectToSignUp functions\n * in favor of the new auth().redirectToSignIn helpers\n * In order to allow for a smooth transition, we need to support the legacy redirectToSignIn for now\n * as we will remove it in v6.\n * In order to make sure that the legacy function works as expected, we will use legacyBuildUrl\n * to build the url if baseUrl is not provided (which is the case for legacy redirectToSignIn)\n * This function can be safely removed when we remove the legacy redirectToSignIn function\n */\nconst legacyBuildUrl = (targetUrl: string, redirectUrl?: string) => {\n let url;\n if (!targetUrl.startsWith('http')) {\n if (!redirectUrl || !redirectUrl.startsWith('http')) {\n throw new Error('destination url or return back url should be an absolute path url!');\n }\n\n const baseURL = new URL(redirectUrl);\n url = new URL(targetUrl, baseURL.origin);\n } else {\n url = new URL(targetUrl);\n }\n\n if (redirectUrl) {\n url.searchParams.set('redirect_url', redirectUrl);\n }\n\n return url.toString();\n};\n\ntype RedirectAdapter = (url: string) => RedirectReturn;\ntype RedirectToParams = { returnBackUrl?: string | URL | null };\nexport type RedirectFun = (params?: RedirectToParams) => ReturnType;\n\n/**\n * @internal\n */\ntype CreateRedirect = (params: {\n publishableKey: string;\n devBrowserToken?: string;\n redirectAdapter: RedirectAdapter;\n baseUrl: URL | string;\n signInUrl?: URL | string;\n signUpUrl?: URL | string;\n sessionStatus?: SessionStatusClaim | null;\n}) => {\n redirectToSignIn: RedirectFun;\n redirectToSignUp: RedirectFun;\n};\n\nexport const createRedirect: CreateRedirect = params => {\n const { publishableKey, redirectAdapter, signInUrl, signUpUrl, baseUrl, sessionStatus } = params;\n const parsedPublishableKey = parsePublishableKey(publishableKey);\n const frontendApi = parsedPublishableKey?.frontendApi;\n const isDevelopment = parsedPublishableKey?.instanceType === 'development';\n const accountsBaseUrl = buildAccountsBaseUrl(frontendApi);\n const hasPendingStatus = sessionStatus === 'pending';\n\n const redirectToTasks = (url: string | URL, { returnBackUrl }: RedirectToParams) => {\n return redirectAdapter(\n buildUrl(baseUrl, `${url}/tasks`, returnBackUrl, isDevelopment ? params.devBrowserToken : null),\n );\n };\n\n const redirectToSignUp = ({ returnBackUrl }: RedirectToParams = {}) => {\n if (!signUpUrl && !accountsBaseUrl) {\n errorThrower.throwMissingPublishableKeyError();\n }\n\n const accountsSignUpUrl = `${accountsBaseUrl}/sign-up`;\n\n // Allows redirection to SignInOrUp path\n function buildSignUpUrl(signIn: string | URL | undefined) {\n if (!signIn) {\n return;\n }\n const url = new URL(signIn, baseUrl);\n url.pathname = `${url.pathname}/create`;\n return url.toString();\n }\n\n const targetUrl = signUpUrl || buildSignUpUrl(signInUrl) || accountsSignUpUrl;\n\n if (hasPendingStatus) {\n return redirectToTasks(targetUrl, { returnBackUrl });\n }\n\n return redirectAdapter(buildUrl(baseUrl, targetUrl, returnBackUrl, isDevelopment ? params.devBrowserToken : null));\n };\n\n const redirectToSignIn = ({ returnBackUrl }: RedirectToParams = {}) => {\n if (!signInUrl && !accountsBaseUrl) {\n errorThrower.throwMissingPublishableKeyError();\n }\n\n const accountsSignInUrl = `${accountsBaseUrl}/sign-in`;\n const targetUrl = signInUrl || accountsSignInUrl;\n\n if (hasPendingStatus) {\n return redirectToTasks(targetUrl, { returnBackUrl });\n }\n\n return redirectAdapter(buildUrl(baseUrl, targetUrl, returnBackUrl, isDevelopment ? params.devBrowserToken : null));\n };\n\n return { redirectToSignUp, redirectToSignIn };\n};\n","export { addClerkPrefix, getScriptUrl, getClerkJsMajorVersionOrTag } from '@clerk/shared/url';\nexport { retry } from '@clerk/shared/retry';\nexport {\n isDevelopmentFromSecretKey,\n isProductionFromSecretKey,\n parsePublishableKey,\n getCookieSuffix,\n getSuffixedCookieName,\n} from '@clerk/shared/keys';\nexport { deprecated, deprecatedProperty } from '@clerk/shared/deprecated';\n\nimport { buildErrorThrower } from '@clerk/shared/error';\nimport { createDevOrStagingUrlCache } from '@clerk/shared/keys';\n// TODO: replace packageName with `${PACKAGE_NAME}@${PACKAGE_VERSION}` from tsup.config.ts\nexport const errorThrower = buildErrorThrower({ packageName: '@clerk/backend' });\n\nexport const { isDevOrStagingUrl } = createDevOrStagingUrlCache();\n","export function mergePreDefinedOptions>(preDefinedOptions: T, options: Partial): T {\n return Object.keys(preDefinedOptions).reduce(\n (obj: T, key: string) => {\n return { ...obj, [key]: options[key] || obj[key] };\n },\n { ...preDefinedOptions },\n );\n}\n","export type TokenCarrier = 'header' | 'cookie';\n\nexport const TokenVerificationErrorCode = {\n InvalidSecretKey: 'clerk_key_invalid',\n};\n\nexport type TokenVerificationErrorCode = (typeof TokenVerificationErrorCode)[keyof typeof TokenVerificationErrorCode];\n\nexport const TokenVerificationErrorReason = {\n TokenExpired: 'token-expired',\n TokenInvalid: 'token-invalid',\n TokenInvalidAlgorithm: 'token-invalid-algorithm',\n TokenInvalidAuthorizedParties: 'token-invalid-authorized-parties',\n TokenInvalidSignature: 'token-invalid-signature',\n TokenNotActiveYet: 'token-not-active-yet',\n TokenIatInTheFuture: 'token-iat-in-the-future',\n TokenVerificationFailed: 'token-verification-failed',\n InvalidSecretKey: 'secret-key-invalid',\n LocalJWKMissing: 'jwk-local-missing',\n RemoteJWKFailedToLoad: 'jwk-remote-failed-to-load',\n RemoteJWKInvalid: 'jwk-remote-invalid',\n RemoteJWKMissing: 'jwk-remote-missing',\n JWKFailedToResolve: 'jwk-failed-to-resolve',\n JWKKidMismatch: 'jwk-kid-mismatch',\n};\n\nexport type TokenVerificationErrorReason =\n (typeof TokenVerificationErrorReason)[keyof typeof TokenVerificationErrorReason];\n\nexport const TokenVerificationErrorAction = {\n ContactSupport: 'Contact support@clerk.com',\n EnsureClerkJWT: 'Make sure that this is a valid Clerk generate JWT.',\n SetClerkJWTKey: 'Set the CLERK_JWT_KEY environment variable.',\n SetClerkSecretKey: 'Set the CLERK_SECRET_KEY environment variable.',\n EnsureClockSync: 'Make sure your system clock is in sync (e.g. turn off and on automatic time synchronization).',\n};\n\nexport type TokenVerificationErrorAction =\n (typeof TokenVerificationErrorAction)[keyof typeof TokenVerificationErrorAction];\n\nexport class TokenVerificationError extends Error {\n action?: TokenVerificationErrorAction;\n reason: TokenVerificationErrorReason;\n tokenCarrier?: TokenCarrier;\n\n constructor({\n action,\n message,\n reason,\n }: {\n action?: TokenVerificationErrorAction;\n message: string;\n reason: TokenVerificationErrorReason;\n }) {\n super(message);\n\n Object.setPrototypeOf(this, TokenVerificationError.prototype);\n\n this.reason = reason;\n this.message = message;\n this.action = action;\n }\n\n public getFullMessage() {\n return `${[this.message, this.action].filter(m => m).join(' ')} (reason=${this.reason}, token-carrier=${\n this.tokenCarrier\n })`;\n }\n}\n\nexport class SignJWTError extends Error {}\n\nexport const MachineTokenVerificationErrorCode = {\n TokenInvalid: 'token-invalid',\n InvalidSecretKey: 'secret-key-invalid',\n UnexpectedError: 'unexpected-error',\n} as const;\n\nexport type MachineTokenVerificationErrorCode =\n (typeof MachineTokenVerificationErrorCode)[keyof typeof MachineTokenVerificationErrorCode];\n\nexport class MachineTokenVerificationError extends Error {\n code: MachineTokenVerificationErrorCode;\n long_message?: string;\n status: number;\n\n constructor({ message, code, status }: { message: string; code: MachineTokenVerificationErrorCode; status: number }) {\n super(message);\n Object.setPrototypeOf(this, MachineTokenVerificationError.prototype);\n\n this.code = code;\n this.status = status;\n }\n\n public getFullMessage() {\n return `${this.message} (code=${this.code}, status=${this.status})`;\n }\n}\n","/**\n * This file exports APIs that vary across runtimes (i.e. Node & Browser - V8 isolates)\n * as a singleton object.\n *\n * Runtime polyfills are written in VanillaJS for now to avoid TS complication. Moreover,\n * due to this issue https://github.com/microsoft/TypeScript/issues/44848, there is not a good way\n * to tell Typescript which conditional import to use during build type.\n *\n * The Runtime type definition ensures type safety for now.\n * Runtime js modules are copied into dist folder with bash script.\n *\n * TODO: Support TS runtime modules\n */\n\n// @ts-ignore - These are package subpaths\nimport { webcrypto as crypto } from '#crypto';\n\ntype Runtime = {\n crypto: Crypto;\n fetch: typeof globalThis.fetch;\n AbortController: typeof globalThis.AbortController;\n Blob: typeof globalThis.Blob;\n FormData: typeof globalThis.FormData;\n Headers: typeof globalThis.Headers;\n Request: typeof globalThis.Request;\n Response: typeof globalThis.Response;\n};\n\n// Invoking the global.fetch without binding it first to the globalObject fails in\n// Cloudflare Workers with an \"Illegal Invocation\" error.\n//\n// The globalThis object is supported for Node >= 12.0.\n//\n// https://github.com/supabase/supabase/issues/4417\nconst globalFetch = fetch.bind(globalThis);\n\nexport const runtime: Runtime = {\n crypto,\n get fetch() {\n // We need to use the globalFetch for Cloudflare Workers but the fetch for testing\n return process.env.NODE_ENV === 'test' ? fetch : globalFetch;\n },\n AbortController: globalThis.AbortController,\n Blob: globalThis.Blob,\n FormData: globalThis.FormData,\n Headers: globalThis.Headers,\n Request: globalThis.Request,\n Response: globalThis.Response,\n};\n","/**\n * The base64url helper was extracted from the rfc4648 package\n * in order to resolve CSJ/ESM interoperability issues\n *\n * https://github.com/swansontec/rfc4648.js\n *\n * For more context please refer to:\n * - https://github.com/evanw/esbuild/issues/1719\n * - https://github.com/evanw/esbuild/issues/532\n * - https://github.com/swansontec/rollup-plugin-mjs-entry\n */\nexport const base64url = {\n parse(string: string, opts?: ParseOptions): Uint8Array {\n return parse(string, base64UrlEncoding, opts);\n },\n\n stringify(data: ArrayLike, opts?: StringifyOptions): string {\n return stringify(data, base64UrlEncoding, opts);\n },\n};\n\nconst base64UrlEncoding: Encoding = {\n chars: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',\n bits: 6,\n};\n\ninterface Encoding {\n bits: number;\n chars: string;\n codes?: { [char: string]: number };\n}\n\ninterface ParseOptions {\n loose?: boolean;\n out?: new (size: number) => { [index: number]: number };\n}\n\ninterface StringifyOptions {\n pad?: boolean;\n}\n\nfunction parse(string: string, encoding: Encoding, opts: ParseOptions = {}): Uint8Array {\n // Build the character lookup table:\n if (!encoding.codes) {\n encoding.codes = {};\n for (let i = 0; i < encoding.chars.length; ++i) {\n encoding.codes[encoding.chars[i]] = i;\n }\n }\n\n // The string must have a whole number of bytes:\n if (!opts.loose && (string.length * encoding.bits) & 7) {\n throw new SyntaxError('Invalid padding');\n }\n\n // Count the padding bytes:\n let end = string.length;\n while (string[end - 1] === '=') {\n --end;\n\n // If we get a whole number of bytes, there is too much padding:\n if (!opts.loose && !(((string.length - end) * encoding.bits) & 7)) {\n throw new SyntaxError('Invalid padding');\n }\n }\n\n // Allocate the output:\n const out = new (opts.out ?? Uint8Array)(((end * encoding.bits) / 8) | 0) as Uint8Array;\n\n // Parse the data:\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n let written = 0; // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = encoding.codes[string[i]];\n if (value === undefined) {\n throw new SyntaxError('Invalid character ' + string[i]);\n }\n\n // Append the bits to the buffer:\n buffer = (buffer << encoding.bits) | value;\n bits += encoding.bits;\n\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8;\n out[written++] = 0xff & (buffer >> bits);\n }\n }\n\n // Verify that we have received just enough bits:\n if (bits >= encoding.bits || 0xff & (buffer << (8 - bits))) {\n throw new SyntaxError('Unexpected end of data');\n }\n\n return out;\n}\n\nfunction stringify(data: ArrayLike, encoding: Encoding, opts: StringifyOptions = {}): string {\n const { pad = true } = opts;\n const mask = (1 << encoding.bits) - 1;\n let out = '';\n\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | (0xff & data[i]);\n bits += 8;\n\n // Write out as much as we can:\n while (bits > encoding.bits) {\n bits -= encoding.bits;\n out += encoding.chars[mask & (buffer >> bits)];\n }\n }\n\n // Partial character:\n if (bits) {\n out += encoding.chars[mask & (buffer << (encoding.bits - bits))];\n }\n\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while ((out.length * encoding.bits) & 7) {\n out += '=';\n }\n }\n\n return out;\n}\n","const algToHash: Record = {\n RS256: 'SHA-256',\n RS384: 'SHA-384',\n RS512: 'SHA-512',\n};\nconst RSA_ALGORITHM_NAME = 'RSASSA-PKCS1-v1_5';\n\nconst jwksAlgToCryptoAlg: Record = {\n RS256: RSA_ALGORITHM_NAME,\n RS384: RSA_ALGORITHM_NAME,\n RS512: RSA_ALGORITHM_NAME,\n};\n\nexport const algs = Object.keys(algToHash);\n\nexport function getCryptoAlgorithm(algorithmName: string): RsaHashedImportParams {\n const hash = algToHash[algorithmName];\n const name = jwksAlgToCryptoAlg[algorithmName];\n\n if (!hash || !name) {\n throw new Error(`Unsupported algorithm ${algorithmName}, expected one of ${algs.join(',')}.`);\n }\n\n return {\n hash: { name: algToHash[algorithmName] },\n name: jwksAlgToCryptoAlg[algorithmName],\n };\n}\n","import { TokenVerificationError, TokenVerificationErrorAction, TokenVerificationErrorReason } from '../errors';\nimport { algs } from './algorithms';\n\nexport type IssuerResolver = string | ((iss: string) => boolean);\n\nconst isArrayString = (s: unknown): s is string[] => {\n return Array.isArray(s) && s.length > 0 && s.every(a => typeof a === 'string');\n};\n\nexport const assertAudienceClaim = (aud?: unknown, audience?: unknown) => {\n const audienceList = [audience].flat().filter(a => !!a);\n const audList = [aud].flat().filter(a => !!a);\n const shouldVerifyAudience = audienceList.length > 0 && audList.length > 0;\n\n if (!shouldVerifyAudience) {\n // Notice: Clerk JWTs use AZP claim instead of Audience\n //\n // return {\n // valid: false,\n // reason: `Invalid JWT audience claim (aud) ${JSON.stringify(\n // aud,\n // )}. Expected a string or a non-empty array of strings.`,\n // };\n return;\n }\n\n if (typeof aud === 'string') {\n if (!audienceList.includes(aud)) {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.EnsureClerkJWT,\n reason: TokenVerificationErrorReason.TokenVerificationFailed,\n message: `Invalid JWT audience claim (aud) ${JSON.stringify(aud)}. Is not included in \"${JSON.stringify(\n audienceList,\n )}\".`,\n });\n }\n } else if (isArrayString(aud)) {\n if (!aud.some(a => audienceList.includes(a))) {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.EnsureClerkJWT,\n reason: TokenVerificationErrorReason.TokenVerificationFailed,\n message: `Invalid JWT audience claim array (aud) ${JSON.stringify(aud)}. Is not included in \"${JSON.stringify(\n audienceList,\n )}\".`,\n });\n }\n }\n};\n\nexport const assertHeaderType = (typ?: unknown) => {\n if (typeof typ === 'undefined') {\n return;\n }\n\n if (typ !== 'JWT') {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.EnsureClerkJWT,\n reason: TokenVerificationErrorReason.TokenInvalid,\n message: `Invalid JWT type ${JSON.stringify(typ)}. Expected \"JWT\".`,\n });\n }\n};\n\nexport const assertHeaderAlgorithm = (alg: string) => {\n if (!algs.includes(alg)) {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.EnsureClerkJWT,\n reason: TokenVerificationErrorReason.TokenInvalidAlgorithm,\n message: `Invalid JWT algorithm ${JSON.stringify(alg)}. Supported: ${algs}.`,\n });\n }\n};\n\nexport const assertSubClaim = (sub?: string) => {\n if (typeof sub !== 'string') {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.EnsureClerkJWT,\n reason: TokenVerificationErrorReason.TokenVerificationFailed,\n message: `Subject claim (sub) is required and must be a string. Received ${JSON.stringify(sub)}.`,\n });\n }\n};\n\nexport const assertAuthorizedPartiesClaim = (azp?: string, authorizedParties?: string[]) => {\n if (!azp || !authorizedParties || authorizedParties.length === 0) {\n return;\n }\n\n if (!authorizedParties.includes(azp)) {\n throw new TokenVerificationError({\n reason: TokenVerificationErrorReason.TokenInvalidAuthorizedParties,\n message: `Invalid JWT Authorized party claim (azp) ${JSON.stringify(azp)}. Expected \"${authorizedParties}\".`,\n });\n }\n};\n\nexport const assertExpirationClaim = (exp: number, clockSkewInMs: number) => {\n if (typeof exp !== 'number') {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.EnsureClerkJWT,\n reason: TokenVerificationErrorReason.TokenVerificationFailed,\n message: `Invalid JWT expiry date claim (exp) ${JSON.stringify(exp)}. Expected number.`,\n });\n }\n\n const currentDate = new Date(Date.now());\n const expiryDate = new Date(0);\n expiryDate.setUTCSeconds(exp);\n\n const expired = expiryDate.getTime() <= currentDate.getTime() - clockSkewInMs;\n if (expired) {\n throw new TokenVerificationError({\n reason: TokenVerificationErrorReason.TokenExpired,\n message: `JWT is expired. Expiry date: ${expiryDate.toUTCString()}, Current date: ${currentDate.toUTCString()}.`,\n });\n }\n};\n\nexport const assertActivationClaim = (nbf: number | undefined, clockSkewInMs: number) => {\n if (typeof nbf === 'undefined') {\n return;\n }\n\n if (typeof nbf !== 'number') {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.EnsureClerkJWT,\n reason: TokenVerificationErrorReason.TokenVerificationFailed,\n message: `Invalid JWT not before date claim (nbf) ${JSON.stringify(nbf)}. Expected number.`,\n });\n }\n\n const currentDate = new Date(Date.now());\n const notBeforeDate = new Date(0);\n notBeforeDate.setUTCSeconds(nbf);\n\n const early = notBeforeDate.getTime() > currentDate.getTime() + clockSkewInMs;\n if (early) {\n throw new TokenVerificationError({\n reason: TokenVerificationErrorReason.TokenNotActiveYet,\n message: `JWT cannot be used prior to not before date claim (nbf). Not before date: ${notBeforeDate.toUTCString()}; Current date: ${currentDate.toUTCString()};`,\n });\n }\n};\n\nexport const assertIssuedAtClaim = (iat: number | undefined, clockSkewInMs: number) => {\n if (typeof iat === 'undefined') {\n return;\n }\n\n if (typeof iat !== 'number') {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.EnsureClerkJWT,\n reason: TokenVerificationErrorReason.TokenVerificationFailed,\n message: `Invalid JWT issued at date claim (iat) ${JSON.stringify(iat)}. Expected number.`,\n });\n }\n\n const currentDate = new Date(Date.now());\n const issuedAtDate = new Date(0);\n issuedAtDate.setUTCSeconds(iat);\n\n const postIssued = issuedAtDate.getTime() > currentDate.getTime() + clockSkewInMs;\n if (postIssued) {\n throw new TokenVerificationError({\n reason: TokenVerificationErrorReason.TokenIatInTheFuture,\n message: `JWT issued at date claim (iat) is in the future. Issued at date: ${issuedAtDate.toUTCString()}; Current date: ${currentDate.toUTCString()};`,\n });\n }\n};\n","import { isomorphicAtob } from '@clerk/shared/isomorphicAtob';\n\nimport { runtime } from '../runtime';\n\n// https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/importKey#pkcs_8_import\nfunction pemToBuffer(secret: string): ArrayBuffer {\n const trimmed = secret\n .replace(/-----BEGIN.*?-----/g, '')\n .replace(/-----END.*?-----/g, '')\n .replace(/\\s/g, '');\n\n const decoded = isomorphicAtob(trimmed);\n\n const buffer = new ArrayBuffer(decoded.length);\n const bufView = new Uint8Array(buffer);\n\n for (let i = 0, strLen = decoded.length; i < strLen; i++) {\n bufView[i] = decoded.charCodeAt(i);\n }\n\n return bufView;\n}\n\nexport function importKey(\n key: JsonWebKey | string,\n algorithm: RsaHashedImportParams,\n keyUsage: 'verify' | 'sign',\n): Promise {\n if (typeof key === 'object') {\n return runtime.crypto.subtle.importKey('jwk', key, algorithm, false, [keyUsage]);\n }\n\n const keyData = pemToBuffer(key);\n const format = keyUsage === 'sign' ? 'pkcs8' : 'spki';\n\n return runtime.crypto.subtle.importKey(format, keyData, algorithm, false, [keyUsage]);\n}\n","import type { Jwt, JwtPayload } from '@clerk/types';\n\nimport { TokenVerificationError, TokenVerificationErrorAction, TokenVerificationErrorReason } from '../errors';\nimport { runtime } from '../runtime';\nimport { base64url } from '../util/rfc4648';\nimport { getCryptoAlgorithm } from './algorithms';\nimport {\n assertActivationClaim,\n assertAudienceClaim,\n assertAuthorizedPartiesClaim,\n assertExpirationClaim,\n assertHeaderAlgorithm,\n assertHeaderType,\n assertIssuedAtClaim,\n assertSubClaim,\n} from './assertions';\nimport { importKey } from './cryptoKeys';\nimport type { JwtReturnType } from './types';\n\nconst DEFAULT_CLOCK_SKEW_IN_MS = 5 * 1000;\n\nexport async function hasValidSignature(jwt: Jwt, key: JsonWebKey | string): Promise> {\n const { header, signature, raw } = jwt;\n const encoder = new TextEncoder();\n const data = encoder.encode([raw.header, raw.payload].join('.'));\n const algorithm = getCryptoAlgorithm(header.alg);\n\n try {\n const cryptoKey = await importKey(key, algorithm, 'verify');\n\n const verified = await runtime.crypto.subtle.verify(algorithm.name, cryptoKey, signature, data);\n return { data: verified };\n } catch (error) {\n return {\n errors: [\n new TokenVerificationError({\n reason: TokenVerificationErrorReason.TokenInvalidSignature,\n message: (error as Error)?.message,\n }),\n ],\n };\n }\n}\n\nexport function decodeJwt(token: string): JwtReturnType {\n const tokenParts = (token || '').toString().split('.');\n if (tokenParts.length !== 3) {\n return {\n errors: [\n new TokenVerificationError({\n reason: TokenVerificationErrorReason.TokenInvalid,\n message: `Invalid JWT form. A JWT consists of three parts separated by dots.`,\n }),\n ],\n };\n }\n\n const [rawHeader, rawPayload, rawSignature] = tokenParts;\n\n const decoder = new TextDecoder();\n\n // To verify a JWS with SubtleCrypto you need to be careful to encode and decode\n // the data properly between binary and base64url representation. Unfortunately\n // the standard implementation in the V8 of btoa() and atob() are difficult to\n // work with as they use \"a Unicode string containing only characters in the\n // range U+0000 to U+00FF, each representing a binary byte with values 0x00 to\n // 0xFF respectively\" as the representation of binary data.\n\n // A better solution to represent binary data in Javascript is to use ES6 TypedArray\n // and use a Javascript library to convert them to base64url that honors RFC 4648.\n\n // Side note: The difference between base64 and base64url is the characters selected\n // for value 62 and 63 in the standard, base64 encode them to + and / while base64url\n // encode - and _.\n\n // More info at https://stackoverflow.com/questions/54062583/how-to-verify-a-signed-jwt-with-subtlecrypto-of-the-web-crypto-API\n const header = JSON.parse(decoder.decode(base64url.parse(rawHeader, { loose: true })));\n const payload = JSON.parse(decoder.decode(base64url.parse(rawPayload, { loose: true })));\n\n const signature = base64url.parse(rawSignature, { loose: true });\n\n const data = {\n header,\n payload,\n signature,\n raw: {\n header: rawHeader,\n payload: rawPayload,\n signature: rawSignature,\n text: token,\n },\n } satisfies Jwt;\n\n return { data };\n}\n\n/**\n * @inline\n */\nexport type VerifyJwtOptions = {\n /**\n * A string or list of [audiences](https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.3). If passed, it is checked against the `aud` claim in the token.\n */\n audience?: string | string[];\n /**\n * An allowlist of origins to verify against, to protect your application from the subdomain cookie leaking attack.\n * @example\n * ```ts\n * ['http://localhost:3000', 'https://example.com']\n * ```\n */\n authorizedParties?: string[];\n /**\n * Specifies the allowed time difference (in milliseconds) between the Clerk server (which generates the token) and the clock of the user's application server when validating a token.\n * @default 5000\n */\n clockSkewInMs?: number;\n /**\n * @internal\n */\n key: JsonWebKey | string;\n};\n\nexport async function verifyJwt(\n token: string,\n options: VerifyJwtOptions,\n): Promise> {\n const { audience, authorizedParties, clockSkewInMs, key } = options;\n const clockSkew = clockSkewInMs || DEFAULT_CLOCK_SKEW_IN_MS;\n\n const { data: decoded, errors } = decodeJwt(token);\n if (errors) {\n return { errors };\n }\n\n const { header, payload } = decoded;\n try {\n // Header verifications\n const { typ, alg } = header;\n\n assertHeaderType(typ);\n assertHeaderAlgorithm(alg);\n\n // Payload verifications\n const { azp, sub, aud, iat, exp, nbf } = payload;\n\n assertSubClaim(sub);\n assertAudienceClaim([aud], [audience]);\n assertAuthorizedPartiesClaim(azp, authorizedParties);\n assertExpirationClaim(exp, clockSkew);\n assertActivationClaim(nbf, clockSkew);\n assertIssuedAtClaim(iat, clockSkew);\n } catch (err) {\n return { errors: [err as TokenVerificationError] };\n }\n\n const { data: signatureValid, errors: signatureErrors } = await hasValidSignature(decoded, key);\n if (signatureErrors) {\n return {\n errors: [\n new TokenVerificationError({\n action: TokenVerificationErrorAction.EnsureClerkJWT,\n reason: TokenVerificationErrorReason.TokenVerificationFailed,\n message: `Error verifying JWT signature. ${signatureErrors[0]}`,\n }),\n ],\n };\n }\n\n if (!signatureValid) {\n return {\n errors: [\n new TokenVerificationError({\n reason: TokenVerificationErrorReason.TokenInvalidSignature,\n message: 'JWT signature is invalid.',\n }),\n ],\n };\n }\n\n return { data: payload };\n}\n","import { parsePublishableKey } from './shared';\n\nexport function assertValidSecretKey(val: unknown): asserts val is string {\n if (!val || typeof val !== 'string') {\n throw Error('Missing Clerk Secret Key. Go to https://dashboard.clerk.com and get your key for your instance.');\n }\n\n //TODO: Check if the key is invalid and throw error\n}\n\nexport function assertValidPublishableKey(val: unknown): asserts val is string {\n parsePublishableKey(val as string | undefined, { fatal: true });\n}\n","import { buildAccountsBaseUrl } from '@clerk/shared/buildAccountsBaseUrl';\nimport { isCurrentDevAccountPortalOrigin, isLegacyDevAccountPortalOrigin } from '@clerk/shared/url';\nimport type { Jwt } from '@clerk/types';\n\nimport { constants } from '../constants';\nimport { decodeJwt } from '../jwt/verifyJwt';\nimport { runtime } from '../runtime';\nimport { assertValidPublishableKey } from '../util/optionsAssertions';\nimport { getCookieSuffix, getSuffixedCookieName, parsePublishableKey } from '../util/shared';\nimport type { ClerkRequest } from './clerkRequest';\nimport { TokenType } from './tokenTypes';\nimport type { AuthenticateRequestOptions } from './types';\n\ninterface AuthenticateContext extends AuthenticateRequestOptions {\n // header-based values\n accept: string | undefined;\n forwardedHost: string | undefined;\n forwardedProto: string | undefined;\n host: string | undefined;\n origin: string | undefined;\n referrer: string | undefined;\n secFetchDest: string | undefined;\n tokenInHeader: string | undefined;\n userAgent: string | undefined;\n\n // cookie-based values\n clientUat: number;\n refreshTokenInCookie: string | undefined;\n sessionTokenInCookie: string | undefined;\n\n // handshake-related values\n devBrowserToken: string | undefined;\n handshakeNonce: string | undefined;\n handshakeRedirectLoopCounter: number;\n handshakeToken: string | undefined;\n\n // url derived from headers\n clerkUrl: URL;\n // enforce existence of the following props\n frontendApi: string;\n instanceType: string;\n publishableKey: string;\n}\n\n/**\n * All data required to authenticate a request.\n * This is the data we use to decide whether a request\n * is in a signed in or signed out state or if we need\n * to perform a handshake.\n */\nclass AuthenticateContext implements AuthenticateContext {\n /**\n * The original Clerk frontend API URL, extracted from publishable key before proxy URL override.\n * Used for backend operations like token validation and issuer checking.\n */\n private originalFrontendApi: string = '';\n\n /**\n * Retrieves the session token from either the cookie or the header.\n *\n * @returns {string | undefined} The session token if available, otherwise undefined.\n */\n public get sessionToken(): string | undefined {\n return this.sessionTokenInCookie || this.tokenInHeader;\n }\n\n public constructor(\n private cookieSuffix: string,\n private clerkRequest: ClerkRequest,\n options: AuthenticateRequestOptions,\n ) {\n if (options.acceptsToken === TokenType.M2MToken || options.acceptsToken === TokenType.ApiKey) {\n // For non-session tokens, we only want to set the header values.\n this.initHeaderValues();\n } else {\n // Even though the options are assigned to this later in this function\n // we set the publishableKey here because it is being used in cookies/headers/handshake-values\n // as part of getMultipleAppsCookie.\n this.initPublishableKeyValues(options);\n this.initHeaderValues();\n // initCookieValues should be used before initHandshakeValues because it depends on suffixedCookies\n this.initCookieValues();\n this.initHandshakeValues();\n }\n\n Object.assign(this, options);\n this.clerkUrl = this.clerkRequest.clerkUrl;\n }\n\n public usesSuffixedCookies(): boolean {\n const suffixedClientUat = this.getSuffixedCookie(constants.Cookies.ClientUat);\n const clientUat = this.getCookie(constants.Cookies.ClientUat);\n const suffixedSession = this.getSuffixedCookie(constants.Cookies.Session) || '';\n const session = this.getCookie(constants.Cookies.Session) || '';\n\n // In the case of malformed session cookies (eg missing the iss claim), we should\n // use the un-suffixed cookies to return signed-out state instead of triggering\n // handshake\n if (session && !this.tokenHasIssuer(session)) {\n return false;\n }\n\n // If there's a token in un-suffixed, and it doesn't belong to this\n // instance, then we must trust suffixed\n if (session && !this.tokenBelongsToInstance(session)) {\n return true;\n }\n\n // If there are no suffixed cookies use un-suffixed\n if (!suffixedClientUat && !suffixedSession) {\n return false;\n }\n\n const { data: sessionData } = decodeJwt(session);\n const sessionIat = sessionData?.payload.iat || 0;\n const { data: suffixedSessionData } = decodeJwt(suffixedSession);\n const suffixedSessionIat = suffixedSessionData?.payload.iat || 0;\n\n // Both indicate signed in, but un-suffixed is newer\n // Trust un-suffixed because it's newer\n if (suffixedClientUat !== '0' && clientUat !== '0' && sessionIat > suffixedSessionIat) {\n return false;\n }\n\n // Suffixed indicates signed out, but un-suffixed indicates signed in\n // Trust un-suffixed because it gets set with both new and old clerk.js,\n // so we can assume it's newer\n if (suffixedClientUat === '0' && clientUat !== '0') {\n return false;\n }\n\n // Suffixed indicates signed in, un-suffixed indicates signed out\n // This is the tricky one\n\n // In production, suffixed_uat should be set reliably, since it's\n // set by FAPI and not clerk.js. So in the scenario where a developer\n // downgrades, the state will look like this:\n // - un-suffixed session cookie: empty\n // - un-suffixed uat: 0\n // - suffixed session cookie: (possibly filled, possibly empty)\n // - suffixed uat: 0\n\n // Our SDK honors client_uat over the session cookie, so we don't\n // need a special case for production. We can rely on suffixed,\n // and the fact that the suffixed uat is set properly means and\n // suffixed session cookie will be ignored.\n\n // The important thing to make sure we have a test that confirms\n // the user ends up as signed out in this scenario, and the suffixed\n // session cookie is ignored\n\n // In development, suffixed_uat is not set reliably, since it's done\n // by clerk.js. If the developer downgrades to a pinned version of\n // clerk.js, the suffixed uat will no longer be updated\n\n // The best we can do is look to see if the suffixed token is expired.\n // This means that, if a developer downgrades, and then immediately\n // signs out, all in the span of 1 minute, then they will inadvertently\n // remain signed in for the rest of that minute. This is a known\n // limitation of the strategy but seems highly unlikely.\n if (this.instanceType !== 'production') {\n const isSuffixedSessionExpired = this.sessionExpired(suffixedSessionData);\n if (suffixedClientUat !== '0' && clientUat === '0' && isSuffixedSessionExpired) {\n return false;\n }\n }\n\n // If a suffixed session cookie exists but the corresponding client_uat cookie is missing, fallback to using\n // unsuffixed cookies.\n // This handles the scenario where an app has been deployed using an SDK version that supports suffixed\n // cookies, but FAPI for its Clerk instance has the feature disabled (eg: if we need to temporarily disable the feature).\n if (!suffixedClientUat && suffixedSession) {\n return false;\n }\n\n return true;\n }\n\n /**\n * Determines if the request came from a different origin based on the referrer header.\n * Used for cross-origin detection in multi-domain authentication flows.\n *\n * @returns {boolean} True if referrer exists and is from a different origin, false otherwise.\n */\n public isCrossOriginReferrer(): boolean {\n if (!this.referrer || !this.clerkUrl.origin) {\n return false;\n }\n\n try {\n const referrerOrigin = new URL(this.referrer).origin;\n return referrerOrigin !== this.clerkUrl.origin;\n } catch {\n // Invalid referrer URL format\n return false;\n }\n }\n\n /**\n * Determines if the referrer URL is from a Clerk domain (accounts portal or FAPI).\n * This includes both development and production account portal domains, as well as FAPI domains\n * used for redirect-based authentication flows.\n *\n * @returns {boolean} True if the referrer is from a Clerk accounts portal or FAPI domain, false otherwise\n */\n public isKnownClerkReferrer(): boolean {\n if (!this.referrer) {\n return false;\n }\n\n try {\n const referrerOrigin = new URL(this.referrer);\n const referrerHost = referrerOrigin.hostname;\n\n // Check if referrer is the FAPI domain itself (redirect-based auth flows)\n if (this.frontendApi) {\n const fapiHost = this.frontendApi.startsWith('http') ? new URL(this.frontendApi).hostname : this.frontendApi;\n if (referrerHost === fapiHost) {\n return true;\n }\n }\n\n // Check for development account portal patterns\n if (isLegacyDevAccountPortalOrigin(referrerHost) || isCurrentDevAccountPortalOrigin(referrerHost)) {\n return true;\n }\n\n // Check for production account portal by comparing with expected accounts URL\n const expectedAccountsUrl = buildAccountsBaseUrl(this.frontendApi);\n if (expectedAccountsUrl) {\n const expectedAccountsOrigin = new URL(expectedAccountsUrl).origin;\n if (referrerOrigin.origin === expectedAccountsOrigin) {\n return true;\n }\n }\n\n // Check for generic production accounts patterns (accounts.*)\n if (referrerHost.startsWith('accounts.')) {\n return true;\n }\n\n return false;\n } catch {\n // Invalid URL format\n return false;\n }\n }\n\n private initPublishableKeyValues(options: AuthenticateRequestOptions) {\n assertValidPublishableKey(options.publishableKey);\n this.publishableKey = options.publishableKey;\n\n const originalPk = parsePublishableKey(this.publishableKey, {\n fatal: true,\n domain: options.domain,\n isSatellite: options.isSatellite,\n });\n this.originalFrontendApi = originalPk.frontendApi;\n\n const pk = parsePublishableKey(this.publishableKey, {\n fatal: true,\n proxyUrl: options.proxyUrl,\n domain: options.domain,\n isSatellite: options.isSatellite,\n });\n this.instanceType = pk.instanceType;\n this.frontendApi = pk.frontendApi;\n }\n\n private initHeaderValues() {\n this.tokenInHeader = this.parseAuthorizationHeader(this.getHeader(constants.Headers.Authorization));\n this.origin = this.getHeader(constants.Headers.Origin);\n this.host = this.getHeader(constants.Headers.Host);\n this.forwardedHost = this.getHeader(constants.Headers.ForwardedHost);\n this.forwardedProto =\n this.getHeader(constants.Headers.CloudFrontForwardedProto) || this.getHeader(constants.Headers.ForwardedProto);\n this.referrer = this.getHeader(constants.Headers.Referrer);\n this.userAgent = this.getHeader(constants.Headers.UserAgent);\n this.secFetchDest = this.getHeader(constants.Headers.SecFetchDest);\n this.accept = this.getHeader(constants.Headers.Accept);\n }\n\n private initCookieValues() {\n // suffixedCookies needs to be set first because it's used in getMultipleAppsCookie\n this.sessionTokenInCookie = this.getSuffixedOrUnSuffixedCookie(constants.Cookies.Session);\n this.refreshTokenInCookie = this.getSuffixedCookie(constants.Cookies.Refresh);\n this.clientUat = Number.parseInt(this.getSuffixedOrUnSuffixedCookie(constants.Cookies.ClientUat) || '') || 0;\n }\n\n private initHandshakeValues() {\n this.devBrowserToken =\n this.getQueryParam(constants.QueryParameters.DevBrowser) ||\n this.getSuffixedOrUnSuffixedCookie(constants.Cookies.DevBrowser);\n // Using getCookie since we don't suffix the handshake token cookie\n this.handshakeToken =\n this.getQueryParam(constants.QueryParameters.Handshake) || this.getCookie(constants.Cookies.Handshake);\n this.handshakeRedirectLoopCounter = Number(this.getCookie(constants.Cookies.RedirectCount)) || 0;\n this.handshakeNonce =\n this.getQueryParam(constants.QueryParameters.HandshakeNonce) || this.getCookie(constants.Cookies.HandshakeNonce);\n }\n\n private getQueryParam(name: string) {\n return this.clerkRequest.clerkUrl.searchParams.get(name);\n }\n\n private getHeader(name: string) {\n return this.clerkRequest.headers.get(name) || undefined;\n }\n\n private getCookie(name: string) {\n return this.clerkRequest.cookies.get(name) || undefined;\n }\n\n private getSuffixedCookie(name: string) {\n return this.getCookie(getSuffixedCookieName(name, this.cookieSuffix)) || undefined;\n }\n\n private getSuffixedOrUnSuffixedCookie(cookieName: string) {\n if (this.usesSuffixedCookies()) {\n return this.getSuffixedCookie(cookieName);\n }\n return this.getCookie(cookieName);\n }\n\n private parseAuthorizationHeader(authorizationHeader: string | undefined | null): string | undefined {\n if (!authorizationHeader) {\n return undefined;\n }\n\n const [scheme, token] = authorizationHeader.split(' ', 2);\n\n if (!token) {\n // No scheme specified, treat the entire value as the token\n return scheme;\n }\n\n if (scheme === 'Bearer') {\n return token;\n }\n\n // Skip all other schemes\n return undefined;\n }\n\n private tokenHasIssuer(token: string): boolean {\n const { data, errors } = decodeJwt(token);\n if (errors) {\n return false;\n }\n return !!data.payload.iss;\n }\n\n private tokenBelongsToInstance(token: string): boolean {\n if (!token) {\n return false;\n }\n\n const { data, errors } = decodeJwt(token);\n if (errors) {\n return false;\n }\n const tokenIssuer = data.payload.iss.replace(/https?:\\/\\//gi, '');\n // Use original frontend API for token validation since tokens are issued by the actual Clerk API, not proxy\n return this.originalFrontendApi === tokenIssuer;\n }\n\n private sessionExpired(jwt: Jwt | undefined): boolean {\n return !!jwt && jwt?.payload.exp <= (Date.now() / 1000) >> 0;\n }\n}\n\nexport type { AuthenticateContext };\n\nexport const createAuthenticateContext = async (\n clerkRequest: ClerkRequest,\n options: AuthenticateRequestOptions,\n): Promise => {\n const cookieSuffix = options.publishableKey\n ? await getCookieSuffix(options.publishableKey, runtime.crypto.subtle)\n : '';\n return new AuthenticateContext(cookieSuffix, clerkRequest, options);\n};\n","export const TokenType = {\n SessionToken: 'session_token',\n ApiKey: 'api_key',\n M2MToken: 'm2m_token',\n OAuthToken: 'oauth_token',\n} as const;\n\n/**\n * @inline\n */\nexport type TokenType = (typeof TokenType)[keyof typeof TokenType];\n\n/**\n * @inline\n */\nexport type SessionTokenType = typeof TokenType.SessionToken;\n/**\n * @inline\n */\nexport type MachineTokenType = Exclude;\n","import { createCheckAuthorization } from '@clerk/shared/authorization';\nimport { __experimental_JWTPayloadToAuthObjectProperties } from '@clerk/shared/jwtPayloadParser';\nimport type {\n CheckAuthorizationFromSessionClaims,\n Jwt,\n JwtPayload,\n PendingSessionOptions,\n ServerGetToken,\n ServerGetTokenOptions,\n SessionStatusClaim,\n SharedSignedInAuthObjectProperties,\n} from '@clerk/types';\n\nimport type { APIKey, CreateBackendApiOptions, IdPOAuthAccessToken, M2MToken } from '../api';\nimport { createBackendApiClient } from '../api';\nimport { isTokenTypeAccepted } from '../internal';\nimport type { AuthenticateContext } from './authenticateContext';\nimport { isMachineTokenType } from './machine';\nimport type { MachineTokenType, SessionTokenType } from './tokenTypes';\nimport { TokenType } from './tokenTypes';\nimport type { AuthenticateRequestOptions, MachineAuthType } from './types';\n\n/**\n * @inline\n */\ntype AuthObjectDebugData = Record;\n/**\n * @inline\n */\ntype AuthObjectDebug = () => AuthObjectDebugData;\n\ntype Claims = Record;\n\n/**\n * @internal\n */\nexport type SignedInAuthObjectOptions = CreateBackendApiOptions & {\n token: string;\n};\n\n/**\n * @internal\n */\nexport type SignedInAuthObject = SharedSignedInAuthObjectProperties & {\n /**\n * The allowed token type.\n */\n tokenType: SessionTokenType;\n /**\n * A function that gets the current user's [session token](https://clerk.com/docs/backend-requests/resources/session-tokens) or a [custom JWT template](https://clerk.com/docs/backend-requests/jwt-templates).\n */\n getToken: ServerGetToken;\n /**\n * A function that checks if the user has an organization role or custom permission.\n */\n has: CheckAuthorizationFromSessionClaims;\n /**\n * Used to help debug issues when using Clerk in development.\n */\n debug: AuthObjectDebug;\n isAuthenticated: true;\n};\n\n/**\n * @internal\n */\nexport type SignedOutAuthObject = {\n sessionClaims: null;\n sessionId: null;\n sessionStatus: SessionStatusClaim | null;\n actor: null;\n tokenType: SessionTokenType;\n userId: null;\n orgId: null;\n orgRole: null;\n orgSlug: null;\n orgPermissions: null;\n factorVerificationAge: null;\n getToken: ServerGetToken;\n has: CheckAuthorizationFromSessionClaims;\n debug: AuthObjectDebug;\n isAuthenticated: false;\n};\n\n/**\n * Extended properties specific to each machine token type.\n * While all machine token types share common properties (id, name, subject, etc),\n * this type defines the additional properties that are unique to each token type.\n *\n * @template TAuthenticated - Whether the machine object is authenticated or not\n */\ntype MachineObjectExtendedProperties = {\n api_key: TAuthenticated extends true\n ?\n | { name: string; claims: Claims | null; userId: string; orgId: null }\n | { name: string; claims: Claims | null; userId: null; orgId: string }\n : { name: null; claims: null; userId: null; orgId: null };\n m2m_token: {\n claims: TAuthenticated extends true ? Claims | null : null;\n machineId: TAuthenticated extends true ? string : null;\n };\n oauth_token: {\n userId: TAuthenticated extends true ? string : null;\n clientId: TAuthenticated extends true ? string : null;\n };\n};\n\n/**\n * @internal\n *\n * Uses `T extends any` to create a distributive conditional type.\n * This ensures that union types like `'api_key' | 'oauth_token'` are processed\n * individually, creating proper discriminated unions where each token type\n * gets its own distinct properties (e.g., oauth_token won't have claims).\n */\nexport type AuthenticatedMachineObject = T extends any\n ? {\n id: string;\n subject: string;\n scopes: string[];\n getToken: () => Promise;\n has: CheckAuthorizationFromSessionClaims;\n debug: AuthObjectDebug;\n tokenType: T;\n isAuthenticated: true;\n } & MachineObjectExtendedProperties[T]\n : never;\n\n/**\n * @internal\n *\n * Uses `T extends any` to create a distributive conditional type.\n * This ensures that union types like `'api_key' | 'oauth_token'` are processed\n * individually, creating proper discriminated unions where each token type\n * gets its own distinct properties (e.g., oauth_token won't have claims).\n */\nexport type UnauthenticatedMachineObject = T extends any\n ? {\n id: null;\n subject: null;\n scopes: null;\n getToken: () => Promise;\n has: CheckAuthorizationFromSessionClaims;\n debug: AuthObjectDebug;\n tokenType: T;\n isAuthenticated: false;\n } & MachineObjectExtendedProperties[T]\n : never;\n\nexport type InvalidTokenAuthObject = {\n isAuthenticated: false;\n tokenType: null;\n getToken: () => Promise;\n has: () => false;\n debug: AuthObjectDebug;\n};\n\n/**\n * @interface\n */\nexport type AuthObject =\n | SignedInAuthObject\n | SignedOutAuthObject\n | AuthenticatedMachineObject\n | UnauthenticatedMachineObject\n | InvalidTokenAuthObject;\n\nconst createDebug = (data: AuthObjectDebugData | undefined) => {\n return () => {\n const res = { ...data };\n res.secretKey = (res.secretKey || '').substring(0, 7);\n res.jwtKey = (res.jwtKey || '').substring(0, 7);\n return { ...res };\n };\n};\n\n/**\n * @internal\n */\nexport function signedInAuthObject(\n authenticateContext: Partial,\n sessionToken: string,\n sessionClaims: JwtPayload,\n): SignedInAuthObject {\n const { actor, sessionId, sessionStatus, userId, orgId, orgRole, orgSlug, orgPermissions, factorVerificationAge } =\n __experimental_JWTPayloadToAuthObjectProperties(sessionClaims);\n const apiClient = createBackendApiClient(authenticateContext);\n const getToken = createGetToken({\n sessionId,\n sessionToken,\n fetcher: async (sessionId, template, expiresInSeconds) =>\n (await apiClient.sessions.getToken(sessionId, template || '', expiresInSeconds)).jwt,\n });\n return {\n tokenType: TokenType.SessionToken,\n actor,\n sessionClaims,\n sessionId,\n sessionStatus,\n userId,\n orgId,\n orgRole,\n orgSlug,\n orgPermissions,\n factorVerificationAge,\n getToken,\n has: createCheckAuthorization({\n orgId,\n orgRole,\n orgPermissions,\n userId,\n factorVerificationAge,\n features: (sessionClaims.fea as string) || '',\n plans: (sessionClaims.pla as string) || '',\n }),\n debug: createDebug({ ...authenticateContext, sessionToken }),\n isAuthenticated: true,\n };\n}\n\n/**\n * @internal\n */\nexport function signedOutAuthObject(\n debugData?: AuthObjectDebugData,\n initialSessionStatus?: SessionStatusClaim,\n): SignedOutAuthObject {\n return {\n tokenType: TokenType.SessionToken,\n sessionClaims: null,\n sessionId: null,\n sessionStatus: initialSessionStatus ?? null,\n userId: null,\n actor: null,\n orgId: null,\n orgRole: null,\n orgSlug: null,\n orgPermissions: null,\n factorVerificationAge: null,\n getToken: () => Promise.resolve(null),\n has: () => false,\n debug: createDebug(debugData),\n isAuthenticated: false,\n };\n}\n\n/**\n * @internal\n */\nexport function authenticatedMachineObject(\n tokenType: T,\n token: string,\n verificationResult: MachineAuthType,\n debugData?: AuthObjectDebugData,\n): AuthenticatedMachineObject {\n const baseObject = {\n id: verificationResult.id,\n subject: verificationResult.subject,\n getToken: () => Promise.resolve(token),\n has: () => false,\n debug: createDebug(debugData),\n isAuthenticated: true,\n };\n\n // Type assertions are safe here since we know the verification result type matches the tokenType.\n // We need these assertions because TS can't infer the specific type\n // just from the tokenType discriminator.\n\n switch (tokenType) {\n case TokenType.ApiKey: {\n const result = verificationResult as APIKey;\n return {\n ...baseObject,\n tokenType,\n name: result.name,\n claims: result.claims,\n scopes: result.scopes,\n userId: result.subject.startsWith('user_') ? result.subject : null,\n orgId: result.subject.startsWith('org_') ? result.subject : null,\n } as unknown as AuthenticatedMachineObject;\n }\n case TokenType.M2MToken: {\n const result = verificationResult as M2MToken;\n return {\n ...baseObject,\n tokenType,\n claims: result.claims,\n scopes: result.scopes,\n machineId: result.subject,\n } as unknown as AuthenticatedMachineObject;\n }\n case TokenType.OAuthToken: {\n const result = verificationResult as IdPOAuthAccessToken;\n return {\n ...baseObject,\n tokenType,\n scopes: result.scopes,\n userId: result.subject,\n clientId: result.clientId,\n } as unknown as AuthenticatedMachineObject;\n }\n default:\n throw new Error(`Invalid token type: ${tokenType}`);\n }\n}\n\n/**\n * @internal\n */\nexport function unauthenticatedMachineObject(\n tokenType: T,\n debugData?: AuthObjectDebugData,\n): UnauthenticatedMachineObject {\n const baseObject = {\n id: null,\n subject: null,\n scopes: null,\n has: () => false,\n getToken: () => Promise.resolve(null),\n debug: createDebug(debugData),\n isAuthenticated: false,\n };\n\n switch (tokenType) {\n case TokenType.ApiKey: {\n return {\n ...baseObject,\n tokenType,\n name: null,\n claims: null,\n scopes: null,\n userId: null,\n orgId: null,\n } as unknown as UnauthenticatedMachineObject;\n }\n case TokenType.M2MToken: {\n return {\n ...baseObject,\n tokenType,\n claims: null,\n scopes: null,\n machineId: null,\n } as unknown as UnauthenticatedMachineObject;\n }\n case TokenType.OAuthToken: {\n return {\n ...baseObject,\n tokenType,\n scopes: null,\n userId: null,\n clientId: null,\n } as unknown as UnauthenticatedMachineObject;\n }\n default:\n throw new Error(`Invalid token type: ${tokenType}`);\n }\n}\n\n/**\n * @internal\n */\nexport function invalidTokenAuthObject(): InvalidTokenAuthObject {\n return {\n isAuthenticated: false,\n tokenType: null,\n getToken: () => Promise.resolve(null),\n has: () => false,\n debug: () => ({}),\n };\n}\n\n/**\n * Auth objects moving through the server -> client boundary need to be serializable\n * as we need to ensure that they can be transferred via the network as pure strings.\n * Some frameworks like Remix or Next (/pages dir only) handle this serialization by simply\n * ignoring any non-serializable keys, however Nextjs /app directory is stricter and\n * throws an error if a non-serializable value is found.\n *\n * @internal\n */\nexport const makeAuthObjectSerializable = >(obj: T): T => {\n // remove any non-serializable props from the returned object\n\n const { debug, getToken, has, ...rest } = obj as unknown as AuthObject;\n return rest as unknown as T;\n};\n\n/**\n * A function that fetches a session token from the Clerk API.\n *\n * @param sessionId - The ID of the session\n * @param template - The JWT template name to use for token generation\n * @param expiresInSeconds - Optional expiration time in seconds for the token\n * @returns A promise that resolves to the token string\n */\ntype TokenFetcher = (sessionId: string, template?: string, expiresInSeconds?: number) => Promise;\n\n/**\n * Factory function type that creates a getToken function for auth objects.\n *\n * @param params - Configuration object containing session information and token fetcher\n * @returns A ServerGetToken function that can be used to retrieve tokens\n */\ntype CreateGetToken = (params: { sessionId: string; sessionToken: string; fetcher: TokenFetcher }) => ServerGetToken;\n\n/**\n * Creates a token retrieval function for authenticated sessions.\n *\n * This factory function returns a getToken function that can either return the raw session token\n * or generate a JWT using a specified template with optional custom expiration.\n *\n * @param params - Configuration object\n * @param params.sessionId - The session ID for token generation\n * @param params.sessionToken - The raw session token to return when no template is specified\n * @param params.fetcher - Function to fetch tokens from the Clerk API\n *\n * @returns A function that retrieves tokens based on the provided options\n */\nconst createGetToken: CreateGetToken = params => {\n const { fetcher, sessionToken, sessionId } = params || {};\n\n return async (options: ServerGetTokenOptions = {}) => {\n if (!sessionId) {\n return null;\n }\n\n if (options.template || options.expiresInSeconds !== undefined) {\n return fetcher(sessionId, options.template, options.expiresInSeconds);\n }\n\n return sessionToken;\n };\n};\n\n/**\n * @internal\n */\nexport const getAuthObjectFromJwt = (\n jwt: Jwt,\n { treatPendingAsSignedOut = true, ...options }: PendingSessionOptions & Partial,\n) => {\n const authObject = signedInAuthObject(options, jwt.raw.text, jwt.payload);\n\n if (treatPendingAsSignedOut && authObject.sessionStatus === 'pending') {\n return signedOutAuthObject(options, authObject.sessionStatus);\n }\n\n return authObject;\n};\n\n/**\n * @internal\n * Returns an auth object matching the requested token type(s).\n *\n * If the parsed token type does not match any in acceptsToken, returns:\n * - an invalid token auth object if the token is not in the accepted array\n * - an unauthenticated machine object for machine tokens, or\n * - a signed-out session object otherwise.\n *\n * This ensures the returned object always matches the developer's intent.\n */\nexport const getAuthObjectForAcceptedToken = ({\n authObject,\n acceptsToken = TokenType.SessionToken,\n}: {\n authObject: AuthObject;\n acceptsToken: AuthenticateRequestOptions['acceptsToken'];\n}): AuthObject => {\n // 1. any token: return as-is\n if (acceptsToken === 'any') {\n return authObject;\n }\n\n // 2. array of tokens: must match one of the accepted types\n if (Array.isArray(acceptsToken)) {\n if (!isTokenTypeAccepted(authObject.tokenType, acceptsToken)) {\n return invalidTokenAuthObject();\n }\n return authObject;\n }\n\n // 3. single token: must match exactly, else return appropriate unauthenticated object\n if (!isTokenTypeAccepted(authObject.tokenType, acceptsToken)) {\n if (isMachineTokenType(acceptsToken)) {\n return unauthenticatedMachineObject(acceptsToken, authObject.debug);\n }\n return signedOutAuthObject(authObject.debug);\n }\n\n // 4. default: return as-is\n return authObject;\n};\n","const SEPARATOR = '/';\nconst MULTIPLE_SEPARATOR_REGEX = new RegExp('(? p)\n .join(SEPARATOR)\n .replace(MULTIPLE_SEPARATOR_REGEX, SEPARATOR);\n}\n","import type { RequestFunction } from '../request';\n\nexport abstract class AbstractAPI {\n constructor(protected request: RequestFunction) {}\n\n protected requireId(id: string) {\n if (!id) {\n throw new Error('A valid resource ID is required.');\n }\n }\n}\n","import { joinPaths } from '../../util/path';\nimport type { ActorToken } from '../resources/ActorToken';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/actor_tokens';\n\ntype ActorTokenActorCreateParams = {\n /**\n * The ID of the actor.\n */\n sub: string;\n /**\n * Additional properties of the actor.\n */\n additionalProperties?: { [k: string]: any };\n};\n\ntype ActorTokenCreateParams = {\n /**\n * The ID of the user being impersonated.\n */\n userId: string;\n /**\n * The actor payload. It needs to include a sub property which should contain the ID of the actor.\n *\n * @remarks\n * This whole payload will be also included in the JWT session token.\n */\n actor: ActorTokenActorCreateParams;\n /**\n * Optional parameter to specify the life duration of the actor token in seconds.\n *\n * @remarks\n * By default, the duration is 1 hour.\n */\n expiresInSeconds?: number | undefined;\n /**\n * The maximum duration that the session which will be created by the generated actor token should last.\n *\n * @remarks\n * By default, the duration of a session created via an actor token, lasts 30 minutes.\n */\n sessionMaxDurationInSeconds?: number | undefined;\n};\n\nexport class ActorTokenAPI extends AbstractAPI {\n public async create(params: ActorTokenCreateParams) {\n return this.request({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async revoke(actorTokenId: string) {\n this.requireId(actorTokenId);\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, actorTokenId, 'revoke'),\n });\n }\n}\n","import { joinPaths } from '../../util/path';\nimport type { AccountlessApplication } from '../resources/AccountlessApplication';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/accountless_applications';\n\nexport class AccountlessApplicationAPI extends AbstractAPI {\n public async createAccountlessApplication(params?: { requestHeaders?: Headers }) {\n const headerParams = params?.requestHeaders ? Object.fromEntries(params.requestHeaders.entries()) : undefined;\n return this.request({\n method: 'POST',\n path: basePath,\n headerParams,\n });\n }\n\n public async completeAccountlessApplicationOnboarding(params?: { requestHeaders?: Headers }) {\n const headerParams = params?.requestHeaders ? Object.fromEntries(params.requestHeaders.entries()) : undefined;\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, 'complete'),\n headerParams,\n });\n }\n}\n","import type { ClerkPaginationRequest } from '@clerk/types';\n\nimport { joinPaths } from '../../util/path';\nimport type { AllowlistIdentifier } from '../resources/AllowlistIdentifier';\nimport type { DeletedObject } from '../resources/DeletedObject';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/allowlist_identifiers';\n\ntype AllowlistIdentifierCreateParams = {\n identifier: string;\n notify: boolean;\n};\n\nexport class AllowlistIdentifierAPI extends AbstractAPI {\n public async getAllowlistIdentifierList(params: ClerkPaginationRequest = {}) {\n return this.request>({\n method: 'GET',\n path: basePath,\n queryParams: { ...params, paginated: true },\n });\n }\n\n public async createAllowlistIdentifier(params: AllowlistIdentifierCreateParams) {\n return this.request({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async deleteAllowlistIdentifier(allowlistIdentifierId: string) {\n this.requireId(allowlistIdentifierId);\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, allowlistIdentifierId),\n });\n }\n}\n","import { joinPaths } from '../../util/path';\nimport type { APIKey } from '../resources/APIKey';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/api_keys';\n\ntype CreateAPIKeyParams = {\n type?: 'api_key';\n /**\n * API key name\n */\n name: string;\n /**\n * user or organization ID the API key is associated with\n */\n subject: string;\n /**\n * API key description\n */\n description?: string | null;\n claims?: Record | null;\n scopes?: string[];\n createdBy?: string | null;\n secondsUntilExpiration?: number | null;\n};\n\ntype RevokeAPIKeyParams = {\n /**\n * API key ID\n */\n apiKeyId: string;\n /**\n * Reason for revocation\n */\n revocationReason?: string | null;\n};\n\nexport class APIKeysAPI extends AbstractAPI {\n async create(params: CreateAPIKeyParams) {\n return this.request({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n async revoke(params: RevokeAPIKeyParams) {\n const { apiKeyId, ...bodyParams } = params;\n\n this.requireId(apiKeyId);\n\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, apiKeyId, 'revoke'),\n bodyParams,\n });\n }\n\n async getSecret(apiKeyId: string) {\n this.requireId(apiKeyId);\n\n return this.request<{ secret: string }>({\n method: 'GET',\n path: joinPaths(basePath, apiKeyId, 'secret'),\n });\n }\n\n async verifySecret(secret: string) {\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, 'verify'),\n bodyParams: { secret },\n });\n }\n}\n","import { joinPaths } from '../../util/path';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/beta_features';\n\ntype ChangeDomainParams = {\n /**\n * The new home URL of the production instance e.g. https://www.example.com\n */\n homeUrl?: string;\n /**\n * Whether this is a domain for a secondary app, meaning that any subdomain\n * provided is significant and will be stored as part of the domain. This is\n * useful for supporting multiple apps (one primary and multiple secondaries)\n * on the same root domain (eTLD+1).\n */\n isSecondary?: boolean;\n};\n\nexport class BetaFeaturesAPI extends AbstractAPI {\n /**\n * Change the domain of a production instance.\n *\n * Changing the domain requires updating the DNS records accordingly, deploying new SSL certificates,\n * updating your Social Connection's redirect URLs and setting the new keys in your code.\n *\n * @remarks\n * WARNING: Changing your domain will invalidate all current user sessions (i.e. users will be logged out).\n * Also, while your application is being deployed, a small downtime is expected to occur.\n */\n public async changeDomain(params: ChangeDomainParams) {\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, 'change_domain'),\n bodyParams: params,\n });\n }\n}\n","import type { ClerkPaginationRequest } from '@clerk/types';\n\nimport { joinPaths } from '../../util/path';\nimport type { BlocklistIdentifier } from '../resources/BlocklistIdentifier';\nimport type { DeletedObject } from '../resources/DeletedObject';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/blocklist_identifiers';\n\ntype BlocklistIdentifierCreateParams = {\n identifier: string;\n};\n\nexport class BlocklistIdentifierAPI extends AbstractAPI {\n public async getBlocklistIdentifierList(params: ClerkPaginationRequest = {}) {\n return this.request>({\n method: 'GET',\n path: basePath,\n queryParams: params,\n });\n }\n\n public async createBlocklistIdentifier(params: BlocklistIdentifierCreateParams) {\n return this.request({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async deleteBlocklistIdentifier(blocklistIdentifierId: string) {\n this.requireId(blocklistIdentifierId);\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, blocklistIdentifierId),\n });\n }\n}\n","import type { ClerkPaginationRequest } from '@clerk/types';\n\nimport { joinPaths } from '../../util/path';\nimport type { Client } from '../resources/Client';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport type { HandshakePayload } from '../resources/HandshakePayload';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/clients';\n\ntype GetHandshakePayloadParams = {\n nonce: string;\n};\n\nexport class ClientAPI extends AbstractAPI {\n public async getClientList(params: ClerkPaginationRequest = {}) {\n return this.request>({\n method: 'GET',\n path: basePath,\n queryParams: { ...params, paginated: true },\n });\n }\n\n public async getClient(clientId: string) {\n this.requireId(clientId);\n return this.request({\n method: 'GET',\n path: joinPaths(basePath, clientId),\n });\n }\n\n public verifyClient(token: string) {\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, 'verify'),\n bodyParams: { token },\n });\n }\n\n public async getHandshakePayload(queryParams: GetHandshakePayloadParams) {\n return this.request({\n method: 'GET',\n path: joinPaths(basePath, 'handshake_payload'),\n queryParams,\n });\n }\n}\n","import { joinPaths } from '../../util/path';\nimport type { DeletedObject } from '../resources/DeletedObject';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport type { Domain } from '../resources/Domain';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/domains';\n\ntype AddDomainParams = {\n /**\n * The new domain name. For development instances, can contain the port, i.e myhostname:3000. For production instances, must be a valid FQDN, i.e mysite.com. Cannot contain protocol scheme.\n */\n name: string;\n /**\n * Marks the new domain as satellite. Only true is accepted at the moment.\n */\n is_satellite: boolean;\n /**\n * The full URL of the proxy which will forward requests to the Clerk Frontend API for this domain. Applicable only to production instances.\n */\n proxy_url?: string | null;\n};\n\ntype UpdateDomainParams = Partial> & {\n /**\n * The ID of the domain that will be updated.\n */\n domainId: string;\n /**\n * Whether this is a domain for a secondary app, meaning that any subdomain provided is significant\n * and will be stored as part of the domain. This is useful for supporting multiple apps\n * (one primary and multiple secondaries) on the same root domain (eTLD+1).\n */\n is_secondary?: boolean | null;\n};\n\nexport class DomainAPI extends AbstractAPI {\n public async list() {\n return this.request>({\n method: 'GET',\n path: basePath,\n });\n }\n\n public async add(params: AddDomainParams) {\n return this.request({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async update(params: UpdateDomainParams) {\n const { domainId, ...bodyParams } = params;\n\n this.requireId(domainId);\n\n return this.request({\n method: 'PATCH',\n path: joinPaths(basePath, domainId),\n bodyParams: bodyParams,\n });\n }\n\n /**\n * Deletes a satellite domain for the instance.\n * It is currently not possible to delete the instance's primary domain.\n */\n public async delete(satelliteDomainId: string) {\n return this.deleteDomain(satelliteDomainId);\n }\n\n /**\n * @deprecated Use `delete` instead\n */\n public async deleteDomain(satelliteDomainId: string) {\n this.requireId(satelliteDomainId);\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, satelliteDomainId),\n });\n }\n}\n","import { joinPaths } from '../../util/path';\nimport type { DeletedObject, EmailAddress } from '../resources';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/email_addresses';\n\ntype CreateEmailAddressParams = {\n userId: string;\n emailAddress: string;\n verified?: boolean;\n primary?: boolean;\n};\n\ntype UpdateEmailAddressParams = {\n verified?: boolean;\n primary?: boolean;\n};\n\nexport class EmailAddressAPI extends AbstractAPI {\n public async getEmailAddress(emailAddressId: string) {\n this.requireId(emailAddressId);\n\n return this.request({\n method: 'GET',\n path: joinPaths(basePath, emailAddressId),\n });\n }\n\n public async createEmailAddress(params: CreateEmailAddressParams) {\n return this.request({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async updateEmailAddress(emailAddressId: string, params: UpdateEmailAddressParams = {}) {\n this.requireId(emailAddressId);\n\n return this.request({\n method: 'PATCH',\n path: joinPaths(basePath, emailAddressId),\n bodyParams: params,\n });\n }\n\n public async deleteEmailAddress(emailAddressId: string) {\n this.requireId(emailAddressId);\n\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, emailAddressId),\n });\n }\n}\n","import { joinPaths } from '../../util/path';\nimport type { IdPOAuthAccessToken } from '../resources';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/oauth_applications/access_tokens';\n\nexport class IdPOAuthAccessTokenApi extends AbstractAPI {\n async verifyAccessToken(accessToken: string) {\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, 'verify'),\n bodyParams: { access_token: accessToken },\n });\n }\n}\n","import { joinPaths } from '../../util/path';\nimport type { Instance } from '../resources/Instance';\nimport type { InstanceRestrictions } from '../resources/InstanceRestrictions';\nimport type { OrganizationSettings } from '../resources/OrganizationSettings';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/instance';\n\ntype UpdateParams = {\n /**\n * Toggles test mode for this instance, allowing the use of test email addresses and phone numbers.\n *\n * @remarks Defaults to true for development instances.\n */\n testMode?: boolean | null | undefined;\n /**\n * Whether the instance should be using the HIBP service to check passwords for breaches\n */\n hibp?: boolean | null | undefined;\n /**\n * The \"enhanced_email_deliverability\" feature will send emails from \"verifications@clerk.dev\" instead of your domain.\n *\n * @remarks This can be helpful if you do not have a high domain reputation.\n */\n enhancedEmailDeliverability?: boolean | null | undefined;\n supportEmail?: string | null | undefined;\n clerkJsVersion?: string | null | undefined;\n developmentOrigin?: string | null | undefined;\n /**\n * For browser-like stacks such as browser extensions, Electron, or Capacitor.js the instance allowed origins need to be updated with the request origin value.\n *\n * @remarks For Chrome extensions popup, background, or service worker pages the origin is chrome-extension://extension_uiid. For Electron apps the default origin is http://localhost:3000. For Capacitor, the origin is capacitor://localhost.\n */\n allowedOrigins?: Array | undefined;\n /**\n * Whether the instance should use URL-based session syncing in development mode (i.e. without third-party cookies).\n */\n urlBasedSessionSyncing?: boolean | null | undefined;\n};\n\ntype UpdateRestrictionsParams = {\n allowlist?: boolean | null | undefined;\n blocklist?: boolean | null | undefined;\n blockEmailSubaddresses?: boolean | null | undefined;\n blockDisposableEmailDomains?: boolean | null | undefined;\n ignoreDotsForGmailAddresses?: boolean | null | undefined;\n};\n\ntype UpdateOrganizationSettingsParams = {\n enabled?: boolean | null | undefined;\n maxAllowedMemberships?: number | null | undefined;\n adminDeleteEnabled?: boolean | null | undefined;\n domainsEnabled?: boolean | null | undefined;\n /**\n * Specifies which [enrollment modes](https://clerk.com/docs/organizations/verified-domains#enrollment-mode) to enable for your Organization Domains.\n *\n * @remarks Supported modes are 'automatic_invitation' & 'automatic_suggestion'.\n */\n domainsEnrollmentModes?: Array | undefined;\n /**\n * Specifies what the default organization role is for an organization creator.\n */\n creatorRoleId?: string | null | undefined;\n /**\n * Specifies what the default organization role is for the organization domains.\n */\n domainsDefaultRoleId?: string | null | undefined;\n};\n\nexport class InstanceAPI extends AbstractAPI {\n public async get() {\n return this.request({\n method: 'GET',\n path: basePath,\n });\n }\n\n public async update(params: UpdateParams) {\n return this.request({\n method: 'PATCH',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async updateRestrictions(params: UpdateRestrictionsParams) {\n return this.request({\n method: 'PATCH',\n path: joinPaths(basePath, 'restrictions'),\n bodyParams: params,\n });\n }\n\n public async updateOrganizationSettings(params: UpdateOrganizationSettingsParams) {\n return this.request({\n method: 'PATCH',\n path: joinPaths(basePath, 'organization_settings'),\n bodyParams: params,\n });\n }\n}\n","import type { ClerkPaginationRequest } from '@clerk/types';\n\nimport { joinPaths } from '../../util/path';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport type { InvitationStatus } from '../resources/Enums';\nimport type { Invitation } from '../resources/Invitation';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/invitations';\n\ntype TemplateSlug = 'invitation' | 'waitlist_invitation';\n\ntype CreateParams = {\n emailAddress: string;\n expiresInDays?: number;\n ignoreExisting?: boolean;\n notify?: boolean;\n publicMetadata?: UserPublicMetadata;\n redirectUrl?: string;\n templateSlug?: TemplateSlug;\n};\n\ntype CreateBulkParams = Array;\n\ntype GetInvitationListParams = ClerkPaginationRequest<{\n /**\n * Filters invitations based on their status.\n *\n * @example\n * Get all revoked invitations\n * ```ts\n * import { createClerkClient } from '@clerk/backend';\n * const clerkClient = createClerkClient(...)\n * await clerkClient.invitations.getInvitationList({ status: 'revoked' })\n * ```\n */\n status?: InvitationStatus;\n /**\n * Filters invitations based on `email_address` or `id`.\n *\n * @example\n * Get all invitations for a specific email address\n * ```ts\n * import { createClerkClient } from '@clerk/backend';\n * const clerkClient = createClerkClient(...)\n * await clerkClient.invitations.getInvitationList({ query: 'user@example.com' })\n * ```\n */\n query?: string;\n}>;\n\nexport class InvitationAPI extends AbstractAPI {\n public async getInvitationList(params: GetInvitationListParams = {}) {\n return this.request>({\n method: 'GET',\n path: basePath,\n queryParams: { ...params, paginated: true },\n });\n }\n\n public async createInvitation(params: CreateParams) {\n return this.request({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async createInvitationBulk(params: CreateBulkParams) {\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, 'bulk'),\n bodyParams: params,\n });\n }\n\n public async revokeInvitation(invitationId: string) {\n this.requireId(invitationId);\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, invitationId, 'revoke'),\n });\n }\n}\n","import type { ClerkPaginationRequest } from '@clerk/types';\n\nimport { joinPaths } from '../../util/path';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport type { Machine } from '../resources/Machine';\nimport type { MachineScope } from '../resources/MachineScope';\nimport type { MachineSecretKey } from '../resources/MachineSecretKey';\nimport { AbstractAPI } from './AbstractApi';\nimport type { WithSign } from './util-types';\n\nconst basePath = '/machines';\n\ntype CreateMachineParams = {\n /**\n * The name of the machine.\n */\n name: string;\n /**\n * Array of machine IDs that this machine will have access to.\n */\n scopedMachines?: string[];\n /**\n * The default time-to-live (TTL) in seconds for tokens created by this machine.\n */\n defaultTokenTtl?: number;\n};\n\ntype UpdateMachineParams = {\n /**\n * The ID of the machine to update.\n */\n machineId: string;\n /**\n * The name of the machine.\n */\n name?: string;\n /**\n * The default time-to-live (TTL) in seconds for tokens created by this machine.\n */\n defaultTokenTtl?: number;\n};\n\ntype GetMachineListParams = ClerkPaginationRequest<{\n /**\n * Sorts machines by name or created_at.\n * By prepending one of those values with + or -, we can choose to sort in ascending (ASC) or descending (DESC) order.\n */\n orderBy?: WithSign<'name' | 'created_at'>;\n /**\n * Returns machines that have a ID or name that matches the given query.\n */\n query?: string;\n}>;\n\ntype RotateMachineSecretKeyParams = {\n /**\n * The ID of the machine to rotate the secret key for.\n */\n machineId: string;\n /**\n * The time in seconds that the previous secret key will remain valid after rotation.\n */\n previousTokenTtl: number;\n};\n\nexport class MachineApi extends AbstractAPI {\n async get(machineId: string) {\n this.requireId(machineId);\n return this.request({\n method: 'GET',\n path: joinPaths(basePath, machineId),\n });\n }\n\n async list(queryParams: GetMachineListParams = {}) {\n return this.request>({\n method: 'GET',\n path: basePath,\n queryParams,\n });\n }\n\n async create(bodyParams: CreateMachineParams) {\n return this.request({\n method: 'POST',\n path: basePath,\n bodyParams,\n });\n }\n\n async update(params: UpdateMachineParams) {\n const { machineId, ...bodyParams } = params;\n this.requireId(machineId);\n return this.request({\n method: 'PATCH',\n path: joinPaths(basePath, machineId),\n bodyParams,\n });\n }\n\n async delete(machineId: string) {\n this.requireId(machineId);\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, machineId),\n });\n }\n\n async getSecretKey(machineId: string) {\n this.requireId(machineId);\n return this.request({\n method: 'GET',\n path: joinPaths(basePath, machineId, 'secret_key'),\n });\n }\n\n async rotateSecretKey(params: RotateMachineSecretKeyParams) {\n const { machineId, previousTokenTtl } = params;\n this.requireId(machineId);\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, machineId, 'secret_key', 'rotate'),\n bodyParams: {\n previousTokenTtl,\n },\n });\n }\n\n /**\n * Creates a new machine scope, allowing the specified machine to access another machine.\n *\n * @param machineId - The ID of the machine that will have access to another machine.\n * @param toMachineId - The ID of the machine that will be scoped to the current machine.\n */\n async createScope(machineId: string, toMachineId: string) {\n this.requireId(machineId);\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, machineId, 'scopes'),\n bodyParams: {\n toMachineId,\n },\n });\n }\n\n /**\n * Deletes a machine scope, removing access from one machine to another.\n *\n * @param machineId - The ID of the machine that has access to another machine.\n * @param otherMachineId - The ID of the machine that is being accessed.\n */\n async deleteScope(machineId: string, otherMachineId: string) {\n this.requireId(machineId);\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, machineId, 'scopes', otherMachineId),\n });\n }\n}\n","import { joinPaths } from '../../util/path';\nimport type { ClerkBackendApiRequestOptions } from '../request';\nimport type { M2MToken } from '../resources/M2MToken';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/m2m_tokens';\n\ntype CreateM2MTokenParams = {\n /**\n * Custom machine secret key for authentication.\n */\n machineSecretKey?: string;\n /**\n * Number of seconds until the token expires.\n *\n * @default null - Token does not expire\n */\n secondsUntilExpiration?: number | null;\n claims?: Record | null;\n};\n\ntype RevokeM2MTokenParams = {\n /**\n * Custom machine secret key for authentication.\n */\n machineSecretKey?: string;\n /**\n * Machine-to-machine token ID to revoke.\n */\n m2mTokenId: string;\n revocationReason?: string | null;\n};\n\ntype VerifyM2MTokenParams = {\n /**\n * Custom machine secret key for authentication.\n */\n machineSecretKey?: string;\n /**\n * Machine-to-machine token to verify.\n */\n token: string;\n};\n\nexport class M2MTokenApi extends AbstractAPI {\n #createRequestOptions(options: ClerkBackendApiRequestOptions, machineSecretKey?: string) {\n if (machineSecretKey) {\n return {\n ...options,\n headerParams: {\n ...options.headerParams,\n Authorization: `Bearer ${machineSecretKey}`,\n },\n };\n }\n\n return options;\n }\n\n async createToken(params?: CreateM2MTokenParams) {\n const { claims = null, machineSecretKey, secondsUntilExpiration = null } = params || {};\n\n const requestOptions = this.#createRequestOptions(\n {\n method: 'POST',\n path: basePath,\n bodyParams: {\n secondsUntilExpiration,\n claims,\n },\n },\n machineSecretKey,\n );\n\n return this.request(requestOptions);\n }\n\n async revokeToken(params: RevokeM2MTokenParams) {\n const { m2mTokenId, revocationReason = null, machineSecretKey } = params;\n\n this.requireId(m2mTokenId);\n\n const requestOptions = this.#createRequestOptions(\n {\n method: 'POST',\n path: joinPaths(basePath, m2mTokenId, 'revoke'),\n bodyParams: {\n revocationReason,\n },\n },\n machineSecretKey,\n );\n\n return this.request(requestOptions);\n }\n\n async verifyToken(params: VerifyM2MTokenParams) {\n const { token, machineSecretKey } = params;\n\n const requestOptions = this.#createRequestOptions(\n {\n method: 'POST',\n path: joinPaths(basePath, 'verify'),\n bodyParams: { token },\n },\n machineSecretKey,\n );\n\n return this.request(requestOptions);\n }\n}\n","import type { JwksJSON } from '../resources/JSON';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/jwks';\n\nexport class JwksAPI extends AbstractAPI {\n public async getJwks() {\n return this.request({\n method: 'GET',\n path: basePath,\n });\n }\n}\n","import type { ClerkPaginationRequest } from '@clerk/types';\nimport { joinPaths } from 'src/util/path';\n\nimport type { DeletedObject, JwtTemplate } from '../resources';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/jwt_templates';\n\ntype Claims = object;\n\ntype CreateJWTTemplateParams = {\n /**\n * JWT template name\n */\n name: string;\n /**\n * JWT template claims in JSON format\n */\n claims: Claims;\n /**\n * JWT token lifetime\n */\n lifetime?: number | null | undefined;\n /**\n * JWT token allowed clock skew\n */\n allowedClockSkew?: number | null | undefined;\n /**\n * Whether a custom signing key/algorithm is also provided for this template\n */\n customSigningKey?: boolean | undefined;\n /**\n * The custom signing algorithm to use when minting JWTs. Required if `custom_signing_key` is `true`.\n */\n signingAlgorithm?: string | null | undefined;\n /**\n * The custom signing private key to use when minting JWTs. Required if `custom_signing_key` is `true`.\n */\n signingKey?: string | null | undefined;\n};\n\ntype UpdateJWTTemplateParams = CreateJWTTemplateParams & {\n /**\n * JWT template ID\n */\n templateId: string;\n};\n\nexport class JwtTemplatesApi extends AbstractAPI {\n public async list(params: ClerkPaginationRequest = {}) {\n return this.request({\n method: 'GET',\n path: basePath,\n queryParams: { ...params, paginated: true },\n });\n }\n\n public async get(templateId: string) {\n this.requireId(templateId);\n\n return this.request({\n method: 'GET',\n path: joinPaths(basePath, templateId),\n });\n }\n\n public async create(params: CreateJWTTemplateParams) {\n return this.request({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async update(params: UpdateJWTTemplateParams) {\n const { templateId, ...bodyParams } = params;\n\n this.requireId(templateId);\n return this.request({\n method: 'PATCH',\n path: joinPaths(basePath, templateId),\n bodyParams,\n });\n }\n\n public async delete(templateId: string) {\n this.requireId(templateId);\n\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, templateId),\n });\n }\n}\n","import type { ClerkPaginationRequest, OrganizationEnrollmentMode } from '@clerk/types';\n\nimport { runtime } from '../../runtime';\nimport { joinPaths } from '../../util/path';\nimport type {\n Organization,\n OrganizationDomain,\n OrganizationInvitation,\n OrganizationInvitationStatus,\n OrganizationMembership,\n} from '../resources';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport type { OrganizationMembershipRole } from '../resources/Enums';\nimport { AbstractAPI } from './AbstractApi';\nimport type { WithSign } from './util-types';\n\nconst basePath = '/organizations';\n\ntype MetadataParams = {\n publicMetadata?: TPublic;\n privateMetadata?: TPrivate;\n};\n\ntype GetOrganizationListParams = ClerkPaginationRequest<{\n includeMembersCount?: boolean;\n query?: string;\n orderBy?: WithSign<'name' | 'created_at' | 'members_count'>;\n organizationId?: string[];\n}>;\n\ntype CreateParams = {\n name: string;\n slug?: string;\n /* The User id for the user creating the organization. The user will become an administrator for the organization. */\n createdBy?: string;\n maxAllowedMemberships?: number;\n} & MetadataParams;\n\ntype GetOrganizationParams = ({ organizationId: string } | { slug: string }) & {\n includeMembersCount?: boolean;\n};\n\ntype UpdateParams = {\n name?: string;\n slug?: string;\n maxAllowedMemberships?: number;\n} & MetadataParams;\n\ntype UpdateLogoParams = {\n file: Blob | File;\n uploaderUserId?: string;\n};\n\ntype UpdateMetadataParams = MetadataParams;\n\ntype GetOrganizationMembershipListParams = ClerkPaginationRequest<{\n organizationId: string;\n\n /**\n * Sorts organizations memberships by phone_number, email_address, created_at, first_name, last_name or username.\n * By prepending one of those values with + or -, we can choose to sort in ascending (ASC) or descending (DESC) order.\n */\n orderBy?: WithSign<'phone_number' | 'email_address' | 'created_at' | 'first_name' | 'last_name' | 'username'>;\n\n /**\n * Returns users with the user ids specified. For each user id, the `+` and `-` can be\n * prepended to the id, which denote whether the respective user id should be included or\n * excluded from the result set. Accepts up to 100 user ids. Any user ids not found are ignored.\n */\n userId?: string[];\n\n /* Returns users with the specified email addresses. Accepts up to 100 email addresses. Any email addresses not found are ignored. */\n emailAddress?: string[];\n\n /* Returns users with the specified phone numbers. Accepts up to 100 phone numbers. Any phone numbers not found are ignored. */\n phoneNumber?: string[];\n\n /* Returns users with the specified usernames. Accepts up to 100 usernames. Any usernames not found are ignored. */\n username?: string[];\n\n /* Returns users with the specified web3 wallet addresses. Accepts up to 100 web3 wallet addresses. Any web3 wallet addressed not found are ignored. */\n web3Wallet?: string[];\n\n /* Returns users with the specified roles. Accepts up to 100 roles. Any roles not found are ignored. */\n role?: OrganizationMembershipRole[];\n\n /**\n * Returns users that match the given query.\n * For possible matches, we check the email addresses, phone numbers, usernames, web3 wallets, user ids, first and last names.\n * The query value doesn't need to match the exact value you are looking for, it is capable of partial matches as well.\n */\n query?: string;\n\n /**\n * Returns users with emails that match the given query, via case-insensitive partial match.\n * For example, `email_address_query=ello` will match a user with the email `HELLO@example.com`.\n */\n emailAddressQuery?: string;\n\n /**\n * Returns users with phone numbers that match the given query, via case-insensitive partial match.\n * For example, `phone_number_query=555` will match a user with the phone number `+1555xxxxxxx`.\n */\n phoneNumberQuery?: string;\n\n /**\n * Returns users with usernames that match the given query, via case-insensitive partial match.\n * For example, `username_query=CoolUser` will match a user with the username `SomeCoolUser`.\n */\n usernameQuery?: string;\n\n /* Returns users with names that match the given query, via case-insensitive partial match. */\n nameQuery?: string;\n\n /**\n * Returns users whose last session activity was before the given date (with millisecond precision).\n * Example: use 1700690400000 to retrieve users whose last session activity was before 2023-11-23.\n */\n lastActiveAtBefore?: number;\n /**\n * Returns users whose last session activity was after the given date (with millisecond precision).\n * Example: use 1700690400000 to retrieve users whose last session activity was after 2023-11-23.\n */\n lastActiveAtAfter?: number;\n\n /**\n * Returns users who have been created before the given date (with millisecond precision).\n * Example: use 1730160000000 to retrieve users who have been created before 2024-10-29.\n */\n createdAtBefore?: number;\n\n /**\n * Returns users who have been created after the given date (with millisecond precision).\n * Example: use 1730160000000 to retrieve users who have been created after 2024-10-29.\n */\n createdAtAfter?: number;\n}>;\n\ntype GetInstanceOrganizationMembershipListParams = ClerkPaginationRequest<{\n /**\n * Sorts organizations memberships by phone_number, email_address, created_at, first_name, last_name or username.\n * By prepending one of those values with + or -, we can choose to sort in ascending (ASC) or descending (DESC) order.\n */\n orderBy?: WithSign<'phone_number' | 'email_address' | 'created_at' | 'first_name' | 'last_name' | 'username'>;\n}>;\n\ntype CreateOrganizationMembershipParams = {\n organizationId: string;\n userId: string;\n role: OrganizationMembershipRole;\n};\n\ntype UpdateOrganizationMembershipParams = CreateOrganizationMembershipParams;\n\ntype UpdateOrganizationMembershipMetadataParams = {\n organizationId: string;\n userId: string;\n} & MetadataParams;\n\ntype DeleteOrganizationMembershipParams = {\n organizationId: string;\n userId: string;\n};\n\ntype CreateOrganizationInvitationParams = {\n organizationId: string;\n emailAddress: string;\n role: OrganizationMembershipRole;\n expiresInDays?: number;\n inviterUserId?: string;\n privateMetadata?: OrganizationInvitationPrivateMetadata;\n publicMetadata?: OrganizationInvitationPublicMetadata;\n redirectUrl?: string;\n};\n\ntype CreateBulkOrganizationInvitationParams = Array<{\n emailAddress: string;\n role: OrganizationMembershipRole;\n expiresInDays?: number;\n inviterUserId?: string;\n privateMetadata?: OrganizationInvitationPrivateMetadata;\n publicMetadata?: OrganizationInvitationPublicMetadata;\n redirectUrl?: string;\n}>;\n\ntype GetOrganizationInvitationListParams = ClerkPaginationRequest<{\n organizationId: string;\n status?: OrganizationInvitationStatus[];\n}>;\n\ntype GetOrganizationInvitationParams = {\n organizationId: string;\n invitationId: string;\n};\n\ntype RevokeOrganizationInvitationParams = {\n organizationId: string;\n invitationId: string;\n requestingUserId?: string;\n};\n\ntype GetOrganizationDomainListParams = {\n organizationId: string;\n limit?: number;\n offset?: number;\n};\n\ntype CreateOrganizationDomainParams = {\n organizationId: string;\n name: string;\n enrollmentMode: OrganizationEnrollmentMode;\n verified?: boolean;\n};\n\ntype UpdateOrganizationDomainParams = {\n organizationId: string;\n domainId: string;\n} & Partial;\n\ntype DeleteOrganizationDomainParams = {\n organizationId: string;\n domainId: string;\n};\n\nexport class OrganizationAPI extends AbstractAPI {\n public async getOrganizationList(params?: GetOrganizationListParams) {\n return this.request>({\n method: 'GET',\n path: basePath,\n queryParams: params,\n });\n }\n\n public async createOrganization(params: CreateParams) {\n return this.request({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async getOrganization(params: GetOrganizationParams) {\n const { includeMembersCount } = params;\n const organizationIdOrSlug = 'organizationId' in params ? params.organizationId : params.slug;\n this.requireId(organizationIdOrSlug);\n\n return this.request({\n method: 'GET',\n path: joinPaths(basePath, organizationIdOrSlug),\n queryParams: {\n includeMembersCount,\n },\n });\n }\n\n public async updateOrganization(organizationId: string, params: UpdateParams) {\n this.requireId(organizationId);\n return this.request({\n method: 'PATCH',\n path: joinPaths(basePath, organizationId),\n bodyParams: params,\n });\n }\n\n public async updateOrganizationLogo(organizationId: string, params: UpdateLogoParams) {\n this.requireId(organizationId);\n\n const formData = new runtime.FormData();\n formData.append('file', params?.file);\n if (params?.uploaderUserId) {\n formData.append('uploader_user_id', params?.uploaderUserId);\n }\n\n return this.request({\n method: 'PUT',\n path: joinPaths(basePath, organizationId, 'logo'),\n formData,\n });\n }\n\n public async deleteOrganizationLogo(organizationId: string) {\n this.requireId(organizationId);\n\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, organizationId, 'logo'),\n });\n }\n\n public async updateOrganizationMetadata(organizationId: string, params: UpdateMetadataParams) {\n this.requireId(organizationId);\n\n return this.request({\n method: 'PATCH',\n path: joinPaths(basePath, organizationId, 'metadata'),\n bodyParams: params,\n });\n }\n\n public async deleteOrganization(organizationId: string) {\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, organizationId),\n });\n }\n\n public async getOrganizationMembershipList(params: GetOrganizationMembershipListParams) {\n const { organizationId, ...queryParams } = params;\n this.requireId(organizationId);\n\n return this.request>({\n method: 'GET',\n path: joinPaths(basePath, organizationId, 'memberships'),\n queryParams,\n });\n }\n\n public async getInstanceOrganizationMembershipList(params: GetInstanceOrganizationMembershipListParams) {\n return this.request>({\n method: 'GET',\n path: '/organization_memberships',\n queryParams: params,\n });\n }\n\n public async createOrganizationMembership(params: CreateOrganizationMembershipParams) {\n const { organizationId, ...bodyParams } = params;\n this.requireId(organizationId);\n\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, organizationId, 'memberships'),\n bodyParams,\n });\n }\n\n public async updateOrganizationMembership(params: UpdateOrganizationMembershipParams) {\n const { organizationId, userId, ...bodyParams } = params;\n this.requireId(organizationId);\n\n return this.request({\n method: 'PATCH',\n path: joinPaths(basePath, organizationId, 'memberships', userId),\n bodyParams,\n });\n }\n\n public async updateOrganizationMembershipMetadata(params: UpdateOrganizationMembershipMetadataParams) {\n const { organizationId, userId, ...bodyParams } = params;\n\n return this.request({\n method: 'PATCH',\n path: joinPaths(basePath, organizationId, 'memberships', userId, 'metadata'),\n bodyParams,\n });\n }\n\n public async deleteOrganizationMembership(params: DeleteOrganizationMembershipParams) {\n const { organizationId, userId } = params;\n this.requireId(organizationId);\n\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, organizationId, 'memberships', userId),\n });\n }\n\n public async getOrganizationInvitationList(params: GetOrganizationInvitationListParams) {\n const { organizationId, ...queryParams } = params;\n this.requireId(organizationId);\n\n return this.request>({\n method: 'GET',\n path: joinPaths(basePath, organizationId, 'invitations'),\n queryParams,\n });\n }\n\n public async createOrganizationInvitation(params: CreateOrganizationInvitationParams) {\n const { organizationId, ...bodyParams } = params;\n this.requireId(organizationId);\n\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, organizationId, 'invitations'),\n bodyParams,\n });\n }\n\n public async createOrganizationInvitationBulk(\n organizationId: string,\n params: CreateBulkOrganizationInvitationParams,\n ) {\n this.requireId(organizationId);\n\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, organizationId, 'invitations', 'bulk'),\n bodyParams: params,\n });\n }\n\n public async getOrganizationInvitation(params: GetOrganizationInvitationParams) {\n const { organizationId, invitationId } = params;\n this.requireId(organizationId);\n this.requireId(invitationId);\n\n return this.request({\n method: 'GET',\n path: joinPaths(basePath, organizationId, 'invitations', invitationId),\n });\n }\n\n public async revokeOrganizationInvitation(params: RevokeOrganizationInvitationParams) {\n const { organizationId, invitationId, ...bodyParams } = params;\n this.requireId(organizationId);\n\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, organizationId, 'invitations', invitationId, 'revoke'),\n bodyParams,\n });\n }\n\n public async getOrganizationDomainList(params: GetOrganizationDomainListParams) {\n const { organizationId, ...queryParams } = params;\n this.requireId(organizationId);\n\n return this.request>({\n method: 'GET',\n path: joinPaths(basePath, organizationId, 'domains'),\n queryParams,\n });\n }\n\n public async createOrganizationDomain(params: CreateOrganizationDomainParams) {\n const { organizationId, ...bodyParams } = params;\n this.requireId(organizationId);\n\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, organizationId, 'domains'),\n bodyParams: {\n ...bodyParams,\n verified: bodyParams.verified ?? true,\n },\n });\n }\n\n public async updateOrganizationDomain(params: UpdateOrganizationDomainParams) {\n const { organizationId, domainId, ...bodyParams } = params;\n this.requireId(organizationId);\n this.requireId(domainId);\n\n return this.request({\n method: 'PATCH',\n path: joinPaths(basePath, organizationId, 'domains', domainId),\n bodyParams,\n });\n }\n\n public async deleteOrganizationDomain(params: DeleteOrganizationDomainParams) {\n const { organizationId, domainId } = params;\n this.requireId(organizationId);\n this.requireId(domainId);\n\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, organizationId, 'domains', domainId),\n });\n }\n}\n","import type { ClerkPaginationRequest } from '@clerk/types';\n\nimport { joinPaths } from '../../util/path';\nimport type { DeletedObject } from '../resources';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport type { OAuthApplication } from '../resources/OAuthApplication';\nimport { AbstractAPI } from './AbstractApi';\nimport type { WithSign } from './util-types';\n\nconst basePath = '/oauth_applications';\n\ntype CreateOAuthApplicationParams = {\n /**\n * The name of the new OAuth application.\n *\n * @remarks Max length: 256\n */\n name: string;\n /**\n * An array of redirect URIs of the new OAuth application\n */\n redirectUris?: Array | null | undefined;\n /**\n * Define the allowed scopes for the new OAuth applications that dictate the user payload of the OAuth user info endpoint. Available scopes are `profile`, `email`, `public_metadata`, `private_metadata`. Provide the requested scopes as a string, separated by spaces.\n */\n scopes?: string | null | undefined;\n /**\n * If true, this client is public and you can use the Proof Key of Code Exchange (PKCE) flow.\n */\n public?: boolean | null | undefined;\n};\n\ntype UpdateOAuthApplicationParams = CreateOAuthApplicationParams & {\n /**\n * The ID of the OAuth application to update\n */\n oauthApplicationId: string;\n};\n\ntype GetOAuthApplicationListParams = ClerkPaginationRequest<{\n /**\n * Sorts OAuth applications by name or created_at.\n * By prepending one of those values with + or -, we can choose to sort in ascending (ASC) or descending (DESC) order.\n */\n orderBy?: WithSign<'name' | 'created_at'>;\n}>;\n\nexport class OAuthApplicationsApi extends AbstractAPI {\n public async list(params: GetOAuthApplicationListParams = {}) {\n return this.request>({\n method: 'GET',\n path: basePath,\n queryParams: params,\n });\n }\n\n public async get(oauthApplicationId: string) {\n this.requireId(oauthApplicationId);\n\n return this.request({\n method: 'GET',\n path: joinPaths(basePath, oauthApplicationId),\n });\n }\n\n public async create(params: CreateOAuthApplicationParams) {\n return this.request({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async update(params: UpdateOAuthApplicationParams) {\n const { oauthApplicationId, ...bodyParams } = params;\n\n this.requireId(oauthApplicationId);\n\n return this.request({\n method: 'PATCH',\n path: joinPaths(basePath, oauthApplicationId),\n bodyParams,\n });\n }\n\n public async delete(oauthApplicationId: string) {\n this.requireId(oauthApplicationId);\n\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, oauthApplicationId),\n });\n }\n\n public async rotateSecret(oauthApplicationId: string) {\n this.requireId(oauthApplicationId);\n\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, oauthApplicationId, 'rotate_secret'),\n });\n }\n}\n","import { joinPaths } from '../../util/path';\nimport type { DeletedObject, PhoneNumber } from '../resources';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/phone_numbers';\n\ntype CreatePhoneNumberParams = {\n userId: string;\n phoneNumber: string;\n verified?: boolean;\n primary?: boolean;\n reservedForSecondFactor?: boolean;\n};\n\ntype UpdatePhoneNumberParams = {\n verified?: boolean;\n primary?: boolean;\n reservedForSecondFactor?: boolean;\n};\n\nexport class PhoneNumberAPI extends AbstractAPI {\n public async getPhoneNumber(phoneNumberId: string) {\n this.requireId(phoneNumberId);\n\n return this.request({\n method: 'GET',\n path: joinPaths(basePath, phoneNumberId),\n });\n }\n\n public async createPhoneNumber(params: CreatePhoneNumberParams) {\n return this.request({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async updatePhoneNumber(phoneNumberId: string, params: UpdatePhoneNumberParams = {}) {\n this.requireId(phoneNumberId);\n\n return this.request({\n method: 'PATCH',\n path: joinPaths(basePath, phoneNumberId),\n bodyParams: params,\n });\n }\n\n public async deletePhoneNumber(phoneNumberId: string) {\n this.requireId(phoneNumberId);\n\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, phoneNumberId),\n });\n }\n}\n","import type { ProxyCheck } from '../resources';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/proxy_checks';\n\ntype VerifyParams = {\n domainId: string;\n proxyUrl: string;\n};\n\nexport class ProxyCheckAPI extends AbstractAPI {\n public async verify(params: VerifyParams) {\n return this.request({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n}\n","import { joinPaths } from '../../util/path';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport type { RedirectUrl } from '../resources/RedirectUrl';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/redirect_urls';\n\ntype CreateRedirectUrlParams = {\n url: string;\n};\n\nexport class RedirectUrlAPI extends AbstractAPI {\n public async getRedirectUrlList() {\n return this.request>({\n method: 'GET',\n path: basePath,\n queryParams: { paginated: true },\n });\n }\n\n public async getRedirectUrl(redirectUrlId: string) {\n this.requireId(redirectUrlId);\n return this.request({\n method: 'GET',\n path: joinPaths(basePath, redirectUrlId),\n });\n }\n\n public async createRedirectUrl(params: CreateRedirectUrlParams) {\n return this.request({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async deleteRedirectUrl(redirectUrlId: string) {\n this.requireId(redirectUrlId);\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, redirectUrlId),\n });\n }\n}\n","import type { ClerkPaginationRequest, SamlIdpSlug } from '@clerk/types';\n\nimport { joinPaths } from '../../util/path';\nimport type { SamlConnection } from '../resources';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport { AbstractAPI } from './AbstractApi';\nimport type { WithSign } from './util-types';\n\nconst basePath = '/saml_connections';\n\ntype SamlConnectionListParams = ClerkPaginationRequest<{\n /**\n * Returns SAML connections that have a name that matches the given query, via case-insensitive partial match.\n */\n query?: string;\n\n /**\n * Sorts SAML connections by phone_number, email_address, created_at, first_name, last_name or username.\n * By prepending one of those values with + or -, we can choose to sort in ascending (ASC) or descending (DESC) order.\n */\n orderBy?: WithSign<'phone_number' | 'email_address' | 'created_at' | 'first_name' | 'last_name' | 'username'>;\n\n /**\n * Returns SAML connections that have an associated organization ID to the given organizations.\n * For each organization id, the + and - can be prepended to the id, which denote whether the\n * respective organization should be included or excluded from the result set. Accepts up to 100 organization ids.\n */\n organizationId?: WithSign[];\n}>;\n\ntype CreateSamlConnectionParams = {\n name: string;\n provider: SamlIdpSlug;\n domain: string;\n organizationId?: string;\n idpEntityId?: string;\n idpSsoUrl?: string;\n idpCertificate?: string;\n idpMetadataUrl?: string;\n idpMetadata?: string;\n attributeMapping?: {\n emailAddress?: string;\n firstName?: string;\n lastName?: string;\n userId?: string;\n };\n};\n\ntype UpdateSamlConnectionParams = {\n name?: string;\n provider?: SamlIdpSlug;\n domain?: string;\n organizationId?: string;\n idpEntityId?: string;\n idpSsoUrl?: string;\n idpCertificate?: string;\n idpMetadataUrl?: string;\n idpMetadata?: string;\n attributeMapping?: {\n emailAddress?: string;\n firstName?: string;\n lastName?: string;\n userId?: string;\n };\n active?: boolean;\n syncUserAttributes?: boolean;\n allowSubdomains?: boolean;\n allowIdpInitiated?: boolean;\n};\n\nexport class SamlConnectionAPI extends AbstractAPI {\n public async getSamlConnectionList(params: SamlConnectionListParams = {}) {\n return this.request>({\n method: 'GET',\n path: basePath,\n queryParams: params,\n });\n }\n\n public async createSamlConnection(params: CreateSamlConnectionParams) {\n return this.request({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n options: {\n deepSnakecaseBodyParamKeys: true,\n },\n });\n }\n\n public async getSamlConnection(samlConnectionId: string) {\n this.requireId(samlConnectionId);\n return this.request({\n method: 'GET',\n path: joinPaths(basePath, samlConnectionId),\n });\n }\n\n public async updateSamlConnection(samlConnectionId: string, params: UpdateSamlConnectionParams = {}) {\n this.requireId(samlConnectionId);\n\n return this.request({\n method: 'PATCH',\n path: joinPaths(basePath, samlConnectionId),\n bodyParams: params,\n options: {\n deepSnakecaseBodyParamKeys: true,\n },\n });\n }\n public async deleteSamlConnection(samlConnectionId: string) {\n this.requireId(samlConnectionId);\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, samlConnectionId),\n });\n }\n}\n","import type { ClerkPaginationRequest, SessionStatus } from '@clerk/types';\n\nimport { joinPaths } from '../../util/path';\nimport type { Cookies } from '../resources/Cookies';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport type { Session } from '../resources/Session';\nimport type { Token } from '../resources/Token';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/sessions';\n\ntype SessionListParams = ClerkPaginationRequest<{\n clientId?: string;\n userId?: string;\n status?: SessionStatus;\n}>;\n\ntype RefreshTokenParams = {\n expired_token: string;\n refresh_token: string;\n request_origin: string;\n request_originating_ip?: string;\n request_headers?: Record;\n suffixed_cookies?: boolean;\n format?: 'token' | 'cookie';\n};\n\ntype CreateSessionParams = {\n userId: string;\n};\n\nexport class SessionAPI extends AbstractAPI {\n public async getSessionList(params: SessionListParams = {}) {\n return this.request>({\n method: 'GET',\n path: basePath,\n queryParams: { ...params, paginated: true },\n });\n }\n\n public async getSession(sessionId: string) {\n this.requireId(sessionId);\n return this.request({\n method: 'GET',\n path: joinPaths(basePath, sessionId),\n });\n }\n\n public async createSession(params: CreateSessionParams) {\n return this.request({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async revokeSession(sessionId: string) {\n this.requireId(sessionId);\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, sessionId, 'revoke'),\n });\n }\n\n public async verifySession(sessionId: string, token: string) {\n this.requireId(sessionId);\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, sessionId, 'verify'),\n bodyParams: { token },\n });\n }\n\n /**\n * Retrieves a session token or generates a JWT using a specified template.\n *\n * @param sessionId - The ID of the session for which to generate the token\n * @param template - Optional name of the JWT template configured in the Clerk Dashboard.\n * @param expiresInSeconds - Optional expiration time for the token in seconds.\n * If not provided, uses the default expiration.\n *\n * @returns A promise that resolves to the generated token\n *\n * @throws {Error} When sessionId is invalid or empty\n */\n public async getToken(sessionId: string, template?: string, expiresInSeconds?: number) {\n this.requireId(sessionId);\n\n const path = template\n ? joinPaths(basePath, sessionId, 'tokens', template)\n : joinPaths(basePath, sessionId, 'tokens');\n\n const requestOptions: any = {\n method: 'POST',\n path,\n };\n\n if (expiresInSeconds !== undefined) {\n requestOptions.bodyParams = { expires_in_seconds: expiresInSeconds };\n }\n\n return this.request(requestOptions);\n }\n\n public async refreshSession(sessionId: string, params: RefreshTokenParams & { format: 'token' }): Promise;\n public async refreshSession(sessionId: string, params: RefreshTokenParams & { format: 'cookie' }): Promise;\n public async refreshSession(sessionId: string, params: RefreshTokenParams): Promise;\n public async refreshSession(sessionId: string, params: RefreshTokenParams): Promise {\n this.requireId(sessionId);\n const { suffixed_cookies, ...restParams } = params;\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, sessionId, 'refresh'),\n bodyParams: restParams,\n queryParams: { suffixed_cookies },\n });\n }\n}\n","import { joinPaths } from '../../util/path';\nimport type { SignInToken } from '../resources/SignInTokens';\nimport { AbstractAPI } from './AbstractApi';\n\ntype CreateSignInTokensParams = {\n userId: string;\n expiresInSeconds: number;\n};\n\nconst basePath = '/sign_in_tokens';\n\nexport class SignInTokenAPI extends AbstractAPI {\n public async createSignInToken(params: CreateSignInTokensParams) {\n return this.request({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async revokeSignInToken(signInTokenId: string) {\n this.requireId(signInTokenId);\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, signInTokenId, 'revoke'),\n });\n }\n}\n","import { joinPaths } from '../../util/path';\nimport type { SignUpAttempt } from '../resources/SignUpAttempt';\nimport { AbstractAPI } from './AbstractApi';\n\ntype UpdateSignUpParams = {\n signUpAttemptId: string;\n externalId?: string | null;\n customAction?: boolean | null;\n};\n\nconst basePath = '/sign_ups';\n\nexport class SignUpAPI extends AbstractAPI {\n public async get(signUpAttemptId: string) {\n this.requireId(signUpAttemptId);\n\n return this.request({\n method: 'GET',\n path: joinPaths(basePath, signUpAttemptId),\n });\n }\n\n public async update(params: UpdateSignUpParams) {\n const { signUpAttemptId, ...bodyParams } = params;\n\n return this.request({\n method: 'PATCH',\n path: joinPaths(basePath, signUpAttemptId),\n bodyParams,\n });\n }\n}\n","import type { TestingToken } from '../resources/TestingToken';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/testing_tokens';\n\nexport class TestingTokenAPI extends AbstractAPI {\n public async createTestingToken() {\n return this.request({\n method: 'POST',\n path: basePath,\n });\n }\n}\n","import type { ClerkPaginationRequest, OAuthProvider, OrganizationInvitationStatus } from '@clerk/types';\n\nimport { runtime } from '../../runtime';\nimport { joinPaths } from '../../util/path';\nimport { deprecated } from '../../util/shared';\nimport type {\n DeletedObject,\n OauthAccessToken,\n OrganizationInvitation,\n OrganizationMembership,\n User,\n} from '../resources';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport { AbstractAPI } from './AbstractApi';\nimport type { WithSign } from './util-types';\n\nconst basePath = '/users';\n\ntype UserCountParams = {\n emailAddress?: string[];\n phoneNumber?: string[];\n username?: string[];\n web3Wallet?: string[];\n query?: string;\n userId?: string[];\n externalId?: string[];\n};\n\ntype UserListParams = ClerkPaginationRequest<\n UserCountParams & {\n orderBy?: WithSign<\n | 'created_at'\n | 'updated_at'\n | 'email_address'\n | 'web3wallet'\n | 'first_name'\n | 'last_name'\n | 'phone_number'\n | 'username'\n | 'last_active_at'\n | 'last_sign_in_at'\n >;\n last_active_at_since?: number;\n organizationId?: string[];\n }\n>;\n\ntype UserMetadataParams = {\n publicMetadata?: UserPublicMetadata;\n privateMetadata?: UserPrivateMetadata;\n unsafeMetadata?: UserUnsafeMetadata;\n};\n\ntype PasswordHasher =\n | 'argon2i'\n | 'argon2id'\n | 'awscognito'\n | 'bcrypt'\n | 'bcrypt_sha256_django'\n | 'md5'\n | 'pbkdf2_sha256'\n | 'pbkdf2_sha256_django'\n | 'pbkdf2_sha1'\n | 'phpass'\n | 'scrypt_firebase'\n | 'scrypt_werkzeug'\n | 'sha256'\n | 'md5_phpass'\n | 'ldap_ssha';\n\ntype UserPasswordHashingParams = {\n passwordDigest: string;\n passwordHasher: PasswordHasher;\n};\n\ntype CreateUserParams = {\n externalId?: string;\n emailAddress?: string[];\n phoneNumber?: string[];\n username?: string;\n password?: string;\n firstName?: string;\n lastName?: string;\n skipPasswordChecks?: boolean;\n skipPasswordRequirement?: boolean;\n skipLegalChecks?: boolean;\n legalAcceptedAt?: Date;\n totpSecret?: string;\n backupCodes?: string[];\n createdAt?: Date;\n} & UserMetadataParams &\n (UserPasswordHashingParams | object);\n\ntype UpdateUserParams = {\n /** The first name to assign to the user. */\n firstName?: string;\n\n /** The last name of the user. */\n lastName?: string;\n\n /** The username to give to the user. It must be unique across your instance. */\n username?: string;\n\n /** The plaintext password to give the user. Must be at least 8 characters long, and can not be in any list of hacked passwords. */\n password?: string;\n\n /** Set it to true if you're updating the user's password and want to skip any password policy settings check. This parameter can only be used when providing a password. */\n skipPasswordChecks?: boolean;\n\n /** Set to true to sign out the user from all their active sessions once their password is updated. This parameter can only be used when providing a password. */\n signOutOfOtherSessions?: boolean;\n\n /** The ID of the email address to set as primary. It must be verified, and present on the current user. */\n primaryEmailAddressID?: string;\n\n /** If set to true, the user will be notified that their primary email address has changed. By default, no notification is sent. */\n notifyPrimaryEmailAddressChanged?: boolean;\n\n /** The ID of the phone number to set as primary. It must be verified, and present on the current user. */\n primaryPhoneNumberID?: string;\n\n /** The ID of the web3 wallets to set as primary. It must be verified, and present on the current user. */\n primaryWeb3WalletID?: string;\n\n /** The ID of the image to set as the user's profile image */\n profileImageID?: string;\n\n /**\n * In case TOTP is configured on the instance, you can provide the secret to enable it on the specific user without the need to reset it.\n * Please note that currently the supported options are:\n * - Period: 30 seconds\n * - Code length: 6 digits\n * - Algorithm: SHA1\n */\n totpSecret?: string;\n\n /** If Backup Codes are configured on the instance, you can provide them to enable it on the specific user without the need to reset them. You must provide the backup codes in plain format or the corresponding bcrypt digest. */\n backupCodes?: string[];\n\n /** The ID of the user as used in your external systems or your previous authentication solution. Must be unique across your instance. */\n externalId?: string;\n\n /** A custom timestamp denoting when the user signed up to the application, specified in RFC3339 format (e.g. 2012-10-20T07:15:20.902Z). */\n createdAt?: Date;\n\n /** When set to true all legal checks are skipped. It is not recommended to skip legal checks unless you are migrating a user to Clerk. */\n skipLegalChecks?: boolean;\n\n /** A custom timestamp denoting when the user accepted legal requirements, specified in RFC3339 format (e.g. 2012-10-20T07:15:20.902Z). */\n legalAcceptedAt?: Date;\n\n /** If true, the user can delete themselves with the Frontend API. */\n deleteSelfEnabled?: boolean;\n\n /** If true, the user can create organizations with the Frontend API. */\n createOrganizationEnabled?: boolean;\n\n /** The maximum number of organizations the user can create. 0 means unlimited. */\n createOrganizationsLimit?: number;\n} & UserMetadataParams &\n (UserPasswordHashingParams | object);\n\ntype GetOrganizationMembershipListParams = ClerkPaginationRequest<{\n userId: string;\n}>;\n\ntype GetOrganizationInvitationListParams = ClerkPaginationRequest<{\n userId: string;\n status?: OrganizationInvitationStatus;\n}>;\n\ntype VerifyPasswordParams = {\n userId: string;\n password: string;\n};\n\ntype VerifyTOTPParams = {\n userId: string;\n code: string;\n};\n\ntype DeleteUserPasskeyParams = {\n userId: string;\n passkeyIdentificationId: string;\n};\n\ntype DeleteWeb3WalletParams = {\n userId: string;\n web3WalletIdentificationId: string;\n};\n\ntype DeleteUserExternalAccountParams = {\n userId: string;\n externalAccountId: string;\n};\n\ntype UserID = {\n userId: string;\n};\n\nexport class UserAPI extends AbstractAPI {\n public async getUserList(params: UserListParams = {}) {\n const { limit, offset, orderBy, ...userCountParams } = params;\n // TODO(dimkl): Temporary change to populate totalCount using a 2nd BAPI call to /users/count endpoint\n // until we update the /users endpoint to be paginated in a next BAPI version.\n // In some edge cases the data.length != totalCount due to a creation of a user between the 2 api responses\n const [data, totalCount] = await Promise.all([\n this.request({\n method: 'GET',\n path: basePath,\n queryParams: params,\n }),\n this.getCount(userCountParams),\n ]);\n return { data, totalCount } as PaginatedResourceResponse;\n }\n\n public async getUser(userId: string) {\n this.requireId(userId);\n return this.request({\n method: 'GET',\n path: joinPaths(basePath, userId),\n });\n }\n\n public async createUser(params: CreateUserParams) {\n return this.request({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async updateUser(userId: string, params: UpdateUserParams = {}) {\n this.requireId(userId);\n\n return this.request({\n method: 'PATCH',\n path: joinPaths(basePath, userId),\n bodyParams: params,\n });\n }\n\n public async updateUserProfileImage(userId: string, params: { file: Blob | File }) {\n this.requireId(userId);\n\n const formData = new runtime.FormData();\n formData.append('file', params?.file);\n\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, userId, 'profile_image'),\n formData,\n });\n }\n\n public async updateUserMetadata(userId: string, params: UserMetadataParams) {\n this.requireId(userId);\n\n return this.request({\n method: 'PATCH',\n path: joinPaths(basePath, userId, 'metadata'),\n bodyParams: params,\n });\n }\n\n public async deleteUser(userId: string) {\n this.requireId(userId);\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, userId),\n });\n }\n\n public async getCount(params: UserCountParams = {}) {\n return this.request({\n method: 'GET',\n path: joinPaths(basePath, 'count'),\n queryParams: params,\n });\n }\n\n /** @deprecated Use `getUserOauthAccessToken` without the `oauth_` provider prefix . */\n public async getUserOauthAccessToken(\n userId: string,\n provider: `oauth_${OAuthProvider}`,\n ): Promise>;\n public async getUserOauthAccessToken(\n userId: string,\n provider: OAuthProvider,\n ): Promise>;\n public async getUserOauthAccessToken(userId: string, provider: `oauth_${OAuthProvider}` | OAuthProvider) {\n this.requireId(userId);\n const hasPrefix = provider.startsWith('oauth_');\n const _provider = hasPrefix ? provider : `oauth_${provider}`;\n\n if (hasPrefix) {\n deprecated(\n 'getUserOauthAccessToken(userId, provider)',\n 'Remove the `oauth_` prefix from the `provider` argument.',\n );\n }\n\n return this.request>({\n method: 'GET',\n path: joinPaths(basePath, userId, 'oauth_access_tokens', _provider),\n queryParams: { paginated: true },\n });\n }\n\n public async disableUserMFA(userId: string) {\n this.requireId(userId);\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, userId, 'mfa'),\n });\n }\n\n public async getOrganizationMembershipList(params: GetOrganizationMembershipListParams) {\n const { userId, limit, offset } = params;\n this.requireId(userId);\n\n return this.request>({\n method: 'GET',\n path: joinPaths(basePath, userId, 'organization_memberships'),\n queryParams: { limit, offset },\n });\n }\n\n public async getOrganizationInvitationList(params: GetOrganizationInvitationListParams) {\n const { userId, ...queryParams } = params;\n this.requireId(userId);\n\n return this.request>({\n method: 'GET',\n path: joinPaths(basePath, userId, 'organization_invitations'),\n queryParams,\n });\n }\n\n public async verifyPassword(params: VerifyPasswordParams) {\n const { userId, password } = params;\n this.requireId(userId);\n\n return this.request<{ verified: true }>({\n method: 'POST',\n path: joinPaths(basePath, userId, 'verify_password'),\n bodyParams: { password },\n });\n }\n\n public async verifyTOTP(params: VerifyTOTPParams) {\n const { userId, code } = params;\n this.requireId(userId);\n\n return this.request<{ verified: true; code_type: 'totp' }>({\n method: 'POST',\n path: joinPaths(basePath, userId, 'verify_totp'),\n bodyParams: { code },\n });\n }\n\n public async banUser(userId: string) {\n this.requireId(userId);\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, userId, 'ban'),\n });\n }\n\n public async unbanUser(userId: string) {\n this.requireId(userId);\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, userId, 'unban'),\n });\n }\n\n public async lockUser(userId: string) {\n this.requireId(userId);\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, userId, 'lock'),\n });\n }\n\n public async unlockUser(userId: string) {\n this.requireId(userId);\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, userId, 'unlock'),\n });\n }\n\n public async deleteUserProfileImage(userId: string) {\n this.requireId(userId);\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, userId, 'profile_image'),\n });\n }\n\n public async deleteUserPasskey(params: DeleteUserPasskeyParams) {\n this.requireId(params.userId);\n this.requireId(params.passkeyIdentificationId);\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, params.userId, 'passkeys', params.passkeyIdentificationId),\n });\n }\n\n public async deleteUserWeb3Wallet(params: DeleteWeb3WalletParams) {\n this.requireId(params.userId);\n this.requireId(params.web3WalletIdentificationId);\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, params.userId, 'web3_wallets', params.web3WalletIdentificationId),\n });\n }\n\n public async deleteUserExternalAccount(params: DeleteUserExternalAccountParams) {\n this.requireId(params.userId);\n this.requireId(params.externalAccountId);\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, params.userId, 'external_accounts', params.externalAccountId),\n });\n }\n\n public async deleteUserBackupCodes(userId: string) {\n this.requireId(userId);\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, userId, 'backup_code'),\n });\n }\n\n public async deleteUserTOTP(userId: string) {\n this.requireId(userId);\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, userId, 'totp'),\n });\n }\n}\n","import type { ClerkPaginationRequest } from '@clerk/types';\nimport { joinPaths } from 'src/util/path';\n\nimport type { DeletedObject } from '../resources/DeletedObject';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport type { WaitlistEntryStatus } from '../resources/Enums';\nimport type { WaitlistEntry } from '../resources/WaitlistEntry';\nimport { AbstractAPI } from './AbstractApi';\nimport type { WithSign } from './util-types';\n\nconst basePath = '/waitlist_entries';\n\ntype WaitlistEntryListParams = ClerkPaginationRequest<{\n /**\n * Filter waitlist entries by `email_address` or `id`\n */\n query?: string;\n status?: WaitlistEntryStatus;\n orderBy?: WithSign<'created_at' | 'invited_at' | 'email_address'>;\n}>;\n\ntype WaitlistEntryCreateParams = {\n emailAddress: string;\n notify?: boolean;\n};\n\ntype WaitlistEntryInviteParams = {\n /**\n * When true, do not error if an invitation already exists. Default: false.\n */\n ignoreExisting?: boolean;\n};\n\nexport class WaitlistEntryAPI extends AbstractAPI {\n /**\n * List waitlist entries.\n * @param params Optional parameters (e.g., `query`, `status`, `orderBy`).\n */\n public async list(params: WaitlistEntryListParams = {}) {\n return this.request>({\n method: 'GET',\n path: basePath,\n queryParams: params,\n });\n }\n\n /**\n * Create a waitlist entry.\n * @param params The parameters for creating a waitlist entry.\n */\n public async create(params: WaitlistEntryCreateParams) {\n return this.request({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n /**\n * Invite a waitlist entry.\n * @param id The waitlist entry ID.\n * @param params Optional parameters (e.g., `ignoreExisting`).\n */\n public async invite(id: string, params: WaitlistEntryInviteParams = {}) {\n this.requireId(id);\n\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, id, 'invite'),\n bodyParams: params,\n });\n }\n\n /**\n * Reject a waitlist entry.\n * @param id The waitlist entry ID.\n */\n public async reject(id: string) {\n this.requireId(id);\n\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, id, 'reject'),\n });\n }\n\n /**\n * Delete a waitlist entry.\n * @param id The waitlist entry ID.\n */\n public async delete(id: string) {\n this.requireId(id);\n\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, id),\n });\n }\n}\n","import { joinPaths } from '../../util/path';\nimport type { WebhooksSvixJSON } from '../resources/JSON';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/webhooks';\n\nexport class WebhookAPI extends AbstractAPI {\n public async createSvixApp() {\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, 'svix'),\n });\n }\n\n public async generateSvixAuthURL() {\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, 'svix_url'),\n });\n }\n\n public async deleteSvixApp() {\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, 'svix'),\n });\n }\n}\n","import type { ClerkPaginationRequest } from '@clerk/types';\n\nimport { joinPaths } from '../../util/path';\nimport type { BillingPlan } from '../resources/CommercePlan';\nimport type { BillingSubscription } from '../resources/CommerceSubscription';\nimport type { BillingSubscriptionItem } from '../resources/CommerceSubscriptionItem';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/commerce';\nconst organizationBasePath = '/organizations';\nconst userBasePath = '/users';\n\ntype GetOrganizationListParams = ClerkPaginationRequest<{\n payerType: 'org' | 'user';\n}>;\n\ntype CancelSubscriptionItemParams = {\n /**\n * If true, the subscription item will be canceled immediately. If false or undefined, the subscription item will be canceled at the end of the current billing period.\n * @default undefined\n */\n endNow?: boolean;\n};\n\ntype ExtendSubscriptionItemFreeTrialParams = {\n /**\n * RFC3339 timestamp to extend the free trial to.\n * Must be in the future and not more than 365 days from the current trial end.\n */\n extendTo: Date;\n};\n\nexport class BillingAPI extends AbstractAPI {\n /**\n * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes.\n */\n public async getPlanList(params?: GetOrganizationListParams) {\n return this.request>({\n method: 'GET',\n path: joinPaths(basePath, 'plans'),\n queryParams: params,\n });\n }\n\n /**\n * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes.\n */\n public async cancelSubscriptionItem(subscriptionItemId: string, params?: CancelSubscriptionItemParams) {\n this.requireId(subscriptionItemId);\n return this.request({\n method: 'DELETE',\n path: joinPaths(basePath, 'subscription_items', subscriptionItemId),\n queryParams: params,\n });\n }\n\n /**\n * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes.\n */\n public async extendSubscriptionItemFreeTrial(\n subscriptionItemId: string,\n params: ExtendSubscriptionItemFreeTrialParams,\n ) {\n this.requireId(subscriptionItemId);\n return this.request({\n method: 'POST',\n path: joinPaths('/billing', 'subscription_items', subscriptionItemId, 'extend_free_trial'),\n bodyParams: params,\n });\n }\n\n /**\n * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes.\n */\n public async getOrganizationBillingSubscription(organizationId: string) {\n this.requireId(organizationId);\n return this.request({\n method: 'GET',\n path: joinPaths(organizationBasePath, organizationId, 'billing', 'subscription'),\n });\n }\n\n /**\n * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes.\n */\n public async getUserBillingSubscription(userId: string) {\n this.requireId(userId);\n return this.request({\n method: 'GET',\n path: joinPaths(userBasePath, userId, 'billing', 'subscription'),\n });\n }\n}\n","import { ClerkAPIResponseError, parseError } from '@clerk/shared/error';\nimport type { ClerkAPIError, ClerkAPIErrorJSON } from '@clerk/types';\nimport snakecaseKeys from 'snakecase-keys';\n\nimport { API_URL, API_VERSION, constants, SUPPORTED_BAPI_VERSION, USER_AGENT } from '../constants';\nimport { runtime } from '../runtime';\nimport { assertValidSecretKey } from '../util/optionsAssertions';\nimport { joinPaths } from '../util/path';\nimport { deserialize } from './resources/Deserializer';\n\ntype ClerkBackendApiRequestOptionsUrlOrPath =\n | {\n url: string;\n path?: string;\n }\n | {\n url?: string;\n path: string;\n };\n\ntype ClerkBackendApiRequestOptionsBodyParams =\n | {\n bodyParams: Record | Array>;\n options?: {\n /**\n * If true, snakecases the keys of the bodyParams object recursively.\n * @default false\n */\n deepSnakecaseBodyParamKeys?: boolean;\n };\n }\n | {\n bodyParams?: never;\n options?: {\n deepSnakecaseBodyParamKeys?: never;\n };\n };\n\nexport type ClerkBackendApiRequestOptions = {\n method: 'GET' | 'POST' | 'PATCH' | 'DELETE' | 'PUT';\n queryParams?: Record;\n headerParams?: Record;\n formData?: FormData;\n} & ClerkBackendApiRequestOptionsUrlOrPath &\n ClerkBackendApiRequestOptionsBodyParams;\n\nexport type ClerkBackendApiResponse =\n | {\n data: T;\n errors: null;\n totalCount?: number;\n }\n | {\n data: null;\n errors: ClerkAPIError[];\n totalCount?: never;\n clerkTraceId?: string;\n status?: number;\n statusText?: string;\n retryAfter?: number;\n };\n\nexport type RequestFunction = ReturnType;\n\ntype BuildRequestOptions = {\n /* Secret Key */\n secretKey?: string;\n /* Backend API URL */\n apiUrl?: string;\n /* Backend API version */\n apiVersion?: string;\n /* Library/SDK name */\n userAgent?: string;\n /**\n * Allow requests without specifying a secret key. In most cases this should be set to `false`.\n * @default true\n */\n requireSecretKey?: boolean;\n /**\n * If true, omits the API version from the request URL path.\n * This is required for bapi-proxy endpoints, which do not use versioning in the URL.\n *\n * Note: API versioning for these endpoints is instead handled via the `Clerk-API-Version` HTTP header.\n *\n * @default false\n */\n skipApiVersionInUrl?: boolean;\n /* Machine secret key */\n machineSecretKey?: string;\n /**\n * If true, uses machineSecretKey for authorization instead of secretKey.\n *\n * Note: This is only used for machine-to-machine tokens.\n *\n * @default false\n */\n useMachineSecretKey?: boolean;\n};\n\nexport function buildRequest(options: BuildRequestOptions) {\n const requestFn = async (requestOptions: ClerkBackendApiRequestOptions): Promise> => {\n const {\n secretKey,\n machineSecretKey,\n useMachineSecretKey = false,\n requireSecretKey = true,\n apiUrl = API_URL,\n apiVersion = API_VERSION,\n userAgent = USER_AGENT,\n skipApiVersionInUrl = false,\n } = options;\n const { path, method, queryParams, headerParams, bodyParams, formData, options: opts } = requestOptions;\n const { deepSnakecaseBodyParamKeys = false } = opts || {};\n\n if (requireSecretKey) {\n assertValidSecretKey(secretKey);\n }\n\n const url = skipApiVersionInUrl ? joinPaths(apiUrl, path) : joinPaths(apiUrl, apiVersion, path);\n\n // Build final URL with search parameters\n const finalUrl = new URL(url);\n\n if (queryParams) {\n // Snakecase query parameters\n const snakecasedQueryParams = snakecaseKeys({ ...queryParams });\n\n // Support array values for queryParams such as { foo: [42, 43] }\n for (const [key, val] of Object.entries(snakecasedQueryParams)) {\n if (val) {\n [val].flat().forEach(v => finalUrl.searchParams.append(key, v as string));\n }\n }\n }\n\n // Build headers\n const headers = new Headers({\n 'Clerk-API-Version': SUPPORTED_BAPI_VERSION,\n [constants.Headers.UserAgent]: userAgent,\n ...headerParams,\n });\n\n // If Authorization header already exists, preserve it.\n // Otherwise, use machine secret key if enabled, or fall back to regular secret key\n const authorizationHeader = constants.Headers.Authorization;\n if (!headers.has(authorizationHeader)) {\n if (useMachineSecretKey && machineSecretKey) {\n headers.set(authorizationHeader, `Bearer ${machineSecretKey}`);\n } else if (secretKey) {\n headers.set(authorizationHeader, `Bearer ${secretKey}`);\n }\n }\n\n let res: Response | undefined;\n try {\n if (formData) {\n res = await runtime.fetch(finalUrl.href, {\n method,\n headers,\n body: formData,\n });\n } else {\n // Enforce application/json for all non form-data requests\n headers.set('Content-Type', 'application/json');\n\n const buildBody = () => {\n const hasBody = method !== 'GET' && bodyParams && Object.keys(bodyParams).length > 0;\n if (!hasBody) {\n return null;\n }\n\n const formatKeys = (object: Parameters[0]) =>\n snakecaseKeys(object, { deep: deepSnakecaseBodyParamKeys });\n\n return {\n body: JSON.stringify(Array.isArray(bodyParams) ? bodyParams.map(formatKeys) : formatKeys(bodyParams)),\n };\n };\n\n res = await runtime.fetch(finalUrl.href, {\n method,\n headers,\n ...buildBody(),\n });\n }\n\n // TODO: Parse JSON or Text response based on a response header\n const isJSONResponse =\n res?.headers && res.headers?.get(constants.Headers.ContentType) === constants.ContentTypes.Json;\n const responseBody = await (isJSONResponse ? res.json() : res.text());\n\n if (!res.ok) {\n return {\n data: null,\n errors: parseErrors(responseBody),\n status: res?.status,\n statusText: res?.statusText,\n clerkTraceId: getTraceId(responseBody, res?.headers),\n retryAfter: getRetryAfter(res?.headers),\n };\n }\n\n return {\n ...deserialize(responseBody),\n errors: null,\n };\n } catch (err) {\n if (err instanceof Error) {\n return {\n data: null,\n errors: [\n {\n code: 'unexpected_error',\n message: err.message || 'Unexpected error',\n },\n ],\n clerkTraceId: getTraceId(err, res?.headers),\n };\n }\n\n return {\n data: null,\n errors: parseErrors(err),\n status: res?.status,\n statusText: res?.statusText,\n clerkTraceId: getTraceId(err, res?.headers),\n retryAfter: getRetryAfter(res?.headers),\n };\n }\n };\n\n return withLegacyRequestReturn(requestFn);\n}\n\n// Returns either clerk_trace_id if present in response json, otherwise defaults to CF-Ray header\n// If the request failed before receiving a response, returns undefined\nfunction getTraceId(data: unknown, headers?: Headers): string {\n if (data && typeof data === 'object' && 'clerk_trace_id' in data && typeof data.clerk_trace_id === 'string') {\n return data.clerk_trace_id;\n }\n\n const cfRay = headers?.get('cf-ray');\n return cfRay || '';\n}\n\nfunction getRetryAfter(headers?: Headers): number | undefined {\n const retryAfter = headers?.get('Retry-After');\n if (!retryAfter) {\n return;\n }\n\n const value = parseInt(retryAfter, 10);\n if (isNaN(value)) {\n return;\n }\n\n return value;\n}\n\nfunction parseErrors(data: unknown): ClerkAPIError[] {\n if (!!data && typeof data === 'object' && 'errors' in data) {\n const errors = data.errors as ClerkAPIErrorJSON[];\n return errors.length > 0 ? errors.map(parseError) : [];\n }\n return [];\n}\n\ntype LegacyRequestFunction = (requestOptions: ClerkBackendApiRequestOptions) => Promise;\n\n// TODO(dimkl): Will be probably be dropped in next major version\nfunction withLegacyRequestReturn(cb: any): LegacyRequestFunction {\n return async (...args) => {\n const { data, errors, totalCount, status, statusText, clerkTraceId, retryAfter } = await cb(...args);\n if (errors) {\n // instead of passing `data: errors`, we have set the `error.errors` because\n // the errors returned from callback is already parsed and passing them as `data`\n // will not be able to assign them to the instance\n const error = new ClerkAPIResponseError(statusText || '', {\n data: [],\n status,\n clerkTraceId,\n retryAfter,\n });\n error.errors = errors;\n throw error;\n }\n\n if (typeof totalCount !== 'undefined') {\n return { data, totalCount };\n }\n\n return data;\n };\n}\n","const isObject = value => typeof value === 'object' && value !== null;\n\n// Customized for this use-case\nconst isObjectCustom = value =>\n\tisObject(value)\n\t&& !(value instanceof RegExp)\n\t&& !(value instanceof Error)\n\t&& !(value instanceof Date)\n\t&& !(globalThis.Blob && value instanceof globalThis.Blob);\n\nexport const mapObjectSkip = Symbol('mapObjectSkip');\n\nconst _mapObject = (object, mapper, options, isSeen = new WeakMap()) => {\n\toptions = {\n\t\tdeep: false,\n\t\ttarget: {},\n\t\t...options,\n\t};\n\n\tif (isSeen.has(object)) {\n\t\treturn isSeen.get(object);\n\t}\n\n\tisSeen.set(object, options.target);\n\n\tconst {target} = options;\n\tdelete options.target;\n\n\tconst mapArray = array => array.map(element => isObjectCustom(element) ? _mapObject(element, mapper, options, isSeen) : element);\n\tif (Array.isArray(object)) {\n\t\treturn mapArray(object);\n\t}\n\n\tfor (const [key, value] of Object.entries(object)) {\n\t\tconst mapResult = mapper(key, value, object);\n\n\t\tif (mapResult === mapObjectSkip) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tlet [newKey, newValue, {shouldRecurse = true} = {}] = mapResult;\n\n\t\t// Drop `__proto__` keys.\n\t\tif (newKey === '__proto__') {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (options.deep && shouldRecurse && isObjectCustom(newValue)) {\n\t\t\tnewValue = Array.isArray(newValue)\n\t\t\t\t? mapArray(newValue)\n\t\t\t\t: _mapObject(newValue, mapper, options, isSeen);\n\t\t}\n\n\t\ttarget[newKey] = newValue;\n\t}\n\n\treturn target;\n};\n\nexport default function mapObject(object, mapper, options) {\n\tif (!isObject(object)) {\n\t\tthrow new TypeError(`Expected an object, got \\`${object}\\` (${typeof object})`);\n\t}\n\n\tif (Array.isArray(object)) {\n\t\tthrow new TypeError('Expected an object, got an array');\n\t}\n\n\treturn _mapObject(object, mapper, options);\n}\n","// Regexps involved with splitting words in various case formats.\nconst SPLIT_LOWER_UPPER_RE = /([\\p{Ll}\\d])(\\p{Lu})/gu;\nconst SPLIT_UPPER_UPPER_RE = /(\\p{Lu})([\\p{Lu}][\\p{Ll}])/gu;\n\n// Used to iterate over the initial split result and separate numbers.\nconst SPLIT_SEPARATE_NUMBER_RE = /(\\d)\\p{Ll}|(\\p{L})\\d/u;\n\n// Regexp involved with stripping non-word characters from the result.\nconst DEFAULT_STRIP_REGEXP = /[^\\p{L}\\d]+/giu;\n\n// The replacement value for splits.\nconst SPLIT_REPLACE_VALUE = \"$1\\0$2\";\n\n// The default characters to keep after transforming case.\nconst DEFAULT_PREFIX_SUFFIX_CHARACTERS = \"\";\n\n/**\n * Supported locale values. Use `false` to ignore locale.\n * Defaults to `undefined`, which uses the host environment.\n */\nexport type Locale = string[] | string | false | undefined;\n\n/**\n * Options used for converting strings to pascal/camel case.\n */\nexport interface PascalCaseOptions extends Options {\n mergeAmbiguousCharacters?: boolean;\n}\n\n/**\n * Options used for converting strings to any case.\n */\nexport interface Options {\n locale?: Locale;\n split?: (value: string) => string[];\n /** @deprecated Pass `split: splitSeparateNumbers` instead. */\n separateNumbers?: boolean;\n delimiter?: string;\n prefixCharacters?: string;\n suffixCharacters?: string;\n}\n\n/**\n * Split any cased input strings into an array of words.\n */\nexport function split(value: string) {\n let result = value.trim();\n\n result = result\n .replace(SPLIT_LOWER_UPPER_RE, SPLIT_REPLACE_VALUE)\n .replace(SPLIT_UPPER_UPPER_RE, SPLIT_REPLACE_VALUE);\n\n result = result.replace(DEFAULT_STRIP_REGEXP, \"\\0\");\n\n let start = 0;\n let end = result.length;\n\n // Trim the delimiter from around the output string.\n while (result.charAt(start) === \"\\0\") start++;\n if (start === end) return [];\n while (result.charAt(end - 1) === \"\\0\") end--;\n\n return result.slice(start, end).split(/\\0/g);\n}\n\n/**\n * Split the input string into an array of words, separating numbers.\n */\nexport function splitSeparateNumbers(value: string) {\n const words = split(value);\n for (let i = 0; i < words.length; i++) {\n const word = words[i];\n const match = SPLIT_SEPARATE_NUMBER_RE.exec(word);\n if (match) {\n const offset = match.index + (match[1] ?? match[2]).length;\n words.splice(i, 1, word.slice(0, offset), word.slice(offset));\n }\n }\n return words;\n}\n\n/**\n * Convert a string to space separated lower case (`foo bar`).\n */\nexport function noCase(input: string, options?: Options) {\n const [prefix, words, suffix] = splitPrefixSuffix(input, options);\n return (\n prefix +\n words.map(lowerFactory(options?.locale)).join(options?.delimiter ?? \" \") +\n suffix\n );\n}\n\n/**\n * Convert a string to camel case (`fooBar`).\n */\nexport function camelCase(input: string, options?: PascalCaseOptions) {\n const [prefix, words, suffix] = splitPrefixSuffix(input, options);\n const lower = lowerFactory(options?.locale);\n const upper = upperFactory(options?.locale);\n const transform = options?.mergeAmbiguousCharacters\n ? capitalCaseTransformFactory(lower, upper)\n : pascalCaseTransformFactory(lower, upper);\n return (\n prefix +\n words\n .map((word, index) => {\n if (index === 0) return lower(word);\n return transform(word, index);\n })\n .join(options?.delimiter ?? \"\") +\n suffix\n );\n}\n\n/**\n * Convert a string to pascal case (`FooBar`).\n */\nexport function pascalCase(input: string, options?: PascalCaseOptions) {\n const [prefix, words, suffix] = splitPrefixSuffix(input, options);\n const lower = lowerFactory(options?.locale);\n const upper = upperFactory(options?.locale);\n const transform = options?.mergeAmbiguousCharacters\n ? capitalCaseTransformFactory(lower, upper)\n : pascalCaseTransformFactory(lower, upper);\n return prefix + words.map(transform).join(options?.delimiter ?? \"\") + suffix;\n}\n\n/**\n * Convert a string to pascal snake case (`Foo_Bar`).\n */\nexport function pascalSnakeCase(input: string, options?: Options) {\n return capitalCase(input, { delimiter: \"_\", ...options });\n}\n\n/**\n * Convert a string to capital case (`Foo Bar`).\n */\nexport function capitalCase(input: string, options?: Options) {\n const [prefix, words, suffix] = splitPrefixSuffix(input, options);\n const lower = lowerFactory(options?.locale);\n const upper = upperFactory(options?.locale);\n return (\n prefix +\n words\n .map(capitalCaseTransformFactory(lower, upper))\n .join(options?.delimiter ?? \" \") +\n suffix\n );\n}\n\n/**\n * Convert a string to constant case (`FOO_BAR`).\n */\nexport function constantCase(input: string, options?: Options) {\n const [prefix, words, suffix] = splitPrefixSuffix(input, options);\n return (\n prefix +\n words.map(upperFactory(options?.locale)).join(options?.delimiter ?? \"_\") +\n suffix\n );\n}\n\n/**\n * Convert a string to dot case (`foo.bar`).\n */\nexport function dotCase(input: string, options?: Options) {\n return noCase(input, { delimiter: \".\", ...options });\n}\n\n/**\n * Convert a string to kebab case (`foo-bar`).\n */\nexport function kebabCase(input: string, options?: Options) {\n return noCase(input, { delimiter: \"-\", ...options });\n}\n\n/**\n * Convert a string to path case (`foo/bar`).\n */\nexport function pathCase(input: string, options?: Options) {\n return noCase(input, { delimiter: \"/\", ...options });\n}\n\n/**\n * Convert a string to path case (`Foo bar`).\n */\nexport function sentenceCase(input: string, options?: Options) {\n const [prefix, words, suffix] = splitPrefixSuffix(input, options);\n const lower = lowerFactory(options?.locale);\n const upper = upperFactory(options?.locale);\n const transform = capitalCaseTransformFactory(lower, upper);\n return (\n prefix +\n words\n .map((word, index) => {\n if (index === 0) return transform(word);\n return lower(word);\n })\n .join(options?.delimiter ?? \" \") +\n suffix\n );\n}\n\n/**\n * Convert a string to snake case (`foo_bar`).\n */\nexport function snakeCase(input: string, options?: Options) {\n return noCase(input, { delimiter: \"_\", ...options });\n}\n\n/**\n * Convert a string to header case (`Foo-Bar`).\n */\nexport function trainCase(input: string, options?: Options) {\n return capitalCase(input, { delimiter: \"-\", ...options });\n}\n\nfunction lowerFactory(locale: Locale): (input: string) => string {\n return locale === false\n ? (input: string) => input.toLowerCase()\n : (input: string) => input.toLocaleLowerCase(locale);\n}\n\nfunction upperFactory(locale: Locale): (input: string) => string {\n return locale === false\n ? (input: string) => input.toUpperCase()\n : (input: string) => input.toLocaleUpperCase(locale);\n}\n\nfunction capitalCaseTransformFactory(\n lower: (input: string) => string,\n upper: (input: string) => string,\n) {\n return (word: string) => `${upper(word[0])}${lower(word.slice(1))}`;\n}\n\nfunction pascalCaseTransformFactory(\n lower: (input: string) => string,\n upper: (input: string) => string,\n) {\n return (word: string, index: number) => {\n const char0 = word[0];\n const initial =\n index > 0 && char0 >= \"0\" && char0 <= \"9\" ? \"_\" + char0 : upper(char0);\n return initial + lower(word.slice(1));\n };\n}\n\nfunction splitPrefixSuffix(\n input: string,\n options: Options = {},\n): [string, string[], string] {\n const splitFn =\n options.split ?? (options.separateNumbers ? splitSeparateNumbers : split);\n const prefixCharacters =\n options.prefixCharacters ?? DEFAULT_PREFIX_SUFFIX_CHARACTERS;\n const suffixCharacters =\n options.suffixCharacters ?? DEFAULT_PREFIX_SUFFIX_CHARACTERS;\n let prefixIndex = 0;\n let suffixIndex = input.length;\n\n while (prefixIndex < input.length) {\n const char = input.charAt(prefixIndex);\n if (!prefixCharacters.includes(char)) break;\n prefixIndex++;\n }\n\n while (suffixIndex > prefixIndex) {\n const index = suffixIndex - 1;\n const char = input.charAt(index);\n if (!suffixCharacters.includes(char)) break;\n suffixIndex = index;\n }\n\n return [\n input.slice(0, prefixIndex),\n splitFn(input.slice(prefixIndex, suffixIndex)),\n input.slice(suffixIndex),\n ];\n}\n","'use strict'\n\nimport map from 'map-obj'\nimport { snakeCase } from 'change-case'\n\nconst PlainObjectConstructor = {}.constructor\n\nfunction snakecaseKeys (obj, options) {\n if (Array.isArray(obj)) {\n if (obj.some(item => item.constructor !== PlainObjectConstructor)) {\n throw new Error('obj must be array of plain objects')\n }\n\n options = { deep: true, exclude: [], parsingOptions: {}, ...options }\n const convertCase = options.snakeCase || ((key) => snakeCase(key, options.parsingOptions))\n\n // Handle arrays by mapping each element\n return obj.map(item => {\n return map(item, (key, val) => {\n return [\n matches(options.exclude, key) ? key : convertCase(key),\n val,\n mapperOptions(key, val, options)\n ]\n }, options)\n })\n } else {\n if (obj.constructor !== PlainObjectConstructor) {\n throw new Error('obj must be an plain object')\n }\n }\n\n options = { deep: true, exclude: [], parsingOptions: {}, ...options }\n\n const convertCase = options.snakeCase || ((key) => snakeCase(key, options.parsingOptions))\n\n return map(obj, (key, val) => {\n return [\n matches(options.exclude, key) ? key : convertCase(key),\n val,\n mapperOptions(key, val, options)\n ]\n }, options)\n}\n\nfunction matches (patterns, value) {\n return patterns.some(pattern => {\n return typeof pattern === 'string'\n ? pattern === value\n : pattern.test(value)\n })\n}\n\nfunction mapperOptions (key, val, options) {\n return options.shouldRecurse\n ? { shouldRecurse: options.shouldRecurse(key, val) }\n : undefined\n}\n\nexport default snakecaseKeys\n","import type { AccountlessApplicationJSON } from './JSON';\n\nexport class AccountlessApplication {\n constructor(\n readonly publishableKey: string,\n readonly secretKey: string,\n readonly claimUrl: string,\n readonly apiKeysUrl: string,\n ) {}\n\n static fromJSON(data: AccountlessApplicationJSON): AccountlessApplication {\n return new AccountlessApplication(data.publishable_key, data.secret_key, data.claim_url, data.api_keys_url);\n }\n}\n","import type { ActorTokenStatus } from './Enums';\nimport type { ActorTokenJSON } from './JSON';\n\nexport class ActorToken {\n constructor(\n readonly id: string,\n readonly status: ActorTokenStatus,\n readonly userId: string,\n readonly actor: Record | null,\n readonly token: string | null | undefined,\n readonly url: string | null | undefined,\n readonly createdAt: number,\n readonly updatedAt: number,\n ) {}\n\n static fromJSON(data: ActorTokenJSON): ActorToken {\n return new ActorToken(\n data.id,\n data.status,\n data.user_id,\n data.actor,\n data.token,\n data.url,\n data.created_at,\n data.updated_at,\n );\n }\n}\n","import type { AllowlistIdentifierType } from './Enums';\nimport type { AllowlistIdentifierJSON } from './JSON';\n\n/**\n * The Backend `AllowlistIdentifier` object represents an identifier that has been added to the allowlist of your application. The Backend `AllowlistIdentifier` object is used in the [Backend API](https://clerk.com/docs/reference/backend-api/tag/Allow-list-Block-list#operation/ListAllowlistIdentifiers) and is not directly accessible from the Frontend API.\n */\nexport class AllowlistIdentifier {\n constructor(\n /**\n * A unique ID for the allowlist identifier.\n */\n readonly id: string,\n /**\n * The [identifier](https://clerk.com/docs/authentication/configuration/sign-up-sign-in-options#identifiers) that was added to the allowlist.\n */\n readonly identifier: string,\n /**\n * The type of the allowlist identifier.\n */\n readonly identifierType: AllowlistIdentifierType,\n /**\n * The date when the allowlist identifier was first created.\n */\n readonly createdAt: number,\n /**\n * The date when the allowlist identifier was last updated.\n */\n readonly updatedAt: number,\n /**\n * The ID of the instance that this allowlist identifier belongs to.\n */\n readonly instanceId?: string,\n /**\n * The ID of the invitation sent to the identifier.\n */\n readonly invitationId?: string,\n ) {}\n\n static fromJSON(data: AllowlistIdentifierJSON): AllowlistIdentifier {\n return new AllowlistIdentifier(\n data.id,\n data.identifier,\n data.identifier_type,\n data.created_at,\n data.updated_at,\n data.instance_id,\n data.invitation_id,\n );\n }\n}\n","import type { APIKeyJSON } from './JSON';\n\nexport class APIKey {\n constructor(\n readonly id: string,\n readonly type: string,\n readonly name: string,\n readonly subject: string,\n readonly scopes: string[],\n readonly claims: Record | null,\n readonly revoked: boolean,\n readonly revocationReason: string | null,\n readonly expired: boolean,\n readonly expiration: number | null,\n readonly createdBy: string | null,\n readonly description: string | null,\n readonly lastUsedAt: number | null,\n readonly createdAt: number,\n readonly updatedAt: number,\n readonly secret?: string,\n ) {}\n\n static fromJSON(data: APIKeyJSON) {\n return new APIKey(\n data.id,\n data.type,\n data.name,\n data.subject,\n data.scopes,\n data.claims,\n data.revoked,\n data.revocation_reason,\n data.expired,\n data.expiration,\n data.created_by,\n data.description,\n data.last_used_at,\n data.created_at,\n data.updated_at,\n data.secret,\n );\n }\n}\n","import type { BlocklistIdentifierType } from './Enums';\nimport type { BlocklistIdentifierJSON } from './JSON';\n\nexport class BlocklistIdentifier {\n constructor(\n readonly id: string,\n readonly identifier: string,\n readonly identifierType: BlocklistIdentifierType,\n readonly createdAt: number,\n readonly updatedAt: number,\n readonly instanceId?: string,\n ) {}\n\n static fromJSON(data: BlocklistIdentifierJSON): BlocklistIdentifier {\n return new BlocklistIdentifier(\n data.id,\n data.identifier,\n data.identifier_type,\n data.created_at,\n data.updated_at,\n data.instance_id,\n );\n }\n}\n","import type { SessionActivityJSON, SessionJSON } from './JSON';\n\n/**\n * The Backend `SessionActivity` object models the activity of a user session, capturing details such as the device type, browser information, and geographical location.\n */\nexport class SessionActivity {\n constructor(\n /**\n * The unique identifier for the session activity record.\n */\n readonly id: string,\n /**\n * Will be set to `true` if the session activity came from a mobile device. Set to `false` otherwise.\n */\n readonly isMobile: boolean,\n /**\n * The IP address from which this session activity originated.\n */\n readonly ipAddress?: string,\n /**\n * The city from which this session activity occurred. Resolved by IP address geo-location.\n */\n readonly city?: string,\n /**\n * The country from which this session activity occurred. Resolved by IP address geo-location.\n */\n readonly country?: string,\n /**\n * The version of the browser from which this session activity occurred.\n */\n readonly browserVersion?: string,\n /**\n * The name of the browser from which this session activity occurred.\n */\n readonly browserName?: string,\n /**\n * The type of the device which was used in this session activity.\n */\n readonly deviceType?: string,\n ) {}\n\n static fromJSON(data: SessionActivityJSON): SessionActivity {\n return new SessionActivity(\n data.id,\n data.is_mobile,\n data.ip_address,\n data.city,\n data.country,\n data.browser_version,\n data.browser_name,\n data.device_type,\n );\n }\n}\n\n/**\n * The Backend `Session` object is similar to the [`Session`](https://clerk.com/docs/references/javascript/session) object as it is an abstraction over an HTTP session and models the period of information exchange between a user and the server. However, the Backend `Session` object is different as it is used in the [Backend API](https://clerk.com/docs/reference/backend-api/tag/Sessions#operation/GetSessionList) and is not directly accessible from the Frontend API.\n */\nexport class Session {\n constructor(\n /**\n * The unique identifier for the `Session`.\n */\n readonly id: string,\n /**\n * The ID of the client associated with the `Session`.\n */\n readonly clientId: string,\n /**\n * The ID of the user associated with the `Session`.\n */\n readonly userId: string,\n /**\n * The current state of the `Session`.\n */\n readonly status: string,\n /**\n * The time the session was last active on the [`Client`](https://clerk.com/docs/references/backend/types/backend-client).\n */\n readonly lastActiveAt: number,\n /**\n * The date when the `Session` will expire.\n */\n readonly expireAt: number,\n /**\n * The date when the `Session` will be abandoned.\n */\n readonly abandonAt: number,\n /**\n * The date when the `Session` was first created.\n */\n readonly createdAt: number,\n /**\n * The date when the `Session` was last updated.\n */\n readonly updatedAt: number,\n /**\n * The ID of the last active organization.\n */\n readonly lastActiveOrganizationId?: string,\n /**\n * An object that provides additional information about this session, focused around user activity data.\n */\n readonly latestActivity?: SessionActivity,\n /**\n * The JWT actor for the session. Holds identifier for the user that is impersonating the current user. Read more about [impersonation](https://clerk.com/docs/users/user-impersonation).\n */\n readonly actor: Record | null = null,\n ) {}\n\n static fromJSON(data: SessionJSON): Session {\n return new Session(\n data.id,\n data.client_id,\n data.user_id,\n data.status,\n data.last_active_at,\n data.expire_at,\n data.abandon_at,\n data.created_at,\n data.updated_at,\n data.last_active_organization_id,\n data.latest_activity && SessionActivity.fromJSON(data.latest_activity),\n data.actor,\n );\n }\n}\n","import type { LastAuthenticationStrategy } from '@clerk/types';\n\nimport type { ClientJSON } from './JSON';\nimport { Session } from './Session';\n\n/**\n * The Backend `Client` object is similar to the [`Client`](https://clerk.com/docs/references/javascript/client) object as it holds information about the authenticated sessions in the current device. However, the Backend `Client` object is different from the `Client` object in that it is used in the [Backend API](https://clerk.com/docs/reference/backend-api/tag/Clients#operation/GetClient) and is not directly accessible from the Frontend API.\n */\nexport class Client {\n constructor(\n /**\n * The unique identifier for the `Client`.\n */\n readonly id: string,\n /**\n * An array of [Session](https://clerk.com/docs/references/backend/types/backend-session){{ target: '_blank' }} IDs associated with the `Client`.\n */\n readonly sessionIds: string[],\n /**\n * An array of [Session](https://clerk.com/docs/references/backend/types/backend-session){{ target: '_blank' }} objects associated with the `Client`.\n */\n readonly sessions: Session[],\n /**\n * The ID of the [`SignIn`](https://clerk.com/docs/references/javascript/sign-in){{ target: '_blank' }}.\n */\n readonly signInId: string | null,\n /**\n * The ID of the [`SignUp`](https://clerk.com/docs/references/javascript/sign-up){{ target: '_blank' }}.\n */\n readonly signUpId: string | null,\n /**\n * The ID of the last active [Session](https://clerk.com/docs/references/backend/types/backend-session).\n */\n readonly lastActiveSessionId: string | null,\n /**\n * The last authentication strategy used by the `Client`.\n */\n readonly lastAuthenticationStrategy: LastAuthenticationStrategy | null,\n /**\n * The date when the `Client` was first created.\n */\n readonly createdAt: number,\n /**\n * The date when the `Client` was last updated.\n */\n readonly updatedAt: number,\n ) {}\n\n static fromJSON(data: ClientJSON): Client {\n return new Client(\n data.id,\n data.session_ids,\n data.sessions.map(x => Session.fromJSON(x)),\n data.sign_in_id,\n data.sign_up_id,\n data.last_active_session_id,\n data.last_authentication_strategy,\n data.created_at,\n data.updated_at,\n );\n }\n}\n","import type { CnameTargetJSON } from './JSON';\n\nexport class CnameTarget {\n constructor(\n readonly host: string,\n readonly value: string,\n readonly required: boolean,\n ) {}\n\n static fromJSON(data: CnameTargetJSON): CnameTarget {\n return new CnameTarget(data.host, data.value, data.required);\n }\n}\n","import type { CookiesJSON } from './JSON';\n\nexport class Cookies {\n constructor(readonly cookies: string[]) {}\n\n static fromJSON(data: CookiesJSON): Cookies {\n return new Cookies(data.cookies);\n }\n}\n","import type { DeletedObjectJSON } from './JSON';\n\nexport class DeletedObject {\n constructor(\n readonly object: string,\n readonly id: string | null,\n readonly slug: string | null,\n readonly deleted: boolean,\n ) {}\n\n static fromJSON(data: DeletedObjectJSON) {\n return new DeletedObject(data.object, data.id || null, data.slug || null, data.deleted);\n }\n}\n","import { CnameTarget } from './CnameTarget';\nimport type { DomainJSON } from './JSON';\n\nexport class Domain {\n constructor(\n readonly id: string,\n readonly name: string,\n readonly isSatellite: boolean,\n readonly frontendApiUrl: string,\n readonly developmentOrigin: string,\n readonly cnameTargets: CnameTarget[],\n readonly accountsPortalUrl?: string | null,\n readonly proxyUrl?: string | null,\n ) {}\n\n static fromJSON(data: DomainJSON): Domain {\n return new Domain(\n data.id,\n data.name,\n data.is_satellite,\n data.frontend_api_url,\n data.development_origin,\n data.cname_targets && data.cname_targets.map(x => CnameTarget.fromJSON(x)),\n data.accounts_portal_url,\n data.proxy_url,\n );\n }\n}\n","import type { EmailJSON } from './JSON';\n\nexport class Email {\n constructor(\n readonly id: string,\n readonly fromEmailName: string,\n readonly emailAddressId: string | null,\n readonly toEmailAddress?: string,\n readonly subject?: string,\n readonly body?: string,\n readonly bodyPlain?: string | null,\n readonly status?: string,\n readonly slug?: string | null,\n readonly data?: Record | null,\n readonly deliveredByClerk?: boolean,\n ) {}\n\n static fromJSON(data: EmailJSON): Email {\n return new Email(\n data.id,\n data.from_email_name,\n data.email_address_id,\n data.to_email_address,\n data.subject,\n data.body,\n data.body_plain,\n data.status,\n data.slug,\n data.data,\n data.delivered_by_clerk,\n );\n }\n}\n","import type { IdentificationLinkJSON } from './JSON';\n\n/**\n * Contains information about any identifications that might be linked to the email address.\n */\nexport class IdentificationLink {\n constructor(\n /**\n * The unique identifier for the identification link.\n */\n readonly id: string,\n /**\n * The type of the identification link, e.g., `\"email_address\"`, `\"phone_number\"`, etc.\n */\n readonly type: string,\n ) {}\n\n static fromJSON(data: IdentificationLinkJSON): IdentificationLink {\n return new IdentificationLink(data.id, data.type);\n }\n}\n","import type { VerificationStatus } from '@clerk/types';\n\nimport type { OrganizationDomainVerificationJSON, VerificationJSON } from './JSON';\n\n/**\n * The Backend `Verification` object describes the state of the verification process of a sign-in or sign-up attempt.\n */\nexport class Verification {\n constructor(\n /**\n * The state of the verification.\n *\n *
    \n *
  • `unverified`: The verification has not been verified yet.
  • \n *
  • `verified`: The verification has been verified.
  • \n *
  • `transferable`: The verification is transferable to between sign-in and sign-up flows.
  • \n *
  • `failed`: The verification has failed.
  • \n *
  • `expired`: The verification has expired.
  • \n *
\n */\n readonly status: VerificationStatus,\n /**\n * The strategy pertaining to the parent sign-up or sign-in attempt.\n */\n readonly strategy: string,\n /**\n * The redirect URL for an external verification.\n */\n readonly externalVerificationRedirectURL: URL | null = null,\n /**\n * The number of attempts related to the verification.\n */\n readonly attempts: number | null = null,\n /**\n * The time the verification will expire at.\n */\n readonly expireAt: number | null = null,\n /**\n * The [nonce](https://en.wikipedia.org/wiki/Cryptographic_nonce) pertaining to the verification.\n */\n readonly nonce: string | null = null,\n /**\n * The message that will be presented to the user's Web3 wallet for signing during authentication. This follows the [Sign-In with Ethereum (SIWE) protocol format](https://docs.login.xyz/general-information/siwe-overview/eip-4361#example-message-to-be-signed), which typically includes details like the requesting service, wallet address, terms acceptance, nonce, timestamp, and any additional resources.\n */\n readonly message: string | null = null,\n ) {}\n\n static fromJSON(data: VerificationJSON): Verification {\n return new Verification(\n data.status,\n data.strategy,\n data.external_verification_redirect_url ? new URL(data.external_verification_redirect_url) : null,\n data.attempts,\n data.expire_at,\n data.nonce,\n );\n }\n}\n\nexport class OrganizationDomainVerification {\n constructor(\n readonly status: string,\n readonly strategy: string,\n readonly attempts: number | null = null,\n readonly expireAt: number | null = null,\n ) {}\n\n static fromJSON(data: OrganizationDomainVerificationJSON): OrganizationDomainVerification {\n return new OrganizationDomainVerification(data.status, data.strategy, data.attempts, data.expires_at);\n }\n}\n","import { IdentificationLink } from './IdentificationLink';\nimport type { EmailAddressJSON } from './JSON';\nimport { Verification } from './Verification';\n\n/**\n * The Backend `EmailAddress` object is a model around an email address. Email addresses are one of the [identifiers](https://clerk.com/docs/authentication/configuration/sign-up-sign-in-options#identifiers) used to provide identification for users.\n *\n * Email addresses must be **verified** to ensure that they are assigned to their rightful owners. The `EmailAddress` object holds all necessary state around the verification process.\n *\n * For implementation examples for adding and verifying email addresses, see the [email link custom flow](https://clerk.com/docs/custom-flows/email-links) and [email code custom flow](https://clerk.com/docs/custom-flows/add-email) guides.\n */\nexport class EmailAddress {\n constructor(\n /**\n * The unique identifier for the email address.\n */\n readonly id: string,\n /**\n * The value of the email address.\n */\n readonly emailAddress: string,\n /**\n * An object holding information on the verification of the email address.\n */\n readonly verification: Verification | null,\n /**\n * An array of objects containing information about any identifications that might be linked to the email address.\n */\n readonly linkedTo: IdentificationLink[],\n ) {}\n\n static fromJSON(data: EmailAddressJSON): EmailAddress {\n return new EmailAddress(\n data.id,\n data.email_address,\n data.verification && Verification.fromJSON(data.verification),\n data.linked_to.map(link => IdentificationLink.fromJSON(link)),\n );\n }\n}\n","import type { ExternalAccountJSON } from './JSON';\nimport { Verification } from './Verification';\n\n/**\n * The Backend `ExternalAccount` object is a model around an identification obtained by an external provider (e.g. a social provider such as Google).\n *\n * External account must be verified, so that you can make sure they can be assigned to their rightful owners. The `ExternalAccount` object holds all necessary state around the verification process.\n */\nexport class ExternalAccount {\n constructor(\n /**\n * The unique identifier for this external account.\n */\n readonly id: string,\n /**\n * The provider name (e.g., `google`).\n */\n readonly provider: string,\n /**\n * The identification with which this external account is associated.\n */\n readonly identificationId: string,\n /**\n * The unique ID of the user in the provider.\n */\n readonly externalId: string,\n /**\n * The scopes that the user has granted access to.\n */\n readonly approvedScopes: string,\n /**\n * The user's email address.\n */\n readonly emailAddress: string,\n /**\n * The user's first name.\n */\n readonly firstName: string,\n /**\n * The user's last name.\n */\n readonly lastName: string,\n /**\n * The user's image URL.\n */\n readonly imageUrl: string,\n /**\n * The user's username.\n */\n readonly username: string | null,\n /**\n * The phone number related to this specific external account.\n */\n readonly phoneNumber: string | null,\n /**\n * Metadata that can be read from the Frontend API and Backend API and can be set only from the Backend API.\n */\n readonly publicMetadata: Record | null = {},\n /**\n * A descriptive label to differentiate multiple external accounts of the same user for the same provider.\n */\n readonly label: string | null,\n /**\n * An object holding information on the verification of this external account.\n */\n readonly verification: Verification | null,\n ) {}\n\n static fromJSON(data: ExternalAccountJSON): ExternalAccount {\n return new ExternalAccount(\n data.id,\n data.provider,\n data.identification_id,\n data.provider_user_id,\n data.approved_scopes,\n data.email_address,\n data.first_name,\n data.last_name,\n data.image_url || '',\n data.username,\n data.phone_number,\n data.public_metadata,\n data.label,\n data.verification && Verification.fromJSON(data.verification),\n );\n }\n}\n","import type { IdPOAuthAccessTokenJSON } from './JSON';\n\nexport class IdPOAuthAccessToken {\n constructor(\n readonly id: string,\n readonly clientId: string,\n readonly type: string,\n readonly subject: string,\n readonly scopes: string[],\n readonly revoked: boolean,\n readonly revocationReason: string | null,\n readonly expired: boolean,\n readonly expiration: number | null,\n readonly createdAt: number,\n readonly updatedAt: number,\n ) {}\n\n static fromJSON(data: IdPOAuthAccessTokenJSON) {\n return new IdPOAuthAccessToken(\n data.id,\n data.client_id,\n data.type,\n data.subject,\n data.scopes,\n data.revoked,\n data.revocation_reason,\n data.expired,\n data.expiration,\n data.created_at,\n data.updated_at,\n );\n }\n}\n","import type { InstanceJSON } from './JSON';\n\nexport class Instance {\n constructor(\n readonly id: string,\n readonly environmentType: string,\n readonly allowedOrigins: Array | null,\n ) {}\n\n static fromJSON(data: InstanceJSON): Instance {\n return new Instance(data.id, data.environment_type, data.allowed_origins);\n }\n}\n","import type { InstanceRestrictionsJSON } from './JSON';\n\nexport class InstanceRestrictions {\n constructor(\n readonly allowlist: boolean,\n readonly blocklist: boolean,\n readonly blockEmailSubaddresses: boolean,\n readonly blockDisposableEmailDomains: boolean,\n readonly ignoreDotsForGmailAddresses: boolean,\n ) {}\n\n static fromJSON(data: InstanceRestrictionsJSON): InstanceRestrictions {\n return new InstanceRestrictions(\n data.allowlist,\n data.blocklist,\n data.block_email_subaddresses,\n data.block_disposable_email_domains,\n data.ignore_dots_for_gmail_addresses,\n );\n }\n}\n","import type { InstanceSettingsJSON } from './JSON';\n\nexport class InstanceSettings {\n constructor(\n readonly id?: string | undefined,\n readonly restrictedToAllowlist?: boolean | undefined,\n readonly fromEmailAddress?: string | undefined,\n readonly progressiveSignUp?: boolean | undefined,\n readonly enhancedEmailDeliverability?: boolean | undefined,\n ) {}\n\n static fromJSON(data: InstanceSettingsJSON): InstanceSettings {\n return new InstanceSettings(\n data.id,\n data.restricted_to_allowlist,\n data.from_email_address,\n data.progressive_sign_up,\n data.enhanced_email_deliverability,\n );\n }\n}\n","import type { InvitationStatus } from './Enums';\nimport type { InvitationJSON } from './JSON';\n\n/**\n * The Backend `Invitation` object represents an invitation to join your application.\n */\nexport class Invitation {\n private _raw: InvitationJSON | null = null;\n\n public get raw(): InvitationJSON | null {\n return this._raw;\n }\n\n constructor(\n /**\n * The unique identifier for the `Invitation`.\n */\n readonly id: string,\n /**\n * The email address that the invitation was sent to.\n */\n readonly emailAddress: string,\n /**\n * [Metadata](https://clerk.com/docs/references/javascript/types/metadata#user-public-metadata){{ target: '_blank' }} that can be read from the Frontend API and [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }} and can be set only from the Backend API. Once the user accepts the invitation and signs up, these metadata will end up in the user's public metadata.\n */\n readonly publicMetadata: Record | null,\n /**\n * The date when the `Invitation` was first created.\n */\n readonly createdAt: number,\n /**\n * The date when the `Invitation` was last updated.\n */\n readonly updatedAt: number,\n /**\n * The status of the `Invitation`.\n */\n readonly status: InvitationStatus,\n /**\n * The URL that the user can use to accept the invitation.\n */\n readonly url?: string,\n /**\n * Whether the `Invitation` has been revoked.\n */\n readonly revoked?: boolean,\n ) {}\n\n static fromJSON(data: InvitationJSON): Invitation {\n const res = new Invitation(\n data.id,\n data.email_address,\n data.public_metadata,\n data.created_at,\n data.updated_at,\n data.status,\n data.url,\n data.revoked,\n );\n res._raw = data;\n return res;\n }\n}\n","import type { LastAuthenticationStrategy, SignUpStatus, VerificationStatus } from '@clerk/types';\n\nimport type {\n ActorTokenStatus,\n AllowlistIdentifierType,\n BlocklistIdentifierType,\n DomainsEnrollmentModes,\n InvitationStatus,\n OrganizationDomainVerificationStatus,\n OrganizationDomainVerificationStrategy,\n OrganizationEnrollmentMode,\n OrganizationInvitationStatus,\n OrganizationMembershipRole,\n SignInStatus,\n SignUpVerificationNextAction,\n WaitlistEntryStatus,\n} from './Enums';\n\nexport const ObjectType = {\n AccountlessApplication: 'accountless_application',\n ActorToken: 'actor_token',\n AllowlistIdentifier: 'allowlist_identifier',\n ApiKey: 'api_key',\n BlocklistIdentifier: 'blocklist_identifier',\n Client: 'client',\n Cookies: 'cookies',\n Domain: 'domain',\n Email: 'email',\n EmailAddress: 'email_address',\n ExternalAccount: 'external_account',\n FacebookAccount: 'facebook_account',\n GoogleAccount: 'google_account',\n Instance: 'instance',\n InstanceRestrictions: 'instance_restrictions',\n InstanceSettings: 'instance_settings',\n Invitation: 'invitation',\n Machine: 'machine',\n MachineScope: 'machine_scope',\n MachineSecretKey: 'machine_secret_key',\n M2MToken: 'machine_to_machine_token',\n JwtTemplate: 'jwt_template',\n OauthAccessToken: 'oauth_access_token',\n IdpOAuthAccessToken: 'clerk_idp_oauth_access_token',\n OAuthApplication: 'oauth_application',\n Organization: 'organization',\n OrganizationDomain: 'organization_domain',\n OrganizationInvitation: 'organization_invitation',\n OrganizationMembership: 'organization_membership',\n OrganizationSettings: 'organization_settings',\n PhoneNumber: 'phone_number',\n ProxyCheck: 'proxy_check',\n RedirectUrl: 'redirect_url',\n SamlAccount: 'saml_account',\n SamlConnection: 'saml_connection',\n Session: 'session',\n SignInAttempt: 'sign_in_attempt',\n SignInToken: 'sign_in_token',\n SignUpAttempt: 'sign_up_attempt',\n SmsMessage: 'sms_message',\n User: 'user',\n WaitlistEntry: 'waitlist_entry',\n Web3Wallet: 'web3_wallet',\n Token: 'token',\n TotalCount: 'total_count',\n TestingToken: 'testing_token',\n Role: 'role',\n Permission: 'permission',\n BillingPayer: 'commerce_payer',\n BillingPaymentAttempt: 'commerce_payment_attempt',\n BillingSubscription: 'commerce_subscription',\n BillingSubscriptionItem: 'commerce_subscription_item',\n BillingPlan: 'commerce_plan',\n Feature: 'feature',\n} as const;\n\nexport type ObjectType = (typeof ObjectType)[keyof typeof ObjectType];\n\nexport interface ClerkResourceJSON {\n /**\n * The type of the resource.\n */\n object: ObjectType;\n /**\n * The unique identifier for the resource.\n */\n id: string;\n}\n\nexport interface CookiesJSON {\n object: typeof ObjectType.Cookies;\n cookies: string[];\n}\n\nexport interface TokenJSON {\n object: typeof ObjectType.Token;\n jwt: string;\n}\n\nexport interface AccountlessApplicationJSON extends ClerkResourceJSON {\n object: typeof ObjectType.AccountlessApplication;\n publishable_key: string;\n secret_key: string;\n claim_url: string;\n api_keys_url: string;\n}\n\nexport interface ActorTokenJSON extends ClerkResourceJSON {\n object: typeof ObjectType.ActorToken;\n id: string;\n status: ActorTokenStatus;\n user_id: string;\n actor: Record | null;\n token?: string | null;\n url?: string | null;\n created_at: number;\n updated_at: number;\n}\n\nexport interface AllowlistIdentifierJSON extends ClerkResourceJSON {\n object: typeof ObjectType.AllowlistIdentifier;\n identifier: string;\n identifier_type: AllowlistIdentifierType;\n instance_id?: string;\n invitation_id?: string;\n created_at: number;\n updated_at: number;\n}\n\nexport interface BlocklistIdentifierJSON extends ClerkResourceJSON {\n object: typeof ObjectType.BlocklistIdentifier;\n identifier: string;\n identifier_type: BlocklistIdentifierType;\n instance_id?: string;\n created_at: number;\n updated_at: number;\n}\n\nexport interface ClientJSON extends ClerkResourceJSON {\n object: typeof ObjectType.Client;\n session_ids: string[];\n sessions: SessionJSON[];\n sign_in_id: string | null;\n sign_up_id: string | null;\n last_active_session_id: string | null;\n last_authentication_strategy: LastAuthenticationStrategy | null;\n created_at: number;\n updated_at: number;\n}\n\nexport interface CnameTargetJSON {\n host: string;\n value: string;\n /**\n * Denotes whether this CNAME target is required to be set in order for the domain to be considered deployed.\n */\n required: boolean;\n}\n\nexport interface DomainJSON extends ClerkResourceJSON {\n object: typeof ObjectType.Domain;\n id: string;\n name: string;\n is_satellite: boolean;\n frontend_api_url: string;\n /**\n * null for satellite domains\n */\n accounts_portal_url?: string | null;\n proxy_url?: string;\n development_origin: string;\n cname_targets: CnameTargetJSON[];\n}\n\nexport interface EmailJSON extends ClerkResourceJSON {\n object: typeof ObjectType.Email;\n slug?: string | null;\n from_email_name: string;\n to_email_address?: string;\n email_address_id: string | null;\n user_id?: string | null;\n subject?: string;\n body?: string;\n body_plain?: string | null;\n status?: string;\n data?: Record | null;\n delivered_by_clerk: boolean;\n}\n\nexport interface EmailAddressJSON extends ClerkResourceJSON {\n object: typeof ObjectType.EmailAddress;\n email_address: string;\n verification: VerificationJSON | null;\n linked_to: IdentificationLinkJSON[];\n}\n\nexport interface ExternalAccountJSON extends ClerkResourceJSON {\n object: typeof ObjectType.ExternalAccount;\n provider: string;\n identification_id: string;\n provider_user_id: string;\n approved_scopes: string;\n email_address: string;\n first_name: string;\n last_name: string;\n image_url?: string;\n username: string | null;\n phone_number: string | null;\n public_metadata?: Record | null;\n label: string | null;\n verification: VerificationJSON | null;\n}\n\nexport interface JwksJSON {\n keys?: JwksKeyJSON[];\n}\n\nexport interface JwksKeyJSON {\n use: string;\n kty: string;\n kid: string;\n alg: string;\n n: string;\n e: string;\n}\n\nexport interface JwtTemplateJSON extends ClerkResourceJSON {\n object: typeof ObjectType.JwtTemplate;\n id: string;\n name: string;\n claims: object;\n lifetime: number;\n allowed_clock_skew: number;\n custom_signing_key: boolean;\n signing_algorithm: string;\n created_at: number;\n updated_at: number;\n}\n\nexport interface SamlAccountJSON extends ClerkResourceJSON {\n object: typeof ObjectType.SamlAccount;\n provider: string;\n provider_user_id: string | null;\n active: boolean;\n email_address: string;\n first_name: string;\n last_name: string;\n verification: VerificationJSON | null;\n saml_connection: SamlAccountConnectionJSON | null;\n}\n\nexport interface IdentificationLinkJSON extends ClerkResourceJSON {\n type: string;\n}\n\nexport interface OrganizationSettingsJSON extends ClerkResourceJSON {\n object: typeof ObjectType.OrganizationSettings;\n enabled: boolean;\n max_allowed_memberships: number;\n max_allowed_roles: number;\n max_allowed_permissions: number;\n creator_role: string;\n admin_delete_enabled: boolean;\n domains_enabled: boolean;\n domains_enrollment_modes: Array;\n domains_default_role: string;\n}\n\nexport interface InstanceJSON extends ClerkResourceJSON {\n object: typeof ObjectType.Instance;\n id: string;\n environment_type: string;\n allowed_origins: Array | null;\n}\n\nexport interface InstanceRestrictionsJSON extends ClerkResourceJSON {\n object: typeof ObjectType.InstanceRestrictions;\n allowlist: boolean;\n blocklist: boolean;\n block_email_subaddresses: boolean;\n block_disposable_email_domains: boolean;\n ignore_dots_for_gmail_addresses: boolean;\n}\n\nexport interface InstanceSettingsJSON extends ClerkResourceJSON {\n object: typeof ObjectType.InstanceSettings;\n id: string;\n restricted_to_allowlist: boolean;\n from_email_address: string;\n progressive_sign_up: boolean;\n enhanced_email_deliverability: boolean;\n}\n\nexport interface InvitationJSON extends ClerkResourceJSON {\n object: typeof ObjectType.Invitation;\n email_address: string;\n public_metadata: Record | null;\n revoked?: boolean;\n status: InvitationStatus;\n url?: string;\n created_at: number;\n updated_at: number;\n}\n\nexport interface OauthAccessTokenJSON {\n external_account_id: string;\n object: typeof ObjectType.OauthAccessToken;\n token: string;\n provider: string;\n public_metadata: Record;\n label: string | null;\n // Only set in OAuth 2.0 tokens\n scopes?: string[];\n // Only set in OAuth 1.0 tokens\n token_secret?: string;\n expires_at?: number;\n}\n\nexport interface OAuthApplicationJSON extends ClerkResourceJSON {\n object: typeof ObjectType.OAuthApplication;\n id: string;\n instance_id: string;\n name: string;\n client_id: string;\n client_uri: string | null;\n client_image_url: string | null;\n dynamically_registered: boolean;\n consent_screen_enabled: boolean;\n pkce_required: boolean;\n public: boolean;\n scopes: string;\n redirect_uris: Array;\n authorize_url: string;\n token_fetch_url: string;\n user_info_url: string;\n discovery_url: string;\n token_introspection_url: string;\n created_at: number;\n updated_at: number;\n client_secret?: string;\n}\n\nexport interface OrganizationJSON extends ClerkResourceJSON {\n object: typeof ObjectType.Organization;\n name: string;\n slug: string;\n image_url?: string;\n has_image: boolean;\n members_count?: number;\n pending_invitations_count?: number;\n max_allowed_memberships: number;\n admin_delete_enabled: boolean;\n public_metadata: OrganizationPublicMetadata | null;\n private_metadata?: OrganizationPrivateMetadata;\n created_by?: string;\n created_at: number;\n updated_at: number;\n}\n\nexport interface OrganizationDomainJSON extends ClerkResourceJSON {\n object: typeof ObjectType.OrganizationDomain;\n id: string;\n name: string;\n organization_id: string;\n enrollment_mode: OrganizationEnrollmentMode;\n verification: OrganizationDomainVerificationJSON | null;\n affiliation_email_address: string | null;\n created_at: number;\n updated_at: number;\n total_pending_invitations: number;\n total_pending_suggestions: number;\n}\n\nexport interface OrganizationDomainVerificationJSON {\n status: OrganizationDomainVerificationStatus;\n strategy: OrganizationDomainVerificationStrategy;\n attempts: number;\n expires_at: number;\n}\n\nexport interface OrganizationInvitationJSON extends ClerkResourceJSON {\n email_address: string;\n role: OrganizationMembershipRole;\n role_name: string;\n organization_id: string;\n public_organization_data?: PublicOrganizationDataJSON | null;\n status?: OrganizationInvitationStatus;\n public_metadata: OrganizationInvitationPublicMetadata;\n private_metadata: OrganizationInvitationPrivateMetadata;\n url: string | null;\n created_at: number;\n updated_at: number;\n expires_at: number;\n}\n\n/**\n * @interface\n */\nexport interface PublicOrganizationDataJSON extends ClerkResourceJSON {\n /**\n * The name of the organization.\n */\n name: string;\n /**\n * The slug of the organization.\n */\n slug: string;\n /**\n * Holds the default organization profile image. Compatible with Clerk's [Image Optimization](https://clerk.com/docs/guides/image-optimization).\n */\n image_url?: string;\n /**\n * Whether the organization has a profile image.\n */\n has_image: boolean;\n}\n\nexport interface OrganizationMembershipJSON extends ClerkResourceJSON {\n object: typeof ObjectType.OrganizationMembership;\n public_metadata: OrganizationMembershipPublicMetadata;\n private_metadata?: OrganizationMembershipPrivateMetadata;\n role: OrganizationMembershipRole;\n permissions: string[];\n created_at: number;\n updated_at: number;\n organization: OrganizationJSON;\n public_user_data: OrganizationMembershipPublicUserDataJSON;\n}\n\nexport interface OrganizationMembershipPublicUserDataJSON {\n identifier: string;\n first_name: string | null;\n last_name: string | null;\n image_url: string;\n has_image: boolean;\n user_id: string;\n}\n\nexport interface PhoneNumberJSON extends ClerkResourceJSON {\n object: typeof ObjectType.PhoneNumber;\n phone_number: string;\n reserved_for_second_factor: boolean;\n default_second_factor: boolean;\n reserved: boolean;\n verification: VerificationJSON | null;\n linked_to: IdentificationLinkJSON[];\n backup_codes: string[];\n}\n\nexport type ProxyCheckJSON = {\n object: typeof ObjectType.ProxyCheck;\n id: string;\n domain_id: string;\n last_run_at: number | null;\n proxy_url: string;\n successful: boolean;\n created_at: number;\n updated_at: number;\n};\n\nexport interface RedirectUrlJSON extends ClerkResourceJSON {\n object: typeof ObjectType.RedirectUrl;\n url: string;\n created_at: number;\n updated_at: number;\n}\n\nexport interface SessionActivityJSON extends ClerkResourceJSON {\n id: string;\n device_type?: string;\n is_mobile: boolean;\n browser_name?: string;\n browser_version?: string;\n ip_address?: string;\n city?: string;\n country?: string;\n}\n\nexport interface SessionJSON extends ClerkResourceJSON {\n object: typeof ObjectType.Session;\n client_id: string;\n user_id: string;\n status: string;\n last_active_organization_id?: string;\n actor: Record | null;\n latest_activity?: SessionActivityJSON;\n last_active_at: number;\n expire_at: number;\n abandon_at: number;\n created_at: number;\n updated_at: number;\n}\n\nexport interface SignInJSON extends ClerkResourceJSON {\n object: typeof ObjectType.SignInToken;\n status: SignInStatus;\n identifier: string;\n created_session_id: string | null;\n}\n\nexport interface SignInTokenJSON extends ClerkResourceJSON {\n object: typeof ObjectType.SignInToken;\n user_id: string;\n token: string;\n status: 'pending' | 'accepted' | 'revoked';\n url: string;\n created_at: number;\n updated_at: number;\n}\n\nexport interface SignUpJSON extends ClerkResourceJSON {\n object: typeof ObjectType.SignUpAttempt;\n id: string;\n status: SignUpStatus;\n required_fields: string[];\n optional_fields: string[];\n missing_fields: string[];\n unverified_fields: string[];\n verifications: SignUpVerificationsJSON;\n username: string | null;\n email_address: string | null;\n phone_number: string | null;\n web3_wallet: string | null;\n password_enabled: boolean;\n first_name: string | null;\n last_name: string | null;\n public_metadata?: Record | null;\n unsafe_metadata?: Record | null;\n custom_action: boolean;\n external_id: string | null;\n created_session_id: string | null;\n created_user_id: string | null;\n abandon_at: number | null;\n legal_accepted_at: number | null;\n\n /**\n * @deprecated Please use `verifications.external_account` instead\n */\n external_account: object | null;\n}\n\nexport interface SignUpVerificationsJSON {\n email_address: SignUpVerificationJSON;\n phone_number: SignUpVerificationJSON;\n web3_wallet: SignUpVerificationJSON;\n external_account: VerificationJSON;\n}\n\nexport interface SignUpVerificationJSON {\n next_action: SignUpVerificationNextAction;\n supported_strategies: string[];\n}\n\nexport interface SMSMessageJSON extends ClerkResourceJSON {\n object: typeof ObjectType.SmsMessage;\n from_phone_number: string;\n to_phone_number: string;\n phone_number_id: string | null;\n user_id?: string;\n message: string;\n status: string;\n slug?: string | null;\n data?: Record | null;\n delivered_by_clerk: boolean;\n}\n\nexport interface UserJSON extends ClerkResourceJSON {\n object: typeof ObjectType.User;\n username: string | null;\n first_name: string | null;\n last_name: string | null;\n image_url: string;\n has_image: boolean;\n primary_email_address_id: string | null;\n primary_phone_number_id: string | null;\n primary_web3_wallet_id: string | null;\n password_enabled: boolean;\n two_factor_enabled: boolean;\n totp_enabled: boolean;\n backup_code_enabled: boolean;\n email_addresses: EmailAddressJSON[];\n phone_numbers: PhoneNumberJSON[];\n web3_wallets: Web3WalletJSON[];\n organization_memberships: OrganizationMembershipJSON[] | null;\n external_accounts: ExternalAccountJSON[];\n saml_accounts: SamlAccountJSON[];\n password_last_updated_at: number | null;\n public_metadata: UserPublicMetadata;\n private_metadata: UserPrivateMetadata;\n unsafe_metadata: UserUnsafeMetadata;\n external_id: string | null;\n last_sign_in_at: number | null;\n banned: boolean;\n locked: boolean;\n lockout_expires_in_seconds: number | null;\n verification_attempts_remaining: number | null;\n created_at: number;\n updated_at: number;\n last_active_at: number | null;\n create_organization_enabled: boolean;\n create_organizations_limit: number | null;\n delete_self_enabled: boolean;\n legal_accepted_at: number | null;\n}\n\nexport interface VerificationJSON extends ClerkResourceJSON {\n status: VerificationStatus;\n strategy: string;\n attempts: number | null;\n expire_at: number | null;\n verified_at_client?: string;\n external_verification_redirect_url?: string | null;\n nonce?: string | null;\n message?: string | null;\n}\n\nexport interface WaitlistEntryJSON extends ClerkResourceJSON {\n object: typeof ObjectType.WaitlistEntry;\n id: string;\n status: WaitlistEntryStatus;\n email_address: string;\n invitation: InvitationJSON | null;\n is_locked: boolean;\n created_at: number;\n updated_at: number;\n}\n\nexport interface Web3WalletJSON extends ClerkResourceJSON {\n object: typeof ObjectType.Web3Wallet;\n web3_wallet: string;\n verification: VerificationJSON | null;\n}\n\nexport interface DeletedObjectJSON {\n object: string;\n id?: string;\n slug?: string;\n deleted: boolean;\n}\n\nexport interface PaginatedResponseJSON {\n data: object[];\n total_count?: number;\n}\n\nexport interface SamlConnectionJSON extends ClerkResourceJSON {\n object: typeof ObjectType.SamlConnection;\n name: string;\n domain: string;\n organization_id: string | null;\n idp_entity_id: string;\n idp_sso_url: string;\n idp_certificate: string;\n idp_metadata_url: string;\n idp_metadata: string;\n acs_url: string;\n sp_entity_id: string;\n sp_metadata_url: string;\n active: boolean;\n provider: string;\n user_count: number;\n sync_user_attributes: boolean;\n allow_subdomains: boolean;\n allow_idp_initiated: boolean;\n created_at: number;\n updated_at: number;\n attribute_mapping: AttributeMappingJSON;\n}\n\nexport interface AttributeMappingJSON {\n user_id: string;\n email_address: string;\n first_name: string;\n last_name: string;\n}\n\nexport interface TestingTokenJSON {\n object: typeof ObjectType.TestingToken;\n token: string;\n expires_at: number;\n}\n\nexport interface RoleJSON extends ClerkResourceJSON {\n object: typeof ObjectType.Role;\n key: string;\n name: string;\n description: string;\n permissions: PermissionJSON[];\n is_creator_eligible: boolean;\n created_at: number;\n updated_at: number;\n}\n\nexport interface PermissionJSON extends ClerkResourceJSON {\n object: typeof ObjectType.Permission;\n key: string;\n name: string;\n description: string;\n created_at: number;\n updated_at: number;\n}\n\nexport interface SamlAccountConnectionJSON extends ClerkResourceJSON {\n id: string;\n name: string;\n domain: string;\n active: boolean;\n provider: string;\n sync_user_attributes: boolean;\n allow_subdomains: boolean;\n allow_idp_initiated: boolean;\n disable_additional_identifications: boolean;\n created_at: number;\n updated_at: number;\n}\n\nexport interface MachineJSON extends ClerkResourceJSON {\n object: typeof ObjectType.Machine;\n id: string;\n name: string;\n instance_id: string;\n created_at: number;\n updated_at: number;\n default_token_ttl: number;\n scoped_machines: MachineJSON[];\n secret_key?: string;\n}\n\nexport interface MachineScopeJSON {\n object: typeof ObjectType.MachineScope;\n from_machine_id: string;\n to_machine_id: string;\n created_at?: number;\n deleted?: boolean;\n}\n\nexport interface MachineSecretKeyJSON {\n object: typeof ObjectType.MachineSecretKey;\n secret: string;\n}\n\nexport interface M2MTokenJSON extends ClerkResourceJSON {\n object: typeof ObjectType.M2MToken;\n token?: string;\n subject: string;\n scopes: string[];\n claims: Record | null;\n revoked: boolean;\n revocation_reason: string | null;\n expired: boolean;\n expiration: number | null;\n created_at: number;\n updated_at: number;\n}\n\nexport interface APIKeyJSON extends ClerkResourceJSON {\n object: typeof ObjectType.ApiKey;\n type: string;\n name: string;\n secret?: string;\n subject: string;\n scopes: string[];\n claims: Record | null;\n revoked: boolean;\n revocation_reason: string | null;\n expired: boolean;\n expiration: number | null;\n created_by: string | null;\n description: string | null;\n last_used_at: number | null;\n created_at: number;\n updated_at: number;\n}\n\nexport interface IdPOAuthAccessTokenJSON extends ClerkResourceJSON {\n object: typeof ObjectType.IdpOAuthAccessToken;\n client_id: string;\n type: string;\n subject: string;\n scopes: string[];\n revoked: boolean;\n revocation_reason: string | null;\n expired: boolean;\n expiration: number | null;\n created_at: number;\n updated_at: number;\n}\n\nexport interface BillingPayerJSON extends ClerkResourceJSON {\n object: typeof ObjectType.BillingPayer;\n instance_id: string;\n user_id?: string;\n first_name?: string;\n last_name?: string;\n email: string;\n organization_id?: string;\n organization_name?: string;\n image_url: string;\n created_at: number;\n updated_at: number;\n}\n\ninterface BillingPayeeJSON {\n id: string;\n gateway_type: string;\n gateway_external_id: string;\n gateway_status: 'active' | 'pending' | 'restricted' | 'disconnected';\n}\n\ninterface BillingMoneyAmountJSON {\n amount: number;\n amount_formatted: string;\n currency: string;\n currency_symbol: string;\n}\n\ninterface BillingTotalsJSON {\n subtotal: BillingMoneyAmountJSON;\n tax_total: BillingMoneyAmountJSON;\n grand_total: BillingMoneyAmountJSON;\n}\n\nexport interface FeatureJSON extends ClerkResourceJSON {\n object: typeof ObjectType.Feature;\n name: string;\n description: string;\n slug: string;\n avatar_url: string;\n}\n\n/**\n * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes.\n */\nexport interface BillingPlanJSON extends ClerkResourceJSON {\n object: typeof ObjectType.BillingPlan;\n id: string;\n product_id: string;\n name: string;\n slug: string;\n description?: string;\n is_default: boolean;\n is_recurring: boolean;\n has_base_fee: boolean;\n publicly_visible: boolean;\n fee: BillingMoneyAmountJSON;\n annual_fee: BillingMoneyAmountJSON;\n annual_monthly_fee: BillingMoneyAmountJSON;\n for_payer_type: 'org' | 'user';\n features: FeatureJSON[];\n}\n\ntype BillingSubscriptionItemStatus =\n | 'abandoned'\n | 'active'\n | 'canceled'\n | 'ended'\n | 'expired'\n | 'incomplete'\n | 'past_due'\n | 'upcoming';\n\n/**\n * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes.\n */\nexport interface BillingSubscriptionItemJSON extends ClerkResourceJSON {\n object: typeof ObjectType.BillingSubscriptionItem;\n status: BillingSubscriptionItemStatus;\n plan_period: 'month' | 'annual';\n payer_id: string;\n period_start: number;\n period_end: number | null;\n is_free_trial?: boolean;\n ended_at: number | null;\n created_at: number;\n updated_at: number;\n canceled_at: number | null;\n past_due_at: number | null;\n lifetime_paid: BillingMoneyAmountJSON;\n next_payment: {\n amount: number;\n date: number;\n } | null;\n amount: BillingMoneyAmountJSON | null;\n plan: BillingPlanJSON;\n plan_id: string;\n}\n\n/**\n * Webhooks specific interface for BillingSubscriptionItem.\n */\nexport interface BillingSubscriptionItemWebhookEventJSON extends ClerkResourceJSON {\n object: typeof ObjectType.BillingSubscriptionItem;\n status: BillingSubscriptionItemStatus;\n credit: {\n amount: BillingMoneyAmountJSON;\n cycle_days_remaining: number;\n cycle_days_total: number;\n cycle_remaining_percent: number;\n };\n proration_date: string;\n plan_period: 'month' | 'annual';\n period_start: number;\n period_end?: number;\n canceled_at?: number;\n past_due_at?: number;\n lifetime_paid: number;\n next_payment_amount: number;\n next_payment_date: number;\n amount: BillingMoneyAmountJSON;\n plan: {\n id: string;\n instance_id: string;\n product_id: string;\n name: string;\n slug: string;\n description?: string;\n is_default: boolean;\n is_recurring: boolean;\n amount: number;\n period: 'month' | 'annual';\n interval: number;\n has_base_fee: boolean;\n currency: string;\n annual_monthly_amount: number;\n publicly_visible: boolean;\n };\n plan_id: string;\n}\n\n/**\n * Webhooks specific interface for BillingPaymentAttempt.\n */\nexport interface BillingPaymentAttemptWebhookEventJSON extends ClerkResourceJSON {\n object: typeof ObjectType.BillingPaymentAttempt;\n instance_id: string;\n payment_id: string;\n statement_id: string;\n gateway_external_id: string;\n status: 'pending' | 'paid' | 'failed';\n created_at: number;\n updated_at: number;\n paid_at?: number;\n failed_at?: number;\n failed_reason?: {\n code: string;\n decline_code: string;\n };\n billing_date: number;\n charge_type: 'checkout' | 'recurring';\n payee: BillingPayeeJSON;\n payer: BillingPayerJSON;\n totals: BillingTotalsJSON;\n payment_source: {\n id: string;\n gateway: string;\n gateway_external_id: string;\n gateway_external_account_id?: string;\n payment_method: string;\n status: 'active' | 'disconnected';\n card_type?: string;\n last4?: string;\n };\n subscription_items: BillingSubscriptionItemWebhookEventJSON[];\n}\n\n/**\n * Webhooks specific interface for BillingSubscription.\n */\nexport interface BillingSubscriptionWebhookEventJSON extends ClerkResourceJSON {\n object: typeof ObjectType.BillingSubscription;\n status: 'abandoned' | 'active' | 'canceled' | 'ended' | 'expired' | 'incomplete' | 'past_due' | 'upcoming';\n active_at?: number;\n canceled_at?: number;\n created_at: number;\n ended_at?: number;\n past_due_at?: number;\n updated_at: number;\n latest_payment_id: string;\n payer_id: string;\n payer: BillingPayerJSON;\n payment_source_id: string;\n items: BillingSubscriptionItemWebhookEventJSON[];\n}\n\nexport interface BillingSubscriptionJSON extends ClerkResourceJSON {\n object: typeof ObjectType.BillingSubscription;\n status: 'active' | 'past_due' | 'canceled' | 'ended' | 'abandoned' | 'incomplete';\n payer_id: string;\n created_at: number;\n updated_at: number;\n active_at: number | null;\n past_due_at: number | null;\n subscription_items: BillingSubscriptionItemJSON[];\n next_payment?: {\n date: number;\n amount: BillingMoneyAmountJSON;\n };\n eligible_for_free_trial?: boolean;\n}\n\nexport interface WebhooksSvixJSON {\n svix_url: string;\n}\n","import type { MachineJSON } from './JSON';\n\n/**\n * The Backend `Machine` object holds information about a machine.\n */\nexport class Machine {\n constructor(\n readonly id: string,\n readonly name: string,\n readonly instanceId: string,\n readonly createdAt: number,\n readonly updatedAt: number,\n readonly scopedMachines: Machine[],\n readonly defaultTokenTtl: number,\n readonly secretKey?: string,\n ) {}\n\n static fromJSON(data: MachineJSON): Machine {\n return new Machine(\n data.id,\n data.name,\n data.instance_id,\n data.created_at,\n data.updated_at,\n data.scoped_machines.map(\n m =>\n new Machine(\n m.id,\n m.name,\n m.instance_id,\n m.created_at,\n m.updated_at,\n [], // Nested machines don't have scoped_machines\n m.default_token_ttl,\n ),\n ),\n data.default_token_ttl,\n data.secret_key,\n );\n }\n}\n","import type { MachineScopeJSON } from './JSON';\n\n/**\n * The Backend `MachineScope` object holds information about a machine scope.\n */\nexport class MachineScope {\n constructor(\n readonly fromMachineId: string,\n readonly toMachineId: string,\n readonly createdAt?: number,\n readonly deleted?: boolean,\n ) {}\n\n static fromJSON(data: MachineScopeJSON): MachineScope {\n return new MachineScope(data.from_machine_id, data.to_machine_id, data.created_at, data.deleted);\n }\n}\n","import type { MachineSecretKeyJSON } from './JSON';\n\n/**\n * The Backend `MachineSecretKey` object holds information about a machine secret key.\n */\nexport class MachineSecretKey {\n constructor(readonly secret: string) {}\n\n static fromJSON(data: MachineSecretKeyJSON): MachineSecretKey {\n return new MachineSecretKey(data.secret);\n }\n}\n","import type { M2MTokenJSON } from './JSON';\n\n/**\n * The Backend `M2MToken` object holds information about a machine-to-machine token.\n */\nexport class M2MToken {\n constructor(\n readonly id: string,\n readonly subject: string,\n readonly scopes: string[],\n readonly claims: Record | null,\n readonly revoked: boolean,\n readonly revocationReason: string | null,\n readonly expired: boolean,\n readonly expiration: number | null,\n readonly createdAt: number,\n readonly updatedAt: number,\n readonly token?: string,\n ) {}\n\n static fromJSON(data: M2MTokenJSON): M2MToken {\n return new M2MToken(\n data.id,\n data.subject,\n data.scopes,\n data.claims,\n data.revoked,\n data.revocation_reason,\n data.expired,\n data.expiration,\n data.created_at,\n data.updated_at,\n data.token,\n );\n }\n}\n","import type { JwtTemplateJSON } from './JSON';\n\nexport class JwtTemplate {\n constructor(\n readonly id: string,\n readonly name: string,\n readonly claims: object,\n readonly lifetime: number,\n readonly allowedClockSkew: number,\n readonly customSigningKey: boolean,\n readonly signingAlgorithm: string,\n readonly createdAt: number,\n readonly updatedAt: number,\n ) {}\n\n static fromJSON(data: JwtTemplateJSON): JwtTemplate {\n return new JwtTemplate(\n data.id,\n data.name,\n data.claims,\n data.lifetime,\n data.allowed_clock_skew,\n data.custom_signing_key,\n data.signing_algorithm,\n data.created_at,\n data.updated_at,\n );\n }\n}\n","import type { OauthAccessTokenJSON } from './JSON';\n\nexport class OauthAccessToken {\n constructor(\n readonly externalAccountId: string,\n readonly provider: string,\n readonly token: string,\n readonly publicMetadata: Record = {},\n readonly label: string,\n readonly scopes?: string[],\n readonly tokenSecret?: string,\n readonly expiresAt?: number,\n ) {}\n\n static fromJSON(data: OauthAccessTokenJSON) {\n return new OauthAccessToken(\n data.external_account_id,\n data.provider,\n data.token,\n data.public_metadata,\n data.label || '',\n data.scopes,\n data.token_secret,\n data.expires_at,\n );\n }\n}\n","import type { OAuthApplicationJSON } from './JSON';\n\n/**\n * The Backend `OAuthApplication` object holds information about an OAuth application.\n */\nexport class OAuthApplication {\n constructor(\n /**\n * The unique identifier for the OAuth application.\n */\n readonly id: string,\n /**\n * The ID of the instance that this OAuth application belongs to.\n */\n readonly instanceId: string,\n /**\n * The name of the new OAuth application.\n */\n readonly name: string,\n /**\n * The ID of the client associated with the OAuth application.\n */\n readonly clientId: string,\n /**\n * The public-facing URL of the OAuth application, often shown on consent screens.\n */\n readonly clientUri: string | null,\n /**\n * The URL of the image or logo representing the OAuth application.\n */\n readonly clientImageUrl: string | null,\n /**\n * Specifies whether the OAuth application is dynamically registered.\n */\n readonly dynamicallyRegistered: boolean,\n /**\n * Specifies whether the consent screen should be displayed in the authentication flow. Cannot be disabled for dynamically registered OAuth applications.\n */\n readonly consentScreenEnabled: boolean,\n /**\n * Specifies whether the Proof Key of Code Exchange (PKCE) flow should be required in the authentication flow.\n */\n readonly pkceRequired: boolean,\n /**\n * Indicates whether the client is public. If true, the Proof Key of Code Exchange (PKCE) flow can be used.\n */\n readonly isPublic: boolean, // NOTE: `public` is reserved\n /**\n * Scopes for the new OAuth application.\n */\n readonly scopes: string,\n /**\n * An array of redirect URIs of the new OAuth application.\n */\n readonly redirectUris: Array,\n /**\n * The URL used to authorize the user and obtain an authorization code.\n */\n readonly authorizeUrl: string,\n /**\n * The URL used by the client to exchange an authorization code for an access token.\n */\n readonly tokenFetchUrl: string,\n /**\n * The URL where the client can retrieve user information using an access token.\n */\n readonly userInfoUrl: string,\n /**\n * The OpenID Connect discovery endpoint URL for this OAuth application.\n */\n readonly discoveryUrl: string,\n /**\n * The URL used to introspect and validate issued access tokens.\n */\n readonly tokenIntrospectionUrl: string,\n /**\n * The date when the OAuth application was first created.\n */\n readonly createdAt: number,\n /**\n * The date when the OAuth application was last updated.\n */\n readonly updatedAt: number,\n /**\n * The client secret associated with the OAuth application. Empty if public client.\n */\n readonly clientSecret?: string,\n ) {}\n\n static fromJSON(data: OAuthApplicationJSON) {\n return new OAuthApplication(\n data.id,\n data.instance_id,\n data.name,\n data.client_id,\n data.client_uri,\n data.client_image_url,\n data.dynamically_registered,\n data.consent_screen_enabled,\n data.pkce_required,\n data.public,\n data.scopes,\n data.redirect_uris,\n data.authorize_url,\n data.token_fetch_url,\n data.user_info_url,\n data.discovery_url,\n data.token_introspection_url,\n data.created_at,\n data.updated_at,\n data.client_secret,\n );\n }\n}\n","import type { OrganizationJSON } from './JSON';\n\n/**\n * The Backend `Organization` object is similar to the [`Organization`](https://clerk.com/docs/references/javascript/organization) object as it holds information about an organization, as well as methods for managing it. However, the Backend `Organization` object is different in that it is used in the [Backend API](https://clerk.com/docs/reference/backend-api/tag/Organizations#operation/ListOrganizations){{ target: '_blank' }} and is not directly accessible from the Frontend API.\n */\nexport class Organization {\n private _raw: OrganizationJSON | null = null;\n\n public get raw(): OrganizationJSON | null {\n return this._raw;\n }\n\n constructor(\n /**\n * The unique identifier for the organization.\n */\n readonly id: string,\n /**\n * The name of the organization.\n */\n readonly name: string,\n /**\n * The URL-friendly identifier of the user's active organization. If supplied, it must be unique for the instance.\n */\n readonly slug: string,\n /**\n * Holds the organization's logo. Compatible with Clerk's [Image Optimization](https://clerk.com/docs/guides/image-optimization).\n */\n readonly imageUrl: string,\n /**\n * Whether the organization has an image.\n */\n readonly hasImage: boolean,\n /**\n * The date when the organization was first created.\n */\n readonly createdAt: number,\n /**\n * The date when the organization was last updated.\n */\n readonly updatedAt: number,\n /**\n * Metadata that can be read from the Frontend API and [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }} and can be set only from the Backend API.\n */\n readonly publicMetadata: OrganizationPublicMetadata | null = {},\n /**\n * Metadata that can be read and set only from the [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }}.\n */\n readonly privateMetadata: OrganizationPrivateMetadata = {},\n /**\n * The maximum number of memberships allowed in the organization.\n */\n readonly maxAllowedMemberships: number,\n /**\n * Whether the organization allows admins to delete users.\n */\n readonly adminDeleteEnabled: boolean,\n /**\n * The number of members in the organization.\n */\n readonly membersCount?: number,\n /**\n * The ID of the user who created the organization.\n */\n readonly createdBy?: string,\n ) {}\n\n static fromJSON(data: OrganizationJSON): Organization {\n const res = new Organization(\n data.id,\n data.name,\n data.slug,\n data.image_url || '',\n data.has_image,\n data.created_at,\n data.updated_at,\n data.public_metadata,\n data.private_metadata,\n data.max_allowed_memberships,\n data.admin_delete_enabled,\n data.members_count,\n data.created_by,\n );\n res._raw = data;\n return res;\n }\n}\n","import type { OrganizationInvitationStatus, OrganizationMembershipRole } from './Enums';\nimport type { OrganizationInvitationJSON, PublicOrganizationDataJSON } from './JSON';\n\n/**\n * The Backend `OrganizationInvitation` object is similar to the [`OrganizationInvitation`](https://clerk.com/docs/references/javascript/types/organization-invitation) object as it's the model around an organization invitation. However, the Backend `OrganizationInvitation` object is different in that it's used in the [Backend API](https://clerk.com/docs/reference/backend-api/tag/Organization-Invitations#operation/CreateOrganizationInvitation){{ target: '_blank' }} and is not directly accessible from the Frontend API.\n */\nexport class OrganizationInvitation {\n private _raw: OrganizationInvitationJSON | null = null;\n\n public get raw(): OrganizationInvitationJSON | null {\n return this._raw;\n }\n\n constructor(\n /**\n * The unique identifier for the `OrganizationInvitation`.\n */\n readonly id: string,\n /**\n * The email address of the user who is invited to the [`Organization`](https://clerk.com/docs/references/backend/types/backend-organization).\n */\n readonly emailAddress: string,\n /**\n * The role of the invited user.\n */\n readonly role: OrganizationMembershipRole,\n /**\n * The name of the role of the invited user.\n */\n readonly roleName: string,\n /**\n * The ID of the [`Organization`](https://clerk.com/docs/references/backend/types/backend-organization) that the user is invited to.\n */\n readonly organizationId: string,\n /**\n * The date when the invitation was first created.\n */\n readonly createdAt: number,\n /**\n * The date when the invitation was last updated.\n */\n readonly updatedAt: number,\n /**\n * The date when the invitation expires.\n */\n readonly expiresAt: number,\n /**\n * The URL that the user can use to accept the invitation.\n */\n readonly url: string | null,\n /**\n * The status of the invitation.\n */\n readonly status?: OrganizationInvitationStatus,\n /**\n * Metadata that can be read from the Frontend API and [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }} and can be set only from the Backend API.\n */\n readonly publicMetadata: OrganizationInvitationPublicMetadata = {},\n /**\n * Metadata that can be read and set only from the [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }}.\n */\n readonly privateMetadata: OrganizationInvitationPrivateMetadata = {},\n /**\n * Public data about the organization that the user is invited to.\n */\n readonly publicOrganizationData?: PublicOrganizationDataJSON | null,\n ) {}\n\n static fromJSON(data: OrganizationInvitationJSON) {\n const res = new OrganizationInvitation(\n data.id,\n data.email_address,\n data.role,\n data.role_name,\n data.organization_id,\n data.created_at,\n data.updated_at,\n data.expires_at,\n data.url,\n data.status,\n data.public_metadata,\n data.private_metadata,\n data.public_organization_data,\n );\n res._raw = data;\n return res;\n }\n}\n","import { Organization } from '../resources';\nimport type { OrganizationMembershipRole } from './Enums';\nimport type { OrganizationMembershipJSON, OrganizationMembershipPublicUserDataJSON } from './JSON';\n\n/**\n * The Backend `OrganizationMembership` object is similar to the [`OrganizationMembership`](https://clerk.com/docs/references/javascript/types/organization-membership) object as it's the model around an organization membership entity and describes the relationship between users and organizations. However, the Backend `OrganizationMembership` object is different in that it's used in the [Backend API](https://clerk.com/docs/reference/backend-api/tag/Organization-Memberships#operation/CreateOrganizationMembership){{ target: '_blank' }} and is not directly accessible from the Frontend API.\n */\nexport class OrganizationMembership {\n private _raw: OrganizationMembershipJSON | null = null;\n\n public get raw(): OrganizationMembershipJSON | null {\n return this._raw;\n }\n\n constructor(\n /**\n * The unique identifier for the membership.\n */\n readonly id: string,\n /**\n * The role of the user.\n */\n readonly role: OrganizationMembershipRole,\n /**\n * The permissions granted to the user in the organization.\n */\n readonly permissions: string[],\n /**\n * Metadata that can be read from the Frontend API and [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }} and can be set only from the Backend API.\n */\n readonly publicMetadata: OrganizationMembershipPublicMetadata = {},\n /**\n * Metadata that can be read and set only from the [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }}.\n */\n readonly privateMetadata: OrganizationMembershipPrivateMetadata = {},\n /**\n * The date when the membership was first created.\n */\n readonly createdAt: number,\n /**\n * The date when the membership was last updated.\n */\n readonly updatedAt: number,\n /**\n * The organization that the user is a member of.\n */\n readonly organization: Organization,\n /**\n * Public information about the user that this membership belongs to.\n */\n readonly publicUserData?: OrganizationMembershipPublicUserData | null,\n ) {}\n\n static fromJSON(data: OrganizationMembershipJSON) {\n const res = new OrganizationMembership(\n data.id,\n data.role,\n data.permissions,\n data.public_metadata,\n data.private_metadata,\n data.created_at,\n data.updated_at,\n Organization.fromJSON(data.organization),\n OrganizationMembershipPublicUserData.fromJSON(data.public_user_data),\n );\n res._raw = data;\n return res;\n }\n}\n\n/**\n * @class\n */\nexport class OrganizationMembershipPublicUserData {\n constructor(\n /**\n * The [identifier](https://clerk.com/docs/authentication/configuration/sign-up-sign-in-options#identifiers) of the user.\n */\n readonly identifier: string,\n /**\n * The first name of the user.\n */\n readonly firstName: string | null,\n /**\n * The last name of the user.\n */\n readonly lastName: string | null,\n /**\n * Holds the default avatar or user's uploaded profile image. Compatible with Clerk's [Image Optimization](https://clerk.com/docs/guides/image-optimization).\n */\n readonly imageUrl: string,\n /**\n * Whether the user has a profile picture.\n */\n readonly hasImage: boolean,\n /**\n * The ID of the user that this public data belongs to.\n */\n readonly userId: string,\n ) {}\n\n static fromJSON(data: OrganizationMembershipPublicUserDataJSON) {\n return new OrganizationMembershipPublicUserData(\n data.identifier,\n data.first_name,\n data.last_name,\n data.image_url,\n data.has_image,\n data.user_id,\n );\n }\n}\n","import type { DomainsEnrollmentModes } from './Enums';\nimport type { OrganizationSettingsJSON } from './JSON';\n\nexport class OrganizationSettings {\n constructor(\n readonly enabled: boolean,\n readonly maxAllowedMemberships: number,\n readonly maxAllowedRoles: number,\n readonly maxAllowedPermissions: number,\n readonly creatorRole: string,\n readonly adminDeleteEnabled: boolean,\n readonly domainsEnabled: boolean,\n readonly domainsEnrollmentModes: Array,\n readonly domainsDefaultRole: string,\n ) {}\n\n static fromJSON(data: OrganizationSettingsJSON): OrganizationSettings {\n return new OrganizationSettings(\n data.enabled,\n data.max_allowed_memberships,\n data.max_allowed_roles,\n data.max_allowed_permissions,\n data.creator_role,\n data.admin_delete_enabled,\n data.domains_enabled,\n data.domains_enrollment_modes,\n data.domains_default_role,\n );\n }\n}\n","import { IdentificationLink } from './IdentificationLink';\nimport type { PhoneNumberJSON } from './JSON';\nimport { Verification } from './Verification';\n\n/**\n * The Backend `PhoneNumber` object describes a phone number. Phone numbers can be used as a proof of identification for users, or simply as a means of contacting users.\n *\n * Phone numbers must be **verified** to ensure that they can be assigned to their rightful owners. The `PhoneNumber` object holds all the necessary state around the verification process.\n *\n * Finally, phone numbers can be used as part of [multi-factor authentication](https://clerk.com/docs/authentication/configuration/sign-up-sign-in-options#multi-factor-authentication). During sign in, users can opt in to an extra verification step where they will receive an SMS message with a one-time code. This code must be entered to complete the sign in process.\n */\nexport class PhoneNumber {\n constructor(\n /**\n * The unique identifier for this phone number.\n */\n readonly id: string,\n /**\n * The value of this phone number, in [E.164 format](https://en.wikipedia.org/wiki/E.164).\n */\n readonly phoneNumber: string,\n /**\n * Set to `true` if this phone number is reserved for multi-factor authentication (2FA). Set to `false` otherwise.\n */\n readonly reservedForSecondFactor: boolean,\n /**\n * Set to `true` if this phone number is the default second factor. Set to `false` otherwise. A user must have exactly one default second factor, if multi-factor authentication (2FA) is enabled.\n */\n readonly defaultSecondFactor: boolean,\n /**\n * An object holding information on the verification of this phone number.\n */\n readonly verification: Verification | null,\n /**\n * An object containing information about any other identification that might be linked to this phone number.\n */\n readonly linkedTo: IdentificationLink[],\n ) {}\n\n static fromJSON(data: PhoneNumberJSON): PhoneNumber {\n return new PhoneNumber(\n data.id,\n data.phone_number,\n data.reserved_for_second_factor,\n data.default_second_factor,\n data.verification && Verification.fromJSON(data.verification),\n data.linked_to.map(link => IdentificationLink.fromJSON(link)),\n );\n }\n}\n","import type { ProxyCheckJSON } from './JSON';\n\nexport class ProxyCheck {\n constructor(\n readonly id: string,\n readonly domainId: string,\n readonly lastRunAt: number | null,\n readonly proxyUrl: string,\n readonly successful: boolean,\n readonly createdAt: number,\n readonly updatedAt: number,\n ) {}\n\n static fromJSON(data: ProxyCheckJSON): ProxyCheck {\n return new ProxyCheck(\n data.id,\n data.domain_id,\n data.last_run_at,\n data.proxy_url,\n data.successful,\n data.created_at,\n data.updated_at,\n );\n }\n}\n","import type { RedirectUrlJSON } from './JSON';\n\n/**\n * Redirect URLs are whitelisted URLs that facilitate secure authentication flows in native applications (e.g. React Native, Expo). In these contexts, Clerk ensures that security-critical nonces are passed only to the whitelisted URLs.\n\nThe Backend `RedirectUrl` object represents a redirect URL in your application. This object is used in the Backend API.\n */\nexport class RedirectUrl {\n constructor(\n /**\n * The unique identifier for the redirect URL.\n */\n readonly id: string,\n /**\n * The full URL value prefixed with `https://` or a custom scheme.\n * @example https://my-app.com/oauth-callback\n * @example my-app://oauth-callback\n */\n readonly url: string,\n /**\n * The date when the redirect URL was first created.\n */\n readonly createdAt: number,\n /**\n * The date when the redirect URL was last updated.\n */\n readonly updatedAt: number,\n ) {}\n\n static fromJSON(data: RedirectUrlJSON): RedirectUrl {\n return new RedirectUrl(data.id, data.url, data.created_at, data.updated_at);\n }\n}\n","import type { AttributeMappingJSON, SamlAccountConnectionJSON, SamlConnectionJSON } from './JSON';\n\n/**\n * The Backend `SamlConnection` object holds information about a SAML connection for an organization.\n */\nexport class SamlConnection {\n constructor(\n /**\n * The unique identifier for the connection.\n */\n readonly id: string,\n /**\n * The name to use as a label for the connection.\n */\n readonly name: string,\n /**\n * The domain of your organization. Sign in flows using an email with this domain will use the connection.\n */\n readonly domain: string,\n /**\n * The organization ID of the organization.\n */\n readonly organizationId: string | null,\n /**\n * The Entity ID as provided by the Identity Provider (IdP).\n */\n readonly idpEntityId: string | null,\n /**\n * The Single-Sign On URL as provided by the Identity Provider (IdP).\n */\n readonly idpSsoUrl: string | null,\n /**\n * The X.509 certificate as provided by the Identity Provider (IdP).\n */\n readonly idpCertificate: string | null,\n /**\n * The URL which serves the Identity Provider (IdP) metadata. If present, it takes priority over the corresponding individual properties.\n */\n readonly idpMetadataUrl: string | null,\n /**\n * The XML content of the Identity Provider (IdP) metadata file. If present, it takes priority over the corresponding individual properties.\n */\n readonly idpMetadata: string | null,\n /**\n * The Assertion Consumer Service (ACS) URL of the connection.\n */\n readonly acsUrl: string,\n /**\n * The Entity ID as provided by the Service Provider (Clerk).\n */\n readonly spEntityId: string,\n /**\n * The metadata URL as provided by the Service Provider (Clerk).\n */\n readonly spMetadataUrl: string,\n /**\n * Indicates whether the connection is active or not.\n */\n readonly active: boolean,\n /**\n * The Identity Provider (IdP) of the connection.\n */\n readonly provider: string,\n /**\n * The number of users associated with the connection.\n */\n readonly userCount: number,\n /**\n * Indicates whether the connection syncs user attributes between the Service Provider (SP) and Identity Provider (IdP) or not.\n */\n readonly syncUserAttributes: boolean,\n /**\n * Indicates whether users with an email address subdomain are allowed to use this connection in order to authenticate or not.\n */\n readonly allowSubdomains: boolean,\n /**\n * Indicates whether the connection allows Identity Provider (IdP) initiated flows or not.\n */\n readonly allowIdpInitiated: boolean,\n /**\n * The date when the connection was first created.\n */\n readonly createdAt: number,\n /**\n * The date when the SAML connection was last updated.\n */\n readonly updatedAt: number,\n /**\n * Defines the attribute name mapping between the Identity Provider (IdP) and Clerk's [`User`](https://clerk.com/docs/references/javascript/user) properties.\n */\n readonly attributeMapping: AttributeMapping,\n ) {}\n static fromJSON(data: SamlConnectionJSON): SamlConnection {\n return new SamlConnection(\n data.id,\n data.name,\n data.domain,\n data.organization_id,\n data.idp_entity_id,\n data.idp_sso_url,\n data.idp_certificate,\n data.idp_metadata_url,\n data.idp_metadata,\n data.acs_url,\n data.sp_entity_id,\n data.sp_metadata_url,\n data.active,\n data.provider,\n data.user_count,\n data.sync_user_attributes,\n data.allow_subdomains,\n data.allow_idp_initiated,\n data.created_at,\n data.updated_at,\n data.attribute_mapping && AttributeMapping.fromJSON(data.attribute_mapping),\n );\n }\n}\n\nexport class SamlAccountConnection {\n constructor(\n readonly id: string,\n readonly name: string,\n readonly domain: string,\n readonly active: boolean,\n readonly provider: string,\n readonly syncUserAttributes: boolean,\n readonly allowSubdomains: boolean,\n readonly allowIdpInitiated: boolean,\n readonly createdAt: number,\n readonly updatedAt: number,\n ) {}\n static fromJSON(data: SamlAccountConnectionJSON): SamlAccountConnection {\n return new SamlAccountConnection(\n data.id,\n data.name,\n data.domain,\n data.active,\n data.provider,\n data.sync_user_attributes,\n data.allow_subdomains,\n data.allow_idp_initiated,\n data.created_at,\n data.updated_at,\n );\n }\n}\n\nclass AttributeMapping {\n constructor(\n /**\n * The user ID attribute name.\n */\n readonly userId: string,\n /**\n * The email address attribute name.\n */\n readonly emailAddress: string,\n /**\n * The first name attribute name.\n */\n readonly firstName: string,\n /**\n * The last name attribute name.\n */\n readonly lastName: string,\n ) {}\n\n static fromJSON(data: AttributeMappingJSON): AttributeMapping {\n return new AttributeMapping(data.user_id, data.email_address, data.first_name, data.last_name);\n }\n}\n","import type { SamlAccountJSON } from './JSON';\nimport { SamlAccountConnection } from './SamlConnection';\nimport { Verification } from './Verification';\n\n/**\n * The Backend `SamlAccount` object describes a SAML account.\n */\nexport class SamlAccount {\n constructor(\n /**\n * The unique identifier for the SAML account.\n */\n readonly id: string,\n /**\n * The provider of the SAML account.\n */\n readonly provider: string,\n /**\n * The user's ID as used in the provider.\n */\n readonly providerUserId: string | null,\n /**\n * A boolean that indicates whether the SAML account is active.\n */\n readonly active: boolean,\n /**\n * The email address of the SAML account.\n */\n readonly emailAddress: string,\n /**\n * The first name of the SAML account.\n */\n readonly firstName: string,\n /**\n * The last name of the SAML account.\n */\n readonly lastName: string,\n /**\n * The verification of the SAML account.\n */\n readonly verification: Verification | null,\n /**\n * The SAML connection of the SAML account.\n */\n readonly samlConnection: SamlAccountConnection | null,\n ) {}\n\n static fromJSON(data: SamlAccountJSON): SamlAccount {\n return new SamlAccount(\n data.id,\n data.provider,\n data.provider_user_id,\n data.active,\n data.email_address,\n data.first_name,\n data.last_name,\n data.verification && Verification.fromJSON(data.verification),\n data.saml_connection && SamlAccountConnection.fromJSON(data.saml_connection),\n );\n }\n}\n","import type { SignInTokenJSON } from './JSON';\n\nexport class SignInToken {\n constructor(\n readonly id: string,\n readonly userId: string,\n readonly token: string,\n readonly status: string,\n readonly url: string,\n readonly createdAt: number,\n readonly updatedAt: number,\n ) {}\n\n static fromJSON(data: SignInTokenJSON): SignInToken {\n return new SignInToken(data.id, data.user_id, data.token, data.status, data.url, data.created_at, data.updated_at);\n }\n}\n","import type { SignUpStatus } from '@clerk/types';\n\nimport type { SignUpVerificationNextAction } from './Enums';\nimport type { SignUpJSON, SignUpVerificationJSON, SignUpVerificationsJSON } from './JSON';\n\nexport class SignUpAttemptVerification {\n constructor(\n readonly nextAction: SignUpVerificationNextAction,\n readonly supportedStrategies: string[],\n ) {}\n\n static fromJSON(data: SignUpVerificationJSON): SignUpAttemptVerification {\n return new SignUpAttemptVerification(data.next_action, data.supported_strategies);\n }\n}\n\nexport class SignUpAttemptVerifications {\n constructor(\n readonly emailAddress: SignUpAttemptVerification | null,\n readonly phoneNumber: SignUpAttemptVerification | null,\n readonly web3Wallet: SignUpAttemptVerification | null,\n readonly externalAccount: object | null,\n ) {}\n\n static fromJSON(data: SignUpVerificationsJSON): SignUpAttemptVerifications {\n return new SignUpAttemptVerifications(\n data.email_address && SignUpAttemptVerification.fromJSON(data.email_address),\n data.phone_number && SignUpAttemptVerification.fromJSON(data.phone_number),\n data.web3_wallet && SignUpAttemptVerification.fromJSON(data.web3_wallet),\n data.external_account,\n );\n }\n}\n\nexport class SignUpAttempt {\n constructor(\n readonly id: string,\n readonly status: SignUpStatus,\n readonly requiredFields: string[],\n readonly optionalFields: string[],\n readonly missingFields: string[],\n readonly unverifiedFields: string[],\n readonly verifications: SignUpAttemptVerifications | null,\n readonly username: string | null,\n readonly emailAddress: string | null,\n readonly phoneNumber: string | null,\n readonly web3Wallet: string | null,\n readonly passwordEnabled: boolean,\n readonly firstName: string | null,\n readonly lastName: string | null,\n readonly customAction: boolean,\n readonly externalId: string | null,\n readonly createdSessionId: string | null,\n readonly createdUserId: string | null,\n readonly abandonAt: number | null,\n readonly legalAcceptedAt: number | null,\n readonly publicMetadata?: Record | null,\n readonly unsafeMetadata?: Record | null,\n ) {}\n\n static fromJSON(data: SignUpJSON): SignUpAttempt {\n return new SignUpAttempt(\n data.id,\n data.status,\n data.required_fields,\n data.optional_fields,\n data.missing_fields,\n data.unverified_fields,\n data.verifications ? SignUpAttemptVerifications.fromJSON(data.verifications) : null,\n data.username,\n data.email_address,\n data.phone_number,\n data.web3_wallet,\n data.password_enabled,\n data.first_name,\n data.last_name,\n data.custom_action,\n data.external_id,\n data.created_session_id,\n data.created_user_id,\n data.abandon_at,\n data.legal_accepted_at,\n data.public_metadata,\n data.unsafe_metadata,\n );\n }\n}\n","import type { SMSMessageJSON } from './JSON';\n\nexport class SMSMessage {\n constructor(\n readonly id: string,\n readonly fromPhoneNumber: string,\n readonly toPhoneNumber: string,\n readonly message: string,\n readonly status: string,\n readonly phoneNumberId: string | null,\n readonly data?: Record | null,\n ) {}\n\n static fromJSON(data: SMSMessageJSON): SMSMessage {\n return new SMSMessage(\n data.id,\n data.from_phone_number,\n data.to_phone_number,\n data.message,\n data.status,\n data.phone_number_id,\n data.data,\n );\n }\n}\n","import type { TokenJSON } from './JSON';\n\nexport class Token {\n constructor(readonly jwt: string) {}\n\n static fromJSON(data: TokenJSON): Token {\n return new Token(data.jwt);\n }\n}\n","import type { Web3WalletJSON } from './JSON';\nimport { Verification } from './Verification';\n\n/**\n * The Backend `Web3Wallet` object describes a Web3 wallet address. The address can be used as a proof of identification for users.\n *\n * Web3 addresses must be verified to ensure that they can be assigned to their rightful owners. The verification is completed via Web3 wallet browser extensions, such as [Metamask](https://metamask.io/), [Coinbase Wallet](https://www.coinbase.com/wallet), and [OKX Wallet](https://www.okx.com/help/section/faq-web3-wallet). The `Web3Wallet3` object holds all the necessary state around the verification process.\n */\nexport class Web3Wallet {\n constructor(\n /**\n * The unique ID for the Web3 wallet.\n */\n readonly id: string,\n /**\n * The Web3 wallet address, made up of 0x + 40 hexadecimal characters.\n */\n readonly web3Wallet: string,\n /**\n * An object holding information on the verification of this Web3 wallet.\n */\n readonly verification: Verification | null,\n ) {}\n\n static fromJSON(data: Web3WalletJSON): Web3Wallet {\n return new Web3Wallet(data.id, data.web3_wallet, data.verification && Verification.fromJSON(data.verification));\n }\n}\n","import { EmailAddress } from './EmailAddress';\nimport { ExternalAccount } from './ExternalAccount';\nimport type { ExternalAccountJSON, SamlAccountJSON, UserJSON } from './JSON';\nimport { PhoneNumber } from './PhoneNumber';\nimport { SamlAccount } from './SamlAccount';\nimport { Web3Wallet } from './Web3Wallet';\n\n/**\n * The Backend `User` object is similar to the `User` object as it holds information about a user of your application, such as their unique identifier, name, email addresses, phone numbers, and more. However, the Backend `User` object is different from the `User` object in that it is used in the [Backend API](https://clerk.com/docs/reference/backend-api/tag/Users#operation/GetUser){{ target: '_blank' }} and is not directly accessible from the Frontend API.\n */\nexport class User {\n private _raw: UserJSON | null = null;\n\n public get raw(): UserJSON | null {\n return this._raw;\n }\n\n constructor(\n /**\n * The unique identifier for the user.\n */\n readonly id: string,\n /**\n * A boolean indicating whether the user has a password on their account.\n */\n readonly passwordEnabled: boolean,\n /**\n * A boolean indicating whether the user has enabled TOTP by generating a TOTP secret and verifying it via an authenticator app.\n */\n readonly totpEnabled: boolean,\n /**\n * A boolean indicating whether the user has enabled Backup codes.\n */\n readonly backupCodeEnabled: boolean,\n /**\n * A boolean indicating whether the user has enabled two-factor authentication.\n */\n readonly twoFactorEnabled: boolean,\n /**\n * A boolean indicating whether the user is banned or not.\n */\n readonly banned: boolean,\n /**\n * A boolean indicating whether the user is banned or not.\n */\n readonly locked: boolean,\n /**\n * The date when the user was first created.\n */\n readonly createdAt: number,\n /**\n * The date when the user was last updated.\n */\n readonly updatedAt: number,\n /**\n * The URL of the user's profile image.\n */\n readonly imageUrl: string,\n /**\n * A getter boolean to check if the user has uploaded an image or one was copied from OAuth. Returns `false` if Clerk is displaying an avatar for the user.\n */\n readonly hasImage: boolean,\n /**\n * The ID for the `EmailAddress` that the user has set as primary.\n */\n readonly primaryEmailAddressId: string | null,\n /**\n * The ID for the `PhoneNumber` that the user has set as primary.\n */\n readonly primaryPhoneNumberId: string | null,\n /**\n * The ID for the [`Web3Wallet`](https://clerk.com/docs/references/backend/types/backend-web3-wallet) that the user signed up with.\n */\n readonly primaryWeb3WalletId: string | null,\n /**\n * The date when the user last signed in. May be empty if the user has never signed in.\n */\n readonly lastSignInAt: number | null,\n /**\n * The ID of the user as used in your external systems. Must be unique across your instance.\n */\n readonly externalId: string | null,\n /**\n * The user's username.\n */\n readonly username: string | null,\n /**\n * The user's first name.\n */\n readonly firstName: string | null,\n /**\n * The user's last name.\n */\n readonly lastName: string | null,\n /**\n * Metadata that can be read from the Frontend API and [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }} and can be set only from the Backend API.\n */\n readonly publicMetadata: UserPublicMetadata = {},\n /**\n * Metadata that can be read and set only from the [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }}.\n */\n readonly privateMetadata: UserPrivateMetadata = {},\n /**\n * Metadata that can be read and set from the Frontend API. It's considered unsafe because it can be modified from the frontend.\n */\n readonly unsafeMetadata: UserUnsafeMetadata = {},\n /**\n * An array of all the `EmailAddress` objects associated with the user. Includes the primary.\n */\n readonly emailAddresses: EmailAddress[] = [],\n /**\n * An array of all the `PhoneNumber` objects associated with the user. Includes the primary.\n */\n readonly phoneNumbers: PhoneNumber[] = [],\n /**\n * An array of all the `Web3Wallet` objects associated with the user. Includes the primary.\n */\n readonly web3Wallets: Web3Wallet[] = [],\n /**\n * An array of all the `ExternalAccount` objects associated with the user via OAuth. **Note**: This includes both verified & unverified external accounts.\n */\n readonly externalAccounts: ExternalAccount[] = [],\n /**\n * An array of all the `SamlAccount` objects associated with the user via SAML.\n */\n readonly samlAccounts: SamlAccount[] = [],\n /**\n * Date when the user was last active.\n */\n readonly lastActiveAt: number | null,\n /**\n * A boolean indicating whether the organization creation is enabled for the user or not.\n */\n readonly createOrganizationEnabled: boolean,\n /**\n * An integer indicating the number of organizations that can be created by the user. If the value is `0`, then the user can create unlimited organizations. Default is `null`.\n */\n readonly createOrganizationsLimit: number | null = null,\n /**\n * A boolean indicating whether the user can delete their own account.\n */\n readonly deleteSelfEnabled: boolean,\n /**\n * The unix timestamp of when the user accepted the legal requirements. `null` if [**Require express consent to legal documents**](https://clerk.com/docs/authentication/configuration/legal-compliance) is not enabled.\n */\n readonly legalAcceptedAt: number | null,\n ) {}\n\n static fromJSON(data: UserJSON): User {\n const res = new User(\n data.id,\n data.password_enabled,\n data.totp_enabled,\n data.backup_code_enabled,\n data.two_factor_enabled,\n data.banned,\n data.locked,\n data.created_at,\n data.updated_at,\n data.image_url,\n data.has_image,\n data.primary_email_address_id,\n data.primary_phone_number_id,\n data.primary_web3_wallet_id,\n data.last_sign_in_at,\n data.external_id,\n data.username,\n data.first_name,\n data.last_name,\n data.public_metadata,\n data.private_metadata,\n data.unsafe_metadata,\n (data.email_addresses || []).map(x => EmailAddress.fromJSON(x)),\n (data.phone_numbers || []).map(x => PhoneNumber.fromJSON(x)),\n (data.web3_wallets || []).map(x => Web3Wallet.fromJSON(x)),\n (data.external_accounts || []).map((x: ExternalAccountJSON) => ExternalAccount.fromJSON(x)),\n (data.saml_accounts || []).map((x: SamlAccountJSON) => SamlAccount.fromJSON(x)),\n data.last_active_at,\n data.create_organization_enabled,\n data.create_organizations_limit,\n data.delete_self_enabled,\n data.legal_accepted_at,\n );\n res._raw = data;\n return res;\n }\n\n /**\n * The primary email address of the user.\n */\n get primaryEmailAddress() {\n return this.emailAddresses.find(({ id }) => id === this.primaryEmailAddressId) ?? null;\n }\n\n /**\n * The primary phone number of the user.\n */\n get primaryPhoneNumber() {\n return this.phoneNumbers.find(({ id }) => id === this.primaryPhoneNumberId) ?? null;\n }\n\n /**\n * The primary web3 wallet of the user.\n */\n get primaryWeb3Wallet() {\n return this.web3Wallets.find(({ id }) => id === this.primaryWeb3WalletId) ?? null;\n }\n\n /**\n * The full name of the user.\n */\n get fullName() {\n return [this.firstName, this.lastName].join(' ').trim() || null;\n }\n}\n","import type { WaitlistEntryStatus } from './Enums';\nimport { Invitation } from './Invitation';\nimport type { WaitlistEntryJSON } from './JSON';\n\nexport class WaitlistEntry {\n constructor(\n readonly id: string,\n readonly emailAddress: string,\n readonly status: WaitlistEntryStatus,\n readonly invitation: Invitation | null,\n readonly createdAt: number,\n readonly updatedAt: number,\n readonly isLocked?: boolean,\n ) {}\n\n static fromJSON(data: WaitlistEntryJSON): WaitlistEntry {\n return new WaitlistEntry(\n data.id,\n data.email_address,\n data.status,\n data.invitation && Invitation.fromJSON(data.invitation),\n data.created_at,\n data.updated_at,\n data.is_locked,\n );\n }\n}\n","import type { FeatureJSON } from './JSON';\n\n/**\n * The `Feature` object represents a feature of a subscription plan.\n *\n * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes.\n */\nexport class Feature {\n constructor(\n /**\n * The unique identifier for the feature.\n */\n readonly id: string,\n /**\n * The name of the feature.\n */\n readonly name: string,\n /**\n * The description of the feature.\n */\n readonly description: string,\n /**\n * The URL-friendly identifier of the feature.\n */\n readonly slug: string,\n /**\n * The URL of the feature's avatar image.\n */\n readonly avatarUrl: string,\n ) {}\n\n static fromJSON(data: FeatureJSON): Feature {\n return new Feature(data.id, data.name, data.description, data.slug, data.avatar_url);\n }\n}\n","import type { BillingMoneyAmount } from '@clerk/types';\n\nimport { Feature } from './Feature';\nimport type { BillingPlanJSON } from './JSON';\n\n/**\n * The `BillingPlan` object is similar to the [`BillingPlanResource`](/docs/references/javascript/types/billing-plan-resource) object as it holds information about a plan, as well as methods for managing it. However, the `BillingPlan` object is different in that it is used in the [Backend API](https://clerk.com/docs/reference/backend-api/tag/commerce/get/commerce/plans) and is not directly accessible from the Frontend API.\n *\n * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes.\n */\nexport class BillingPlan {\n constructor(\n /**\n * The unique identifier for the plan.\n */\n readonly id: string,\n /**\n * The ID of the product the plan belongs to.\n */\n readonly productId: string,\n /**\n * The name of the plan.\n */\n readonly name: string,\n /**\n * The URL-friendly identifier of the plan.\n */\n readonly slug: string,\n /**\n * The description of the plan.\n */\n readonly description: string | undefined,\n /**\n * Whether the plan is the default plan.\n */\n readonly isDefault: boolean,\n /**\n * Whether the plan is recurring.\n */\n readonly isRecurring: boolean,\n /**\n * Whether the plan has a base fee.\n */\n readonly hasBaseFee: boolean,\n /**\n * Whether the plan is displayed in the `` component.\n */\n readonly publiclyVisible: boolean,\n /**\n * The monthly fee of the plan.\n */\n readonly fee: BillingMoneyAmount,\n /**\n * The annual fee of the plan.\n */\n readonly annualFee: BillingMoneyAmount,\n /**\n * The annual fee of the plan on a monthly basis.\n */\n readonly annualMonthlyFee: BillingMoneyAmount,\n /**\n * The type of payer for the plan.\n */\n readonly forPayerType: 'org' | 'user',\n /**\n * The features the plan offers.\n */\n readonly features: Feature[],\n ) {}\n\n static fromJSON(data: BillingPlanJSON): BillingPlan {\n const formatAmountJSON = (fee: BillingPlanJSON['fee']) => {\n return {\n amount: fee.amount,\n amountFormatted: fee.amount_formatted,\n currency: fee.currency,\n currencySymbol: fee.currency_symbol,\n };\n };\n return new BillingPlan(\n data.id,\n data.product_id,\n data.name,\n data.slug,\n data.description,\n data.is_default,\n data.is_recurring,\n data.has_base_fee,\n data.publicly_visible,\n formatAmountJSON(data.fee),\n formatAmountJSON(data.annual_fee),\n formatAmountJSON(data.annual_monthly_fee),\n data.for_payer_type,\n data.features.map(feature => Feature.fromJSON(feature)),\n );\n }\n}\n","import type { BillingMoneyAmount, BillingMoneyAmountJSON } from '@clerk/types';\n\nimport { BillingPlan } from './CommercePlan';\nimport type { BillingSubscriptionItemJSON } from './JSON';\n\n/**\n * The `BillingSubscriptionItem` object is similar to the [`BillingSubscriptionItemResource`](/docs/references/javascript/types/commerce-subscription-item-resource) object as it holds information about a subscription item, as well as methods for managing it. However, the `BillingSubscriptionItem` object is different in that it is used in the [Backend API](https://clerk.com/docs/reference/backend-api/tag/commerce/get/commerce/subscription_items) and is not directly accessible from the Frontend API.\n *\n * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes.\n */\nexport class BillingSubscriptionItem {\n constructor(\n /**\n * The unique identifier for the subscription item.\n */\n readonly id: string,\n /**\n * The status of the subscription item.\n */\n readonly status: BillingSubscriptionItemJSON['status'],\n /**\n * The plan period for the subscription item.\n */\n readonly planPeriod: 'month' | 'annual',\n /**\n * Unix timestamp (milliseconds) of when the current period starts.\n */\n readonly periodStart: number,\n /**\n * The next payment information.\n */\n readonly nextPayment: {\n /**\n * The amount of the next payment.\n */\n amount: number;\n /**\n * Unix timestamp (milliseconds) of when the next payment is scheduled.\n */\n date: number;\n } | null,\n /**\n * The current amount for the subscription item.\n */\n readonly amount: BillingMoneyAmount | null | undefined,\n /**\n * The plan associated with this subscription item.\n */\n readonly plan: BillingPlan,\n /**\n * The plan ID.\n */\n readonly planId: string,\n /**\n * Unix timestamp (milliseconds) of when the subscription item was created.\n */\n readonly createdAt: number,\n /**\n * Unix timestamp (milliseconds) of when the subscription item was last updated.\n */\n readonly updatedAt: number,\n /**\n * Unix timestamp (milliseconds) of when the current period ends.\n */\n readonly periodEnd: number | null,\n /**\n * Unix timestamp (milliseconds) of when the subscription item was canceled.\n */\n readonly canceledAt: number | null,\n /**\n * Unix timestamp (milliseconds) of when the subscription item became past due.\n */\n readonly pastDueAt: number | null,\n /**\n * Unix timestamp (milliseconds) of when the subscription item ended.\n */\n readonly endedAt: number | null,\n /**\n * The payer ID.\n */\n readonly payerId: string,\n /**\n * Whether this subscription item is currently in a free trial period.\n */\n readonly isFreeTrial?: boolean,\n /**\n * The lifetime amount paid for this subscription item.\n */\n readonly lifetimePaid?: BillingMoneyAmount | null,\n ) {}\n\n static fromJSON(data: BillingSubscriptionItemJSON): BillingSubscriptionItem {\n function formatAmountJSON(\n amount: BillingMoneyAmountJSON | null | undefined,\n ): BillingMoneyAmount | null | undefined {\n if (!amount) {\n return amount;\n }\n\n return {\n amount: amount.amount,\n amountFormatted: amount.amount_formatted,\n currency: amount.currency,\n currencySymbol: amount.currency_symbol,\n };\n }\n\n return new BillingSubscriptionItem(\n data.id,\n data.status,\n data.plan_period,\n data.period_start,\n data.next_payment,\n formatAmountJSON(data.amount),\n BillingPlan.fromJSON(data.plan),\n data.plan_id,\n data.created_at,\n data.updated_at,\n data.period_end,\n data.canceled_at,\n data.past_due_at,\n data.ended_at,\n data.payer_id,\n data.is_free_trial,\n formatAmountJSON(data.lifetime_paid),\n );\n }\n}\n","import type { BillingMoneyAmount } from '@clerk/types';\n\nimport { BillingSubscriptionItem } from './CommerceSubscriptionItem';\nimport type { BillingSubscriptionJSON } from './JSON';\n\n/**\n * The `BillingSubscription` object is similar to the [`BillingSubscriptionResource`](/docs/references/javascript/types/commerce-subscription-resource) object as it holds information about a subscription, as well as methods for managing it. However, the `BillingSubscription` object is different in that it is used in the [Backend API](https://clerk.com/docs/reference/backend-api/tag/billing/get/organizations/%7Borganization_id%7D/billing/subscription) and is not directly accessible from the Frontend API.\n *\n * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes.\n */\nexport class BillingSubscription {\n constructor(\n /**\n * The unique identifier for the billing subscription.\n */\n readonly id: string,\n /**\n * The current status of the subscription.\n */\n readonly status: BillingSubscriptionJSON['status'],\n /**\n * The ID of the payer for this subscription.\n */\n readonly payerId: string,\n /**\n * Unix timestamp (milliseconds) of when the subscription was created.\n */\n readonly createdAt: number,\n /**\n * Unix timestamp (milliseconds) of when the subscription was last updated.\n */\n readonly updatedAt: number,\n /**\n * Unix timestamp (milliseconds) of when the subscription became active.\n */\n readonly activeAt: number | null,\n /**\n * Unix timestamp (milliseconds) of when the subscription became past due.\n */\n readonly pastDueAt: number | null,\n /**\n * Array of subscription items in this subscription.\n */\n readonly subscriptionItems: BillingSubscriptionItem[],\n /**\n * Information about the next scheduled payment.\n */\n readonly nextPayment: { date: number; amount: BillingMoneyAmount } | null,\n /**\n * Whether the payer is eligible for a free trial.\n */\n readonly eligibleForFreeTrial: boolean,\n ) {}\n\n static fromJSON(data: BillingSubscriptionJSON): BillingSubscription {\n const nextPayment = data.next_payment\n ? {\n date: data.next_payment.date,\n amount: {\n amount: data.next_payment.amount.amount,\n amountFormatted: data.next_payment.amount.amount_formatted,\n currency: data.next_payment.amount.currency,\n currencySymbol: data.next_payment.amount.currency_symbol,\n },\n }\n : null;\n\n return new BillingSubscription(\n data.id,\n data.status,\n data.payer_id,\n data.created_at,\n data.updated_at,\n data.active_at ?? null,\n data.past_due_at ?? null,\n data.subscription_items.map(item => BillingSubscriptionItem.fromJSON(item)),\n nextPayment,\n data.eligible_for_free_trial ?? false,\n );\n }\n}\n","import {\n ActorToken,\n AllowlistIdentifier,\n APIKey,\n BlocklistIdentifier,\n Client,\n Cookies,\n DeletedObject,\n Domain,\n Email,\n EmailAddress,\n IdPOAuthAccessToken,\n Instance,\n InstanceRestrictions,\n InstanceSettings,\n Invitation,\n JwtTemplate,\n M2MToken,\n Machine,\n MachineScope,\n MachineSecretKey,\n OauthAccessToken,\n OAuthApplication,\n Organization,\n OrganizationInvitation,\n OrganizationMembership,\n OrganizationSettings,\n PhoneNumber,\n ProxyCheck,\n RedirectUrl,\n SamlConnection,\n Session,\n SignInToken,\n SignUpAttempt,\n SMSMessage,\n Token,\n User,\n} from '.';\nimport { AccountlessApplication } from './AccountlessApplication';\nimport { BillingPlan } from './CommercePlan';\nimport { BillingSubscription } from './CommerceSubscription';\nimport { BillingSubscriptionItem } from './CommerceSubscriptionItem';\nimport { Feature } from './Feature';\nimport type { PaginatedResponseJSON } from './JSON';\nimport { ObjectType } from './JSON';\nimport { WaitlistEntry } from './WaitlistEntry';\n\ntype ResourceResponse = {\n /**\n * An array that contains the fetched data.\n */\n data: T;\n};\n\n/**\n * An interface that describes the response of a method that returns a paginated list of resources.\n *\n * If the promise resolves, you will get back the [properties](#properties) listed below. `data` will be an array of the resource type you requested. You can use the `totalCount` property to determine how many total items exist remotely.\n *\n * Some methods that return this type allow pagination with the `limit` and `offset` parameters, in which case the first 10 items will be returned by default. For methods such as [`getAllowlistIdentifierList()`](https://clerk.com/docs/references/backend/allowlist/get-allowlist-identifier-list), which do not take a `limit` or `offset`, all items will be returned.\n *\n * If the promise is rejected, you will receive a `ClerkAPIResponseError` or network error.\n *\n * @interface\n */\nexport type PaginatedResourceResponse = ResourceResponse & {\n /**\n * The total count of data that exist remotely.\n */\n totalCount: number;\n};\n\nexport function deserialize(payload: unknown): PaginatedResourceResponse | ResourceResponse {\n let data, totalCount: number | undefined;\n\n if (Array.isArray(payload)) {\n const data = payload.map(item => jsonToObject(item)) as U;\n return { data };\n } else if (isPaginated(payload)) {\n data = payload.data.map(item => jsonToObject(item)) as U;\n totalCount = payload.total_count;\n\n return { data, totalCount };\n } else {\n return { data: jsonToObject(payload) };\n }\n}\n\nfunction isPaginated(payload: unknown): payload is PaginatedResponseJSON {\n if (!payload || typeof payload !== 'object' || !('data' in payload)) {\n return false;\n }\n\n return Array.isArray(payload.data) && payload.data !== undefined;\n}\n\nfunction getCount(item: PaginatedResponseJSON) {\n return item.total_count;\n}\n\n// TODO: Revise response deserialization\nfunction jsonToObject(item: any): any {\n // Special case: DeletedObject\n // TODO: Improve this check\n if (typeof item !== 'string' && 'object' in item && 'deleted' in item) {\n return DeletedObject.fromJSON(item);\n }\n\n switch (item.object) {\n case ObjectType.AccountlessApplication:\n return AccountlessApplication.fromJSON(item);\n case ObjectType.ActorToken:\n return ActorToken.fromJSON(item);\n case ObjectType.AllowlistIdentifier:\n return AllowlistIdentifier.fromJSON(item);\n case ObjectType.ApiKey:\n return APIKey.fromJSON(item);\n case ObjectType.BlocklistIdentifier:\n return BlocklistIdentifier.fromJSON(item);\n case ObjectType.Client:\n return Client.fromJSON(item);\n case ObjectType.Cookies:\n return Cookies.fromJSON(item);\n case ObjectType.Domain:\n return Domain.fromJSON(item);\n case ObjectType.EmailAddress:\n return EmailAddress.fromJSON(item);\n case ObjectType.Email:\n return Email.fromJSON(item);\n case ObjectType.IdpOAuthAccessToken:\n return IdPOAuthAccessToken.fromJSON(item);\n case ObjectType.Instance:\n return Instance.fromJSON(item);\n case ObjectType.InstanceRestrictions:\n return InstanceRestrictions.fromJSON(item);\n case ObjectType.InstanceSettings:\n return InstanceSettings.fromJSON(item);\n case ObjectType.Invitation:\n return Invitation.fromJSON(item);\n case ObjectType.JwtTemplate:\n return JwtTemplate.fromJSON(item);\n case ObjectType.Machine:\n return Machine.fromJSON(item);\n case ObjectType.MachineScope:\n return MachineScope.fromJSON(item);\n case ObjectType.MachineSecretKey:\n return MachineSecretKey.fromJSON(item);\n case ObjectType.M2MToken:\n return M2MToken.fromJSON(item);\n case ObjectType.OauthAccessToken:\n return OauthAccessToken.fromJSON(item);\n case ObjectType.OAuthApplication:\n return OAuthApplication.fromJSON(item);\n case ObjectType.Organization:\n return Organization.fromJSON(item);\n case ObjectType.OrganizationInvitation:\n return OrganizationInvitation.fromJSON(item);\n case ObjectType.OrganizationMembership:\n return OrganizationMembership.fromJSON(item);\n case ObjectType.OrganizationSettings:\n return OrganizationSettings.fromJSON(item);\n case ObjectType.PhoneNumber:\n return PhoneNumber.fromJSON(item);\n case ObjectType.ProxyCheck:\n return ProxyCheck.fromJSON(item);\n case ObjectType.RedirectUrl:\n return RedirectUrl.fromJSON(item);\n case ObjectType.SamlConnection:\n return SamlConnection.fromJSON(item);\n case ObjectType.SignInToken:\n return SignInToken.fromJSON(item);\n case ObjectType.SignUpAttempt:\n return SignUpAttempt.fromJSON(item);\n case ObjectType.Session:\n return Session.fromJSON(item);\n case ObjectType.SmsMessage:\n return SMSMessage.fromJSON(item);\n case ObjectType.Token:\n return Token.fromJSON(item);\n case ObjectType.TotalCount:\n return getCount(item);\n case ObjectType.User:\n return User.fromJSON(item);\n case ObjectType.WaitlistEntry:\n return WaitlistEntry.fromJSON(item);\n case ObjectType.BillingPlan:\n return BillingPlan.fromJSON(item);\n case ObjectType.BillingSubscription:\n return BillingSubscription.fromJSON(item);\n case ObjectType.BillingSubscriptionItem:\n return BillingSubscriptionItem.fromJSON(item);\n case ObjectType.Feature:\n return Feature.fromJSON(item);\n default:\n return item;\n }\n}\n","import {\n AccountlessApplicationAPI,\n ActorTokenAPI,\n AllowlistIdentifierAPI,\n APIKeysAPI,\n BetaFeaturesAPI,\n BlocklistIdentifierAPI,\n ClientAPI,\n DomainAPI,\n EmailAddressAPI,\n IdPOAuthAccessTokenApi,\n InstanceAPI,\n InvitationAPI,\n JwksAPI,\n JwtTemplatesApi,\n M2MTokenApi,\n MachineApi,\n OAuthApplicationsApi,\n OrganizationAPI,\n PhoneNumberAPI,\n ProxyCheckAPI,\n RedirectUrlAPI,\n SamlConnectionAPI,\n SessionAPI,\n SignInTokenAPI,\n SignUpAPI,\n TestingTokenAPI,\n UserAPI,\n WaitlistEntryAPI,\n WebhookAPI,\n} from './endpoints';\nimport { BillingAPI } from './endpoints/BillingApi';\nimport { buildRequest } from './request';\n\nexport type CreateBackendApiOptions = Parameters[0];\n\nexport type ApiClient = ReturnType;\n\nexport function createBackendApiClient(options: CreateBackendApiOptions) {\n const request = buildRequest(options);\n\n return {\n __experimental_accountlessApplications: new AccountlessApplicationAPI(\n buildRequest({ ...options, requireSecretKey: false }),\n ),\n actorTokens: new ActorTokenAPI(request),\n allowlistIdentifiers: new AllowlistIdentifierAPI(request),\n apiKeys: new APIKeysAPI(\n buildRequest({\n ...options,\n skipApiVersionInUrl: true,\n }),\n ),\n betaFeatures: new BetaFeaturesAPI(request),\n blocklistIdentifiers: new BlocklistIdentifierAPI(request),\n /**\n * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes.\n */\n billing: new BillingAPI(request),\n clients: new ClientAPI(request),\n domains: new DomainAPI(request),\n emailAddresses: new EmailAddressAPI(request),\n idPOAuthAccessToken: new IdPOAuthAccessTokenApi(\n buildRequest({\n ...options,\n skipApiVersionInUrl: true,\n }),\n ),\n instance: new InstanceAPI(request),\n invitations: new InvitationAPI(request),\n jwks: new JwksAPI(request),\n jwtTemplates: new JwtTemplatesApi(request),\n machines: new MachineApi(request),\n m2m: new M2MTokenApi(\n buildRequest({\n ...options,\n skipApiVersionInUrl: true,\n requireSecretKey: false,\n useMachineSecretKey: true,\n }),\n ),\n oauthApplications: new OAuthApplicationsApi(request),\n organizations: new OrganizationAPI(request),\n phoneNumbers: new PhoneNumberAPI(request),\n proxyChecks: new ProxyCheckAPI(request),\n redirectUrls: new RedirectUrlAPI(request),\n samlConnections: new SamlConnectionAPI(request),\n sessions: new SessionAPI(request),\n signInTokens: new SignInTokenAPI(request),\n signUps: new SignUpAPI(request),\n testingTokens: new TestingTokenAPI(request),\n users: new UserAPI(request),\n waitlistEntries: new WaitlistEntryAPI(request),\n webhooks: new WebhookAPI(request),\n };\n}\n","import type { AuthenticateRequestOptions } from '../tokens/types';\nimport type { MachineTokenType } from './tokenTypes';\nimport { TokenType } from './tokenTypes';\n\nexport const M2M_TOKEN_PREFIX = 'mt_';\nexport const OAUTH_TOKEN_PREFIX = 'oat_';\nexport const API_KEY_PREFIX = 'ak_';\n\nconst MACHINE_TOKEN_PREFIXES = [M2M_TOKEN_PREFIX, OAUTH_TOKEN_PREFIX, API_KEY_PREFIX] as const;\n\n/**\n * Checks if a token is a machine token by looking at its prefix.\n *\n * @remarks\n * In the future, this will support custom prefixes that can be prepended to the base prefixes\n * (e.g. \"org_a_m2m_\", \"org_a_oauth_access_\", \"org_a_api_key_\")\n *\n * @param token - The token string to check\n * @returns true if the token starts with a recognized machine token prefix\n */\nexport function isMachineTokenByPrefix(token: string): boolean {\n return MACHINE_TOKEN_PREFIXES.some(prefix => token.startsWith(prefix));\n}\n\n/**\n * Gets the specific type of machine token based on its prefix.\n *\n * @remarks\n * In the future, this will support custom prefixes that can be prepended to the base prefixes\n * (e.g. \"org_a_m2m_\", \"org_a_oauth_access_\", \"org_a_api_key_\")\n *\n * @param token - The token string to check\n * @returns The specific MachineTokenType\n * @throws Error if the token doesn't match any known machine token prefix\n */\nexport function getMachineTokenType(token: string): MachineTokenType {\n if (token.startsWith(M2M_TOKEN_PREFIX)) {\n return TokenType.M2MToken;\n }\n\n if (token.startsWith(OAUTH_TOKEN_PREFIX)) {\n return TokenType.OAuthToken;\n }\n\n if (token.startsWith(API_KEY_PREFIX)) {\n return TokenType.ApiKey;\n }\n\n throw new Error('Unknown machine token type');\n}\n\n/**\n * Check if a token type is accepted given a requested token type or list of token types.\n *\n * @param tokenType - The token type to check (can be null if the token is invalid)\n * @param acceptsToken - The requested token type or list of token types\n * @returns true if the token type is accepted\n */\nexport const isTokenTypeAccepted = (\n tokenType: TokenType | null,\n acceptsToken: NonNullable,\n): boolean => {\n if (!tokenType) {\n return false;\n }\n\n if (acceptsToken === 'any') {\n return true;\n }\n\n const tokenTypes = Array.isArray(acceptsToken) ? acceptsToken : [acceptsToken];\n return tokenTypes.includes(tokenType);\n};\n\n/**\n * Checks if a token type string is a machine token type (api_key, m2m_token, or oauth_token).\n *\n * @param type - The token type string to check\n * @returns true if the type is a machine token type\n */\nexport function isMachineTokenType(type: string): type is MachineTokenType {\n return type === TokenType.ApiKey || type === TokenType.M2MToken || type === TokenType.OAuthToken;\n}\n","import type { JwtPayload, PendingSessionOptions } from '@clerk/types';\n\nimport { constants } from '../constants';\nimport type { TokenVerificationErrorReason } from '../errors';\nimport type { AuthenticateContext } from './authenticateContext';\nimport type {\n AuthenticatedMachineObject,\n InvalidTokenAuthObject,\n SignedInAuthObject,\n SignedOutAuthObject,\n UnauthenticatedMachineObject,\n} from './authObjects';\nimport {\n authenticatedMachineObject,\n invalidTokenAuthObject,\n signedInAuthObject,\n signedOutAuthObject,\n unauthenticatedMachineObject,\n} from './authObjects';\nimport type { MachineTokenType, SessionTokenType } from './tokenTypes';\nimport { TokenType } from './tokenTypes';\nimport type { MachineAuthType } from './types';\n\nexport const AuthStatus = {\n SignedIn: 'signed-in',\n SignedOut: 'signed-out',\n Handshake: 'handshake',\n} as const;\n\nexport type AuthStatus = (typeof AuthStatus)[keyof typeof AuthStatus];\n\ntype ToAuth = T extends null\n ? () => InvalidTokenAuthObject\n : T extends SessionTokenType\n ? Authenticated extends true\n ? (opts?: PendingSessionOptions) => SignedInAuthObject\n : () => SignedOutAuthObject\n : Authenticated extends true\n ? () => AuthenticatedMachineObject>\n : () => UnauthenticatedMachineObject>;\n\nexport type AuthenticatedState = {\n status: typeof AuthStatus.SignedIn;\n reason: null;\n message: null;\n proxyUrl?: string;\n publishableKey: string;\n isSatellite: boolean;\n domain: string;\n signInUrl: string;\n signUpUrl: string;\n afterSignInUrl: string;\n afterSignUpUrl: string;\n /**\n * @deprecated Use `isAuthenticated` instead.\n */\n isSignedIn: true;\n isAuthenticated: true;\n headers: Headers;\n token: string;\n tokenType: T;\n toAuth: ToAuth;\n};\n\nexport type UnauthenticatedState = {\n status: typeof AuthStatus.SignedOut;\n reason: AuthReason;\n message: string;\n proxyUrl?: string;\n publishableKey: string;\n isSatellite: boolean;\n domain: string;\n signInUrl: string;\n signUpUrl: string;\n afterSignInUrl: string;\n afterSignUpUrl: string;\n /**\n * @deprecated Use `isAuthenticated` instead.\n */\n isSignedIn: false;\n isAuthenticated: false;\n tokenType: T;\n headers: Headers;\n token: null;\n toAuth: ToAuth;\n};\n\nexport type HandshakeState = Omit, 'status' | 'toAuth' | 'tokenType'> & {\n tokenType: SessionTokenType;\n status: typeof AuthStatus.Handshake;\n headers: Headers;\n toAuth: () => null;\n};\n\n/**\n * @deprecated Use AuthenticatedState instead\n */\nexport type SignedInState = AuthenticatedState;\n\n/**\n * @deprecated Use UnauthenticatedState instead\n */\nexport type SignedOutState = UnauthenticatedState;\n\nexport const AuthErrorReason = {\n ClientUATWithoutSessionToken: 'client-uat-but-no-session-token',\n DevBrowserMissing: 'dev-browser-missing',\n DevBrowserSync: 'dev-browser-sync',\n PrimaryRespondsToSyncing: 'primary-responds-to-syncing',\n PrimaryDomainCrossOriginSync: 'primary-domain-cross-origin-sync',\n SatelliteCookieNeedsSyncing: 'satellite-needs-syncing',\n SessionTokenAndUATMissing: 'session-token-and-uat-missing',\n SessionTokenMissing: 'session-token-missing',\n SessionTokenExpired: 'session-token-expired',\n SessionTokenIATBeforeClientUAT: 'session-token-iat-before-client-uat',\n SessionTokenNBF: 'session-token-nbf',\n SessionTokenIatInTheFuture: 'session-token-iat-in-the-future',\n SessionTokenWithoutClientUAT: 'session-token-but-no-client-uat',\n ActiveOrganizationMismatch: 'active-organization-mismatch',\n TokenTypeMismatch: 'token-type-mismatch',\n UnexpectedError: 'unexpected-error',\n} as const;\n\nexport type AuthErrorReason = (typeof AuthErrorReason)[keyof typeof AuthErrorReason];\n\nexport type AuthReason = AuthErrorReason | TokenVerificationErrorReason;\n\nexport type RequestState =\n | AuthenticatedState\n | UnauthenticatedState\n | (T extends SessionTokenType ? HandshakeState : never);\n\ntype BaseSignedInParams = {\n authenticateContext: AuthenticateContext;\n headers?: Headers;\n token: string;\n tokenType: TokenType;\n};\n\ntype SignedInParams =\n | (BaseSignedInParams & { tokenType: SessionTokenType; sessionClaims: JwtPayload })\n | (BaseSignedInParams & { tokenType: MachineTokenType; machineData: MachineAuthType });\n\nexport function signedIn(params: SignedInParams & { tokenType: T }): AuthenticatedState {\n const { authenticateContext, headers = new Headers(), token } = params;\n\n const toAuth = (({ treatPendingAsSignedOut = true } = {}) => {\n if (params.tokenType === TokenType.SessionToken) {\n const { sessionClaims } = params as { sessionClaims: JwtPayload };\n const authObject = signedInAuthObject(authenticateContext, token, sessionClaims);\n\n if (treatPendingAsSignedOut && authObject.sessionStatus === 'pending') {\n return signedOutAuthObject(undefined, authObject.sessionStatus);\n }\n\n return authObject;\n }\n\n const { machineData } = params as { machineData: MachineAuthType };\n return authenticatedMachineObject(params.tokenType, token, machineData, authenticateContext);\n }) as ToAuth;\n\n return {\n status: AuthStatus.SignedIn,\n reason: null,\n message: null,\n proxyUrl: authenticateContext.proxyUrl || '',\n publishableKey: authenticateContext.publishableKey || '',\n isSatellite: authenticateContext.isSatellite || false,\n domain: authenticateContext.domain || '',\n signInUrl: authenticateContext.signInUrl || '',\n signUpUrl: authenticateContext.signUpUrl || '',\n afterSignInUrl: authenticateContext.afterSignInUrl || '',\n afterSignUpUrl: authenticateContext.afterSignUpUrl || '',\n isSignedIn: true,\n isAuthenticated: true,\n tokenType: params.tokenType,\n toAuth,\n headers,\n token,\n };\n}\n\ntype SignedOutParams = Omit & {\n reason: AuthReason;\n message?: string;\n};\n\nexport function signedOut(params: SignedOutParams & { tokenType: T }): UnauthenticatedState {\n const { authenticateContext, headers = new Headers(), reason, message = '', tokenType } = params;\n\n const toAuth = (() => {\n if (tokenType === TokenType.SessionToken) {\n return signedOutAuthObject({ ...authenticateContext, status: AuthStatus.SignedOut, reason, message });\n }\n\n return unauthenticatedMachineObject(tokenType, { reason, message, headers });\n }) as ToAuth;\n\n return withDebugHeaders({\n status: AuthStatus.SignedOut,\n reason,\n message,\n proxyUrl: authenticateContext.proxyUrl || '',\n publishableKey: authenticateContext.publishableKey || '',\n isSatellite: authenticateContext.isSatellite || false,\n domain: authenticateContext.domain || '',\n signInUrl: authenticateContext.signInUrl || '',\n signUpUrl: authenticateContext.signUpUrl || '',\n afterSignInUrl: authenticateContext.afterSignInUrl || '',\n afterSignUpUrl: authenticateContext.afterSignUpUrl || '',\n isSignedIn: false,\n isAuthenticated: false,\n tokenType,\n toAuth,\n headers,\n token: null,\n });\n}\n\nexport function handshake(\n authenticateContext: AuthenticateContext,\n reason: AuthReason,\n message = '',\n headers: Headers,\n): HandshakeState {\n return withDebugHeaders({\n status: AuthStatus.Handshake,\n reason,\n message,\n publishableKey: authenticateContext.publishableKey || '',\n isSatellite: authenticateContext.isSatellite || false,\n domain: authenticateContext.domain || '',\n proxyUrl: authenticateContext.proxyUrl || '',\n signInUrl: authenticateContext.signInUrl || '',\n signUpUrl: authenticateContext.signUpUrl || '',\n afterSignInUrl: authenticateContext.afterSignInUrl || '',\n afterSignUpUrl: authenticateContext.afterSignUpUrl || '',\n isSignedIn: false,\n isAuthenticated: false,\n tokenType: TokenType.SessionToken,\n toAuth: () => null,\n headers,\n token: null,\n });\n}\n\nexport function signedOutInvalidToken(): UnauthenticatedState {\n const authObject = invalidTokenAuthObject();\n return withDebugHeaders({\n status: AuthStatus.SignedOut,\n reason: AuthErrorReason.TokenTypeMismatch,\n message: '',\n proxyUrl: '',\n publishableKey: '',\n isSatellite: false,\n domain: '',\n signInUrl: '',\n signUpUrl: '',\n afterSignInUrl: '',\n afterSignUpUrl: '',\n isSignedIn: false,\n isAuthenticated: false,\n tokenType: null,\n toAuth: () => authObject,\n headers: new Headers(),\n token: null,\n });\n}\n\nconst withDebugHeaders = (\n requestState: T,\n): T => {\n const headers = new Headers(requestState.headers || {});\n\n if (requestState.message) {\n try {\n headers.set(constants.Headers.AuthMessage, requestState.message);\n } catch {\n // headers.set can throw if unicode strings are passed to it. In this case, simply do nothing\n }\n }\n\n if (requestState.reason) {\n try {\n headers.set(constants.Headers.AuthReason, requestState.reason);\n } catch {\n /* empty */\n }\n }\n\n if (requestState.status) {\n try {\n headers.set(constants.Headers.AuthStatus, requestState.status);\n } catch {\n /* empty */\n }\n }\n\n requestState.headers = headers;\n\n return requestState;\n};\n","import { parse } from 'cookie';\n\nimport { constants } from '../constants';\nimport type { ClerkUrl } from './clerkUrl';\nimport { createClerkUrl } from './clerkUrl';\n\n/**\n * A class that extends the native Request class,\n * adds cookies helpers and a normalised clerkUrl that is constructed by using the values found\n * in req.headers so it is able to work reliably when the app is running behind a proxy server.\n */\nclass ClerkRequest extends Request {\n readonly clerkUrl: ClerkUrl;\n readonly cookies: Map;\n\n public constructor(input: ClerkRequest | Request | RequestInfo, init?: RequestInit) {\n // The usual way to duplicate a request object is to\n // pass the original request object to the Request constructor\n // both as the `input` and `init` parameters, eg: super(req, req)\n // However, this fails in certain environments like Vercel Edge Runtime\n // when a framework like Remix polyfills the global Request object.\n // This happens because `undici` performs the following instanceof check\n // which, instead of testing against the global Request object, tests against\n // the Request class defined in the same file (local Request class).\n // For more details, please refer to:\n // https://github.com/nodejs/undici/issues/2155\n // https://github.com/nodejs/undici/blob/7153a1c78d51840bbe16576ce353e481c3934701/lib/fetch/request.js#L854\n const url = typeof input !== 'string' && 'url' in input ? input.url : String(input);\n super(url, init || typeof input === 'string' ? undefined : input);\n this.clerkUrl = this.deriveUrlFromHeaders(this);\n this.cookies = this.parseCookies(this);\n }\n\n public toJSON() {\n return {\n url: this.clerkUrl.href,\n method: this.method,\n headers: JSON.stringify(Object.fromEntries(this.headers)),\n clerkUrl: this.clerkUrl.toString(),\n cookies: JSON.stringify(Object.fromEntries(this.cookies)),\n };\n }\n\n /**\n * Used to fix request.url using the x-forwarded-* headers\n * TODO add detailed description of the issues this solves\n */\n private deriveUrlFromHeaders(req: Request) {\n const initialUrl = new URL(req.url);\n const forwardedProto = req.headers.get(constants.Headers.ForwardedProto);\n const forwardedHost = req.headers.get(constants.Headers.ForwardedHost);\n const host = req.headers.get(constants.Headers.Host);\n const protocol = initialUrl.protocol;\n\n const resolvedHost = this.getFirstValueFromHeader(forwardedHost) ?? host;\n const resolvedProtocol = this.getFirstValueFromHeader(forwardedProto) ?? protocol?.replace(/[:/]/, '');\n const origin = resolvedHost && resolvedProtocol ? `${resolvedProtocol}://${resolvedHost}` : initialUrl.origin;\n\n if (origin === initialUrl.origin) {\n return createClerkUrl(initialUrl);\n }\n return createClerkUrl(initialUrl.pathname + initialUrl.search, origin);\n }\n\n private getFirstValueFromHeader(value?: string | null) {\n return value?.split(',')[0];\n }\n\n private parseCookies(req: Request) {\n const cookiesRecord = parse(this.decodeCookieValue(req.headers.get('cookie') || ''));\n return new Map(Object.entries(cookiesRecord));\n }\n\n private decodeCookieValue(str: string) {\n return str ? str.replace(/(%[0-9A-Z]{2})+/g, decodeURIComponent) : str;\n }\n}\n\nexport const createClerkRequest = (...args: ConstructorParameters): ClerkRequest => {\n return args[0] instanceof ClerkRequest ? args[0] : new ClerkRequest(...args);\n};\n\nexport type { ClerkRequest };\n","class ClerkUrl extends URL {\n public isCrossOrigin(other: URL | string) {\n return this.origin !== new URL(other.toString()).origin;\n }\n}\n\nexport type WithClerkUrl = T & {\n /**\n * When a NextJs app is hosted on a platform different from Vercel\n * or inside a container (Netlify, Fly.io, AWS Amplify, docker etc),\n * req.url is always set to `localhost:3000` instead of the actual host of the app.\n *\n * The `authMiddleware` uses the value of the available req.headers in order to construct\n * and use the correct url internally. This url is then exposed as `experimental_clerkUrl`,\n * intended to be used within `beforeAuth` and `afterAuth` if needed.\n */\n clerkUrl: ClerkUrl;\n};\n\nexport const createClerkUrl = (...args: ConstructorParameters): ClerkUrl => {\n return new ClerkUrl(...args);\n};\n\nexport type { ClerkUrl };\n","export const getCookieName = (cookieDirective: string): string => {\n return cookieDirective.split(';')[0]?.split('=')[0];\n};\n\nexport const getCookieValue = (cookieDirective: string): string => {\n return cookieDirective.split(';')[0]?.split('=')[1];\n};\n","import {\n API_URL,\n API_VERSION,\n MAX_CACHE_LAST_UPDATED_AT_SECONDS,\n SUPPORTED_BAPI_VERSION,\n USER_AGENT,\n} from '../constants';\nimport {\n TokenVerificationError,\n TokenVerificationErrorAction,\n TokenVerificationErrorCode,\n TokenVerificationErrorReason,\n} from '../errors';\nimport { runtime } from '../runtime';\nimport { joinPaths } from '../util/path';\nimport { retry } from '../util/shared';\n\ntype JsonWebKeyWithKid = JsonWebKey & { kid: string };\n\ntype JsonWebKeyCache = Record;\n\nlet cache: JsonWebKeyCache = {};\nlet lastUpdatedAt = 0;\n\nfunction getFromCache(kid: string) {\n return cache[kid];\n}\n\nfunction getCacheValues() {\n return Object.values(cache);\n}\n\nfunction setInCache(jwk: JsonWebKeyWithKid, shouldExpire = true) {\n cache[jwk.kid] = jwk;\n lastUpdatedAt = shouldExpire ? Date.now() : -1;\n}\n\nconst LocalJwkKid = 'local';\nconst PEM_HEADER = '-----BEGIN PUBLIC KEY-----';\nconst PEM_TRAILER = '-----END PUBLIC KEY-----';\nconst RSA_PREFIX = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA';\nconst RSA_SUFFIX = 'IDAQAB';\n\n/**\n *\n * Loads a local PEM key usually from process.env and transform it to JsonWebKey format.\n * The result is also cached on the module level to avoid unnecessary computations in subsequent invocations.\n *\n * @param {string} localKey\n * @returns {JsonWebKey} key\n */\nexport function loadClerkJWKFromLocal(localKey?: string): JsonWebKey {\n if (!getFromCache(LocalJwkKid)) {\n if (!localKey) {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.SetClerkJWTKey,\n message: 'Missing local JWK.',\n reason: TokenVerificationErrorReason.LocalJWKMissing,\n });\n }\n\n const modulus = localKey\n .replace(/\\r\\n|\\n|\\r/g, '')\n .replace(PEM_HEADER, '')\n .replace(PEM_TRAILER, '')\n .replace(RSA_PREFIX, '')\n .replace(RSA_SUFFIX, '')\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_');\n\n // JWK https://datatracker.ietf.org/doc/html/rfc7517\n setInCache(\n {\n kid: 'local',\n kty: 'RSA',\n alg: 'RS256',\n n: modulus,\n e: 'AQAB',\n },\n false, // local key never expires in cache\n );\n }\n\n return getFromCache(LocalJwkKid);\n}\n\n/**\n * @internal\n */\nexport type LoadClerkJWKFromRemoteOptions = {\n /**\n * @internal\n */\n kid: string;\n /**\n * @deprecated This cache TTL will be removed in the next major version. Specifying a cache TTL is a no-op.\n */\n jwksCacheTtlInMs?: number;\n /**\n * A flag to ignore the JWKS cache and always fetch JWKS before each JWT verification.\n */\n skipJwksCache?: boolean;\n /**\n * The Clerk Secret Key from the [**API keys**](https://dashboard.clerk.com/last-active?path=api-keys) page in the Clerk Dashboard.\n */\n secretKey?: string;\n /**\n * The [Clerk Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }} endpoint.\n * @default 'https://api.clerk.com'\n */\n apiUrl?: string;\n /**\n * The version passed to the Clerk API.\n * @default 'v1'\n */\n apiVersion?: string;\n};\n\n/**\n *\n * Loads a key from JWKS retrieved from the well-known Frontend API endpoint of the issuer.\n * The result is also cached on the module level to avoid network requests in subsequent invocations.\n * The cache lasts up to 5 minutes.\n *\n * @param {Object} options\n * @param {string} options.kid - The id of the key that the JWT was signed with\n * @param {string} options.alg - The algorithm of the JWT\n * @returns {JsonWebKey} key\n */\nexport async function loadClerkJWKFromRemote({\n secretKey,\n apiUrl = API_URL,\n apiVersion = API_VERSION,\n kid,\n skipJwksCache,\n}: LoadClerkJWKFromRemoteOptions): Promise {\n if (skipJwksCache || cacheHasExpired() || !getFromCache(kid)) {\n if (!secretKey) {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.ContactSupport,\n message: 'Failed to load JWKS from Clerk Backend or Frontend API.',\n reason: TokenVerificationErrorReason.RemoteJWKFailedToLoad,\n });\n }\n const fetcher = () => fetchJWKSFromBAPI(apiUrl, secretKey, apiVersion) as Promise<{ keys: JsonWebKeyWithKid[] }>;\n const { keys } = await retry(fetcher);\n\n if (!keys || !keys.length) {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.ContactSupport,\n message: 'The JWKS endpoint did not contain any signing keys. Contact support@clerk.com.',\n reason: TokenVerificationErrorReason.RemoteJWKFailedToLoad,\n });\n }\n\n keys.forEach(key => setInCache(key));\n }\n\n const jwk = getFromCache(kid);\n\n if (!jwk) {\n const cacheValues = getCacheValues();\n const jwkKeys = cacheValues\n .map(jwk => jwk.kid)\n .sort()\n .join(', ');\n\n throw new TokenVerificationError({\n action: `Go to your Dashboard and validate your secret and public keys are correct. ${TokenVerificationErrorAction.ContactSupport} if the issue persists.`,\n message: `Unable to find a signing key in JWKS that matches the kid='${kid}' of the provided session token. Please make sure that the __session cookie or the HTTP authorization header contain a Clerk-generated session JWT. The following kid is available: ${jwkKeys}`,\n reason: TokenVerificationErrorReason.JWKKidMismatch,\n });\n }\n\n return jwk;\n}\n\nasync function fetchJWKSFromBAPI(apiUrl: string, key: string, apiVersion: string) {\n if (!key) {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.SetClerkSecretKey,\n message:\n 'Missing Clerk Secret Key or API Key. Go to https://dashboard.clerk.com and get your key for your instance.',\n reason: TokenVerificationErrorReason.RemoteJWKFailedToLoad,\n });\n }\n\n const url = new URL(apiUrl);\n url.pathname = joinPaths(url.pathname, apiVersion, '/jwks');\n\n const response = await runtime.fetch(url.href, {\n headers: {\n Authorization: `Bearer ${key}`,\n 'Clerk-API-Version': SUPPORTED_BAPI_VERSION,\n 'Content-Type': 'application/json',\n 'User-Agent': USER_AGENT,\n },\n });\n\n if (!response.ok) {\n const json = await response.json();\n const invalidSecretKeyError = getErrorObjectByCode(json?.errors, TokenVerificationErrorCode.InvalidSecretKey);\n\n if (invalidSecretKeyError) {\n const reason = TokenVerificationErrorReason.InvalidSecretKey;\n\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.ContactSupport,\n message: invalidSecretKeyError.message,\n reason,\n });\n }\n\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.ContactSupport,\n message: `Error loading Clerk JWKS from ${url.href} with code=${response.status}`,\n reason: TokenVerificationErrorReason.RemoteJWKFailedToLoad,\n });\n }\n\n return response.json();\n}\n\nfunction cacheHasExpired() {\n // If lastUpdatedAt is -1, it means that we're using a local JWKS and it never expires\n if (lastUpdatedAt === -1) {\n return false;\n }\n\n // If the cache has expired, clear the value so we don't attempt to make decisions based on stale data\n const isExpired = Date.now() - lastUpdatedAt >= MAX_CACHE_LAST_UPDATED_AT_SECONDS * 1000;\n\n if (isExpired) {\n cache = {};\n }\n\n return isExpired;\n}\n\ntype ErrorFields = {\n message: string;\n long_message: string;\n code: string;\n};\n\nconst getErrorObjectByCode = (errors: ErrorFields[], code: string) => {\n if (!errors) {\n return null;\n }\n\n return errors.find((err: ErrorFields) => err.code === code);\n};\n","import { isClerkAPIResponseError } from '@clerk/shared/error';\nimport type { JwtPayload } from '@clerk/types';\n\nimport type { APIKey, IdPOAuthAccessToken, M2MToken } from '../api';\nimport { createBackendApiClient } from '../api/factory';\nimport {\n MachineTokenVerificationError,\n MachineTokenVerificationErrorCode,\n TokenVerificationError,\n TokenVerificationErrorAction,\n TokenVerificationErrorReason,\n} from '../errors';\nimport type { VerifyJwtOptions } from '../jwt';\nimport type { JwtReturnType, MachineTokenReturnType } from '../jwt/types';\nimport { decodeJwt, verifyJwt } from '../jwt/verifyJwt';\nimport type { LoadClerkJWKFromRemoteOptions } from './keys';\nimport { loadClerkJWKFromLocal, loadClerkJWKFromRemote } from './keys';\nimport { API_KEY_PREFIX, M2M_TOKEN_PREFIX, OAUTH_TOKEN_PREFIX } from './machine';\nimport type { MachineTokenType } from './tokenTypes';\nimport { TokenType } from './tokenTypes';\n\n/**\n * @interface\n */\nexport type VerifyTokenOptions = Omit &\n Omit & {\n /**\n * Used to verify the session token in a networkless manner. Supply the PEM public key from the **[**API keys**](https://dashboard.clerk.com/last-active?path=api-keys) page -> Show JWT public key -> PEM Public Key** section in the Clerk Dashboard. **It's recommended to use [the environment variable](https://clerk.com/docs/deployments/clerk-environment-variables) instead.** For more information, refer to [Manual JWT verification](https://clerk.com/docs/backend-requests/manual-jwt).\n */\n jwtKey?: string;\n };\n\n/**\n * > [!WARNING]\n * > This is a lower-level method intended for more advanced use-cases. It's recommended to use [`authenticateRequest()`](https://clerk.com/docs/references/backend/authenticate-request), which fully authenticates a token passed from the `request` object.\n *\n * Verifies a Clerk-generated token signature. Networkless if the `jwtKey` is provided. Otherwise, performs a network call to retrieve the JWKS from the [Backend API](https://clerk.com/docs/reference/backend-api/tag/JWKS#operation/GetJWKS){{ target: '_blank' }}.\n *\n * @param token - The token to verify.\n * @param options - Options for verifying the token.\n *\n * @displayFunctionSignature\n *\n * @paramExtension\n *\n * ### `VerifyTokenOptions`\n *\n * It is recommended to set these options as [environment variables](/docs/deployments/clerk-environment-variables#api-and-sdk-configuration) where possible, and then pass them to the function. For example, you can set the `secretKey` option using the `CLERK_SECRET_KEY` environment variable, and then pass it to the function like this: `createClerkClient({ secretKey: process.env.CLERK_SECRET_KEY })`.\n *\n * > [!WARNING]\n * You must provide either `jwtKey` or `secretKey`.\n *\n * \n *\n * @example\n *\n * The following example demonstrates how to use the [JavaScript Backend SDK](https://clerk.com/docs/references/backend/overview) to verify the token signature.\n *\n * In the following example:\n *\n * 1. The **JWKS Public Key** from the Clerk Dashboard is set in the environment variable `CLERK_JWT_KEY`.\n * 1. The session token is retrieved from the `__session` cookie or the Authorization header.\n * 1. The token is verified in a networkless manner by passing the `jwtKey` prop.\n * 1. The `authorizedParties` prop is passed to verify that the session token is generated from the expected frontend application.\n * 1. If the token is valid, the response contains the verified token.\n *\n * ```ts\n * import { verifyToken } from '@clerk/backend'\n * import { cookies } from 'next/headers'\n *\n * export async function GET(request: Request) {\n * const cookieStore = cookies()\n * const sessToken = cookieStore.get('__session')?.value\n * const bearerToken = request.headers.get('Authorization')?.replace('Bearer ', '')\n * const token = sessToken || bearerToken\n *\n * if (!token) {\n * return Response.json({ error: 'Token not found. User must sign in.' }, { status: 401 })\n * }\n *\n * try {\n * const verifiedToken = await verifyToken(token, {\n * jwtKey: process.env.CLERK_JWT_KEY,\n * authorizedParties: ['http://localhost:3001', 'api.example.com'], // Replace with your authorized parties\n * })\n *\n * return Response.json({ verifiedToken })\n * } catch (error) {\n * return Response.json({ error: 'Token not verified.' }, { status: 401 })\n * }\n * }\n * ```\n *\n * If the token is valid, the response will contain a JSON object that looks something like this:\n *\n * ```json\n * {\n * \"verifiedToken\": {\n * \"azp\": \"http://localhost:3000\",\n * \"exp\": 1687906422,\n * \"iat\": 1687906362,\n * \"iss\": \"https://magical-marmoset-51.clerk.accounts.dev\",\n * \"nbf\": 1687906352,\n * \"sid\": \"sess_2Ro7e2IxrffdqBboq8KfB6eGbIy\",\n * \"sub\": \"user_2RfWKJREkjKbHZy0Wqa5qrHeAnb\"\n * }\n * }\n * ```\n */\nexport async function verifyToken(\n token: string,\n options: VerifyTokenOptions,\n): Promise> {\n const { data: decodedResult, errors } = decodeJwt(token);\n if (errors) {\n return { errors };\n }\n\n const { header } = decodedResult;\n const { kid } = header;\n\n try {\n let key;\n\n if (options.jwtKey) {\n key = loadClerkJWKFromLocal(options.jwtKey);\n } else if (options.secretKey) {\n // Fetch JWKS from Backend API using the key\n key = await loadClerkJWKFromRemote({ ...options, kid });\n } else {\n return {\n errors: [\n new TokenVerificationError({\n action: TokenVerificationErrorAction.SetClerkJWTKey,\n message: 'Failed to resolve JWK during verification.',\n reason: TokenVerificationErrorReason.JWKFailedToResolve,\n }),\n ],\n };\n }\n\n return await verifyJwt(token, { ...options, key });\n } catch (error) {\n return { errors: [error as TokenVerificationError] };\n }\n}\n\n/**\n * Handles errors from Clerk API responses for machine tokens\n * @param tokenType - The type of machine token\n * @param err - The error from the Clerk API\n * @param notFoundMessage - Custom message for 404 errors\n */\nfunction handleClerkAPIError(\n tokenType: MachineTokenType,\n err: any,\n notFoundMessage: string,\n): MachineTokenReturnType {\n if (isClerkAPIResponseError(err)) {\n let code: MachineTokenVerificationErrorCode;\n let message: string;\n\n switch (err.status) {\n case 401:\n code = MachineTokenVerificationErrorCode.InvalidSecretKey;\n message = err.errors[0]?.message || 'Invalid secret key';\n break;\n case 404:\n code = MachineTokenVerificationErrorCode.TokenInvalid;\n message = notFoundMessage;\n break;\n default:\n code = MachineTokenVerificationErrorCode.UnexpectedError;\n message = 'Unexpected error';\n }\n\n return {\n data: undefined,\n tokenType,\n errors: [\n new MachineTokenVerificationError({\n message,\n code,\n status: err.status,\n }),\n ],\n };\n }\n\n return {\n data: undefined,\n tokenType,\n errors: [\n new MachineTokenVerificationError({\n message: 'Unexpected error',\n code: MachineTokenVerificationErrorCode.UnexpectedError,\n status: err.status,\n }),\n ],\n };\n}\n\nasync function verifyM2MToken(\n token: string,\n options: VerifyTokenOptions & { machineSecretKey?: string },\n): Promise> {\n try {\n const client = createBackendApiClient(options);\n const verifiedToken = await client.m2m.verifyToken({ token });\n return { data: verifiedToken, tokenType: TokenType.M2MToken, errors: undefined };\n } catch (err: any) {\n return handleClerkAPIError(TokenType.M2MToken, err, 'Machine token not found');\n }\n}\n\nasync function verifyOAuthToken(\n accessToken: string,\n options: VerifyTokenOptions,\n): Promise> {\n try {\n const client = createBackendApiClient(options);\n const verifiedToken = await client.idPOAuthAccessToken.verifyAccessToken(accessToken);\n return { data: verifiedToken, tokenType: TokenType.OAuthToken, errors: undefined };\n } catch (err: any) {\n return handleClerkAPIError(TokenType.OAuthToken, err, 'OAuth token not found');\n }\n}\n\nasync function verifyAPIKey(\n secret: string,\n options: VerifyTokenOptions,\n): Promise> {\n try {\n const client = createBackendApiClient(options);\n const verifiedToken = await client.apiKeys.verifySecret(secret);\n return { data: verifiedToken, tokenType: TokenType.ApiKey, errors: undefined };\n } catch (err: any) {\n return handleClerkAPIError(TokenType.ApiKey, err, 'API key not found');\n }\n}\n\n/**\n * Verifies any type of machine token by detecting its type from the prefix.\n *\n * @param token - The token to verify (e.g. starts with \"m2m_\", \"oauth_\", \"api_key_\", etc.)\n * @param options - Options including secretKey for BAPI authorization\n */\nexport async function verifyMachineAuthToken(token: string, options: VerifyTokenOptions) {\n if (token.startsWith(M2M_TOKEN_PREFIX)) {\n return verifyM2MToken(token, options);\n }\n if (token.startsWith(OAUTH_TOKEN_PREFIX)) {\n return verifyOAuthToken(token, options);\n }\n if (token.startsWith(API_KEY_PREFIX)) {\n return verifyAPIKey(token, options);\n }\n\n throw new Error('Unknown machine token type');\n}\n","import { constants, SUPPORTED_BAPI_VERSION } from '../constants';\nimport { TokenVerificationError, TokenVerificationErrorAction, TokenVerificationErrorReason } from '../errors';\nimport type { VerifyJwtOptions } from '../jwt';\nimport { assertHeaderAlgorithm, assertHeaderType } from '../jwt/assertions';\nimport { decodeJwt, hasValidSignature } from '../jwt/verifyJwt';\nimport type { AuthenticateContext } from './authenticateContext';\nimport type { SignedInState, SignedOutState } from './authStatus';\nimport { AuthErrorReason, signedIn, signedOut } from './authStatus';\nimport { getCookieName, getCookieValue } from './cookie';\nimport { loadClerkJWKFromLocal, loadClerkJWKFromRemote } from './keys';\nimport type { OrganizationMatcher } from './organizationMatcher';\nimport { TokenType } from './tokenTypes';\nimport type { OrganizationSyncOptions, OrganizationSyncTarget } from './types';\nimport type { VerifyTokenOptions } from './verify';\nimport { verifyToken } from './verify';\n\nasync function verifyHandshakeJwt(token: string, { key }: VerifyJwtOptions): Promise<{ handshake: string[] }> {\n const { data: decoded, errors } = decodeJwt(token);\n if (errors) {\n throw errors[0];\n }\n\n const { header, payload } = decoded;\n\n // Header verifications\n const { typ, alg } = header;\n\n assertHeaderType(typ);\n assertHeaderAlgorithm(alg);\n\n const { data: signatureValid, errors: signatureErrors } = await hasValidSignature(decoded, key);\n if (signatureErrors) {\n throw new TokenVerificationError({\n reason: TokenVerificationErrorReason.TokenVerificationFailed,\n message: `Error verifying handshake token. ${signatureErrors[0]}`,\n });\n }\n\n if (!signatureValid) {\n throw new TokenVerificationError({\n reason: TokenVerificationErrorReason.TokenInvalidSignature,\n message: 'Handshake signature is invalid.',\n });\n }\n\n return payload as unknown as { handshake: string[] };\n}\n\n/**\n * Similar to our verifyToken flow for Clerk-issued JWTs, but this verification flow is for our signed handshake payload.\n * The handshake payload requires fewer verification steps.\n */\nexport async function verifyHandshakeToken(\n token: string,\n options: VerifyTokenOptions,\n): Promise<{ handshake: string[] }> {\n const { secretKey, apiUrl, apiVersion, jwksCacheTtlInMs, jwtKey, skipJwksCache } = options;\n\n const { data, errors } = decodeJwt(token);\n if (errors) {\n throw errors[0];\n }\n\n const { kid } = data.header;\n\n let key;\n\n if (jwtKey) {\n key = loadClerkJWKFromLocal(jwtKey);\n } else if (secretKey) {\n // Fetch JWKS from Backend API using the key\n key = await loadClerkJWKFromRemote({ secretKey, apiUrl, apiVersion, kid, jwksCacheTtlInMs, skipJwksCache });\n } else {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.SetClerkJWTKey,\n message: 'Failed to resolve JWK during handshake verification.',\n reason: TokenVerificationErrorReason.JWKFailedToResolve,\n });\n }\n\n return await verifyHandshakeJwt(token, {\n key,\n });\n}\n\nexport class HandshakeService {\n private readonly authenticateContext: AuthenticateContext;\n private readonly organizationMatcher: OrganizationMatcher;\n private readonly options: { organizationSyncOptions?: OrganizationSyncOptions };\n\n constructor(\n authenticateContext: AuthenticateContext,\n options: { organizationSyncOptions?: OrganizationSyncOptions },\n organizationMatcher: OrganizationMatcher,\n ) {\n this.authenticateContext = authenticateContext;\n this.options = options;\n this.organizationMatcher = organizationMatcher;\n }\n\n /**\n * Determines if a request is eligible for handshake based on its headers\n *\n * Currently, a request is only eligible for a handshake if we can say it's *probably* a request for a document, not a fetch or some other exotic request.\n * This heuristic should give us a reliable enough signal for browsers that support `Sec-Fetch-Dest` and for those that don't.\n *\n * @returns boolean indicating if the request is eligible for handshake\n */\n isRequestEligibleForHandshake(): boolean {\n const { accept, secFetchDest } = this.authenticateContext;\n\n // NOTE: we could also check sec-fetch-mode === navigate here, but according to the spec, sec-fetch-dest: document should indicate that the request is the data of a user navigation.\n // Also, we check for 'iframe' because it's the value set when a doc request is made by an iframe.\n if (secFetchDest === 'document' || secFetchDest === 'iframe') {\n return true;\n }\n\n if (!secFetchDest && accept?.startsWith('text/html')) {\n return true;\n }\n\n return false;\n }\n\n /**\n * Builds the redirect headers for a handshake request\n * @param reason - The reason for the handshake (e.g. 'session-token-expired')\n * @returns Headers object containing the Location header for redirect\n * @throws Error if clerkUrl is missing in authenticateContext\n */\n buildRedirectToHandshake(reason: string): Headers {\n if (!this.authenticateContext?.clerkUrl) {\n throw new Error('Missing clerkUrl in authenticateContext');\n }\n\n const redirectUrl = this.removeDevBrowserFromURL(this.authenticateContext.clerkUrl);\n\n let baseUrl = this.authenticateContext.frontendApi.startsWith('http')\n ? this.authenticateContext.frontendApi\n : `https://${this.authenticateContext.frontendApi}`;\n\n baseUrl = baseUrl.replace(/\\/+$/, '') + '/';\n\n const url = new URL('v1/client/handshake', baseUrl);\n url.searchParams.append('redirect_url', redirectUrl?.href || '');\n url.searchParams.append('__clerk_api_version', SUPPORTED_BAPI_VERSION);\n url.searchParams.append(\n constants.QueryParameters.SuffixedCookies,\n this.authenticateContext.usesSuffixedCookies().toString(),\n );\n url.searchParams.append(constants.QueryParameters.HandshakeReason, reason);\n url.searchParams.append(constants.QueryParameters.HandshakeFormat, 'nonce');\n\n if (this.authenticateContext.instanceType === 'development' && this.authenticateContext.devBrowserToken) {\n url.searchParams.append(constants.QueryParameters.DevBrowser, this.authenticateContext.devBrowserToken);\n }\n\n const toActivate = this.getOrganizationSyncTarget(this.authenticateContext.clerkUrl, this.organizationMatcher);\n if (toActivate) {\n const params = this.getOrganizationSyncQueryParams(toActivate);\n params.forEach((value, key) => {\n url.searchParams.append(key, value);\n });\n }\n\n return new Headers({ [constants.Headers.Location]: url.href });\n }\n\n /**\n * Gets cookies from either a handshake nonce or a handshake token\n * @returns Promise resolving to string array of cookie directives\n */\n public async getCookiesFromHandshake(): Promise {\n const cookiesToSet: string[] = [];\n\n if (this.authenticateContext.handshakeNonce) {\n try {\n const handshakePayload = await this.authenticateContext.apiClient?.clients.getHandshakePayload({\n nonce: this.authenticateContext.handshakeNonce,\n });\n if (handshakePayload) {\n cookiesToSet.push(...handshakePayload.directives);\n }\n } catch (error) {\n console.error('Clerk: HandshakeService: error getting handshake payload:', error);\n }\n } else if (this.authenticateContext.handshakeToken) {\n const handshakePayload = await verifyHandshakeToken(\n this.authenticateContext.handshakeToken,\n this.authenticateContext,\n );\n if (handshakePayload && Array.isArray(handshakePayload.handshake)) {\n cookiesToSet.push(...handshakePayload.handshake);\n }\n }\n\n return cookiesToSet;\n }\n\n /**\n * Resolves a handshake request by verifying the handshake token and setting appropriate cookies\n * @returns Promise resolving to either a SignedInState or SignedOutState\n * @throws Error if handshake verification fails or if there are issues with the session token\n */\n async resolveHandshake(): Promise {\n const headers = new Headers({\n 'Access-Control-Allow-Origin': 'null',\n 'Access-Control-Allow-Credentials': 'true',\n });\n\n const cookiesToSet = await this.getCookiesFromHandshake();\n\n let sessionToken = '';\n cookiesToSet.forEach((x: string) => {\n headers.append('Set-Cookie', x);\n if (getCookieName(x).startsWith(constants.Cookies.Session)) {\n sessionToken = getCookieValue(x);\n }\n });\n\n if (this.authenticateContext.instanceType === 'development') {\n const newUrl = new URL(this.authenticateContext.clerkUrl);\n newUrl.searchParams.delete(constants.QueryParameters.Handshake);\n newUrl.searchParams.delete(constants.QueryParameters.HandshakeHelp);\n newUrl.searchParams.delete(constants.QueryParameters.DevBrowser);\n headers.append(constants.Headers.Location, newUrl.toString());\n headers.set(constants.Headers.CacheControl, 'no-store');\n }\n\n if (sessionToken === '') {\n return signedOut({\n tokenType: TokenType.SessionToken,\n authenticateContext: this.authenticateContext,\n reason: AuthErrorReason.SessionTokenMissing,\n message: '',\n headers,\n });\n }\n\n const { data, errors: [error] = [] } = await verifyToken(sessionToken, this.authenticateContext);\n if (data) {\n return signedIn({\n tokenType: TokenType.SessionToken,\n authenticateContext: this.authenticateContext,\n sessionClaims: data,\n headers,\n token: sessionToken,\n });\n }\n\n if (\n this.authenticateContext.instanceType === 'development' &&\n (error?.reason === TokenVerificationErrorReason.TokenExpired ||\n error?.reason === TokenVerificationErrorReason.TokenNotActiveYet ||\n error?.reason === TokenVerificationErrorReason.TokenIatInTheFuture)\n ) {\n // Create a new error object with the same properties\n const developmentError = new TokenVerificationError({\n action: error.action,\n message: error.message,\n reason: error.reason,\n });\n // Set the tokenCarrier after construction\n developmentError.tokenCarrier = 'cookie';\n\n console.error(\n `Clerk: Clock skew detected. This usually means that your system clock is inaccurate. Clerk will attempt to account for the clock skew in development.\n\nTo resolve this issue, make sure your system's clock is set to the correct time (e.g. turn off and on automatic time synchronization).\n\n---\n\n${developmentError.getFullMessage()}`,\n );\n\n const { data: retryResult, errors: [retryError] = [] } = await verifyToken(sessionToken, {\n ...this.authenticateContext,\n clockSkewInMs: 86_400_000,\n });\n if (retryResult) {\n return signedIn({\n tokenType: TokenType.SessionToken,\n authenticateContext: this.authenticateContext,\n sessionClaims: retryResult,\n headers,\n token: sessionToken,\n });\n }\n\n throw new Error(retryError?.message || 'Clerk: Handshake retry failed.');\n }\n\n throw new Error(error?.message || 'Clerk: Handshake failed.');\n }\n\n /**\n * Handles handshake token verification errors in development mode\n * @param error - The TokenVerificationError that occurred\n * @throws Error with a descriptive message about the verification failure\n */\n handleTokenVerificationErrorInDevelopment(error: TokenVerificationError): void {\n // In development, the handshake token is being transferred in the URL as a query parameter, so there is no\n // possibility of collision with a handshake token of another app running on the same local domain\n // (etc one app on localhost:3000 and one on localhost:3001).\n // Therefore, if the handshake token is invalid, it is likely that the user has switched Clerk keys locally.\n // We make sure to throw a descriptive error message and then stop the handshake flow in every case,\n // to avoid the possibility of an infinite loop.\n if (error.reason === TokenVerificationErrorReason.TokenInvalidSignature) {\n const msg = `Clerk: Handshake token verification failed due to an invalid signature. If you have switched Clerk keys locally, clear your cookies and try again.`;\n throw new Error(msg);\n }\n throw new Error(`Clerk: Handshake token verification failed: ${error.getFullMessage()}.`);\n }\n\n /**\n * Checks if a redirect loop is detected and sets headers to track redirect count\n * @param headers - The Headers object to modify\n * @returns boolean indicating if a redirect loop was detected (true) or if the request can proceed (false)\n */\n checkAndTrackRedirectLoop(headers: Headers): boolean {\n if (this.authenticateContext.handshakeRedirectLoopCounter === 3) {\n return true;\n }\n\n const newCounterValue = this.authenticateContext.handshakeRedirectLoopCounter + 1;\n const cookieName = constants.Cookies.RedirectCount;\n headers.append('Set-Cookie', `${cookieName}=${newCounterValue}; SameSite=Lax; HttpOnly; Max-Age=2`);\n return false;\n }\n\n private removeDevBrowserFromURL(url: URL): URL {\n const updatedURL = new URL(url);\n updatedURL.searchParams.delete(constants.QueryParameters.DevBrowser);\n updatedURL.searchParams.delete(constants.QueryParameters.LegacyDevBrowser);\n return updatedURL;\n }\n\n private getOrganizationSyncTarget(url: URL, matchers: OrganizationMatcher): OrganizationSyncTarget | null {\n return matchers.findTarget(url);\n }\n\n private getOrganizationSyncQueryParams(toActivate: OrganizationSyncTarget): Map {\n const ret = new Map();\n if (toActivate.type === 'personalAccount') {\n ret.set('organization_id', '');\n }\n if (toActivate.type === 'organization') {\n if (toActivate.organizationId) {\n ret.set('organization_id', toActivate.organizationId);\n }\n if (toActivate.organizationSlug) {\n ret.set('organization_id', toActivate.organizationSlug);\n }\n }\n return ret;\n }\n}\n","import type { MatchFunction } from '@clerk/shared/pathToRegexp';\nimport { match } from '@clerk/shared/pathToRegexp';\n\nimport type { OrganizationSyncOptions, OrganizationSyncTarget } from './types';\n\nexport class OrganizationMatcher {\n private readonly organizationPattern: MatchFunction | null;\n private readonly personalAccountPattern: MatchFunction | null;\n\n constructor(options?: OrganizationSyncOptions) {\n this.organizationPattern = this.createMatcher(options?.organizationPatterns);\n this.personalAccountPattern = this.createMatcher(options?.personalAccountPatterns);\n }\n\n private createMatcher(pattern?: string[]): MatchFunction | null {\n if (!pattern) {\n return null;\n }\n try {\n return match(pattern);\n } catch (e) {\n throw new Error(`Invalid pattern \"${pattern}\": ${e}`);\n }\n }\n\n findTarget(url: URL): OrganizationSyncTarget | null {\n const orgTarget = this.findOrganizationTarget(url);\n if (orgTarget) {\n return orgTarget;\n }\n\n return this.findPersonalAccountTarget(url);\n }\n\n private findOrganizationTarget(url: URL): OrganizationSyncTarget | null {\n if (!this.organizationPattern) {\n return null;\n }\n\n try {\n const result = this.organizationPattern(url.pathname);\n if (!result || !('params' in result)) {\n return null;\n }\n\n const params = result.params as { id?: string; slug?: string };\n if (params.id) {\n return { type: 'organization', organizationId: params.id };\n }\n if (params.slug) {\n return { type: 'organization', organizationSlug: params.slug };\n }\n\n return null;\n } catch (e) {\n console.error('Failed to match organization pattern:', e);\n return null;\n }\n }\n\n private findPersonalAccountTarget(url: URL): OrganizationSyncTarget | null {\n if (!this.personalAccountPattern) {\n return null;\n }\n\n try {\n const result = this.personalAccountPattern(url.pathname);\n return result ? { type: 'personalAccount' } : null;\n } catch (e) {\n console.error('Failed to match personal account pattern:', e);\n return null;\n }\n }\n}\n","import type { JwtPayload } from '@clerk/types';\n\nimport { constants } from '../constants';\nimport type { TokenCarrier } from '../errors';\nimport { MachineTokenVerificationError, TokenVerificationError, TokenVerificationErrorReason } from '../errors';\nimport { decodeJwt } from '../jwt/verifyJwt';\nimport { assertValidSecretKey } from '../util/optionsAssertions';\nimport { isDevelopmentFromSecretKey } from '../util/shared';\nimport type { AuthenticateContext } from './authenticateContext';\nimport { createAuthenticateContext } from './authenticateContext';\nimport type { SignedInAuthObject } from './authObjects';\nimport type { HandshakeState, RequestState, SignedInState, SignedOutState, UnauthenticatedState } from './authStatus';\nimport { AuthErrorReason, handshake, signedIn, signedOut, signedOutInvalidToken } from './authStatus';\nimport { createClerkRequest } from './clerkRequest';\nimport { getCookieName, getCookieValue } from './cookie';\nimport { HandshakeService } from './handshake';\nimport { getMachineTokenType, isMachineTokenByPrefix, isTokenTypeAccepted } from './machine';\nimport { OrganizationMatcher } from './organizationMatcher';\nimport type { MachineTokenType, SessionTokenType } from './tokenTypes';\nimport { TokenType } from './tokenTypes';\nimport type { AuthenticateRequestOptions } from './types';\nimport { verifyMachineAuthToken, verifyToken } from './verify';\n\nexport const RefreshTokenErrorReason = {\n NonEligibleNoCookie: 'non-eligible-no-refresh-cookie',\n NonEligibleNonGet: 'non-eligible-non-get',\n InvalidSessionToken: 'invalid-session-token',\n MissingApiClient: 'missing-api-client',\n MissingSessionToken: 'missing-session-token',\n MissingRefreshToken: 'missing-refresh-token',\n ExpiredSessionTokenDecodeFailed: 'expired-session-token-decode-failed',\n ExpiredSessionTokenMissingSidClaim: 'expired-session-token-missing-sid-claim',\n FetchError: 'fetch-error',\n UnexpectedSDKError: 'unexpected-sdk-error',\n UnexpectedBAPIError: 'unexpected-bapi-error',\n} as const;\n\nfunction assertSignInUrlExists(signInUrl: string | undefined, key: string): asserts signInUrl is string {\n if (!signInUrl && isDevelopmentFromSecretKey(key)) {\n throw new Error(`Missing signInUrl. Pass a signInUrl for dev instances if an app is satellite`);\n }\n}\n\nfunction assertProxyUrlOrDomain(proxyUrlOrDomain: string | undefined) {\n if (!proxyUrlOrDomain) {\n throw new Error(`Missing domain and proxyUrl. A satellite application needs to specify a domain or a proxyUrl`);\n }\n}\n\nfunction assertSignInUrlFormatAndOrigin(_signInUrl: string, origin: string) {\n let signInUrl: URL;\n try {\n signInUrl = new URL(_signInUrl);\n } catch {\n throw new Error(`The signInUrl needs to have a absolute url format.`);\n }\n\n if (signInUrl.origin === origin) {\n throw new Error(`The signInUrl needs to be on a different origin than your satellite application.`);\n }\n}\n\nfunction assertMachineSecretOrSecretKey(authenticateContext: AuthenticateContext) {\n if (!authenticateContext.machineSecretKey && !authenticateContext.secretKey) {\n throw new Error(\n 'Machine token authentication requires either a Machine secret key or a Clerk secret key. ' +\n 'Ensure a Clerk secret key or Machine secret key is set.',\n );\n }\n}\n\nfunction isRequestEligibleForRefresh(\n err: TokenVerificationError,\n authenticateContext: { refreshTokenInCookie?: string },\n request: Request,\n) {\n return (\n err.reason === TokenVerificationErrorReason.TokenExpired &&\n !!authenticateContext.refreshTokenInCookie &&\n request.method === 'GET'\n );\n}\n\nfunction checkTokenTypeMismatch(\n parsedTokenType: MachineTokenType,\n acceptsToken: NonNullable,\n authenticateContext: AuthenticateContext,\n): UnauthenticatedState | null {\n const mismatch = !isTokenTypeAccepted(parsedTokenType, acceptsToken);\n if (mismatch) {\n const tokenTypeToReturn = (typeof acceptsToken === 'string' ? acceptsToken : parsedTokenType) as MachineTokenType;\n return signedOut({\n tokenType: tokenTypeToReturn,\n authenticateContext,\n reason: AuthErrorReason.TokenTypeMismatch,\n });\n }\n return null;\n}\n\nfunction isTokenTypeInAcceptedArray(acceptsToken: TokenType[], authenticateContext: AuthenticateContext): boolean {\n let parsedTokenType: TokenType | null = null;\n const { tokenInHeader } = authenticateContext;\n if (tokenInHeader) {\n if (isMachineTokenByPrefix(tokenInHeader)) {\n parsedTokenType = getMachineTokenType(tokenInHeader);\n } else {\n parsedTokenType = TokenType.SessionToken;\n }\n }\n const typeToCheck = parsedTokenType ?? TokenType.SessionToken;\n return isTokenTypeAccepted(typeToCheck, acceptsToken);\n}\n\nexport interface AuthenticateRequest {\n /**\n * @example\n * clerkClient.authenticateRequest(request, { acceptsToken: ['session_token', 'api_key'] });\n */\n (\n request: Request,\n options: AuthenticateRequestOptions & { acceptsToken: T },\n ): Promise>;\n\n /**\n * @example\n * clerkClient.authenticateRequest(request, { acceptsToken: 'session_token' });\n */\n (\n request: Request,\n options: AuthenticateRequestOptions & { acceptsToken: T },\n ): Promise>;\n\n /**\n * @example\n * clerkClient.authenticateRequest(request, { acceptsToken: 'any' });\n */\n (request: Request, options: AuthenticateRequestOptions & { acceptsToken: 'any' }): Promise>;\n\n /**\n * @example\n * clerkClient.authenticateRequest(request);\n */\n (request: Request, options?: AuthenticateRequestOptions): Promise>;\n}\n\nexport const authenticateRequest: AuthenticateRequest = (async (\n request: Request,\n options: AuthenticateRequestOptions,\n): Promise | UnauthenticatedState> => {\n const authenticateContext = await createAuthenticateContext(createClerkRequest(request), options);\n\n // Default tokenType is session_token for backwards compatibility.\n const acceptsToken = options.acceptsToken ?? TokenType.SessionToken;\n\n // machine-to-machine tokens can accept a machine secret or a secret key\n if (acceptsToken !== TokenType.M2MToken) {\n assertValidSecretKey(authenticateContext.secretKey);\n\n if (authenticateContext.isSatellite) {\n assertSignInUrlExists(authenticateContext.signInUrl, authenticateContext.secretKey);\n if (authenticateContext.signInUrl && authenticateContext.origin) {\n assertSignInUrlFormatAndOrigin(authenticateContext.signInUrl, authenticateContext.origin);\n }\n assertProxyUrlOrDomain(authenticateContext.proxyUrl || authenticateContext.domain);\n }\n }\n\n // Make sure a machine secret or instance secret key is provided if acceptsToken is m2m_token\n if (acceptsToken === TokenType.M2MToken) {\n assertMachineSecretOrSecretKey(authenticateContext);\n }\n\n const organizationMatcher = new OrganizationMatcher(options.organizationSyncOptions);\n const handshakeService = new HandshakeService(\n authenticateContext,\n { organizationSyncOptions: options.organizationSyncOptions },\n organizationMatcher,\n );\n\n async function refreshToken(\n authenticateContext: AuthenticateContext,\n ): Promise<{ data: string[]; error: null } | { data: null; error: any }> {\n // To perform a token refresh, apiClient must be defined.\n if (!options.apiClient) {\n return {\n data: null,\n error: {\n message: 'An apiClient is needed to perform token refresh.',\n cause: { reason: RefreshTokenErrorReason.MissingApiClient },\n },\n };\n }\n const { sessionToken: expiredSessionToken, refreshTokenInCookie: refreshToken } = authenticateContext;\n if (!expiredSessionToken) {\n return {\n data: null,\n error: {\n message: 'Session token must be provided.',\n cause: { reason: RefreshTokenErrorReason.MissingSessionToken },\n },\n };\n }\n if (!refreshToken) {\n return {\n data: null,\n error: {\n message: 'Refresh token must be provided.',\n cause: { reason: RefreshTokenErrorReason.MissingRefreshToken },\n },\n };\n }\n // The token refresh endpoint requires a sessionId, so we decode that from the expired token.\n const { data: decodeResult, errors: decodedErrors } = decodeJwt(expiredSessionToken);\n if (!decodeResult || decodedErrors) {\n return {\n data: null,\n error: {\n message: 'Unable to decode the expired session token.',\n cause: { reason: RefreshTokenErrorReason.ExpiredSessionTokenDecodeFailed, errors: decodedErrors },\n },\n };\n }\n\n if (!decodeResult?.payload?.sid) {\n return {\n data: null,\n error: {\n message: 'Expired session token is missing the `sid` claim.',\n cause: { reason: RefreshTokenErrorReason.ExpiredSessionTokenMissingSidClaim },\n },\n };\n }\n\n try {\n // Perform the actual token refresh.\n const response = await options.apiClient.sessions.refreshSession(decodeResult.payload.sid, {\n format: 'cookie',\n suffixed_cookies: authenticateContext.usesSuffixedCookies(),\n expired_token: expiredSessionToken || '',\n refresh_token: refreshToken || '',\n request_origin: authenticateContext.clerkUrl.origin,\n // The refresh endpoint expects headers as Record, so we need to transform it.\n request_headers: Object.fromEntries(Array.from(request.headers.entries()).map(([k, v]) => [k, [v]])),\n });\n return { data: response.cookies, error: null };\n } catch (err: any) {\n if (err?.errors?.length) {\n if (err.errors[0].code === 'unexpected_error') {\n return {\n data: null,\n error: {\n message: `Fetch unexpected error`,\n cause: { reason: RefreshTokenErrorReason.FetchError, errors: err.errors },\n },\n };\n }\n return {\n data: null,\n error: {\n message: err.errors[0].code,\n cause: { reason: err.errors[0].code, errors: err.errors },\n },\n };\n } else {\n return {\n data: null,\n error: {\n message: `Unexpected Server/BAPI error`,\n cause: { reason: RefreshTokenErrorReason.UnexpectedBAPIError, errors: [err] },\n },\n };\n }\n }\n }\n\n async function attemptRefresh(\n authenticateContext: AuthenticateContext,\n ): Promise<\n | { data: { jwtPayload: JwtPayload; sessionToken: string; headers: Headers }; error: null }\n | { data: null; error: any }\n > {\n const { data: cookiesToSet, error } = await refreshToken(authenticateContext);\n if (!cookiesToSet || cookiesToSet.length === 0) {\n return { data: null, error };\n }\n\n const headers = new Headers();\n let sessionToken = '';\n cookiesToSet.forEach((x: string) => {\n headers.append('Set-Cookie', x);\n if (getCookieName(x).startsWith(constants.Cookies.Session)) {\n sessionToken = getCookieValue(x);\n }\n });\n\n // Since we're going to return a signedIn response, we need to decode the data from the new sessionToken.\n const { data: jwtPayload, errors } = await verifyToken(sessionToken, authenticateContext);\n if (errors) {\n return {\n data: null,\n error: {\n message: `Clerk: unable to verify refreshed session token.`,\n cause: { reason: RefreshTokenErrorReason.InvalidSessionToken, errors },\n },\n };\n }\n return { data: { jwtPayload, sessionToken, headers }, error: null };\n }\n\n function handleMaybeHandshakeStatus(\n authenticateContext: AuthenticateContext,\n reason: string,\n message: string,\n headers?: Headers,\n ): SignedInState | SignedOutState | HandshakeState {\n if (!handshakeService.isRequestEligibleForHandshake()) {\n return signedOut({\n tokenType: TokenType.SessionToken,\n authenticateContext,\n reason,\n message,\n });\n }\n\n // Right now the only usage of passing in different headers is for multi-domain sync, which redirects somewhere else.\n // In the future if we want to decorate the handshake redirect with additional headers per call we need to tweak this logic.\n const handshakeHeaders = headers ?? handshakeService.buildRedirectToHandshake(reason);\n\n // Chrome aggressively caches inactive tabs. If we don't set the header here,\n // all 307 redirects will be cached and the handshake will end up in an infinite loop.\n if (handshakeHeaders.get(constants.Headers.Location)) {\n handshakeHeaders.set(constants.Headers.CacheControl, 'no-store');\n }\n\n // Introduce the mechanism to protect for infinite handshake redirect loops\n // using a cookie and returning true if it's infinite redirect loop or false if we can\n // proceed with triggering handshake.\n const isRedirectLoop = handshakeService.checkAndTrackRedirectLoop(handshakeHeaders);\n if (isRedirectLoop) {\n const msg = `Clerk: Refreshing the session token resulted in an infinite redirect loop. This usually means that your Clerk instance keys do not match - make sure to copy the correct publishable and secret keys from the Clerk dashboard.`;\n console.log(msg);\n return signedOut({\n tokenType: TokenType.SessionToken,\n authenticateContext,\n reason,\n message,\n });\n }\n\n return handshake(authenticateContext, reason, message, handshakeHeaders);\n }\n\n /**\n * Determines if a handshake must occur to resolve a mismatch between the organization as specified\n * by the URL (according to the options) and the actual active organization on the session.\n *\n * @returns {HandshakeState | SignedOutState | null} - The function can return the following:\n * - {HandshakeState}: If a handshake is needed to resolve the mismatched organization.\n * - {SignedOutState}: If a handshake is required but cannot be performed.\n * - {null}: If no action is required.\n */\n function handleMaybeOrganizationSyncHandshake(\n authenticateContext: AuthenticateContext,\n auth: SignedInAuthObject,\n ): HandshakeState | SignedOutState | null {\n const organizationSyncTarget = organizationMatcher.findTarget(authenticateContext.clerkUrl);\n if (!organizationSyncTarget) {\n return null;\n }\n let mustActivate = false;\n if (organizationSyncTarget.type === 'organization') {\n // Activate an org by slug?\n if (organizationSyncTarget.organizationSlug && organizationSyncTarget.organizationSlug !== auth.orgSlug) {\n mustActivate = true;\n }\n // Activate an org by ID?\n if (organizationSyncTarget.organizationId && organizationSyncTarget.organizationId !== auth.orgId) {\n mustActivate = true;\n }\n }\n // Activate the personal account?\n if (organizationSyncTarget.type === 'personalAccount' && auth.orgId) {\n mustActivate = true;\n }\n if (!mustActivate) {\n return null;\n }\n if (authenticateContext.handshakeRedirectLoopCounter >= 3) {\n // We have an organization that needs to be activated, but this isn't our first time redirecting.\n // This is because we attempted to activate the organization previously, but the organization\n // must not have been valid (either not found, or not valid for this user), and gave us back\n // a null organization. We won't re-try the handshake, and leave it to the server component to handle.\n console.warn(\n 'Clerk: Organization activation handshake loop detected. This is likely due to an invalid organization ID or slug. Skipping organization activation.',\n );\n return null;\n }\n const handshakeState = handleMaybeHandshakeStatus(\n authenticateContext,\n AuthErrorReason.ActiveOrganizationMismatch,\n '',\n );\n if (handshakeState.status !== 'handshake') {\n // Currently, this is only possible if we're in a redirect loop, but the above check should guard against that.\n return null;\n }\n return handshakeState;\n }\n\n async function authenticateRequestWithTokenInHeader() {\n const { tokenInHeader } = authenticateContext;\n\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const { data, errors } = await verifyToken(tokenInHeader!, authenticateContext);\n if (errors) {\n throw errors[0];\n }\n // use `await` to force this try/catch handle the signedIn invocation\n return signedIn({\n tokenType: TokenType.SessionToken,\n authenticateContext,\n sessionClaims: data,\n headers: new Headers(),\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n token: tokenInHeader!,\n });\n } catch (err) {\n return handleSessionTokenError(err, 'header');\n }\n }\n\n async function authenticateRequestWithTokenInCookie() {\n const hasActiveClient = authenticateContext.clientUat;\n const hasSessionToken = !!authenticateContext.sessionTokenInCookie;\n const hasDevBrowserToken = !!authenticateContext.devBrowserToken;\n\n /**\n * If we have a handshakeToken, resolve the handshake and attempt to return a definitive signed in or signed out state.\n */\n if (authenticateContext.handshakeNonce || authenticateContext.handshakeToken) {\n try {\n return await handshakeService.resolveHandshake();\n } catch (error) {\n // In production, the handshake token is being transferred as a cookie, so there is a possibility of collision\n // with a handshake token of another app running on the same etld+1 domain.\n // For example, if one app is running on sub1.clerk.com and another on sub2.clerk.com, the handshake token\n // cookie for both apps will be set on etld+1 (clerk.com) so there's a possibility that one app will accidentally\n // use the handshake token of a different app during the handshake flow.\n // In this scenario, verification will fail with TokenInvalidSignature. In contrast to the development case,\n // we need to allow the flow to continue so the app eventually retries another handshake with the correct token.\n // We need to make sure, however, that we don't allow the flow to continue indefinitely, so we throw an error after X\n // retries to avoid an infinite loop. An infinite loop can happen if the customer switched Clerk keys for their prod app.\n\n // Check the handleTokenVerificationErrorInDevelopment method for the development case.\n if (error instanceof TokenVerificationError && authenticateContext.instanceType === 'development') {\n handshakeService.handleTokenVerificationErrorInDevelopment(error);\n } else {\n console.error('Clerk: unable to resolve handshake:', error);\n }\n }\n }\n /**\n * Otherwise, check for \"known unknown\" auth states that we can resolve with a handshake.\n */\n if (\n authenticateContext.instanceType === 'development' &&\n authenticateContext.clerkUrl.searchParams.has(constants.QueryParameters.DevBrowser)\n ) {\n return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.DevBrowserSync, '');\n }\n\n const isRequestEligibleForMultiDomainSync =\n authenticateContext.isSatellite && authenticateContext.secFetchDest === 'document';\n\n /**\n * Begin multi-domain sync flows\n */\n if (authenticateContext.instanceType === 'production' && isRequestEligibleForMultiDomainSync) {\n return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.SatelliteCookieNeedsSyncing, '');\n }\n\n // Multi-domain development sync flow\n if (\n authenticateContext.instanceType === 'development' &&\n isRequestEligibleForMultiDomainSync &&\n !authenticateContext.clerkUrl.searchParams.has(constants.QueryParameters.ClerkSynced)\n ) {\n // initiate MD sync\n\n // signInUrl exists, checked at the top of `authenticateRequest`\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const redirectURL = new URL(authenticateContext.signInUrl!);\n redirectURL.searchParams.append(\n constants.QueryParameters.ClerkRedirectUrl,\n authenticateContext.clerkUrl.toString(),\n );\n const headers = new Headers({ [constants.Headers.Location]: redirectURL.toString() });\n return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.SatelliteCookieNeedsSyncing, '', headers);\n }\n\n // Multi-domain development sync flow\n const redirectUrl = new URL(authenticateContext.clerkUrl).searchParams.get(\n constants.QueryParameters.ClerkRedirectUrl,\n );\n\n if (authenticateContext.instanceType === 'development' && !authenticateContext.isSatellite && redirectUrl) {\n // Dev MD sync from primary, redirect back to satellite w/ dev browser query param\n const redirectBackToSatelliteUrl = new URL(redirectUrl);\n\n if (authenticateContext.devBrowserToken) {\n redirectBackToSatelliteUrl.searchParams.append(\n constants.QueryParameters.DevBrowser,\n authenticateContext.devBrowserToken,\n );\n }\n redirectBackToSatelliteUrl.searchParams.append(constants.QueryParameters.ClerkSynced, 'true');\n\n const headers = new Headers({ [constants.Headers.Location]: redirectBackToSatelliteUrl.toString() });\n return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.PrimaryRespondsToSyncing, '', headers);\n }\n /**\n * End multi-domain sync flows\n */\n\n if (authenticateContext.instanceType === 'development' && !hasDevBrowserToken) {\n return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.DevBrowserMissing, '');\n }\n\n if (!hasActiveClient && !hasSessionToken) {\n return signedOut({\n tokenType: TokenType.SessionToken,\n authenticateContext,\n reason: AuthErrorReason.SessionTokenAndUATMissing,\n });\n }\n\n // This can eagerly run handshake since client_uat is SameSite=Strict in dev\n if (!hasActiveClient && hasSessionToken) {\n return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.SessionTokenWithoutClientUAT, '');\n }\n\n if (hasActiveClient && !hasSessionToken) {\n return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.ClientUATWithoutSessionToken, '');\n }\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const { data: decodeResult, errors: decodedErrors } = decodeJwt(authenticateContext.sessionTokenInCookie!);\n\n if (decodedErrors) {\n return handleSessionTokenError(decodedErrors[0], 'cookie');\n }\n\n if (decodeResult.payload.iat < authenticateContext.clientUat) {\n return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.SessionTokenIATBeforeClientUAT, '');\n }\n\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const { data, errors } = await verifyToken(authenticateContext.sessionTokenInCookie!, authenticateContext);\n if (errors) {\n throw errors[0];\n }\n\n const signedInRequestState = signedIn({\n tokenType: TokenType.SessionToken,\n authenticateContext,\n sessionClaims: data,\n headers: new Headers(),\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n token: authenticateContext.sessionTokenInCookie!,\n });\n\n // Check for cross-origin requests from satellite domains to primary domain\n const shouldForceHandshakeForCrossDomain =\n !authenticateContext.isSatellite && // We're on primary\n authenticateContext.secFetchDest === 'document' && // Document navigation\n authenticateContext.isCrossOriginReferrer() && // Came from different domain\n !authenticateContext.isKnownClerkReferrer() && // Not from Clerk accounts portal or FAPI\n authenticateContext.handshakeRedirectLoopCounter === 0; // Not in a redirect loop\n\n if (shouldForceHandshakeForCrossDomain) {\n return handleMaybeHandshakeStatus(\n authenticateContext,\n AuthErrorReason.PrimaryDomainCrossOriginSync,\n 'Cross-origin request from satellite domain requires handshake',\n );\n }\n\n const authObject = signedInRequestState.toAuth();\n // Org sync if necessary\n if (authObject.userId) {\n const handshakeRequestState = handleMaybeOrganizationSyncHandshake(authenticateContext, authObject);\n if (handshakeRequestState) {\n return handshakeRequestState;\n }\n }\n\n return signedInRequestState;\n } catch (err) {\n return handleSessionTokenError(err, 'cookie');\n }\n\n // Unreachable\n return signedOut({\n tokenType: TokenType.SessionToken,\n authenticateContext,\n reason: AuthErrorReason.UnexpectedError,\n });\n }\n\n async function handleSessionTokenError(\n err: unknown,\n tokenCarrier: TokenCarrier,\n ): Promise {\n if (!(err instanceof TokenVerificationError)) {\n return signedOut({\n tokenType: TokenType.SessionToken,\n authenticateContext,\n reason: AuthErrorReason.UnexpectedError,\n });\n }\n\n let refreshError: string | null;\n\n if (isRequestEligibleForRefresh(err, authenticateContext, request)) {\n const { data, error } = await attemptRefresh(authenticateContext);\n if (data) {\n return signedIn({\n tokenType: TokenType.SessionToken,\n authenticateContext,\n sessionClaims: data.jwtPayload,\n headers: data.headers,\n token: data.sessionToken,\n });\n }\n\n // If there's any error, simply fallback to the handshake flow including the reason as a query parameter.\n if (error?.cause?.reason) {\n refreshError = error.cause.reason;\n } else {\n refreshError = RefreshTokenErrorReason.UnexpectedSDKError;\n }\n } else {\n if (request.method !== 'GET') {\n refreshError = RefreshTokenErrorReason.NonEligibleNonGet;\n } else if (!authenticateContext.refreshTokenInCookie) {\n refreshError = RefreshTokenErrorReason.NonEligibleNoCookie;\n } else {\n //refresh error is not applicable if token verification error is not 'session-token-expired'\n refreshError = null;\n }\n }\n\n err.tokenCarrier = tokenCarrier;\n\n const reasonToHandshake = [\n TokenVerificationErrorReason.TokenExpired,\n TokenVerificationErrorReason.TokenNotActiveYet,\n TokenVerificationErrorReason.TokenIatInTheFuture,\n ].includes(err.reason);\n\n if (reasonToHandshake) {\n return handleMaybeHandshakeStatus(\n authenticateContext,\n convertTokenVerificationErrorReasonToAuthErrorReason({ tokenError: err.reason, refreshError }),\n err.getFullMessage(),\n );\n }\n\n return signedOut({\n tokenType: TokenType.SessionToken,\n authenticateContext,\n reason: err.reason,\n message: err.getFullMessage(),\n });\n }\n\n function handleMachineError(tokenType: MachineTokenType, err: unknown): UnauthenticatedState {\n if (!(err instanceof MachineTokenVerificationError)) {\n return signedOut({\n tokenType,\n authenticateContext,\n reason: AuthErrorReason.UnexpectedError,\n });\n }\n\n return signedOut({\n tokenType,\n authenticateContext,\n reason: err.code,\n message: err.getFullMessage(),\n });\n }\n\n async function authenticateMachineRequestWithTokenInHeader() {\n const { tokenInHeader } = authenticateContext;\n // Use session token error handling if no token in header (default behavior)\n if (!tokenInHeader) {\n return handleSessionTokenError(new Error('Missing token in header'), 'header');\n }\n\n // Handle case where tokenType is any and the token is not a machine token\n if (!isMachineTokenByPrefix(tokenInHeader)) {\n return signedOut({\n tokenType: acceptsToken as TokenType,\n authenticateContext,\n reason: AuthErrorReason.TokenTypeMismatch,\n message: '',\n });\n }\n\n const parsedTokenType = getMachineTokenType(tokenInHeader);\n const mismatchState = checkTokenTypeMismatch(parsedTokenType, acceptsToken, authenticateContext);\n if (mismatchState) {\n return mismatchState;\n }\n\n const { data, tokenType, errors } = await verifyMachineAuthToken(tokenInHeader, authenticateContext);\n if (errors) {\n return handleMachineError(tokenType, errors[0]);\n }\n return signedIn({\n tokenType,\n authenticateContext,\n machineData: data,\n token: tokenInHeader,\n });\n }\n\n async function authenticateAnyRequestWithTokenInHeader() {\n const { tokenInHeader } = authenticateContext;\n // Use session token error handling if no token in header (default behavior)\n if (!tokenInHeader) {\n return handleSessionTokenError(new Error('Missing token in header'), 'header');\n }\n\n // Handle as a machine token\n if (isMachineTokenByPrefix(tokenInHeader)) {\n const parsedTokenType = getMachineTokenType(tokenInHeader);\n const mismatchState = checkTokenTypeMismatch(parsedTokenType, acceptsToken, authenticateContext);\n if (mismatchState) {\n return mismatchState;\n }\n\n const { data, tokenType, errors } = await verifyMachineAuthToken(tokenInHeader, authenticateContext);\n if (errors) {\n return handleMachineError(tokenType, errors[0]);\n }\n\n return signedIn({\n tokenType,\n authenticateContext,\n machineData: data,\n token: tokenInHeader,\n });\n }\n\n // Handle as a regular session token\n const { data, errors } = await verifyToken(tokenInHeader, authenticateContext);\n if (errors) {\n return handleSessionTokenError(errors[0], 'header');\n }\n\n return signedIn({\n tokenType: TokenType.SessionToken,\n authenticateContext,\n sessionClaims: data,\n token: tokenInHeader,\n });\n }\n\n // If acceptsToken is an array, early check if the token is in the accepted array\n // to avoid unnecessary verification calls\n if (Array.isArray(acceptsToken)) {\n if (!isTokenTypeInAcceptedArray(acceptsToken, authenticateContext)) {\n return signedOutInvalidToken();\n }\n }\n\n if (authenticateContext.tokenInHeader) {\n if (acceptsToken === 'any') {\n return authenticateAnyRequestWithTokenInHeader();\n }\n if (acceptsToken === TokenType.SessionToken) {\n return authenticateRequestWithTokenInHeader();\n }\n return authenticateMachineRequestWithTokenInHeader();\n }\n\n // Machine requests cannot have the token in the cookie, it must be in header.\n if (\n acceptsToken === TokenType.OAuthToken ||\n acceptsToken === TokenType.ApiKey ||\n acceptsToken === TokenType.M2MToken\n ) {\n return signedOut({\n tokenType: acceptsToken,\n authenticateContext,\n reason: 'No token in header',\n });\n }\n\n return authenticateRequestWithTokenInCookie();\n}) as AuthenticateRequest;\n\n/**\n * @internal\n */\nexport const debugRequestState = (params: RequestState) => {\n const { isSignedIn, isAuthenticated, proxyUrl, reason, message, publishableKey, isSatellite, domain } = params;\n return { isSignedIn, isAuthenticated, proxyUrl, reason, message, publishableKey, isSatellite, domain };\n};\n\nconst convertTokenVerificationErrorReasonToAuthErrorReason = ({\n tokenError,\n refreshError,\n}: {\n tokenError: TokenVerificationErrorReason;\n refreshError: string | null;\n}): string => {\n switch (tokenError) {\n case TokenVerificationErrorReason.TokenExpired:\n return `${AuthErrorReason.SessionTokenExpired}-refresh-${refreshError}`;\n case TokenVerificationErrorReason.TokenNotActiveYet:\n return AuthErrorReason.SessionTokenNBF;\n case TokenVerificationErrorReason.TokenIatInTheFuture:\n return AuthErrorReason.SessionTokenIatInTheFuture;\n default:\n return AuthErrorReason.UnexpectedError;\n }\n};\n","import type { ApiClient } from '../api';\nimport { mergePreDefinedOptions } from '../util/mergePreDefinedOptions';\nimport type { AuthenticateRequest } from './request';\nimport { authenticateRequest as authenticateRequestOriginal, debugRequestState } from './request';\nimport type { AuthenticateRequestOptions } from './types';\n\ntype RunTimeOptions = Omit;\ntype BuildTimeOptions = Partial<\n Pick<\n AuthenticateRequestOptions,\n | 'apiUrl'\n | 'apiVersion'\n | 'audience'\n | 'domain'\n | 'isSatellite'\n | 'jwtKey'\n | 'proxyUrl'\n | 'publishableKey'\n | 'secretKey'\n | 'machineSecretKey'\n >\n>;\n\nconst defaultOptions = {\n secretKey: '',\n machineSecretKey: '',\n jwtKey: '',\n apiUrl: undefined,\n apiVersion: undefined,\n proxyUrl: '',\n publishableKey: '',\n isSatellite: false,\n domain: '',\n audience: '',\n} satisfies BuildTimeOptions;\n\n/**\n * @internal\n */\nexport type CreateAuthenticateRequestOptions = {\n options: BuildTimeOptions;\n apiClient: ApiClient;\n};\n\n/**\n * @internal\n */\nexport function createAuthenticateRequest(params: CreateAuthenticateRequestOptions) {\n const buildTimeOptions = mergePreDefinedOptions(defaultOptions, params.options);\n const apiClient = params.apiClient;\n\n const authenticateRequest: AuthenticateRequest = (request: Request, options: RunTimeOptions = {}) => {\n const { apiUrl, apiVersion } = buildTimeOptions;\n const runTimeOptions = mergePreDefinedOptions(buildTimeOptions, options);\n return authenticateRequestOriginal(request, {\n ...options,\n ...runTimeOptions,\n // We should add all the omitted props from options here (eg apiUrl / apiVersion)\n // to avoid runtime options override them.\n apiUrl,\n apiVersion,\n apiClient,\n });\n };\n\n return {\n authenticateRequest,\n debugRequestState,\n };\n}\n","import type { CreateBackendApiOptions, Organization, Session, User } from '../api';\nimport { createBackendApiClient } from '../api';\nimport type { AuthObject, SignedInAuthObject, SignedOutAuthObject } from '../tokens/authObjects';\n\ntype DecorateAuthWithResourcesOptions = {\n loadSession?: boolean;\n loadUser?: boolean;\n loadOrganization?: boolean;\n};\n\ntype WithResources = T & {\n session?: Session | null;\n user?: User | null;\n organization?: Organization | null;\n};\n\n/**\n * @internal\n */\nexport const decorateObjectWithResources = async (\n obj: T,\n authObj: AuthObject,\n opts: CreateBackendApiOptions & DecorateAuthWithResourcesOptions,\n): Promise> => {\n const { loadSession, loadUser, loadOrganization } = opts || {};\n const { userId, sessionId, orgId } = authObj as SignedInAuthObject | SignedOutAuthObject;\n\n const { sessions, users, organizations } = createBackendApiClient({ ...opts });\n\n const [sessionResp, userResp, organizationResp] = await Promise.all([\n loadSession && sessionId ? sessions.getSession(sessionId) : Promise.resolve(undefined),\n loadUser && userId ? users.getUser(userId) : Promise.resolve(undefined),\n loadOrganization && orgId ? organizations.getOrganization({ organizationId: orgId }) : Promise.resolve(undefined),\n ]);\n\n const resources = stripPrivateDataFromObject({\n session: sessionResp,\n user: userResp,\n organization: organizationResp,\n });\n return Object.assign(obj, resources);\n};\n\n/**\n * @internal\n */\nexport function stripPrivateDataFromObject>(authObject: T): T {\n const user = authObject.user ? { ...authObject.user } : authObject.user;\n const organization = authObject.organization ? { ...authObject.organization } : authObject.organization;\n prunePrivateMetadata(user);\n prunePrivateMetadata(organization);\n return { ...authObject, user, organization };\n}\n\nfunction prunePrivateMetadata(resource?: { private_metadata: any } | { privateMetadata: any } | null) {\n // Delete sensitive private metadata from resource before rendering in SSR\n if (resource) {\n if ('privateMetadata' in resource) {\n delete resource['privateMetadata'];\n }\n if ('private_metadata' in resource) {\n delete resource['private_metadata'];\n }\n }\n\n return resource;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAO,IAAM,UAAU;AAChB,IAAM,cAAc;AAEpB,IAAM,aAAa,GAAG,gBAAY,IAAI,QAAe;AACrD,IAAM,oCAAoC,IAAI;AAC9C,IAAM,yBAAyB;AAEtC,IAAM,aAAa;AAAA,EACjB,WAAW;AAAA,EACX,eAAe;AAAA,EACf,YAAY;AAAA,EACZ,YAAY;AAAA,EACZ,aAAa;AAAA,EACb,UAAU;AACZ;AAEA,IAAM,UAAU;AAAA,EACd,SAAS;AAAA,EACT,SAAS;AAAA,EACT,WAAW;AAAA,EACX,WAAW;AAAA,EACX,YAAY;AAAA,EACZ,eAAe;AAAA,EACf,gBAAgB;AAClB;AAEA,IAAM,kBAAkB;AAAA,EACtB,aAAa;AAAA,EACb,iBAAiB;AAAA,EACjB,kBAAkB;AAAA;AAAA,EAElB,YAAY,QAAQ;AAAA,EACpB,WAAW,QAAQ;AAAA,EACnB,eAAe;AAAA,EACf,kBAAkB;AAAA,EAClB,iBAAiB;AAAA,EACjB,gBAAgB,QAAQ;AAAA,EACxB,iBAAiB;AACnB;AAEA,IAAMA,WAAU;AAAA,EACd,QAAQ;AAAA,EACR,aAAa;AAAA,EACb,eAAe;AAAA,EACf,YAAY;AAAA,EACZ,eAAe;AAAA,EACf,YAAY;AAAA,EACZ,WAAW;AAAA,EACX,cAAc;AAAA,EACd,iBAAiB;AAAA,EACjB,kBAAkB;AAAA,EAClB,UAAU;AAAA,EACV,0BAA0B;AAAA,EAC1B,aAAa;AAAA,EACb,uBAAuB;AAAA,EACvB,iCAAiC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,QAAQ,WAAW,MAAM,IAAI;AAErC,QAAM,EAAE,UAAU,OAAO,cAAc,IAAI,uBAAuB,EAAE,GAAG,KAAK,CAAC;AAE7E,QAAM,CAAC,aAAa,UAAU,gBAAgB,IAAI,MAAM,QAAQ,IAAI;AAAA,IAClE,eAAe,YAAY,SAAS,WAAW,SAAS,IAAI,QAAQ,QAAQ,MAAS;AAAA,IACrF,YAAY,SAAS,MAAM,QAAQ,MAAM,IAAI,QAAQ,QAAQ,MAAS;AAAA,IACtE,oBAAoB,QAAQ,cAAc,gBAAgB,EAAE,gBAAgB,MAAM,CAAC,IAAI,QAAQ,QAAQ,MAAS;AAAA,EAClH,CAAC;AAED,QAAM,YAAY,2BAA2B;AAAA,IAC3C,SAAS;AAAA,IACT,MAAM;AAAA,IACN,cAAc;AAAA,EAChB,CAAC;AACD,SAAO,OAAO,OAAO,KAAK,SAAS;AACrC;AAKO,SAAS,2BAA4D,YAAkB;AAC5F,QAAM,OAAO,WAAW,OAAO,EAAE,GAAG,WAAW,KAAK,IAAI,WAAW;AACnE,QAAM,eAAe,WAAW,eAAe,EAAE,GAAG,WAAW,aAAa,IAAI,WAAW;AAC3F,uBAAqB,IAAI;AACzB,uBAAqB,YAAY;AACjC,SAAO,EAAE,GAAG,YAAY,MAAM,aAAa;AAC7C;AAEA,SAAS,qBAAqB,UAAwE;AAEpG,MAAI,UAAU;AACZ,QAAI,qBAAqB,UAAU;AACjC,aAAO,SAAS,iBAAiB;AAAA,IACnC;AACA,QAAI,sBAAsB,UAAU;AAClC,aAAO,SAAS,kBAAkB;AAAA,IACpC;AAAA,EACF;AAEA,SAAO;AACT;;;AlHdA,kCAAiE;","names":["Headers","import_keys","crypto","import_buildAccountsBaseUrl","import_url","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","import_error","match","convertCase","Cookies","data","Cookies","sessionId","jwk","import_error","authenticateContext","refreshToken","data","errors","authenticateRequest"]} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/internal.mjs b/backend/node_modules/@clerk/backend/dist/internal.mjs new file mode 100644 index 000000000..4ac821fcc --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/internal.mjs @@ -0,0 +1,57 @@ +import { + AuthStatus, + TokenType, + authenticatedMachineObject, + constants, + createAuthenticateRequest, + createClerkRequest, + createRedirect, + debugRequestState, + decorateObjectWithResources, + getAuthObjectForAcceptedToken, + getAuthObjectFromJwt, + getMachineTokenType, + invalidTokenAuthObject, + isMachineTokenByPrefix, + isMachineTokenType, + isTokenTypeAccepted, + makeAuthObjectSerializable, + reverificationError, + reverificationErrorResponse, + signedInAuthObject, + signedOutAuthObject, + stripPrivateDataFromObject, + unauthenticatedMachineObject, + verifyMachineAuthToken +} from "./chunk-EEWX6LTS.mjs"; +import "./chunk-LWOXHF4E.mjs"; +import "./chunk-XJ4RTXJG.mjs"; +import "./chunk-YW6OOOXM.mjs"; +import "./chunk-RPS7XK5K.mjs"; +export { + AuthStatus, + TokenType, + authenticatedMachineObject, + constants, + createAuthenticateRequest, + createClerkRequest, + createRedirect, + debugRequestState, + decorateObjectWithResources, + getAuthObjectForAcceptedToken, + getAuthObjectFromJwt, + getMachineTokenType, + invalidTokenAuthObject, + isMachineTokenByPrefix, + isMachineTokenType, + isTokenTypeAccepted, + makeAuthObjectSerializable, + reverificationError, + reverificationErrorResponse, + signedInAuthObject, + signedOutAuthObject, + stripPrivateDataFromObject, + unauthenticatedMachineObject, + verifyMachineAuthToken +}; +//# sourceMappingURL=internal.mjs.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/internal.mjs.map b/backend/node_modules/@clerk/backend/dist/internal.mjs.map new file mode 100644 index 000000000..84c51b288 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/internal.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/jwt/algorithms.d.ts b/backend/node_modules/@clerk/backend/dist/jwt/algorithms.d.ts new file mode 100644 index 000000000..1b86b7613 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/jwt/algorithms.d.ts @@ -0,0 +1,3 @@ +export declare const algs: string[]; +export declare function getCryptoAlgorithm(algorithmName: string): RsaHashedImportParams; +//# sourceMappingURL=algorithms.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/jwt/algorithms.d.ts.map b/backend/node_modules/@clerk/backend/dist/jwt/algorithms.d.ts.map new file mode 100644 index 000000000..59b64a748 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/jwt/algorithms.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"algorithms.d.ts","sourceRoot":"","sources":["../../src/jwt/algorithms.ts"],"names":[],"mappings":"AAaA,eAAO,MAAM,IAAI,UAAyB,CAAC;AAE3C,wBAAgB,kBAAkB,CAAC,aAAa,EAAE,MAAM,GAAG,qBAAqB,CAY/E"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/jwt/assertions.d.ts b/backend/node_modules/@clerk/backend/dist/jwt/assertions.d.ts new file mode 100644 index 000000000..5e2fd5b70 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/jwt/assertions.d.ts @@ -0,0 +1,10 @@ +export type IssuerResolver = string | ((iss: string) => boolean); +export declare const assertAudienceClaim: (aud?: unknown, audience?: unknown) => void; +export declare const assertHeaderType: (typ?: unknown) => void; +export declare const assertHeaderAlgorithm: (alg: string) => void; +export declare const assertSubClaim: (sub?: string) => void; +export declare const assertAuthorizedPartiesClaim: (azp?: string, authorizedParties?: string[]) => void; +export declare const assertExpirationClaim: (exp: number, clockSkewInMs: number) => void; +export declare const assertActivationClaim: (nbf: number | undefined, clockSkewInMs: number) => void; +export declare const assertIssuedAtClaim: (iat: number | undefined, clockSkewInMs: number) => void; +//# sourceMappingURL=assertions.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/jwt/assertions.d.ts.map b/backend/node_modules/@clerk/backend/dist/jwt/assertions.d.ts.map new file mode 100644 index 000000000..920d82952 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/jwt/assertions.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"assertions.d.ts","sourceRoot":"","sources":["../../src/jwt/assertions.ts"],"names":[],"mappings":"AAGA,MAAM,MAAM,cAAc,GAAG,MAAM,GAAG,CAAC,CAAC,GAAG,EAAE,MAAM,KAAK,OAAO,CAAC,CAAC;AAMjE,eAAO,MAAM,mBAAmB,GAAI,MAAM,OAAO,EAAE,WAAW,OAAO,SAsCpE,CAAC;AAEF,eAAO,MAAM,gBAAgB,GAAI,MAAM,OAAO,SAY7C,CAAC;AAEF,eAAO,MAAM,qBAAqB,GAAI,KAAK,MAAM,SAQhD,CAAC;AAEF,eAAO,MAAM,cAAc,GAAI,MAAM,MAAM,SAQ1C,CAAC;AAEF,eAAO,MAAM,4BAA4B,GAAI,MAAM,MAAM,EAAE,oBAAoB,MAAM,EAAE,SAWtF,CAAC;AAEF,eAAO,MAAM,qBAAqB,GAAI,KAAK,MAAM,EAAE,eAAe,MAAM,SAoBvE,CAAC;AAEF,eAAO,MAAM,qBAAqB,GAAI,KAAK,MAAM,GAAG,SAAS,EAAE,eAAe,MAAM,SAwBnF,CAAC;AAEF,eAAO,MAAM,mBAAmB,GAAI,KAAK,MAAM,GAAG,SAAS,EAAE,eAAe,MAAM,SAwBjF,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/jwt/cryptoKeys.d.ts b/backend/node_modules/@clerk/backend/dist/jwt/cryptoKeys.d.ts new file mode 100644 index 000000000..199b09e5b --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/jwt/cryptoKeys.d.ts @@ -0,0 +1,2 @@ +export declare function importKey(key: JsonWebKey | string, algorithm: RsaHashedImportParams, keyUsage: 'verify' | 'sign'): Promise; +//# sourceMappingURL=cryptoKeys.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/jwt/cryptoKeys.d.ts.map b/backend/node_modules/@clerk/backend/dist/jwt/cryptoKeys.d.ts.map new file mode 100644 index 000000000..c9df4bee8 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/jwt/cryptoKeys.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"cryptoKeys.d.ts","sourceRoot":"","sources":["../../src/jwt/cryptoKeys.ts"],"names":[],"mappings":"AAuBA,wBAAgB,SAAS,CACvB,GAAG,EAAE,UAAU,GAAG,MAAM,EACxB,SAAS,EAAE,qBAAqB,EAChC,QAAQ,EAAE,QAAQ,GAAG,MAAM,GAC1B,OAAO,CAAC,SAAS,CAAC,CASpB"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/jwt/index.d.ts b/backend/node_modules/@clerk/backend/dist/jwt/index.d.ts new file mode 100644 index 000000000..9b30082c7 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/jwt/index.d.ts @@ -0,0 +1,7 @@ +export type { VerifyJwtOptions } from './verifyJwt'; +export type { SignJwtOptions } from './signJwt'; +export declare const verifyJwt: (token: string, options: import("./verifyJwt").VerifyJwtOptions) => Promise>; +export declare const decodeJwt: (token: string) => import("@clerk/types").Jwt; +export declare const signJwt: (payload: Record, key: string | JsonWebKey, options: import("./signJwt").SignJwtOptions) => Promise; +export declare const hasValidSignature: (jwt: import("@clerk/types").Jwt, key: string | JsonWebKey) => Promise>; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/jwt/index.d.ts.map b/backend/node_modules/@clerk/backend/dist/jwt/index.d.ts.map new file mode 100644 index 000000000..04a9abedb --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/jwt/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/jwt/index.ts"],"names":[],"mappings":"AAIA,YAAY,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AACpD,YAAY,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAKhD,eAAO,MAAM,SAAS,yIAA+B,CAAC;AACtD,eAAO,MAAM,SAAS,+CAAmC,CAAC;AAE1D,eAAO,MAAM,OAAO,8HAA6B,CAAC;AAClD,eAAO,MAAM,iBAAiB,0GAAuC,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/jwt/index.js b/backend/node_modules/@clerk/backend/dist/jwt/index.js new file mode 100644 index 000000000..a314b5d5d --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/jwt/index.js @@ -0,0 +1,515 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/jwt/index.ts +var jwt_exports = {}; +__export(jwt_exports, { + decodeJwt: () => decodeJwt2, + hasValidSignature: () => hasValidSignature2, + signJwt: () => signJwt2, + verifyJwt: () => verifyJwt2 +}); +module.exports = __toCommonJS(jwt_exports); + +// src/jwt/legacyReturn.ts +function withLegacyReturn(cb) { + return async (...args) => { + const { data, errors } = await cb(...args); + if (errors) { + throw errors[0]; + } + return data; + }; +} +function withLegacySyncReturn(cb) { + return (...args) => { + const { data, errors } = cb(...args); + if (errors) { + throw errors[0]; + } + return data; + }; +} + +// src/errors.ts +var TokenVerificationErrorReason = { + TokenExpired: "token-expired", + TokenInvalid: "token-invalid", + TokenInvalidAlgorithm: "token-invalid-algorithm", + TokenInvalidAuthorizedParties: "token-invalid-authorized-parties", + TokenInvalidSignature: "token-invalid-signature", + TokenNotActiveYet: "token-not-active-yet", + TokenIatInTheFuture: "token-iat-in-the-future", + TokenVerificationFailed: "token-verification-failed", + InvalidSecretKey: "secret-key-invalid", + LocalJWKMissing: "jwk-local-missing", + RemoteJWKFailedToLoad: "jwk-remote-failed-to-load", + RemoteJWKInvalid: "jwk-remote-invalid", + RemoteJWKMissing: "jwk-remote-missing", + JWKFailedToResolve: "jwk-failed-to-resolve", + JWKKidMismatch: "jwk-kid-mismatch" +}; +var TokenVerificationErrorAction = { + ContactSupport: "Contact support@clerk.com", + EnsureClerkJWT: "Make sure that this is a valid Clerk generate JWT.", + SetClerkJWTKey: "Set the CLERK_JWT_KEY environment variable.", + SetClerkSecretKey: "Set the CLERK_SECRET_KEY environment variable.", + EnsureClockSync: "Make sure your system clock is in sync (e.g. turn off and on automatic time synchronization)." +}; +var TokenVerificationError = class _TokenVerificationError extends Error { + constructor({ + action, + message, + reason + }) { + super(message); + Object.setPrototypeOf(this, _TokenVerificationError.prototype); + this.reason = reason; + this.message = message; + this.action = action; + } + getFullMessage() { + return `${[this.message, this.action].filter((m) => m).join(" ")} (reason=${this.reason}, token-carrier=${this.tokenCarrier})`; + } +}; +var SignJWTError = class extends Error { +}; + +// src/runtime.ts +var import_crypto = require("#crypto"); +var globalFetch = fetch.bind(globalThis); +var runtime = { + crypto: import_crypto.webcrypto, + get fetch() { + return process.env.NODE_ENV === "test" ? fetch : globalFetch; + }, + AbortController: globalThis.AbortController, + Blob: globalThis.Blob, + FormData: globalThis.FormData, + Headers: globalThis.Headers, + Request: globalThis.Request, + Response: globalThis.Response +}; + +// src/util/rfc4648.ts +var base64url = { + parse(string, opts) { + return parse(string, base64UrlEncoding, opts); + }, + stringify(data, opts) { + return stringify(data, base64UrlEncoding, opts); + } +}; +var base64UrlEncoding = { + chars: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_", + bits: 6 +}; +function parse(string, encoding, opts = {}) { + if (!encoding.codes) { + encoding.codes = {}; + for (let i = 0; i < encoding.chars.length; ++i) { + encoding.codes[encoding.chars[i]] = i; + } + } + if (!opts.loose && string.length * encoding.bits & 7) { + throw new SyntaxError("Invalid padding"); + } + let end = string.length; + while (string[end - 1] === "=") { + --end; + if (!opts.loose && !((string.length - end) * encoding.bits & 7)) { + throw new SyntaxError("Invalid padding"); + } + } + const out = new (opts.out ?? Uint8Array)(end * encoding.bits / 8 | 0); + let bits = 0; + let buffer = 0; + let written = 0; + for (let i = 0; i < end; ++i) { + const value = encoding.codes[string[i]]; + if (value === void 0) { + throw new SyntaxError("Invalid character " + string[i]); + } + buffer = buffer << encoding.bits | value; + bits += encoding.bits; + if (bits >= 8) { + bits -= 8; + out[written++] = 255 & buffer >> bits; + } + } + if (bits >= encoding.bits || 255 & buffer << 8 - bits) { + throw new SyntaxError("Unexpected end of data"); + } + return out; +} +function stringify(data, encoding, opts = {}) { + const { pad = true } = opts; + const mask = (1 << encoding.bits) - 1; + let out = ""; + let bits = 0; + let buffer = 0; + for (let i = 0; i < data.length; ++i) { + buffer = buffer << 8 | 255 & data[i]; + bits += 8; + while (bits > encoding.bits) { + bits -= encoding.bits; + out += encoding.chars[mask & buffer >> bits]; + } + } + if (bits) { + out += encoding.chars[mask & buffer << encoding.bits - bits]; + } + if (pad) { + while (out.length * encoding.bits & 7) { + out += "="; + } + } + return out; +} + +// src/jwt/algorithms.ts +var algToHash = { + RS256: "SHA-256", + RS384: "SHA-384", + RS512: "SHA-512" +}; +var RSA_ALGORITHM_NAME = "RSASSA-PKCS1-v1_5"; +var jwksAlgToCryptoAlg = { + RS256: RSA_ALGORITHM_NAME, + RS384: RSA_ALGORITHM_NAME, + RS512: RSA_ALGORITHM_NAME +}; +var algs = Object.keys(algToHash); +function getCryptoAlgorithm(algorithmName) { + const hash = algToHash[algorithmName]; + const name = jwksAlgToCryptoAlg[algorithmName]; + if (!hash || !name) { + throw new Error(`Unsupported algorithm ${algorithmName}, expected one of ${algs.join(",")}.`); + } + return { + hash: { name: algToHash[algorithmName] }, + name: jwksAlgToCryptoAlg[algorithmName] + }; +} + +// src/jwt/cryptoKeys.ts +var import_isomorphicAtob = require("@clerk/shared/isomorphicAtob"); +function pemToBuffer(secret) { + const trimmed = secret.replace(/-----BEGIN.*?-----/g, "").replace(/-----END.*?-----/g, "").replace(/\s/g, ""); + const decoded = (0, import_isomorphicAtob.isomorphicAtob)(trimmed); + const buffer = new ArrayBuffer(decoded.length); + const bufView = new Uint8Array(buffer); + for (let i = 0, strLen = decoded.length; i < strLen; i++) { + bufView[i] = decoded.charCodeAt(i); + } + return bufView; +} +function importKey(key, algorithm, keyUsage) { + if (typeof key === "object") { + return runtime.crypto.subtle.importKey("jwk", key, algorithm, false, [keyUsage]); + } + const keyData = pemToBuffer(key); + const format = keyUsage === "sign" ? "pkcs8" : "spki"; + return runtime.crypto.subtle.importKey(format, keyData, algorithm, false, [keyUsage]); +} + +// src/jwt/signJwt.ts +function encodeJwtData(value) { + const stringified = JSON.stringify(value); + const encoder = new TextEncoder(); + const encoded = encoder.encode(stringified); + return base64url.stringify(encoded, { pad: false }); +} +async function signJwt(payload, key, options) { + if (!options.algorithm) { + throw new Error("No algorithm specified"); + } + const encoder = new TextEncoder(); + const algorithm = getCryptoAlgorithm(options.algorithm); + if (!algorithm) { + return { + errors: [new SignJWTError(`Unsupported algorithm ${options.algorithm}`)] + }; + } + const cryptoKey = await importKey(key, algorithm, "sign"); + const header = options.header || { typ: "JWT" }; + header.alg = options.algorithm; + payload.iat = Math.floor(Date.now() / 1e3); + const encodedHeader = encodeJwtData(header); + const encodedPayload = encodeJwtData(payload); + const firstPart = `${encodedHeader}.${encodedPayload}`; + try { + const signature = await runtime.crypto.subtle.sign(algorithm, cryptoKey, encoder.encode(firstPart)); + const encodedSignature = `${firstPart}.${base64url.stringify(new Uint8Array(signature), { pad: false })}`; + return { data: encodedSignature }; + } catch (error) { + return { errors: [new SignJWTError(error?.message)] }; + } +} + +// src/jwt/assertions.ts +var isArrayString = (s) => { + return Array.isArray(s) && s.length > 0 && s.every((a) => typeof a === "string"); +}; +var assertAudienceClaim = (aud, audience) => { + const audienceList = [audience].flat().filter((a) => !!a); + const audList = [aud].flat().filter((a) => !!a); + const shouldVerifyAudience = audienceList.length > 0 && audList.length > 0; + if (!shouldVerifyAudience) { + return; + } + if (typeof aud === "string") { + if (!audienceList.includes(aud)) { + throw new TokenVerificationError({ + action: TokenVerificationErrorAction.EnsureClerkJWT, + reason: TokenVerificationErrorReason.TokenVerificationFailed, + message: `Invalid JWT audience claim (aud) ${JSON.stringify(aud)}. Is not included in "${JSON.stringify( + audienceList + )}".` + }); + } + } else if (isArrayString(aud)) { + if (!aud.some((a) => audienceList.includes(a))) { + throw new TokenVerificationError({ + action: TokenVerificationErrorAction.EnsureClerkJWT, + reason: TokenVerificationErrorReason.TokenVerificationFailed, + message: `Invalid JWT audience claim array (aud) ${JSON.stringify(aud)}. Is not included in "${JSON.stringify( + audienceList + )}".` + }); + } + } +}; +var assertHeaderType = (typ) => { + if (typeof typ === "undefined") { + return; + } + if (typ !== "JWT") { + throw new TokenVerificationError({ + action: TokenVerificationErrorAction.EnsureClerkJWT, + reason: TokenVerificationErrorReason.TokenInvalid, + message: `Invalid JWT type ${JSON.stringify(typ)}. Expected "JWT".` + }); + } +}; +var assertHeaderAlgorithm = (alg) => { + if (!algs.includes(alg)) { + throw new TokenVerificationError({ + action: TokenVerificationErrorAction.EnsureClerkJWT, + reason: TokenVerificationErrorReason.TokenInvalidAlgorithm, + message: `Invalid JWT algorithm ${JSON.stringify(alg)}. Supported: ${algs}.` + }); + } +}; +var assertSubClaim = (sub) => { + if (typeof sub !== "string") { + throw new TokenVerificationError({ + action: TokenVerificationErrorAction.EnsureClerkJWT, + reason: TokenVerificationErrorReason.TokenVerificationFailed, + message: `Subject claim (sub) is required and must be a string. Received ${JSON.stringify(sub)}.` + }); + } +}; +var assertAuthorizedPartiesClaim = (azp, authorizedParties) => { + if (!azp || !authorizedParties || authorizedParties.length === 0) { + return; + } + if (!authorizedParties.includes(azp)) { + throw new TokenVerificationError({ + reason: TokenVerificationErrorReason.TokenInvalidAuthorizedParties, + message: `Invalid JWT Authorized party claim (azp) ${JSON.stringify(azp)}. Expected "${authorizedParties}".` + }); + } +}; +var assertExpirationClaim = (exp, clockSkewInMs) => { + if (typeof exp !== "number") { + throw new TokenVerificationError({ + action: TokenVerificationErrorAction.EnsureClerkJWT, + reason: TokenVerificationErrorReason.TokenVerificationFailed, + message: `Invalid JWT expiry date claim (exp) ${JSON.stringify(exp)}. Expected number.` + }); + } + const currentDate = new Date(Date.now()); + const expiryDate = /* @__PURE__ */ new Date(0); + expiryDate.setUTCSeconds(exp); + const expired = expiryDate.getTime() <= currentDate.getTime() - clockSkewInMs; + if (expired) { + throw new TokenVerificationError({ + reason: TokenVerificationErrorReason.TokenExpired, + message: `JWT is expired. Expiry date: ${expiryDate.toUTCString()}, Current date: ${currentDate.toUTCString()}.` + }); + } +}; +var assertActivationClaim = (nbf, clockSkewInMs) => { + if (typeof nbf === "undefined") { + return; + } + if (typeof nbf !== "number") { + throw new TokenVerificationError({ + action: TokenVerificationErrorAction.EnsureClerkJWT, + reason: TokenVerificationErrorReason.TokenVerificationFailed, + message: `Invalid JWT not before date claim (nbf) ${JSON.stringify(nbf)}. Expected number.` + }); + } + const currentDate = new Date(Date.now()); + const notBeforeDate = /* @__PURE__ */ new Date(0); + notBeforeDate.setUTCSeconds(nbf); + const early = notBeforeDate.getTime() > currentDate.getTime() + clockSkewInMs; + if (early) { + throw new TokenVerificationError({ + reason: TokenVerificationErrorReason.TokenNotActiveYet, + message: `JWT cannot be used prior to not before date claim (nbf). Not before date: ${notBeforeDate.toUTCString()}; Current date: ${currentDate.toUTCString()};` + }); + } +}; +var assertIssuedAtClaim = (iat, clockSkewInMs) => { + if (typeof iat === "undefined") { + return; + } + if (typeof iat !== "number") { + throw new TokenVerificationError({ + action: TokenVerificationErrorAction.EnsureClerkJWT, + reason: TokenVerificationErrorReason.TokenVerificationFailed, + message: `Invalid JWT issued at date claim (iat) ${JSON.stringify(iat)}. Expected number.` + }); + } + const currentDate = new Date(Date.now()); + const issuedAtDate = /* @__PURE__ */ new Date(0); + issuedAtDate.setUTCSeconds(iat); + const postIssued = issuedAtDate.getTime() > currentDate.getTime() + clockSkewInMs; + if (postIssued) { + throw new TokenVerificationError({ + reason: TokenVerificationErrorReason.TokenIatInTheFuture, + message: `JWT issued at date claim (iat) is in the future. Issued at date: ${issuedAtDate.toUTCString()}; Current date: ${currentDate.toUTCString()};` + }); + } +}; + +// src/jwt/verifyJwt.ts +var DEFAULT_CLOCK_SKEW_IN_MS = 5 * 1e3; +async function hasValidSignature(jwt, key) { + const { header, signature, raw } = jwt; + const encoder = new TextEncoder(); + const data = encoder.encode([raw.header, raw.payload].join(".")); + const algorithm = getCryptoAlgorithm(header.alg); + try { + const cryptoKey = await importKey(key, algorithm, "verify"); + const verified = await runtime.crypto.subtle.verify(algorithm.name, cryptoKey, signature, data); + return { data: verified }; + } catch (error) { + return { + errors: [ + new TokenVerificationError({ + reason: TokenVerificationErrorReason.TokenInvalidSignature, + message: error?.message + }) + ] + }; + } +} +function decodeJwt(token) { + const tokenParts = (token || "").toString().split("."); + if (tokenParts.length !== 3) { + return { + errors: [ + new TokenVerificationError({ + reason: TokenVerificationErrorReason.TokenInvalid, + message: `Invalid JWT form. A JWT consists of three parts separated by dots.` + }) + ] + }; + } + const [rawHeader, rawPayload, rawSignature] = tokenParts; + const decoder = new TextDecoder(); + const header = JSON.parse(decoder.decode(base64url.parse(rawHeader, { loose: true }))); + const payload = JSON.parse(decoder.decode(base64url.parse(rawPayload, { loose: true }))); + const signature = base64url.parse(rawSignature, { loose: true }); + const data = { + header, + payload, + signature, + raw: { + header: rawHeader, + payload: rawPayload, + signature: rawSignature, + text: token + } + }; + return { data }; +} +async function verifyJwt(token, options) { + const { audience, authorizedParties, clockSkewInMs, key } = options; + const clockSkew = clockSkewInMs || DEFAULT_CLOCK_SKEW_IN_MS; + const { data: decoded, errors } = decodeJwt(token); + if (errors) { + return { errors }; + } + const { header, payload } = decoded; + try { + const { typ, alg } = header; + assertHeaderType(typ); + assertHeaderAlgorithm(alg); + const { azp, sub, aud, iat, exp, nbf } = payload; + assertSubClaim(sub); + assertAudienceClaim([aud], [audience]); + assertAuthorizedPartiesClaim(azp, authorizedParties); + assertExpirationClaim(exp, clockSkew); + assertActivationClaim(nbf, clockSkew); + assertIssuedAtClaim(iat, clockSkew); + } catch (err) { + return { errors: [err] }; + } + const { data: signatureValid, errors: signatureErrors } = await hasValidSignature(decoded, key); + if (signatureErrors) { + return { + errors: [ + new TokenVerificationError({ + action: TokenVerificationErrorAction.EnsureClerkJWT, + reason: TokenVerificationErrorReason.TokenVerificationFailed, + message: `Error verifying JWT signature. ${signatureErrors[0]}` + }) + ] + }; + } + if (!signatureValid) { + return { + errors: [ + new TokenVerificationError({ + reason: TokenVerificationErrorReason.TokenInvalidSignature, + message: "JWT signature is invalid." + }) + ] + }; + } + return { data: payload }; +} + +// src/jwt/index.ts +var verifyJwt2 = withLegacyReturn(verifyJwt); +var decodeJwt2 = withLegacySyncReturn(decodeJwt); +var signJwt2 = withLegacyReturn(signJwt); +var hasValidSignature2 = withLegacyReturn(hasValidSignature); +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + decodeJwt, + hasValidSignature, + signJwt, + verifyJwt +}); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/jwt/index.js.map b/backend/node_modules/@clerk/backend/dist/jwt/index.js.map new file mode 100644 index 000000000..ebec8a9be --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/jwt/index.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/jwt/index.ts","../../src/jwt/legacyReturn.ts","../../src/errors.ts","../../src/runtime.ts","../../src/util/rfc4648.ts","../../src/jwt/algorithms.ts","../../src/jwt/cryptoKeys.ts","../../src/jwt/signJwt.ts","../../src/jwt/assertions.ts","../../src/jwt/verifyJwt.ts"],"sourcesContent":["import { withLegacyReturn, withLegacySyncReturn } from './legacyReturn';\nimport { signJwt as _signJwt } from './signJwt';\nimport { decodeJwt as _decodeJwt, hasValidSignature as _hasValidSignature, verifyJwt as _verifyJwt } from './verifyJwt';\n\nexport type { VerifyJwtOptions } from './verifyJwt';\nexport type { SignJwtOptions } from './signJwt';\n\n// Introduce compatibility layer to avoid more breaking changes\n// TODO(dimkl): This (probably be drop in the next major version)\n\nexport const verifyJwt = withLegacyReturn(_verifyJwt);\nexport const decodeJwt = withLegacySyncReturn(_decodeJwt);\n\nexport const signJwt = withLegacyReturn(_signJwt);\nexport const hasValidSignature = withLegacyReturn(_hasValidSignature);\n","import type { JwtReturnType } from './types';\n\n// TODO(dimkl): Will be probably be dropped in next major version\nexport function withLegacyReturn Promise>>(cb: T) {\n return async (...args: Parameters): Promise>['data']>> | never => {\n const { data, errors } = await cb(...args);\n if (errors) {\n throw errors[0];\n }\n return data;\n };\n}\n\n// TODO(dimkl): Will be probably be dropped in next major version\nexport function withLegacySyncReturn JwtReturnType>(cb: T) {\n return (...args: Parameters): NonNullable>['data']> | never => {\n const { data, errors } = cb(...args);\n if (errors) {\n throw errors[0];\n }\n return data;\n };\n}\n","export type TokenCarrier = 'header' | 'cookie';\n\nexport const TokenVerificationErrorCode = {\n InvalidSecretKey: 'clerk_key_invalid',\n};\n\nexport type TokenVerificationErrorCode = (typeof TokenVerificationErrorCode)[keyof typeof TokenVerificationErrorCode];\n\nexport const TokenVerificationErrorReason = {\n TokenExpired: 'token-expired',\n TokenInvalid: 'token-invalid',\n TokenInvalidAlgorithm: 'token-invalid-algorithm',\n TokenInvalidAuthorizedParties: 'token-invalid-authorized-parties',\n TokenInvalidSignature: 'token-invalid-signature',\n TokenNotActiveYet: 'token-not-active-yet',\n TokenIatInTheFuture: 'token-iat-in-the-future',\n TokenVerificationFailed: 'token-verification-failed',\n InvalidSecretKey: 'secret-key-invalid',\n LocalJWKMissing: 'jwk-local-missing',\n RemoteJWKFailedToLoad: 'jwk-remote-failed-to-load',\n RemoteJWKInvalid: 'jwk-remote-invalid',\n RemoteJWKMissing: 'jwk-remote-missing',\n JWKFailedToResolve: 'jwk-failed-to-resolve',\n JWKKidMismatch: 'jwk-kid-mismatch',\n};\n\nexport type TokenVerificationErrorReason =\n (typeof TokenVerificationErrorReason)[keyof typeof TokenVerificationErrorReason];\n\nexport const TokenVerificationErrorAction = {\n ContactSupport: 'Contact support@clerk.com',\n EnsureClerkJWT: 'Make sure that this is a valid Clerk generate JWT.',\n SetClerkJWTKey: 'Set the CLERK_JWT_KEY environment variable.',\n SetClerkSecretKey: 'Set the CLERK_SECRET_KEY environment variable.',\n EnsureClockSync: 'Make sure your system clock is in sync (e.g. turn off and on automatic time synchronization).',\n};\n\nexport type TokenVerificationErrorAction =\n (typeof TokenVerificationErrorAction)[keyof typeof TokenVerificationErrorAction];\n\nexport class TokenVerificationError extends Error {\n action?: TokenVerificationErrorAction;\n reason: TokenVerificationErrorReason;\n tokenCarrier?: TokenCarrier;\n\n constructor({\n action,\n message,\n reason,\n }: {\n action?: TokenVerificationErrorAction;\n message: string;\n reason: TokenVerificationErrorReason;\n }) {\n super(message);\n\n Object.setPrototypeOf(this, TokenVerificationError.prototype);\n\n this.reason = reason;\n this.message = message;\n this.action = action;\n }\n\n public getFullMessage() {\n return `${[this.message, this.action].filter(m => m).join(' ')} (reason=${this.reason}, token-carrier=${\n this.tokenCarrier\n })`;\n }\n}\n\nexport class SignJWTError extends Error {}\n\nexport const MachineTokenVerificationErrorCode = {\n TokenInvalid: 'token-invalid',\n InvalidSecretKey: 'secret-key-invalid',\n UnexpectedError: 'unexpected-error',\n} as const;\n\nexport type MachineTokenVerificationErrorCode =\n (typeof MachineTokenVerificationErrorCode)[keyof typeof MachineTokenVerificationErrorCode];\n\nexport class MachineTokenVerificationError extends Error {\n code: MachineTokenVerificationErrorCode;\n long_message?: string;\n status: number;\n\n constructor({ message, code, status }: { message: string; code: MachineTokenVerificationErrorCode; status: number }) {\n super(message);\n Object.setPrototypeOf(this, MachineTokenVerificationError.prototype);\n\n this.code = code;\n this.status = status;\n }\n\n public getFullMessage() {\n return `${this.message} (code=${this.code}, status=${this.status})`;\n }\n}\n","/**\n * This file exports APIs that vary across runtimes (i.e. Node & Browser - V8 isolates)\n * as a singleton object.\n *\n * Runtime polyfills are written in VanillaJS for now to avoid TS complication. Moreover,\n * due to this issue https://github.com/microsoft/TypeScript/issues/44848, there is not a good way\n * to tell Typescript which conditional import to use during build type.\n *\n * The Runtime type definition ensures type safety for now.\n * Runtime js modules are copied into dist folder with bash script.\n *\n * TODO: Support TS runtime modules\n */\n\n// @ts-ignore - These are package subpaths\nimport { webcrypto as crypto } from '#crypto';\n\ntype Runtime = {\n crypto: Crypto;\n fetch: typeof globalThis.fetch;\n AbortController: typeof globalThis.AbortController;\n Blob: typeof globalThis.Blob;\n FormData: typeof globalThis.FormData;\n Headers: typeof globalThis.Headers;\n Request: typeof globalThis.Request;\n Response: typeof globalThis.Response;\n};\n\n// Invoking the global.fetch without binding it first to the globalObject fails in\n// Cloudflare Workers with an \"Illegal Invocation\" error.\n//\n// The globalThis object is supported for Node >= 12.0.\n//\n// https://github.com/supabase/supabase/issues/4417\nconst globalFetch = fetch.bind(globalThis);\n\nexport const runtime: Runtime = {\n crypto,\n get fetch() {\n // We need to use the globalFetch for Cloudflare Workers but the fetch for testing\n return process.env.NODE_ENV === 'test' ? fetch : globalFetch;\n },\n AbortController: globalThis.AbortController,\n Blob: globalThis.Blob,\n FormData: globalThis.FormData,\n Headers: globalThis.Headers,\n Request: globalThis.Request,\n Response: globalThis.Response,\n};\n","/**\n * The base64url helper was extracted from the rfc4648 package\n * in order to resolve CSJ/ESM interoperability issues\n *\n * https://github.com/swansontec/rfc4648.js\n *\n * For more context please refer to:\n * - https://github.com/evanw/esbuild/issues/1719\n * - https://github.com/evanw/esbuild/issues/532\n * - https://github.com/swansontec/rollup-plugin-mjs-entry\n */\nexport const base64url = {\n parse(string: string, opts?: ParseOptions): Uint8Array {\n return parse(string, base64UrlEncoding, opts);\n },\n\n stringify(data: ArrayLike, opts?: StringifyOptions): string {\n return stringify(data, base64UrlEncoding, opts);\n },\n};\n\nconst base64UrlEncoding: Encoding = {\n chars: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',\n bits: 6,\n};\n\ninterface Encoding {\n bits: number;\n chars: string;\n codes?: { [char: string]: number };\n}\n\ninterface ParseOptions {\n loose?: boolean;\n out?: new (size: number) => { [index: number]: number };\n}\n\ninterface StringifyOptions {\n pad?: boolean;\n}\n\nfunction parse(string: string, encoding: Encoding, opts: ParseOptions = {}): Uint8Array {\n // Build the character lookup table:\n if (!encoding.codes) {\n encoding.codes = {};\n for (let i = 0; i < encoding.chars.length; ++i) {\n encoding.codes[encoding.chars[i]] = i;\n }\n }\n\n // The string must have a whole number of bytes:\n if (!opts.loose && (string.length * encoding.bits) & 7) {\n throw new SyntaxError('Invalid padding');\n }\n\n // Count the padding bytes:\n let end = string.length;\n while (string[end - 1] === '=') {\n --end;\n\n // If we get a whole number of bytes, there is too much padding:\n if (!opts.loose && !(((string.length - end) * encoding.bits) & 7)) {\n throw new SyntaxError('Invalid padding');\n }\n }\n\n // Allocate the output:\n const out = new (opts.out ?? Uint8Array)(((end * encoding.bits) / 8) | 0) as Uint8Array;\n\n // Parse the data:\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n let written = 0; // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = encoding.codes[string[i]];\n if (value === undefined) {\n throw new SyntaxError('Invalid character ' + string[i]);\n }\n\n // Append the bits to the buffer:\n buffer = (buffer << encoding.bits) | value;\n bits += encoding.bits;\n\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8;\n out[written++] = 0xff & (buffer >> bits);\n }\n }\n\n // Verify that we have received just enough bits:\n if (bits >= encoding.bits || 0xff & (buffer << (8 - bits))) {\n throw new SyntaxError('Unexpected end of data');\n }\n\n return out;\n}\n\nfunction stringify(data: ArrayLike, encoding: Encoding, opts: StringifyOptions = {}): string {\n const { pad = true } = opts;\n const mask = (1 << encoding.bits) - 1;\n let out = '';\n\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | (0xff & data[i]);\n bits += 8;\n\n // Write out as much as we can:\n while (bits > encoding.bits) {\n bits -= encoding.bits;\n out += encoding.chars[mask & (buffer >> bits)];\n }\n }\n\n // Partial character:\n if (bits) {\n out += encoding.chars[mask & (buffer << (encoding.bits - bits))];\n }\n\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while ((out.length * encoding.bits) & 7) {\n out += '=';\n }\n }\n\n return out;\n}\n","const algToHash: Record = {\n RS256: 'SHA-256',\n RS384: 'SHA-384',\n RS512: 'SHA-512',\n};\nconst RSA_ALGORITHM_NAME = 'RSASSA-PKCS1-v1_5';\n\nconst jwksAlgToCryptoAlg: Record = {\n RS256: RSA_ALGORITHM_NAME,\n RS384: RSA_ALGORITHM_NAME,\n RS512: RSA_ALGORITHM_NAME,\n};\n\nexport const algs = Object.keys(algToHash);\n\nexport function getCryptoAlgorithm(algorithmName: string): RsaHashedImportParams {\n const hash = algToHash[algorithmName];\n const name = jwksAlgToCryptoAlg[algorithmName];\n\n if (!hash || !name) {\n throw new Error(`Unsupported algorithm ${algorithmName}, expected one of ${algs.join(',')}.`);\n }\n\n return {\n hash: { name: algToHash[algorithmName] },\n name: jwksAlgToCryptoAlg[algorithmName],\n };\n}\n","import { isomorphicAtob } from '@clerk/shared/isomorphicAtob';\n\nimport { runtime } from '../runtime';\n\n// https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/importKey#pkcs_8_import\nfunction pemToBuffer(secret: string): ArrayBuffer {\n const trimmed = secret\n .replace(/-----BEGIN.*?-----/g, '')\n .replace(/-----END.*?-----/g, '')\n .replace(/\\s/g, '');\n\n const decoded = isomorphicAtob(trimmed);\n\n const buffer = new ArrayBuffer(decoded.length);\n const bufView = new Uint8Array(buffer);\n\n for (let i = 0, strLen = decoded.length; i < strLen; i++) {\n bufView[i] = decoded.charCodeAt(i);\n }\n\n return bufView;\n}\n\nexport function importKey(\n key: JsonWebKey | string,\n algorithm: RsaHashedImportParams,\n keyUsage: 'verify' | 'sign',\n): Promise {\n if (typeof key === 'object') {\n return runtime.crypto.subtle.importKey('jwk', key, algorithm, false, [keyUsage]);\n }\n\n const keyData = pemToBuffer(key);\n const format = keyUsage === 'sign' ? 'pkcs8' : 'spki';\n\n return runtime.crypto.subtle.importKey(format, keyData, algorithm, false, [keyUsage]);\n}\n","import { SignJWTError } from '../errors';\nimport { runtime } from '../runtime';\nimport { base64url } from '../util/rfc4648';\nimport { getCryptoAlgorithm } from './algorithms';\nimport { importKey } from './cryptoKeys';\nimport type { JwtReturnType } from './types';\n\nexport interface SignJwtOptions {\n algorithm?: string;\n header?: Record;\n}\n\nfunction encodeJwtData(value: unknown): string {\n const stringified = JSON.stringify(value);\n const encoder = new TextEncoder();\n const encoded = encoder.encode(stringified);\n return base64url.stringify(encoded, { pad: false });\n}\n\n/**\n * Signs a JSON Web Token (JWT) with the given payload, key, and options.\n * This function is intended to be used *internally* by other Clerk packages and typically\n * should not be used directly.\n *\n * @internal\n * @param payload The payload to include in the JWT.\n * @param key The key to use for signing the JWT. Can be a string or a JsonWebKey.\n * @param options The options to use for signing the JWT.\n * @returns A Promise that resolves to the signed JWT string.\n * @throws An error if no algorithm is specified or if the specified algorithm is unsupported.\n * @throws An error if there is an issue with importing the key or signing the JWT.\n */\nexport async function signJwt(\n payload: Record,\n key: string | JsonWebKey,\n options: SignJwtOptions,\n): Promise> {\n if (!options.algorithm) {\n throw new Error('No algorithm specified');\n }\n const encoder = new TextEncoder();\n\n const algorithm = getCryptoAlgorithm(options.algorithm);\n if (!algorithm) {\n return {\n errors: [new SignJWTError(`Unsupported algorithm ${options.algorithm}`)],\n };\n }\n\n const cryptoKey = await importKey(key, algorithm, 'sign');\n const header = options.header || { typ: 'JWT' };\n\n header.alg = options.algorithm;\n payload.iat = Math.floor(Date.now() / 1000);\n\n const encodedHeader = encodeJwtData(header);\n const encodedPayload = encodeJwtData(payload);\n const firstPart = `${encodedHeader}.${encodedPayload}`;\n\n try {\n const signature = await runtime.crypto.subtle.sign(algorithm, cryptoKey, encoder.encode(firstPart));\n const encodedSignature = `${firstPart}.${base64url.stringify(new Uint8Array(signature), { pad: false })}`;\n return { data: encodedSignature };\n } catch (error) {\n return { errors: [new SignJWTError((error as Error)?.message)] };\n }\n}\n","import { TokenVerificationError, TokenVerificationErrorAction, TokenVerificationErrorReason } from '../errors';\nimport { algs } from './algorithms';\n\nexport type IssuerResolver = string | ((iss: string) => boolean);\n\nconst isArrayString = (s: unknown): s is string[] => {\n return Array.isArray(s) && s.length > 0 && s.every(a => typeof a === 'string');\n};\n\nexport const assertAudienceClaim = (aud?: unknown, audience?: unknown) => {\n const audienceList = [audience].flat().filter(a => !!a);\n const audList = [aud].flat().filter(a => !!a);\n const shouldVerifyAudience = audienceList.length > 0 && audList.length > 0;\n\n if (!shouldVerifyAudience) {\n // Notice: Clerk JWTs use AZP claim instead of Audience\n //\n // return {\n // valid: false,\n // reason: `Invalid JWT audience claim (aud) ${JSON.stringify(\n // aud,\n // )}. Expected a string or a non-empty array of strings.`,\n // };\n return;\n }\n\n if (typeof aud === 'string') {\n if (!audienceList.includes(aud)) {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.EnsureClerkJWT,\n reason: TokenVerificationErrorReason.TokenVerificationFailed,\n message: `Invalid JWT audience claim (aud) ${JSON.stringify(aud)}. Is not included in \"${JSON.stringify(\n audienceList,\n )}\".`,\n });\n }\n } else if (isArrayString(aud)) {\n if (!aud.some(a => audienceList.includes(a))) {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.EnsureClerkJWT,\n reason: TokenVerificationErrorReason.TokenVerificationFailed,\n message: `Invalid JWT audience claim array (aud) ${JSON.stringify(aud)}. Is not included in \"${JSON.stringify(\n audienceList,\n )}\".`,\n });\n }\n }\n};\n\nexport const assertHeaderType = (typ?: unknown) => {\n if (typeof typ === 'undefined') {\n return;\n }\n\n if (typ !== 'JWT') {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.EnsureClerkJWT,\n reason: TokenVerificationErrorReason.TokenInvalid,\n message: `Invalid JWT type ${JSON.stringify(typ)}. Expected \"JWT\".`,\n });\n }\n};\n\nexport const assertHeaderAlgorithm = (alg: string) => {\n if (!algs.includes(alg)) {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.EnsureClerkJWT,\n reason: TokenVerificationErrorReason.TokenInvalidAlgorithm,\n message: `Invalid JWT algorithm ${JSON.stringify(alg)}. Supported: ${algs}.`,\n });\n }\n};\n\nexport const assertSubClaim = (sub?: string) => {\n if (typeof sub !== 'string') {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.EnsureClerkJWT,\n reason: TokenVerificationErrorReason.TokenVerificationFailed,\n message: `Subject claim (sub) is required and must be a string. Received ${JSON.stringify(sub)}.`,\n });\n }\n};\n\nexport const assertAuthorizedPartiesClaim = (azp?: string, authorizedParties?: string[]) => {\n if (!azp || !authorizedParties || authorizedParties.length === 0) {\n return;\n }\n\n if (!authorizedParties.includes(azp)) {\n throw new TokenVerificationError({\n reason: TokenVerificationErrorReason.TokenInvalidAuthorizedParties,\n message: `Invalid JWT Authorized party claim (azp) ${JSON.stringify(azp)}. Expected \"${authorizedParties}\".`,\n });\n }\n};\n\nexport const assertExpirationClaim = (exp: number, clockSkewInMs: number) => {\n if (typeof exp !== 'number') {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.EnsureClerkJWT,\n reason: TokenVerificationErrorReason.TokenVerificationFailed,\n message: `Invalid JWT expiry date claim (exp) ${JSON.stringify(exp)}. Expected number.`,\n });\n }\n\n const currentDate = new Date(Date.now());\n const expiryDate = new Date(0);\n expiryDate.setUTCSeconds(exp);\n\n const expired = expiryDate.getTime() <= currentDate.getTime() - clockSkewInMs;\n if (expired) {\n throw new TokenVerificationError({\n reason: TokenVerificationErrorReason.TokenExpired,\n message: `JWT is expired. Expiry date: ${expiryDate.toUTCString()}, Current date: ${currentDate.toUTCString()}.`,\n });\n }\n};\n\nexport const assertActivationClaim = (nbf: number | undefined, clockSkewInMs: number) => {\n if (typeof nbf === 'undefined') {\n return;\n }\n\n if (typeof nbf !== 'number') {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.EnsureClerkJWT,\n reason: TokenVerificationErrorReason.TokenVerificationFailed,\n message: `Invalid JWT not before date claim (nbf) ${JSON.stringify(nbf)}. Expected number.`,\n });\n }\n\n const currentDate = new Date(Date.now());\n const notBeforeDate = new Date(0);\n notBeforeDate.setUTCSeconds(nbf);\n\n const early = notBeforeDate.getTime() > currentDate.getTime() + clockSkewInMs;\n if (early) {\n throw new TokenVerificationError({\n reason: TokenVerificationErrorReason.TokenNotActiveYet,\n message: `JWT cannot be used prior to not before date claim (nbf). Not before date: ${notBeforeDate.toUTCString()}; Current date: ${currentDate.toUTCString()};`,\n });\n }\n};\n\nexport const assertIssuedAtClaim = (iat: number | undefined, clockSkewInMs: number) => {\n if (typeof iat === 'undefined') {\n return;\n }\n\n if (typeof iat !== 'number') {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.EnsureClerkJWT,\n reason: TokenVerificationErrorReason.TokenVerificationFailed,\n message: `Invalid JWT issued at date claim (iat) ${JSON.stringify(iat)}. Expected number.`,\n });\n }\n\n const currentDate = new Date(Date.now());\n const issuedAtDate = new Date(0);\n issuedAtDate.setUTCSeconds(iat);\n\n const postIssued = issuedAtDate.getTime() > currentDate.getTime() + clockSkewInMs;\n if (postIssued) {\n throw new TokenVerificationError({\n reason: TokenVerificationErrorReason.TokenIatInTheFuture,\n message: `JWT issued at date claim (iat) is in the future. Issued at date: ${issuedAtDate.toUTCString()}; Current date: ${currentDate.toUTCString()};`,\n });\n }\n};\n","import type { Jwt, JwtPayload } from '@clerk/types';\n\nimport { TokenVerificationError, TokenVerificationErrorAction, TokenVerificationErrorReason } from '../errors';\nimport { runtime } from '../runtime';\nimport { base64url } from '../util/rfc4648';\nimport { getCryptoAlgorithm } from './algorithms';\nimport {\n assertActivationClaim,\n assertAudienceClaim,\n assertAuthorizedPartiesClaim,\n assertExpirationClaim,\n assertHeaderAlgorithm,\n assertHeaderType,\n assertIssuedAtClaim,\n assertSubClaim,\n} from './assertions';\nimport { importKey } from './cryptoKeys';\nimport type { JwtReturnType } from './types';\n\nconst DEFAULT_CLOCK_SKEW_IN_MS = 5 * 1000;\n\nexport async function hasValidSignature(jwt: Jwt, key: JsonWebKey | string): Promise> {\n const { header, signature, raw } = jwt;\n const encoder = new TextEncoder();\n const data = encoder.encode([raw.header, raw.payload].join('.'));\n const algorithm = getCryptoAlgorithm(header.alg);\n\n try {\n const cryptoKey = await importKey(key, algorithm, 'verify');\n\n const verified = await runtime.crypto.subtle.verify(algorithm.name, cryptoKey, signature, data);\n return { data: verified };\n } catch (error) {\n return {\n errors: [\n new TokenVerificationError({\n reason: TokenVerificationErrorReason.TokenInvalidSignature,\n message: (error as Error)?.message,\n }),\n ],\n };\n }\n}\n\nexport function decodeJwt(token: string): JwtReturnType {\n const tokenParts = (token || '').toString().split('.');\n if (tokenParts.length !== 3) {\n return {\n errors: [\n new TokenVerificationError({\n reason: TokenVerificationErrorReason.TokenInvalid,\n message: `Invalid JWT form. A JWT consists of three parts separated by dots.`,\n }),\n ],\n };\n }\n\n const [rawHeader, rawPayload, rawSignature] = tokenParts;\n\n const decoder = new TextDecoder();\n\n // To verify a JWS with SubtleCrypto you need to be careful to encode and decode\n // the data properly between binary and base64url representation. Unfortunately\n // the standard implementation in the V8 of btoa() and atob() are difficult to\n // work with as they use \"a Unicode string containing only characters in the\n // range U+0000 to U+00FF, each representing a binary byte with values 0x00 to\n // 0xFF respectively\" as the representation of binary data.\n\n // A better solution to represent binary data in Javascript is to use ES6 TypedArray\n // and use a Javascript library to convert them to base64url that honors RFC 4648.\n\n // Side note: The difference between base64 and base64url is the characters selected\n // for value 62 and 63 in the standard, base64 encode them to + and / while base64url\n // encode - and _.\n\n // More info at https://stackoverflow.com/questions/54062583/how-to-verify-a-signed-jwt-with-subtlecrypto-of-the-web-crypto-API\n const header = JSON.parse(decoder.decode(base64url.parse(rawHeader, { loose: true })));\n const payload = JSON.parse(decoder.decode(base64url.parse(rawPayload, { loose: true })));\n\n const signature = base64url.parse(rawSignature, { loose: true });\n\n const data = {\n header,\n payload,\n signature,\n raw: {\n header: rawHeader,\n payload: rawPayload,\n signature: rawSignature,\n text: token,\n },\n } satisfies Jwt;\n\n return { data };\n}\n\n/**\n * @inline\n */\nexport type VerifyJwtOptions = {\n /**\n * A string or list of [audiences](https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.3). If passed, it is checked against the `aud` claim in the token.\n */\n audience?: string | string[];\n /**\n * An allowlist of origins to verify against, to protect your application from the subdomain cookie leaking attack.\n * @example\n * ```ts\n * ['http://localhost:3000', 'https://example.com']\n * ```\n */\n authorizedParties?: string[];\n /**\n * Specifies the allowed time difference (in milliseconds) between the Clerk server (which generates the token) and the clock of the user's application server when validating a token.\n * @default 5000\n */\n clockSkewInMs?: number;\n /**\n * @internal\n */\n key: JsonWebKey | string;\n};\n\nexport async function verifyJwt(\n token: string,\n options: VerifyJwtOptions,\n): Promise> {\n const { audience, authorizedParties, clockSkewInMs, key } = options;\n const clockSkew = clockSkewInMs || DEFAULT_CLOCK_SKEW_IN_MS;\n\n const { data: decoded, errors } = decodeJwt(token);\n if (errors) {\n return { errors };\n }\n\n const { header, payload } = decoded;\n try {\n // Header verifications\n const { typ, alg } = header;\n\n assertHeaderType(typ);\n assertHeaderAlgorithm(alg);\n\n // Payload verifications\n const { azp, sub, aud, iat, exp, nbf } = payload;\n\n assertSubClaim(sub);\n assertAudienceClaim([aud], [audience]);\n assertAuthorizedPartiesClaim(azp, authorizedParties);\n assertExpirationClaim(exp, clockSkew);\n assertActivationClaim(nbf, clockSkew);\n assertIssuedAtClaim(iat, clockSkew);\n } catch (err) {\n return { errors: [err as TokenVerificationError] };\n }\n\n const { data: signatureValid, errors: signatureErrors } = await hasValidSignature(decoded, key);\n if (signatureErrors) {\n return {\n errors: [\n new TokenVerificationError({\n action: TokenVerificationErrorAction.EnsureClerkJWT,\n reason: TokenVerificationErrorReason.TokenVerificationFailed,\n message: `Error verifying JWT signature. ${signatureErrors[0]}`,\n }),\n ],\n };\n }\n\n if (!signatureValid) {\n return {\n errors: [\n new TokenVerificationError({\n reason: TokenVerificationErrorReason.TokenInvalidSignature,\n message: 'JWT signature is invalid.',\n }),\n ],\n };\n }\n\n return { data: payload };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA,mBAAAA;AAAA,EAAA,yBAAAC;AAAA,EAAA,eAAAC;AAAA,EAAA,iBAAAC;AAAA;AAAA;;;ACGO,SAAS,iBAAiF,IAAO;AACtG,SAAO,UAAU,SAAsF;AACrG,UAAM,EAAE,MAAM,OAAO,IAAI,MAAM,GAAG,GAAG,IAAI;AACzC,QAAI,QAAQ;AACV,YAAM,OAAO,CAAC;AAAA,IAChB;AACA,WAAO;AAAA,EACT;AACF;AAGO,SAAS,qBAA4E,IAAO;AACjG,SAAO,IAAI,SAA6E;AACtF,UAAM,EAAE,MAAM,OAAO,IAAI,GAAG,GAAG,IAAI;AACnC,QAAI,QAAQ;AACV,YAAM,OAAO,CAAC;AAAA,IAChB;AACA,WAAO;AAAA,EACT;AACF;;;ACdO,IAAM,+BAA+B;AAAA,EAC1C,cAAc;AAAA,EACd,cAAc;AAAA,EACd,uBAAuB;AAAA,EACvB,+BAA+B;AAAA,EAC/B,uBAAuB;AAAA,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ClB;AAEA,QAAM,EAAE,QAAQ,QAAQ,IAAI;AAC5B,MAAI;AAEF,UAAM,EAAE,KAAK,IAAI,IAAI;AAErB,qBAAiB,GAAG;AACpB,0BAAsB,GAAG;AAGzB,UAAM,EAAE,KAAK,KAAK,KAAK,KAAK,KAAK,IAAI,IAAI;AAEzC,mBAAe,GAAG;AAClB,wBAAoB,CAAC,GAAG,GAAG,CAAC,QAAQ,CAAC;AACrC,iCAA6B,KAAK,iBAAiB;AACnD,0BAAsB,KAAK,SAAS;AACpC,0BAAsB,KAAK,SAAS;AACpC,wBAAoB,KAAK,SAAS;AAAA,EACpC,SAAS,KAAK;AACZ,WAAO,EAAE,QAAQ,CAAC,GAA6B,EAAE;AAAA,EACnD;AAEA,QAAM,EAAE,MAAM,gBAAgB,QAAQ,gBAAgB,IAAI,MAAM,kBAAkB,SAAS,GAAG;AAC9F,MAAI,iBAAiB;AACnB,WAAO;AAAA,MACL,QAAQ;AAAA,QACN,IAAI,uBAAuB;AAAA,UACzB,QAAQ,6BAA6B;AAAA,UACrC,QAAQ,6BAA6B;AAAA,UACrC,SAAS,kCAAkC,gBAAgB,CAAC,CAAC;AAAA,QAC/D,CAAC;AAAA,MACH;AAAA,IACF;AAAA,EACF;AAEA,MAAI,CAAC,gBAAgB;AACnB,WAAO;AAAA,MACL,QAAQ;AAAA,QACN,IAAI,uBAAuB;AAAA,UACzB,QAAQ,6BAA6B;AAAA,UACrC,SAAS;AAAA,QACX,CAAC;AAAA,MACH;AAAA,IACF;AAAA,EACF;AAEA,SAAO,EAAE,MAAM,QAAQ;AACzB;;;AT3KO,IAAMC,aAAY,iBAAiB,SAAU;AAC7C,IAAMC,aAAY,qBAAqB,SAAU;AAEjD,IAAMC,WAAU,iBAAiB,OAAQ;AACzC,IAAMC,qBAAoB,iBAAiB,iBAAkB;","names":["decodeJwt","hasValidSignature","signJwt","verifyJwt","crypto","verifyJwt","decodeJwt","signJwt","hasValidSignature"]} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/jwt/index.mjs b/backend/node_modules/@clerk/backend/dist/jwt/index.mjs new file mode 100644 index 000000000..421ca5132 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/jwt/index.mjs @@ -0,0 +1,64 @@ +import { + withLegacyReturn, + withLegacySyncReturn +} from "../chunk-P263NW7Z.mjs"; +import { + base64url, + decodeJwt, + getCryptoAlgorithm, + hasValidSignature, + importKey, + runtime, + verifyJwt +} from "../chunk-XJ4RTXJG.mjs"; +import { + SignJWTError +} from "../chunk-YW6OOOXM.mjs"; +import "../chunk-RPS7XK5K.mjs"; + +// src/jwt/signJwt.ts +function encodeJwtData(value) { + const stringified = JSON.stringify(value); + const encoder = new TextEncoder(); + const encoded = encoder.encode(stringified); + return base64url.stringify(encoded, { pad: false }); +} +async function signJwt(payload, key, options) { + if (!options.algorithm) { + throw new Error("No algorithm specified"); + } + const encoder = new TextEncoder(); + const algorithm = getCryptoAlgorithm(options.algorithm); + if (!algorithm) { + return { + errors: [new SignJWTError(`Unsupported algorithm ${options.algorithm}`)] + }; + } + const cryptoKey = await importKey(key, algorithm, "sign"); + const header = options.header || { typ: "JWT" }; + header.alg = options.algorithm; + payload.iat = Math.floor(Date.now() / 1e3); + const encodedHeader = encodeJwtData(header); + const encodedPayload = encodeJwtData(payload); + const firstPart = `${encodedHeader}.${encodedPayload}`; + try { + const signature = await runtime.crypto.subtle.sign(algorithm, cryptoKey, encoder.encode(firstPart)); + const encodedSignature = `${firstPart}.${base64url.stringify(new Uint8Array(signature), { pad: false })}`; + return { data: encodedSignature }; + } catch (error) { + return { errors: [new SignJWTError(error?.message)] }; + } +} + +// src/jwt/index.ts +var verifyJwt2 = withLegacyReturn(verifyJwt); +var decodeJwt2 = withLegacySyncReturn(decodeJwt); +var signJwt2 = withLegacyReturn(signJwt); +var hasValidSignature2 = withLegacyReturn(hasValidSignature); +export { + decodeJwt2 as decodeJwt, + hasValidSignature2 as hasValidSignature, + signJwt2 as signJwt, + verifyJwt2 as verifyJwt +}; +//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/jwt/index.mjs.map b/backend/node_modules/@clerk/backend/dist/jwt/index.mjs.map new file mode 100644 index 000000000..41263b29e --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/jwt/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/jwt/signJwt.ts","../../src/jwt/index.ts"],"sourcesContent":["import { SignJWTError } from '../errors';\nimport { runtime } from '../runtime';\nimport { base64url } from '../util/rfc4648';\nimport { getCryptoAlgorithm } from './algorithms';\nimport { importKey } from './cryptoKeys';\nimport type { JwtReturnType } from './types';\n\nexport interface SignJwtOptions {\n algorithm?: string;\n header?: Record;\n}\n\nfunction encodeJwtData(value: unknown): string {\n const stringified = JSON.stringify(value);\n const encoder = new TextEncoder();\n const encoded = encoder.encode(stringified);\n return base64url.stringify(encoded, { pad: false });\n}\n\n/**\n * Signs a JSON Web Token (JWT) with the given payload, key, and options.\n * This function is intended to be used *internally* by other Clerk packages and typically\n * should not be used directly.\n *\n * @internal\n * @param payload The payload to include in the JWT.\n * @param key The key to use for signing the JWT. Can be a string or a JsonWebKey.\n * @param options The options to use for signing the JWT.\n * @returns A Promise that resolves to the signed JWT string.\n * @throws An error if no algorithm is specified or if the specified algorithm is unsupported.\n * @throws An error if there is an issue with importing the key or signing the JWT.\n */\nexport async function signJwt(\n payload: Record,\n key: string | JsonWebKey,\n options: SignJwtOptions,\n): Promise> {\n if (!options.algorithm) {\n throw new Error('No algorithm specified');\n }\n const encoder = new TextEncoder();\n\n const algorithm = getCryptoAlgorithm(options.algorithm);\n if (!algorithm) {\n return {\n errors: [new SignJWTError(`Unsupported algorithm ${options.algorithm}`)],\n };\n }\n\n const cryptoKey = await importKey(key, algorithm, 'sign');\n const header = options.header || { typ: 'JWT' };\n\n header.alg = options.algorithm;\n payload.iat = Math.floor(Date.now() / 1000);\n\n const encodedHeader = encodeJwtData(header);\n const encodedPayload = encodeJwtData(payload);\n const firstPart = `${encodedHeader}.${encodedPayload}`;\n\n try {\n const signature = await runtime.crypto.subtle.sign(algorithm, cryptoKey, encoder.encode(firstPart));\n const encodedSignature = `${firstPart}.${base64url.stringify(new Uint8Array(signature), { pad: false })}`;\n return { data: encodedSignature };\n } catch (error) {\n return { errors: [new SignJWTError((error as Error)?.message)] };\n }\n}\n","import { withLegacyReturn, withLegacySyncReturn } from './legacyReturn';\nimport { signJwt as _signJwt } from './signJwt';\nimport { decodeJwt as _decodeJwt, hasValidSignature as _hasValidSignature, verifyJwt as _verifyJwt } from './verifyJwt';\n\nexport type { VerifyJwtOptions } from './verifyJwt';\nexport type { SignJwtOptions } from './signJwt';\n\n// Introduce compatibility layer to avoid more breaking changes\n// TODO(dimkl): This (probably be drop in the next major version)\n\nexport const verifyJwt = withLegacyReturn(_verifyJwt);\nexport const decodeJwt = withLegacySyncReturn(_decodeJwt);\n\nexport const signJwt = withLegacyReturn(_signJwt);\nexport const hasValidSignature = withLegacyReturn(_hasValidSignature);\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAYA,SAAS,cAAc,OAAwB;AAC7C,QAAM,cAAc,KAAK,UAAU,KAAK;AACxC,QAAM,UAAU,IAAI,YAAY;AAChC,QAAM,UAAU,QAAQ,OAAO,WAAW;AAC1C,SAAO,UAAU,UAAU,SAAS,EAAE,KAAK,MAAM,CAAC;AACpD;AAeA,eAAsB,QACpB,SACA,KACA,SACuC;AACvC,MAAI,CAAC,QAAQ,WAAW;AACtB,UAAM,IAAI,MAAM,wBAAwB;AAAA,EAC1C;AACA,QAAM,UAAU,IAAI,YAAY;AAEhC,QAAM,YAAY,mBAAmB,QAAQ,SAAS;AACtD,MAAI,CAAC,WAAW;AACd,WAAO;AAAA,MACL,QAAQ,CAAC,IAAI,aAAa,yBAAyB,QAAQ,SAAS,EAAE,CAAC;AAAA,IACzE;AAAA,EACF;AAEA,QAAM,YAAY,MAAM,UAAU,KAAK,WAAW,MAAM;AACxD,QAAM,SAAS,QAAQ,UAAU,EAAE,KAAK,MAAM;AAE9C,SAAO,MAAM,QAAQ;AACrB,UAAQ,MAAM,KAAK,MAAM,KAAK,IAAI,IAAI,GAAI;AAE1C,QAAM,gBAAgB,cAAc,MAAM;AAC1C,QAAM,iBAAiB,cAAc,OAAO;AAC5C,QAAM,YAAY,GAAG,aAAa,IAAI,cAAc;AAEpD,MAAI;AACF,UAAM,YAAY,MAAM,QAAQ,OAAO,OAAO,KAAK,WAAW,WAAW,QAAQ,OAAO,SAAS,CAAC;AAClG,UAAM,mBAAmB,GAAG,SAAS,IAAI,UAAU,UAAU,IAAI,WAAW,SAAS,GAAG,EAAE,KAAK,MAAM,CAAC,CAAC;AACvG,WAAO,EAAE,MAAM,iBAAiB;AAAA,EAClC,SAAS,OAAO;AACd,WAAO,EAAE,QAAQ,CAAC,IAAI,aAAc,OAAiB,OAAO,CAAC,EAAE;AAAA,EACjE;AACF;;;ACxDO,IAAMA,aAAY,iBAAiB,SAAU;AAC7C,IAAMC,aAAY,qBAAqB,SAAU;AAEjD,IAAMC,WAAU,iBAAiB,OAAQ;AACzC,IAAMC,qBAAoB,iBAAiB,iBAAkB;","names":["verifyJwt","decodeJwt","signJwt","hasValidSignature"]} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/jwt/legacyReturn.d.ts b/backend/node_modules/@clerk/backend/dist/jwt/legacyReturn.d.ts new file mode 100644 index 000000000..f3e947908 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/jwt/legacyReturn.d.ts @@ -0,0 +1,4 @@ +import type { JwtReturnType } from './types'; +export declare function withLegacyReturn Promise>>(cb: T): (...args: Parameters) => Promise>["data"]>> | never; +export declare function withLegacySyncReturn JwtReturnType>(cb: T): (...args: Parameters) => NonNullable>["data"]> | never; +//# sourceMappingURL=legacyReturn.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/jwt/legacyReturn.d.ts.map b/backend/node_modules/@clerk/backend/dist/jwt/legacyReturn.d.ts.map new file mode 100644 index 000000000..56b417697 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/jwt/legacyReturn.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"legacyReturn.d.ts","sourceRoot":"","sources":["../../src/jwt/legacyReturn.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAG7C,wBAAgB,gBAAgB,CAAC,CAAC,SAAS,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,OAAO,CAAC,aAAa,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,IACtF,GAAG,MAAM,UAAU,CAAC,CAAC,CAAC,KAAG,OAAO,CAAC,WAAW,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,KAAK,CAOpG;AAGD,wBAAgB,oBAAoB,CAAC,CAAC,SAAS,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,aAAa,CAAC,GAAG,EAAE,GAAG,CAAC,EAAE,EAAE,EAAE,CAAC,IACvF,GAAG,MAAM,UAAU,CAAC,CAAC,CAAC,KAAG,WAAW,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,GAAG,KAAK,CAOrF"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/jwt/signJwt.d.ts b/backend/node_modules/@clerk/backend/dist/jwt/signJwt.d.ts new file mode 100644 index 000000000..3c973f841 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/jwt/signJwt.d.ts @@ -0,0 +1,20 @@ +import type { JwtReturnType } from './types'; +export interface SignJwtOptions { + algorithm?: string; + header?: Record; +} +/** + * Signs a JSON Web Token (JWT) with the given payload, key, and options. + * This function is intended to be used *internally* by other Clerk packages and typically + * should not be used directly. + * + * @internal + * @param payload The payload to include in the JWT. + * @param key The key to use for signing the JWT. Can be a string or a JsonWebKey. + * @param options The options to use for signing the JWT. + * @returns A Promise that resolves to the signed JWT string. + * @throws An error if no algorithm is specified or if the specified algorithm is unsupported. + * @throws An error if there is an issue with importing the key or signing the JWT. + */ +export declare function signJwt(payload: Record, key: string | JsonWebKey, options: SignJwtOptions): Promise>; +//# sourceMappingURL=signJwt.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/jwt/signJwt.d.ts.map b/backend/node_modules/@clerk/backend/dist/jwt/signJwt.d.ts.map new file mode 100644 index 000000000..41416625a --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/jwt/signJwt.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"signJwt.d.ts","sourceRoot":"","sources":["../../src/jwt/signJwt.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAE7C,MAAM,WAAW,cAAc;IAC7B,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAClC;AASD;;;;;;;;;;;;GAYG;AACH,wBAAsB,OAAO,CAC3B,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAChC,GAAG,EAAE,MAAM,GAAG,UAAU,EACxB,OAAO,EAAE,cAAc,GACtB,OAAO,CAAC,aAAa,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC,CA8BvC"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/jwt/types.d.ts b/backend/node_modules/@clerk/backend/dist/jwt/types.d.ts new file mode 100644 index 000000000..df6950e48 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/jwt/types.d.ts @@ -0,0 +1,18 @@ +import type { MachineTokenType } from '../tokens/tokenTypes'; +export type JwtReturnType = { + data: R; + errors?: undefined; +} | { + data?: undefined; + errors: [E]; +}; +export type MachineTokenReturnType = { + data: R; + tokenType: MachineTokenType; + errors?: undefined; +} | { + data?: undefined; + tokenType: MachineTokenType; + errors: [E]; +}; +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/jwt/types.d.ts.map b/backend/node_modules/@clerk/backend/dist/jwt/types.d.ts.map new file mode 100644 index 000000000..7975ef018 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/jwt/types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/jwt/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AAE7D,MAAM,MAAM,aAAa,CAAC,CAAC,EAAE,CAAC,SAAS,KAAK,IACxC;IACE,IAAI,EAAE,CAAC,CAAC;IACR,MAAM,CAAC,EAAE,SAAS,CAAC;CACpB,GACD;IACE,IAAI,CAAC,EAAE,SAAS,CAAC;IACjB,MAAM,EAAE,CAAC,CAAC,CAAC,CAAC;CACb,CAAC;AAEN,MAAM,MAAM,sBAAsB,CAAC,CAAC,EAAE,CAAC,SAAS,KAAK,IACjD;IACE,IAAI,EAAE,CAAC,CAAC;IACR,SAAS,EAAE,gBAAgB,CAAC;IAC5B,MAAM,CAAC,EAAE,SAAS,CAAC;CACpB,GACD;IACE,IAAI,CAAC,EAAE,SAAS,CAAC;IACjB,SAAS,EAAE,gBAAgB,CAAC;IAC5B,MAAM,EAAE,CAAC,CAAC,CAAC,CAAC;CACb,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/jwt/verifyJwt.d.ts b/backend/node_modules/@clerk/backend/dist/jwt/verifyJwt.d.ts new file mode 100644 index 000000000..440eab57a --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/jwt/verifyJwt.d.ts @@ -0,0 +1,33 @@ +import type { Jwt, JwtPayload } from '@clerk/types'; +import { TokenVerificationError } from '../errors'; +import type { JwtReturnType } from './types'; +export declare function hasValidSignature(jwt: Jwt, key: JsonWebKey | string): Promise>; +export declare function decodeJwt(token: string): JwtReturnType; +/** + * @inline + */ +export type VerifyJwtOptions = { + /** + * A string or list of [audiences](https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.3). If passed, it is checked against the `aud` claim in the token. + */ + audience?: string | string[]; + /** + * An allowlist of origins to verify against, to protect your application from the subdomain cookie leaking attack. + * @example + * ```ts + * ['http://localhost:3000', 'https://example.com'] + * ``` + */ + authorizedParties?: string[]; + /** + * Specifies the allowed time difference (in milliseconds) between the Clerk server (which generates the token) and the clock of the user's application server when validating a token. + * @default 5000 + */ + clockSkewInMs?: number; + /** + * @internal + */ + key: JsonWebKey | string; +}; +export declare function verifyJwt(token: string, options: VerifyJwtOptions): Promise>; +//# sourceMappingURL=verifyJwt.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/jwt/verifyJwt.d.ts.map b/backend/node_modules/@clerk/backend/dist/jwt/verifyJwt.d.ts.map new file mode 100644 index 000000000..51a17263b --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/jwt/verifyJwt.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"verifyJwt.d.ts","sourceRoot":"","sources":["../../src/jwt/verifyJwt.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAEpD,OAAO,EAAE,sBAAsB,EAA8D,MAAM,WAAW,CAAC;AAe/G,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAI7C,wBAAsB,iBAAiB,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,UAAU,GAAG,MAAM,GAAG,OAAO,CAAC,aAAa,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC,CAqBlH;AAED,wBAAgB,SAAS,CAAC,KAAK,EAAE,MAAM,GAAG,aAAa,CAAC,GAAG,EAAE,sBAAsB,CAAC,CAkDnF;AAED;;GAEG;AACH,MAAM,MAAM,gBAAgB,GAAG;IAC7B;;OAEG;IACH,QAAQ,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC;IAC7B;;;;;;OAMG;IACH,iBAAiB,CAAC,EAAE,MAAM,EAAE,CAAC;IAC7B;;;OAGG;IACH,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB;;OAEG;IACH,GAAG,EAAE,UAAU,GAAG,MAAM,CAAC;CAC1B,CAAC;AAEF,wBAAsB,SAAS,CAC7B,KAAK,EAAE,MAAM,EACb,OAAO,EAAE,gBAAgB,GACxB,OAAO,CAAC,aAAa,CAAC,UAAU,EAAE,sBAAsB,CAAC,CAAC,CAuD5D"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/mock-server.d.ts b/backend/node_modules/@clerk/backend/dist/mock-server.d.ts new file mode 100644 index 000000000..945c4ff31 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/mock-server.d.ts @@ -0,0 +1,4 @@ +import { type DefaultBodyType, type HttpResponseResolver, type PathParams } from 'msw'; +export declare const server: import("msw/node").SetupServerApi; +export declare function validateHeaders(resolver: HttpResponseResolver): HttpResponseResolver; +//# sourceMappingURL=mock-server.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/mock-server.d.ts.map b/backend/node_modules/@clerk/backend/dist/mock-server.d.ts.map new file mode 100644 index 000000000..275199a58 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/mock-server.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"mock-server.d.ts","sourceRoot":"","sources":["../src/mock-server.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,eAAe,EAAgB,KAAK,oBAAoB,EAAE,KAAK,UAAU,EAAE,MAAM,KAAK,CAAC;AAKrG,eAAO,MAAM,MAAM,mCAAiC,CAAC;AAGrD,wBAAgB,eAAe,CAC7B,MAAM,SAAS,UAAU,EACzB,eAAe,SAAS,eAAe,EACvC,gBAAgB,SAAS,eAAe,EAExC,QAAQ,EAAE,oBAAoB,CAAC,MAAM,EAAE,eAAe,EAAE,gBAAgB,CAAC,GACxE,oBAAoB,CAAC,MAAM,EAAE,eAAe,EAAE,gBAAgB,CAAC,CAgCjE"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/runtime.d.ts b/backend/node_modules/@clerk/backend/dist/runtime.d.ts new file mode 100644 index 000000000..b187f6d79 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/runtime.d.ts @@ -0,0 +1,26 @@ +/** + * This file exports APIs that vary across runtimes (i.e. Node & Browser - V8 isolates) + * as a singleton object. + * + * Runtime polyfills are written in VanillaJS for now to avoid TS complication. Moreover, + * due to this issue https://github.com/microsoft/TypeScript/issues/44848, there is not a good way + * to tell Typescript which conditional import to use during build type. + * + * The Runtime type definition ensures type safety for now. + * Runtime js modules are copied into dist folder with bash script. + * + * TODO: Support TS runtime modules + */ +type Runtime = { + crypto: Crypto; + fetch: typeof globalThis.fetch; + AbortController: typeof globalThis.AbortController; + Blob: typeof globalThis.Blob; + FormData: typeof globalThis.FormData; + Headers: typeof globalThis.Headers; + Request: typeof globalThis.Request; + Response: typeof globalThis.Response; +}; +export declare const runtime: Runtime; +export {}; +//# sourceMappingURL=runtime.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/runtime.d.ts.map b/backend/node_modules/@clerk/backend/dist/runtime.d.ts.map new file mode 100644 index 000000000..15147ef08 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/runtime.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"runtime.d.ts","sourceRoot":"","sources":["../src/runtime.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAKH,KAAK,OAAO,GAAG;IACb,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,OAAO,UAAU,CAAC,KAAK,CAAC;IAC/B,eAAe,EAAE,OAAO,UAAU,CAAC,eAAe,CAAC;IACnD,IAAI,EAAE,OAAO,UAAU,CAAC,IAAI,CAAC;IAC7B,QAAQ,EAAE,OAAO,UAAU,CAAC,QAAQ,CAAC;IACrC,OAAO,EAAE,OAAO,UAAU,CAAC,OAAO,CAAC;IACnC,OAAO,EAAE,OAAO,UAAU,CAAC,OAAO,CAAC;IACnC,QAAQ,EAAE,OAAO,UAAU,CAAC,QAAQ,CAAC;CACtC,CAAC;AAUF,eAAO,MAAM,OAAO,EAAE,OAYrB,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/runtime/browser/crypto.mjs b/backend/node_modules/@clerk/backend/dist/runtime/browser/crypto.mjs new file mode 100644 index 000000000..558f375dd --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/runtime/browser/crypto.mjs @@ -0,0 +1 @@ +export const webcrypto = crypto; diff --git a/backend/node_modules/@clerk/backend/dist/runtime/node/crypto.js b/backend/node_modules/@clerk/backend/dist/runtime/node/crypto.js new file mode 100644 index 000000000..dc45bca82 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/runtime/node/crypto.js @@ -0,0 +1 @@ +module.exports.webcrypto = require('node:crypto').webcrypto; diff --git a/backend/node_modules/@clerk/backend/dist/runtime/node/crypto.mjs b/backend/node_modules/@clerk/backend/dist/runtime/node/crypto.mjs new file mode 100644 index 000000000..d509c88ff --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/runtime/node/crypto.mjs @@ -0,0 +1 @@ +export { webcrypto } from 'node:crypto'; diff --git a/backend/node_modules/@clerk/backend/dist/tokens/__tests__/getAuth.test-d.d.ts b/backend/node_modules/@clerk/backend/dist/tokens/__tests__/getAuth.test-d.d.ts new file mode 100644 index 000000000..1cd64f857 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/tokens/__tests__/getAuth.test-d.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=getAuth.test-d.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/tokens/__tests__/getAuth.test-d.d.ts.map b/backend/node_modules/@clerk/backend/dist/tokens/__tests__/getAuth.test-d.d.ts.map new file mode 100644 index 000000000..0ef90f6fb --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/tokens/__tests__/getAuth.test-d.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"getAuth.test-d.d.ts","sourceRoot":"","sources":["../../../src/tokens/__tests__/getAuth.test-d.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/tokens/__tests__/request.test-d.d.ts b/backend/node_modules/@clerk/backend/dist/tokens/__tests__/request.test-d.d.ts new file mode 100644 index 000000000..7c7cbf3e3 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/tokens/__tests__/request.test-d.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=request.test-d.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/tokens/__tests__/request.test-d.d.ts.map b/backend/node_modules/@clerk/backend/dist/tokens/__tests__/request.test-d.d.ts.map new file mode 100644 index 000000000..377ba651c --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/tokens/__tests__/request.test-d.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"request.test-d.d.ts","sourceRoot":"","sources":["../../../src/tokens/__tests__/request.test-d.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/tokens/authObjects.d.ts b/backend/node_modules/@clerk/backend/dist/tokens/authObjects.d.ts new file mode 100644 index 000000000..0bb94f976 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/tokens/authObjects.d.ts @@ -0,0 +1,193 @@ +import type { CheckAuthorizationFromSessionClaims, Jwt, JwtPayload, PendingSessionOptions, ServerGetToken, SessionStatusClaim, SharedSignedInAuthObjectProperties } from '@clerk/types'; +import type { CreateBackendApiOptions } from '../api'; +import type { AuthenticateContext } from './authenticateContext'; +import type { MachineTokenType, SessionTokenType } from './tokenTypes'; +import type { AuthenticateRequestOptions, MachineAuthType } from './types'; +/** + * @inline + */ +type AuthObjectDebugData = Record; +/** + * @inline + */ +type AuthObjectDebug = () => AuthObjectDebugData; +type Claims = Record; +/** + * @internal + */ +export type SignedInAuthObjectOptions = CreateBackendApiOptions & { + token: string; +}; +/** + * @internal + */ +export type SignedInAuthObject = SharedSignedInAuthObjectProperties & { + /** + * The allowed token type. + */ + tokenType: SessionTokenType; + /** + * A function that gets the current user's [session token](https://clerk.com/docs/backend-requests/resources/session-tokens) or a [custom JWT template](https://clerk.com/docs/backend-requests/jwt-templates). + */ + getToken: ServerGetToken; + /** + * A function that checks if the user has an organization role or custom permission. + */ + has: CheckAuthorizationFromSessionClaims; + /** + * Used to help debug issues when using Clerk in development. + */ + debug: AuthObjectDebug; + isAuthenticated: true; +}; +/** + * @internal + */ +export type SignedOutAuthObject = { + sessionClaims: null; + sessionId: null; + sessionStatus: SessionStatusClaim | null; + actor: null; + tokenType: SessionTokenType; + userId: null; + orgId: null; + orgRole: null; + orgSlug: null; + orgPermissions: null; + factorVerificationAge: null; + getToken: ServerGetToken; + has: CheckAuthorizationFromSessionClaims; + debug: AuthObjectDebug; + isAuthenticated: false; +}; +/** + * Extended properties specific to each machine token type. + * While all machine token types share common properties (id, name, subject, etc), + * this type defines the additional properties that are unique to each token type. + * + * @template TAuthenticated - Whether the machine object is authenticated or not + */ +type MachineObjectExtendedProperties = { + api_key: TAuthenticated extends true ? { + name: string; + claims: Claims | null; + userId: string; + orgId: null; + } | { + name: string; + claims: Claims | null; + userId: null; + orgId: string; + } : { + name: null; + claims: null; + userId: null; + orgId: null; + }; + m2m_token: { + claims: TAuthenticated extends true ? Claims | null : null; + machineId: TAuthenticated extends true ? string : null; + }; + oauth_token: { + userId: TAuthenticated extends true ? string : null; + clientId: TAuthenticated extends true ? string : null; + }; +}; +/** + * @internal + * + * Uses `T extends any` to create a distributive conditional type. + * This ensures that union types like `'api_key' | 'oauth_token'` are processed + * individually, creating proper discriminated unions where each token type + * gets its own distinct properties (e.g., oauth_token won't have claims). + */ +export type AuthenticatedMachineObject = T extends any ? { + id: string; + subject: string; + scopes: string[]; + getToken: () => Promise; + has: CheckAuthorizationFromSessionClaims; + debug: AuthObjectDebug; + tokenType: T; + isAuthenticated: true; +} & MachineObjectExtendedProperties[T] : never; +/** + * @internal + * + * Uses `T extends any` to create a distributive conditional type. + * This ensures that union types like `'api_key' | 'oauth_token'` are processed + * individually, creating proper discriminated unions where each token type + * gets its own distinct properties (e.g., oauth_token won't have claims). + */ +export type UnauthenticatedMachineObject = T extends any ? { + id: null; + subject: null; + scopes: null; + getToken: () => Promise; + has: CheckAuthorizationFromSessionClaims; + debug: AuthObjectDebug; + tokenType: T; + isAuthenticated: false; +} & MachineObjectExtendedProperties[T] : never; +export type InvalidTokenAuthObject = { + isAuthenticated: false; + tokenType: null; + getToken: () => Promise; + has: () => false; + debug: AuthObjectDebug; +}; +/** + * @interface + */ +export type AuthObject = SignedInAuthObject | SignedOutAuthObject | AuthenticatedMachineObject | UnauthenticatedMachineObject | InvalidTokenAuthObject; +/** + * @internal + */ +export declare function signedInAuthObject(authenticateContext: Partial, sessionToken: string, sessionClaims: JwtPayload): SignedInAuthObject; +/** + * @internal + */ +export declare function signedOutAuthObject(debugData?: AuthObjectDebugData, initialSessionStatus?: SessionStatusClaim): SignedOutAuthObject; +/** + * @internal + */ +export declare function authenticatedMachineObject(tokenType: T, token: string, verificationResult: MachineAuthType, debugData?: AuthObjectDebugData): AuthenticatedMachineObject; +/** + * @internal + */ +export declare function unauthenticatedMachineObject(tokenType: T, debugData?: AuthObjectDebugData): UnauthenticatedMachineObject; +/** + * @internal + */ +export declare function invalidTokenAuthObject(): InvalidTokenAuthObject; +/** + * Auth objects moving through the server -> client boundary need to be serializable + * as we need to ensure that they can be transferred via the network as pure strings. + * Some frameworks like Remix or Next (/pages dir only) handle this serialization by simply + * ignoring any non-serializable keys, however Nextjs /app directory is stricter and + * throws an error if a non-serializable value is found. + * + * @internal + */ +export declare const makeAuthObjectSerializable: >(obj: T) => T; +/** + * @internal + */ +export declare const getAuthObjectFromJwt: (jwt: Jwt, { treatPendingAsSignedOut, ...options }: PendingSessionOptions & Partial) => SignedInAuthObject | SignedOutAuthObject; +/** + * @internal + * Returns an auth object matching the requested token type(s). + * + * If the parsed token type does not match any in acceptsToken, returns: + * - an invalid token auth object if the token is not in the accepted array + * - an unauthenticated machine object for machine tokens, or + * - a signed-out session object otherwise. + * + * This ensures the returned object always matches the developer's intent. + */ +export declare const getAuthObjectForAcceptedToken: ({ authObject, acceptsToken, }: { + authObject: AuthObject; + acceptsToken: AuthenticateRequestOptions["acceptsToken"]; +}) => AuthObject; +export {}; +//# sourceMappingURL=authObjects.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/tokens/authObjects.d.ts.map b/backend/node_modules/@clerk/backend/dist/tokens/authObjects.d.ts.map new file mode 100644 index 000000000..05c893155 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/tokens/authObjects.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"authObjects.d.ts","sourceRoot":"","sources":["../../src/tokens/authObjects.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,mCAAmC,EACnC,GAAG,EACH,UAAU,EACV,qBAAqB,EACrB,cAAc,EAEd,kBAAkB,EAClB,kCAAkC,EACnC,MAAM,cAAc,CAAC;AAEtB,OAAO,KAAK,EAAU,uBAAuB,EAAiC,MAAM,QAAQ,CAAC;AAG7F,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAEjE,OAAO,KAAK,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAEvE,OAAO,KAAK,EAAE,0BAA0B,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAE3E;;GAEG;AACH,KAAK,mBAAmB,GAAG,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;AAC/C;;GAEG;AACH,KAAK,eAAe,GAAG,MAAM,mBAAmB,CAAC;AAEjD,KAAK,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;AAElC;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G;AACH,wBAAgB,sBAAsB,IAAI,sBAAsB,CAQ/D;AAED;;;;;;;;GAQG;AACH,eAAO,MAAM,0BAA0B,GAAI,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,KAAK,CAAC,KAAG,CAKtF,CAAC;AAiDF;;GAEG;AACH,eAAO,MAAM,oBAAoB,GAC/B,KAAK,GAAG,EACR,yCAAgD,qBAAqB,GAAG,OAAO,CAAC,mBAAmB,CAAC,6CASrG,CAAC;AAEF;;;;;;;;;;GAUG;AACH,eAAO,MAAM,6BAA6B,GAAI,+BAG3C;IACD,UAAU,EAAE,UAAU,CAAC;IACvB,YAAY,EAAE,0BAA0B,CAAC,cAAc,CAAC,CAAC;CAC1D,KAAG,UAwBH,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/tokens/authStatus.d.ts b/backend/node_modules/@clerk/backend/dist/tokens/authStatus.d.ts new file mode 100644 index 000000000..171ee1605 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/tokens/authStatus.d.ts @@ -0,0 +1,120 @@ +import type { JwtPayload, PendingSessionOptions } from '@clerk/types'; +import type { TokenVerificationErrorReason } from '../errors'; +import type { AuthenticateContext } from './authenticateContext'; +import type { AuthenticatedMachineObject, InvalidTokenAuthObject, SignedInAuthObject, SignedOutAuthObject, UnauthenticatedMachineObject } from './authObjects'; +import type { MachineTokenType, SessionTokenType } from './tokenTypes'; +import { TokenType } from './tokenTypes'; +import type { MachineAuthType } from './types'; +export declare const AuthStatus: { + readonly SignedIn: "signed-in"; + readonly SignedOut: "signed-out"; + readonly Handshake: "handshake"; +}; +export type AuthStatus = (typeof AuthStatus)[keyof typeof AuthStatus]; +type ToAuth = T extends null ? () => InvalidTokenAuthObject : T extends SessionTokenType ? Authenticated extends true ? (opts?: PendingSessionOptions) => SignedInAuthObject : () => SignedOutAuthObject : Authenticated extends true ? () => AuthenticatedMachineObject> : () => UnauthenticatedMachineObject>; +export type AuthenticatedState = { + status: typeof AuthStatus.SignedIn; + reason: null; + message: null; + proxyUrl?: string; + publishableKey: string; + isSatellite: boolean; + domain: string; + signInUrl: string; + signUpUrl: string; + afterSignInUrl: string; + afterSignUpUrl: string; + /** + * @deprecated Use `isAuthenticated` instead. + */ + isSignedIn: true; + isAuthenticated: true; + headers: Headers; + token: string; + tokenType: T; + toAuth: ToAuth; +}; +export type UnauthenticatedState = { + status: typeof AuthStatus.SignedOut; + reason: AuthReason; + message: string; + proxyUrl?: string; + publishableKey: string; + isSatellite: boolean; + domain: string; + signInUrl: string; + signUpUrl: string; + afterSignInUrl: string; + afterSignUpUrl: string; + /** + * @deprecated Use `isAuthenticated` instead. + */ + isSignedIn: false; + isAuthenticated: false; + tokenType: T; + headers: Headers; + token: null; + toAuth: ToAuth; +}; +export type HandshakeState = Omit, 'status' | 'toAuth' | 'tokenType'> & { + tokenType: SessionTokenType; + status: typeof AuthStatus.Handshake; + headers: Headers; + toAuth: () => null; +}; +/** + * @deprecated Use AuthenticatedState instead + */ +export type SignedInState = AuthenticatedState; +/** + * @deprecated Use UnauthenticatedState instead + */ +export type SignedOutState = UnauthenticatedState; +export declare const AuthErrorReason: { + readonly ClientUATWithoutSessionToken: "client-uat-but-no-session-token"; + readonly DevBrowserMissing: "dev-browser-missing"; + readonly DevBrowserSync: "dev-browser-sync"; + readonly PrimaryRespondsToSyncing: "primary-responds-to-syncing"; + readonly PrimaryDomainCrossOriginSync: "primary-domain-cross-origin-sync"; + readonly SatelliteCookieNeedsSyncing: "satellite-needs-syncing"; + readonly SessionTokenAndUATMissing: "session-token-and-uat-missing"; + readonly SessionTokenMissing: "session-token-missing"; + readonly SessionTokenExpired: "session-token-expired"; + readonly SessionTokenIATBeforeClientUAT: "session-token-iat-before-client-uat"; + readonly SessionTokenNBF: "session-token-nbf"; + readonly SessionTokenIatInTheFuture: "session-token-iat-in-the-future"; + readonly SessionTokenWithoutClientUAT: "session-token-but-no-client-uat"; + readonly ActiveOrganizationMismatch: "active-organization-mismatch"; + readonly TokenTypeMismatch: "token-type-mismatch"; + readonly UnexpectedError: "unexpected-error"; +}; +export type AuthErrorReason = (typeof AuthErrorReason)[keyof typeof AuthErrorReason]; +export type AuthReason = AuthErrorReason | TokenVerificationErrorReason; +export type RequestState = AuthenticatedState | UnauthenticatedState | (T extends SessionTokenType ? HandshakeState : never); +type BaseSignedInParams = { + authenticateContext: AuthenticateContext; + headers?: Headers; + token: string; + tokenType: TokenType; +}; +type SignedInParams = (BaseSignedInParams & { + tokenType: SessionTokenType; + sessionClaims: JwtPayload; +}) | (BaseSignedInParams & { + tokenType: MachineTokenType; + machineData: MachineAuthType; +}); +export declare function signedIn(params: SignedInParams & { + tokenType: T; +}): AuthenticatedState; +type SignedOutParams = Omit & { + reason: AuthReason; + message?: string; +}; +export declare function signedOut(params: SignedOutParams & { + tokenType: T; +}): UnauthenticatedState; +export declare function handshake(authenticateContext: AuthenticateContext, reason: AuthReason, message: string | undefined, headers: Headers): HandshakeState; +export declare function signedOutInvalidToken(): UnauthenticatedState; +export {}; +//# sourceMappingURL=authStatus.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/tokens/authStatus.d.ts.map b/backend/node_modules/@clerk/backend/dist/tokens/authStatus.d.ts.map new file mode 100644 index 000000000..4a64cbe31 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/tokens/authStatus.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"authStatus.d.ts","sourceRoot":"","sources":["../../src/tokens/authStatus.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,qBAAqB,EAAE,MAAM,cAAc,CAAC;AAGtE,OAAO,KAAK,EAAE,4BAA4B,EAAE,MAAM,WAAW,CAAC;AAC9D,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AACjE,OAAO,KAAK,EACV,0BAA0B,EAC1B,sBAAsB,EACtB,kBAAkB,EAClB,mBAAmB,EACnB,4BAA4B,EAC7B,MAA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AAS,CAAC,CAAC,SAAS,SAAS,EAAE,MAAM,EAAE,eAAe,GAAG;IAAE,SAAS,EAAE,CAAC,CAAA;CAAE,GAAG,oBAAoB,CAAC,CAAC,CAAC,CA8BlH;AAED,wBAAgB,SAAS,CACvB,mBAAmB,EAAE,mBAAmB,EACxC,MAAM,EAAE,UAAU,EAClB,OAAO,oBAAK,EACZ,OAAO,EAAE,OAAO,GACf,cAAc,CAoBhB;AAED,wBAAgB,qBAAqB,IAAI,oBAAoB,CAAC,IAAI,CAAC,CAqBlE"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/tokens/authenticateContext.d.ts b/backend/node_modules/@clerk/backend/dist/tokens/authenticateContext.d.ts new file mode 100644 index 000000000..c7e88789a --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/tokens/authenticateContext.d.ts @@ -0,0 +1,78 @@ +import type { ClerkRequest } from './clerkRequest'; +import type { AuthenticateRequestOptions } from './types'; +interface AuthenticateContext extends AuthenticateRequestOptions { + accept: string | undefined; + forwardedHost: string | undefined; + forwardedProto: string | undefined; + host: string | undefined; + origin: string | undefined; + referrer: string | undefined; + secFetchDest: string | undefined; + tokenInHeader: string | undefined; + userAgent: string | undefined; + clientUat: number; + refreshTokenInCookie: string | undefined; + sessionTokenInCookie: string | undefined; + devBrowserToken: string | undefined; + handshakeNonce: string | undefined; + handshakeRedirectLoopCounter: number; + handshakeToken: string | undefined; + clerkUrl: URL; + frontendApi: string; + instanceType: string; + publishableKey: string; +} +/** + * All data required to authenticate a request. + * This is the data we use to decide whether a request + * is in a signed in or signed out state or if we need + * to perform a handshake. + */ +declare class AuthenticateContext implements AuthenticateContext { + private cookieSuffix; + private clerkRequest; + /** + * The original Clerk frontend API URL, extracted from publishable key before proxy URL override. + * Used for backend operations like token validation and issuer checking. + */ + private originalFrontendApi; + /** + * Retrieves the session token from either the cookie or the header. + * + * @returns {string | undefined} The session token if available, otherwise undefined. + */ + get sessionToken(): string | undefined; + constructor(cookieSuffix: string, clerkRequest: ClerkRequest, options: AuthenticateRequestOptions); + usesSuffixedCookies(): boolean; + /** + * Determines if the request came from a different origin based on the referrer header. + * Used for cross-origin detection in multi-domain authentication flows. + * + * @returns {boolean} True if referrer exists and is from a different origin, false otherwise. + */ + isCrossOriginReferrer(): boolean; + /** + * Determines if the referrer URL is from a Clerk domain (accounts portal or FAPI). + * This includes both development and production account portal domains, as well as FAPI domains + * used for redirect-based authentication flows. + * + * @returns {boolean} True if the referrer is from a Clerk accounts portal or FAPI domain, false otherwise + */ + isKnownClerkReferrer(): boolean; + private initPublishableKeyValues; + private initHeaderValues; + private initCookieValues; + private initHandshakeValues; + private getQueryParam; + private getHeader; + private getCookie; + private getSuffixedCookie; + private getSuffixedOrUnSuffixedCookie; + private parseAuthorizationHeader; + private tokenHasIssuer; + private tokenBelongsToInstance; + private sessionExpired; +} +export type { AuthenticateContext }; +export declare const createAuthenticateContext: (clerkRequest: ClerkRequest, options: AuthenticateRequestOptions) => Promise; +//# sourceMappingURL=authenticateContext.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/tokens/authenticateContext.d.ts.map b/backend/node_modules/@clerk/backend/dist/tokens/authenticateContext.d.ts.map new file mode 100644 index 000000000..95a930302 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/tokens/authenticateContext.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"authenticateContext.d.ts","sourceRoot":"","sources":["../../src/tokens/authenticateContext.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAEnD,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,SAAS,CAAC;AAE1D,UAAU,mBAAoB,SAAQ,0BAA0B;IAE9D,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC;IAC3B,aAAa,EAAE,MAAM,GAAG,SAAS,CAAC;IAClC,cAAc,EAAE,MAAM,GAAG,SAAS,CAAC;IACnC,IAAI,EAAE,MAAM,GAAG,SA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jB,OAAO,CAAC,iBAAiB;IAIzB,OAAO,CAAC,6BAA6B;IAOrC,OAAO,CAAC,wBAAwB;IAoBhC,OAAO,CAAC,cAAc;IAQtB,OAAO,CAAC,sBAAsB;IAc9B,OAAO,CAAC,cAAc;CAGvB;AAED,YAAY,EAAE,mBAAmB,EAAE,CAAC;AAEpC,eAAO,MAAM,yBAAyB,GACpC,cAAc,YAAY,EAC1B,SAAS,0BAA0B,KAClC,OAAO,CAAC,mBAAmB,CAK7B,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/tokens/clerkRequest.d.ts b/backend/node_modules/@clerk/backend/dist/tokens/clerkRequest.d.ts new file mode 100644 index 000000000..e6e92af9f --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/tokens/clerkRequest.d.ts @@ -0,0 +1,29 @@ +import type { ClerkUrl } from './clerkUrl'; +/** + * A class that extends the native Request class, + * adds cookies helpers and a normalised clerkUrl that is constructed by using the values found + * in req.headers so it is able to work reliably when the app is running behind a proxy server. + */ +declare class ClerkRequest extends Request { + readonly clerkUrl: ClerkUrl; + readonly cookies: Map; + constructor(input: ClerkRequest | Request | RequestInfo, init?: RequestInit); + toJSON(): { + url: string; + method: string; + headers: string; + clerkUrl: string; + cookies: string; + }; + /** + * Used to fix request.url using the x-forwarded-* headers + * TODO add detailed description of the issues this solves + */ + private deriveUrlFromHeaders; + private getFirstValueFromHeader; + private parseCookies; + private decodeCookieValue; +} +export declare const createClerkRequest: (...args: ConstructorParameters) => ClerkRequest; +export type { ClerkRequest }; +//# sourceMappingURL=clerkRequest.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/tokens/clerkRequest.d.ts.map b/backend/node_modules/@clerk/backend/dist/tokens/clerkRequest.d.ts.map new file mode 100644 index 000000000..5dfd0021e --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/tokens/clerkRequest.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"clerkRequest.d.ts","sourceRoot":"","sources":["../../src/tokens/clerkRequest.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAG3C;;;;GAIG;AACH,cAAM,YAAa,SAAQ,OAAO;IAChC,QAAQ,CAAC,QAAQ,EAAE,QAAQ,CAAC;IAC5B,QAAQ,CAAC,OAAO,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAC;gBAE/B,KAAK,EAAE,YAAY,GAAG,OAAO,GAAG,WAAW,EAAE,IAAI,CAAC,EAAE,WAAW;IAkB3E,MAAM;;;;;;;IAUb;;;OAGG;IACH,OAAO,CAAC,oBAAoB;IAiB5B,OAAO,CAAC,uBAAuB;IAI/B,OAAO,CAAC,YAAY;IAKpB,OAAO,CAAC,iBAAiB;CAG1B;AAED,eAAO,MAAM,kBAAkB,GAAI,GAAG,MAAM,qBAAqB,CAAC,OAAO,YAAY,CAAC,KAAG,YAExF,CAAC;AAEF,YAAY,EAAE,YAAY,EAAE,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/tokens/clerkUrl.d.ts b/backend/node_modules/@clerk/backend/dist/tokens/clerkUrl.d.ts new file mode 100644 index 000000000..42488286d --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/tokens/clerkUrl.d.ts @@ -0,0 +1,18 @@ +declare class ClerkUrl extends URL { + isCrossOrigin(other: URL | string): boolean; +} +export type WithClerkUrl = T & { + /** + * When a NextJs app is hosted on a platform different from Vercel + * or inside a container (Netlify, Fly.io, AWS Amplify, docker etc), + * req.url is always set to `localhost:3000` instead of the actual host of the app. + * + * The `authMiddleware` uses the value of the available req.headers in order to construct + * and use the correct url internally. This url is then exposed as `experimental_clerkUrl`, + * intended to be used within `beforeAuth` and `afterAuth` if needed. + */ + clerkUrl: ClerkUrl; +}; +export declare const createClerkUrl: (...args: ConstructorParameters) => ClerkUrl; +export type { ClerkUrl }; +//# sourceMappingURL=clerkUrl.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/tokens/clerkUrl.d.ts.map b/backend/node_modules/@clerk/backend/dist/tokens/clerkUrl.d.ts.map new file mode 100644 index 000000000..bcd222519 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/tokens/clerkUrl.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"clerkUrl.d.ts","sourceRoot":"","sources":["../../src/tokens/clerkUrl.ts"],"names":[],"mappings":"AAAA,cAAM,QAAS,SAAQ,GAAG;IACjB,aAAa,CAAC,KAAK,EAAE,GAAG,GAAG,MAAM;CAGzC;AAED,MAAM,MAAM,YAAY,CAAC,CAAC,IAAI,CAAC,GAAG;IAChC;;;;;;;;OAQG;IACH,QAAQ,EAAE,QAAQ,CAAC;CACpB,CAAC;AAEF,eAAO,MAAM,cAAc,GAAI,GAAG,MAAM,qBAAqB,CAAC,OAAO,QAAQ,CAAC,KAAG,QAEhF,CAAC;AAEF,YAAY,EAAE,QAAQ,EAAE,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/tokens/cookie.d.ts b/backend/node_modules/@clerk/backend/dist/tokens/cookie.d.ts new file mode 100644 index 000000000..3eeb632d4 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/tokens/cookie.d.ts @@ -0,0 +1,3 @@ +export declare const getCookieName: (cookieDirective: string) => string; +export declare const getCookieValue: (cookieDirective: string) => string; +//# sourceMappingURL=cookie.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/tokens/cookie.d.ts.map b/backend/node_modules/@clerk/backend/dist/tokens/cookie.d.ts.map new file mode 100644 index 000000000..87bba3034 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/tokens/cookie.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"cookie.d.ts","sourceRoot":"","sources":["../../src/tokens/cookie.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,aAAa,GAAI,iBAAiB,MAAM,KAAG,MAEvD,CAAC;AAEF,eAAO,MAAM,cAAc,GAAI,iBAAiB,MAAM,KAAG,MAExD,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/tokens/factory.d.ts b/backend/node_modules/@clerk/backend/dist/tokens/factory.d.ts new file mode 100644 index 000000000..3022c5de8 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/tokens/factory.d.ts @@ -0,0 +1,29 @@ +import type { ApiClient } from '../api'; +import type { AuthenticateRequest } from './request'; +import type { AuthenticateRequestOptions } from './types'; +type BuildTimeOptions = Partial>; +/** + * @internal + */ +export type CreateAuthenticateRequestOptions = { + options: BuildTimeOptions; + apiClient: ApiClient; +}; +/** + * @internal + */ +export declare function createAuthenticateRequest(params: CreateAuthenticateRequestOptions): { + authenticateRequest: AuthenticateRequest; + debugRequestState: (params: import("./authStatus").RequestState) => { + isSignedIn: boolean; + isAuthenticated: boolean; + proxyUrl: string | undefined; + reason: string | null; + message: string | null; + publishableKey: string; + isSatellite: boolean; + domain: string; + }; +}; +export {}; +//# sourceMappingURL=factory.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/tokens/factory.d.ts.map b/backend/node_modules/@clerk/backend/dist/tokens/factory.d.ts.map new file mode 100644 index 000000000..79ef61b08 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/tokens/factory.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"factory.d.ts","sourceRoot":"","sources":["../../src/tokens/factory.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,QAAQ,CAAC;AAExC,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAC;AAErD,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,SAAS,CAAC;AAG1D,KAAK,gBAAgB,GAAG,OAAO,CAC7B,IAAI,CACF,0BAA0B,EACxB,QAAQ,GACR,YAAY,GACZ,UAAU,GACV,QAAQ,GACR,aAAa,GACb,QAAQ,GACR,UAAU,GACV,gBAAgB,GAChB,WAAW,GACX,kBAAkB,CACrB,CACF,CAAC;AAeF;;GAEG;AACH,MAAM,MAAM,gCAAgC,GAAG;IAC7C,OAAO,EAAE,gBAAgB,CAAC;IAC1B,SAAS,EAAE,SAAS,CAAC;CACtB,CAAC;AAEF;;GAEG;AACH,wBAAgB,yBAAyB,CAAC,MAAM,EAAE,gCAAgC;;;;;;;;;;;;EAsBjF"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/tokens/handshake.d.ts b/backend/node_modules/@clerk/backend/dist/tokens/handshake.d.ts new file mode 100644 index 000000000..892d060c6 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/tokens/handshake.d.ts @@ -0,0 +1,64 @@ +import { TokenVerificationError } from '../errors'; +import type { AuthenticateContext } from './authenticateContext'; +import type { SignedInState, SignedOutState } from './authStatus'; +import type { OrganizationMatcher } from './organizationMatcher'; +import type { OrganizationSyncOptions } from './types'; +import type { VerifyTokenOptions } from './verify'; +/** + * Similar to our verifyToken flow for Clerk-issued JWTs, but this verification flow is for our signed handshake payload. + * The handshake payload requires fewer verification steps. + */ +export declare function verifyHandshakeToken(token: string, options: VerifyTokenOptions): Promise<{ + handshake: string[]; +}>; +export declare class HandshakeService { + private readonly authenticateContext; + private readonly organizationMatcher; + private readonly options; + constructor(authenticateContext: AuthenticateContext, options: { + organizationSyncOptions?: OrganizationSyncOptions; + }, organizationMatcher: OrganizationMatcher); + /** + * Determines if a request is eligible for handshake based on its headers + * + * Currently, a request is only eligible for a handshake if we can say it's *probably* a request for a document, not a fetch or some other exotic request. + * This heuristic should give us a reliable enough signal for browsers that support `Sec-Fetch-Dest` and for those that don't. + * + * @returns boolean indicating if the request is eligible for handshake + */ + isRequestEligibleForHandshake(): boolean; + /** + * Builds the redirect headers for a handshake request + * @param reason - The reason for the handshake (e.g. 'session-token-expired') + * @returns Headers object containing the Location header for redirect + * @throws Error if clerkUrl is missing in authenticateContext + */ + buildRedirectToHandshake(reason: string): Headers; + /** + * Gets cookies from either a handshake nonce or a handshake token + * @returns Promise resolving to string array of cookie directives + */ + getCookiesFromHandshake(): Promise; + /** + * Resolves a handshake request by verifying the handshake token and setting appropriate cookies + * @returns Promise resolving to either a SignedInState or SignedOutState + * @throws Error if handshake verification fails or if there are issues with the session token + */ + resolveHandshake(): Promise; + /** + * Handles handshake token verification errors in development mode + * @param error - The TokenVerificationError that occurred + * @throws Error with a descriptive message about the verification failure + */ + handleTokenVerificationErrorInDevelopment(error: TokenVerificationError): void; + /** + * Checks if a redirect loop is detected and sets headers to track redirect count + * @param headers - The Headers object to modify + * @returns boolean indicating if a redirect loop was detected (true) or if the request can proceed (false) + */ + checkAndTrackRedirectLoop(headers: Headers): boolean; + private removeDevBrowserFromURL; + private getOrganizationSyncTarget; + private getOrganizationSyncQueryParams; +} +//# sourceMappingURL=handshake.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/tokens/handshake.d.ts.map b/backend/node_modules/@clerk/backend/dist/tokens/handshake.d.ts.map new file mode 100644 index 000000000..5abd9d457 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/tokens/handshake.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"handshake.d.ts","sourceRoot":"","sources":["../../src/tokens/handshake.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,sBAAsB,EAA8D,MAAM,WAAW,CAAC;AAI/G,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AACjE,OAAO,KAAK,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAIlE,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAEjE,OAAO,KAAK,EAAE,uBAAuB,EAA0B,MAAM,SAAS,CAAC;AAC/E,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,UAAU,CAAC;AAmCnD;;;GAGG;AACH,wBAAsB,oBAAoB,CACxC,KAAK,EAAE,MAAM,EACb,OAAO,EAAE,kBAAkB,GAC1B,OAAO,CAAC;IAAE,SAAS,EAAE,MAAM,EAAE,CAAA;CAAE,CAAC,CA4BlC;AAED,qBAAa,gBAAgB;IAC3B,OAAO,CAAC,QAAQ,CAAC,mBAAmB,CAAsB;IAC1D,OAAO,CAAC,QAAQ,CAAC,mBAAmB,CAAsB;IAC1D,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAwD;gBAG9E,mBAAmB,EAAE,mBAAmB,EACxC,OAAO,EAAE;QAAE,uBAAuB,CAAC,EAAE,uBAAuB,CAAA;KAAE,EAC9D,mBAAmB,EAAE,mBAAmB;IAO1C;;;;;;;OAOG;IACH,6BAA6B,IAAI,OAAO;IAgBxC;;;;;OAKG;IACH,wBAAwB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO;IAsCjD;;;OAGG;IACU,uBAAuB,IAAI,OAAO,CAAC,MAAM,EAAE,CAAC;IA2BzD;;;;OAIG;IACG,gBAAgB,IAAI,OAAO,CAAC,aAAa,GAAG,cAAc,CAAC;IA2FjE;;;;OAIG;IACH,yCAAyC,CAAC,KAAK,EAAE,sBAAsB,GAAG,IAAI;IAc9E;;;;OAIG;IACH,yBAAyB,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO;IAWpD,OAAO,CAAC,uBAAuB;IAO/B,OAAO,CAAC,yBAAyB;IAIjC,OAAO,CAAC,8BAA8B;CAevC"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/tokens/keys.d.ts b/backend/node_modules/@clerk/backend/dist/tokens/keys.d.ts new file mode 100644 index 000000000..8a3152d15 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/tokens/keys.d.ts @@ -0,0 +1,53 @@ +/** + * + * Loads a local PEM key usually from process.env and transform it to JsonWebKey format. + * The result is also cached on the module level to avoid unnecessary computations in subsequent invocations. + * + * @param {string} localKey + * @returns {JsonWebKey} key + */ +export declare function loadClerkJWKFromLocal(localKey?: string): JsonWebKey; +/** + * @internal + */ +export type LoadClerkJWKFromRemoteOptions = { + /** + * @internal + */ + kid: string; + /** + * @deprecated This cache TTL will be removed in the next major version. Specifying a cache TTL is a no-op. + */ + jwksCacheTtlInMs?: number; + /** + * A flag to ignore the JWKS cache and always fetch JWKS before each JWT verification. + */ + skipJwksCache?: boolean; + /** + * The Clerk Secret Key from the [**API keys**](https://dashboard.clerk.com/last-active?path=api-keys) page in the Clerk Dashboard. + */ + secretKey?: string; + /** + * The [Clerk Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }} endpoint. + * @default 'https://api.clerk.com' + */ + apiUrl?: string; + /** + * The version passed to the Clerk API. + * @default 'v1' + */ + apiVersion?: string; +}; +/** + * + * Loads a key from JWKS retrieved from the well-known Frontend API endpoint of the issuer. + * The result is also cached on the module level to avoid network requests in subsequent invocations. + * The cache lasts up to 5 minutes. + * + * @param {Object} options + * @param {string} options.kid - The id of the key that the JWT was signed with + * @param {string} options.alg - The algorithm of the JWT + * @returns {JsonWebKey} key + */ +export declare function loadClerkJWKFromRemote({ secretKey, apiUrl, apiVersion, kid, skipJwksCache, }: LoadClerkJWKFromRemoteOptions): Promise; +//# sourceMappingURL=keys.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/tokens/keys.d.ts.map b/backend/node_modules/@clerk/backend/dist/tokens/keys.d.ts.map new file mode 100644 index 000000000..8addb3e84 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/tokens/keys.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"keys.d.ts","sourceRoot":"","sources":["../../src/tokens/keys.ts"],"names":[],"mappings":"AA2CA;;;;;;;GAOG;AACH,wBAAgB,qBAAqB,CAAC,QAAQ,CAAC,EAAE,MAAM,GAAG,UAAU,CAiCnE;AAED;;GAEG;AACH,MAAM,MAAM,6BAA6B,GAAG;IAC1C;;OAEG;IACH,GAAG,EAAE,MAAM,CAAC;IACZ;;OAEG;IACH,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B;;OAEG;IACH,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB;;OAEG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB;;;OAGG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;;OAGG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB,CAAC;AAEF;;;;;;;;;;GAUG;AACH,wBAAsB,sBAAsB,CAAC,EAC3C,SAAS,EACT,MAAgB,EAChB,UAAwB,EACxB,GAAG,EACH,aAAa,GACd,EAAE,6BAA6B,GAAG,OAAO,CAAC,UAAU,CAAC,CAwCrD"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/tokens/machine.d.ts b/backend/node_modules/@clerk/backend/dist/tokens/machine.d.ts new file mode 100644 index 000000000..eb04134d7 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/tokens/machine.d.ts @@ -0,0 +1,45 @@ +import type { AuthenticateRequestOptions } from '../tokens/types'; +import type { MachineTokenType } from './tokenTypes'; +import { TokenType } from './tokenTypes'; +export declare const M2M_TOKEN_PREFIX = "mt_"; +export declare const OAUTH_TOKEN_PREFIX = "oat_"; +export declare const API_KEY_PREFIX = "ak_"; +/** + * Checks if a token is a machine token by looking at its prefix. + * + * @remarks + * In the future, this will support custom prefixes that can be prepended to the base prefixes + * (e.g. "org_a_m2m_", "org_a_oauth_access_", "org_a_api_key_") + * + * @param token - The token string to check + * @returns true if the token starts with a recognized machine token prefix + */ +export declare function isMachineTokenByPrefix(token: string): boolean; +/** + * Gets the specific type of machine token based on its prefix. + * + * @remarks + * In the future, this will support custom prefixes that can be prepended to the base prefixes + * (e.g. "org_a_m2m_", "org_a_oauth_access_", "org_a_api_key_") + * + * @param token - The token string to check + * @returns The specific MachineTokenType + * @throws Error if the token doesn't match any known machine token prefix + */ +export declare function getMachineTokenType(token: string): MachineTokenType; +/** + * Check if a token type is accepted given a requested token type or list of token types. + * + * @param tokenType - The token type to check (can be null if the token is invalid) + * @param acceptsToken - The requested token type or list of token types + * @returns true if the token type is accepted + */ +export declare const isTokenTypeAccepted: (tokenType: TokenType | null, acceptsToken: NonNullable) => boolean; +/** + * Checks if a token type string is a machine token type (api_key, m2m_token, or oauth_token). + * + * @param type - The token type string to check + * @returns true if the type is a machine token type + */ +export declare function isMachineTokenType(type: string): type is MachineTokenType; +//# sourceMappingURL=machine.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/tokens/machine.d.ts.map b/backend/node_modules/@clerk/backend/dist/tokens/machine.d.ts.map new file mode 100644 index 000000000..02c790d19 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/tokens/machine.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"machine.d.ts","sourceRoot":"","sources":["../../src/tokens/machine.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,iBAAiB,CAAC;AAClE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AACrD,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC,eAAO,MAAM,gBAAgB,QAAQ,CAAC;AACtC,eAAO,MAAM,kBAAkB,SAAS,CAAC;AACzC,eAAO,MAAM,cAAc,QAAQ,CAAC;AAIpC;;;;;;;;;GASG;AACH,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAE7D;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,MAAM,GAAG,gBAAgB,CAcnE;AAED;;;;;;GAMG;AACH,eAAO,MAAM,mBAAmB,GAC9B,WAAW,SAAS,GAAG,IAAI,EAC3B,cAAc,WAAW,CAAC,0BAA0B,CAAC,cAAc,CAAC,CAAC,KACpE,OAWF,CAAC;AAEF;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,IAAI,gBAAgB,CAEzE"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/tokens/organizationMatcher.d.ts b/backend/node_modules/@clerk/backend/dist/tokens/organizationMatcher.d.ts new file mode 100644 index 000000000..914eedcf8 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/tokens/organizationMatcher.d.ts @@ -0,0 +1,11 @@ +import type { OrganizationSyncOptions, OrganizationSyncTarget } from './types'; +export declare class OrganizationMatcher { + private readonly organizationPattern; + private readonly personalAccountPattern; + constructor(options?: OrganizationSyncOptions); + private createMatcher; + findTarget(url: URL): OrganizationSyncTarget | null; + private findOrganizationTarget; + private findPersonalAccountTarget; +} +//# sourceMappingURL=organizationMatcher.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/tokens/organizationMatcher.d.ts.map b/backend/node_modules/@clerk/backend/dist/tokens/organizationMatcher.d.ts.map new file mode 100644 index 000000000..871d6827b --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/tokens/organizationMatcher.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"organizationMatcher.d.ts","sourceRoot":"","sources":["../../src/tokens/organizationMatcher.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,uBAAuB,EAAE,sBAAsB,EAAE,MAAM,SAAS,CAAC;AAE/E,qBAAa,mBAAmB;IAC9B,OAAO,CAAC,QAAQ,CAAC,mBAAmB,CAAuB;IAC3D,OAAO,CAAC,QAAQ,CAAC,sBAAsB,CAAuB;gBAElD,OAAO,CAAC,EAAE,uBAAuB;IAK7C,OAAO,CAAC,aAAa;IAWrB,UAAU,CAAC,GAAG,EAAE,GAAG,GAAG,sBAAsB,GAAG,IAAI;IASnD,OAAO,CAAC,sBAAsB;IA0B9B,OAAO,CAAC,yBAAyB;CAalC"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/tokens/request.d.ts b/backend/node_modules/@clerk/backend/dist/tokens/request.d.ts new file mode 100644 index 000000000..4c932b56b --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/tokens/request.d.ts @@ -0,0 +1,60 @@ +import type { RequestState } from './authStatus'; +import type { SessionTokenType } from './tokenTypes'; +import { TokenType } from './tokenTypes'; +import type { AuthenticateRequestOptions } from './types'; +export declare const RefreshTokenErrorReason: { + readonly NonEligibleNoCookie: "non-eligible-no-refresh-cookie"; + readonly NonEligibleNonGet: "non-eligible-non-get"; + readonly InvalidSessionToken: "invalid-session-token"; + readonly MissingApiClient: "missing-api-client"; + readonly MissingSessionToken: "missing-session-token"; + readonly MissingRefreshToken: "missing-refresh-token"; + readonly ExpiredSessionTokenDecodeFailed: "expired-session-token-decode-failed"; + readonly ExpiredSessionTokenMissingSidClaim: "expired-session-token-missing-sid-claim"; + readonly FetchError: "fetch-error"; + readonly UnexpectedSDKError: "unexpected-sdk-error"; + readonly UnexpectedBAPIError: "unexpected-bapi-error"; +}; +export interface AuthenticateRequest { + /** + * @example + * clerkClient.authenticateRequest(request, { acceptsToken: ['session_token', 'api_key'] }); + */ + (request: Request, options: AuthenticateRequestOptions & { + acceptsToken: T; + }): Promise>; + /** + * @example + * clerkClient.authenticateRequest(request, { acceptsToken: 'session_token' }); + */ + (request: Request, options: AuthenticateRequestOptions & { + acceptsToken: T; + }): Promise>; + /** + * @example + * clerkClient.authenticateRequest(request, { acceptsToken: 'any' }); + */ + (request: Request, options: AuthenticateRequestOptions & { + acceptsToken: 'any'; + }): Promise>; + /** + * @example + * clerkClient.authenticateRequest(request); + */ + (request: Request, options?: AuthenticateRequestOptions): Promise>; +} +export declare const authenticateRequest: AuthenticateRequest; +/** + * @internal + */ +export declare const debugRequestState: (params: RequestState) => { + isSignedIn: boolean; + isAuthenticated: boolean; + proxyUrl: string | undefined; + reason: string | null; + message: string | null; + publishableKey: string; + isSatellite: boolean; + domain: string; +}; +//# sourceMappingURL=request.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/tokens/request.d.ts.map b/backend/node_modules/@clerk/backend/dist/tokens/request.d.ts.map new file mode 100644 index 000000000..32451554a --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/tokens/request.d.ts.map @@ -0,0 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AAC"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/tokens/tokenTypes.d.ts b/backend/node_modules/@clerk/backend/dist/tokens/tokenTypes.d.ts new file mode 100644 index 000000000..ff0234e4b --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/tokens/tokenTypes.d.ts @@ -0,0 +1,19 @@ +export declare const TokenType: { + readonly SessionToken: "session_token"; + readonly ApiKey: "api_key"; + readonly M2MToken: "m2m_token"; + readonly OAuthToken: "oauth_token"; +}; +/** + * @inline + */ +export type TokenType = (typeof TokenType)[keyof typeof TokenType]; +/** + * @inline + */ +export type SessionTokenType = typeof TokenType.SessionToken; +/** + * @inline + */ +export type MachineTokenType = Exclude; +//# sourceMappingURL=tokenTypes.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/tokens/tokenTypes.d.ts.map b/backend/node_modules/@clerk/backend/dist/tokens/tokenTypes.d.ts.map new file mode 100644 index 000000000..34d4cd399 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/tokens/tokenTypes.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"tokenTypes.d.ts","sourceRoot":"","sources":["../../src/tokens/tokenTypes.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,SAAS;;;;;CAKZ,CAAC;AAEX;;GAEG;AACH,MAAM,MAAM,SAAS,GAAG,CAAC,OAAO,SAAS,CAAC,CAAC,MAAM,OAAO,SAAS,CAAC,CAAC;AAEnE;;GAEG;AACH,MAAM,MAAM,gBAAgB,GAAG,OAAO,SAAS,CAAC,YAAY,CAAC;AAC7D;;GAEG;AACH,MAAM,MAAM,gBAAgB,GAAG,OAAO,CAAC,SAAS,EAAE,gBAAgB,CAAC,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/tokens/types.d.ts b/backend/node_modules/@clerk/backend/dist/tokens/types.d.ts new file mode 100644 index 000000000..26f3a7571 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/tokens/types.d.ts @@ -0,0 +1,206 @@ +import type { MatchFunction } from '@clerk/shared/pathToRegexp'; +import type { PendingSessionOptions } from '@clerk/types'; +import type { ApiClient, APIKey, IdPOAuthAccessToken, M2MToken } from '../api'; +import type { AuthenticatedMachineObject, AuthObject, InvalidTokenAuthObject, SignedInAuthObject, SignedOutAuthObject, UnauthenticatedMachineObject } from './authObjects'; +import type { SessionTokenType, TokenType } from './tokenTypes'; +import type { VerifyTokenOptions } from './verify'; +/** + * @interface + */ +export type AuthenticateRequestOptions = { + /** + * The Clerk Publishable Key from the [**API keys**](https://dashboard.clerk.com/last-active?path=api-keys) page in the Clerk Dashboard. + */ + publishableKey?: string; + /** + * The domain of a [satellite application](https://clerk.com/docs/advanced-usage/satellite-domains) in a multi-domain setup. + */ + domain?: string; + /** + * Whether the instance is a satellite domain in a multi-domain setup. + * @default false + */ + isSatellite?: boolean; + /** + * The proxy URL from a multi-domain setup. + */ + proxyUrl?: string; + /** + * The sign-in URL from a multi-domain setup. + */ + signInUrl?: string; + /** + * The sign-up URL from a multi-domain setup. + */ + signUpUrl?: string; + /** + * Full URL or path to navigate to after successful sign in. + * @default '/' + */ + afterSignInUrl?: string; + /** + * Full URL or path to navigate to after successful sign up. + * @default '/' + */ + afterSignUpUrl?: string; + /** + * Used to activate a specific [organization](https://clerk.com/docs/organizations/overview) or [personal account](https://clerk.com/docs/organizations/organization-workspaces) based on URL path parameters. If there's a mismatch between the active organization in the session (e.g., as reported by `auth()`) and the organization indicated by the URL, an attempt to activate the organization specified in the URL will be made. + * + * If the activation can't be performed, either because an organization doesn't exist or the user lacks access, the active organization in the session won't be changed. Ultimately, it's the responsibility of the page to verify that the resources are appropriate to render given the URL and handle mismatches appropriately (e.g., by returning a 404). + */ + organizationSyncOptions?: OrganizationSyncOptions; + /** + * @internal + */ + apiClient?: ApiClient; + /** + * The type of token to accept. + * @default 'session_token' + */ + acceptsToken?: TokenType | TokenType[] | 'any'; + /** + * The machine secret key to use when verifying machine-to-machine tokens. + * This will override the Clerk secret key. + */ + machineSecretKey?: string; +} & VerifyTokenOptions; +/** + * @inline + */ +export type OrganizationSyncOptions = { + /** + * Specifies URL patterns that are organization-specific, containing an organization ID or slug as a path parameter. If a request matches this path, the organization identifier will be used to set that org as active. + * + * If the route also matches the `personalAccountPatterns` prop, this prop takes precedence. + * + * Patterns must have a path parameter named either `:id` (to match a Clerk organization ID) or `:slug` (to match a Clerk organization slug). + * + * If the organization can't be activated—either because it doesn't exist or the user lacks access—the previously active organization will remain unchanged. Components must detect this case and provide an appropriate error and/or resolution pathway, such as calling `notFound()` or displaying an [``](https://clerk.com/docs/components/organization/organization-switcher). + * + * @example + * ["/orgs/:slug", "/orgs/:slug/(.*)"] + * @example + * ["/orgs/:id", "/orgs/:id/(.*)"] + * @example + * ["/app/:any/orgs/:slug", "/app/:any/orgs/:slug/(.*)"] + */ + organizationPatterns?: Pattern[]; + /** + * URL patterns for resources that exist within the context of a [Clerk Personal Account](https://clerk.com/docs/organizations/organization-workspaces) (user-specific, outside any organization). + * + * If the route also matches the `organizationPattern` prop, the `organizationPattern` prop takes precedence. + * + * @example + * ["/user", "/user/(.*)"] + * @example + * ["/user/:any", "/user/:any/(.*)"] + */ + personalAccountPatterns?: Pattern[]; +}; +/** + * A `Pattern` is a `string` that represents the structure of a URL path. In addition to any valid URL, it may include: + * - Named path parameters prefixed with a colon (e.g., `:id`, `:slug`, `:any`). + * - Wildcard token, `(.*)`, which matches the remainder of the path. + * + * @example + * /orgs/:slug + * + * ```ts + * '/orgs/acmecorp' // matches (`:slug` value: acmecorp) + * '/orgs' // does not match + * '/orgs/acmecorp/settings' // does not match + * ``` + * + * @example + * /app/:any/orgs/:id + * + * ```ts + * '/app/petstore/orgs/org_123' // matches (`:id` value: org_123) + * '/app/dogstore/v2/orgs/org_123' // does not match + * ``` + * + * @example + * /personal-account/(.*) + * + * ```ts + * '/personal-account/settings' // matches + * '/personal-account' // does not match + * ``` + */ +type Pattern = string; +export type MachineAuthType = M2MToken | APIKey | IdPOAuthAccessToken; +export type OrganizationSyncTargetMatchers = { + OrganizationMatcher: MatchFunction>> | null; + PersonalAccountMatcher: MatchFunction>> | null; +}; +/** + * Represents an organization or a personal account - e.g. an + * entity that can be activated by the handshake API. + */ +export type OrganizationSyncTarget = { + type: 'personalAccount'; +} | { + type: 'organization'; + organizationId?: string; + organizationSlug?: string; +}; +/** + * Infers auth object type from an array of token types. + * - Session token only -> SessionType + * - Mixed tokens -> SessionType | MachineType + * - Machine tokens only -> MachineType + */ +export type InferAuthObjectFromTokenArray = SessionTokenType extends T[number] ? T[number] extends SessionTokenType ? SessionType : SessionType | (MachineType & { + tokenType: Exclude; +}) : MachineType & { + tokenType: Exclude; +}; +/** + * Infers auth object type from a single token type. + * Returns SessionType for session tokens, or MachineType for machine tokens. + */ +export type InferAuthObjectFromToken = T extends SessionTokenType ? SessionType : MachineType & { + tokenType: Exclude; +}; +export type SessionAuthObject = SignedInAuthObject | SignedOutAuthObject; +export type MachineAuthObject> = T extends any ? AuthenticatedMachineObject | UnauthenticatedMachineObject : never; +type AuthOptions = PendingSessionOptions & { + acceptsToken?: AuthenticateRequestOptions['acceptsToken']; +}; +type MaybePromise = IsPromise extends true ? Promise : T; +/** + * Shared generic overload type for getAuth() helpers across SDKs. + * + * - Parameterized by the request type (RequestType). + * - Handles different accepted token types and their corresponding return types. + */ +export interface GetAuthFn { + /** + * @example + * const auth = await getAuth(req, { acceptsToken: ['session_token', 'api_key'] }) + */ + (req: RequestType, options: AuthOptions & { + acceptsToken: T; + }): MaybePromise>> | InvalidTokenAuthObject, ReturnsPromise>; + /** + * @example + * const auth = await getAuth(req, { acceptsToken: 'session_token' }) + */ + (req: RequestType, options: AuthOptions & { + acceptsToken: T; + }): MaybePromise>>, ReturnsPromise>; + /** + * @example + * const auth = await getAuth(req, { acceptsToken: 'any' }) + */ + (req: RequestType, options: AuthOptions & { + acceptsToken: 'any'; + }): MaybePromise; + /** + * @example + * const auth = await getAuth(req) + */ + (req: RequestType, options?: PendingSessionOptions): MaybePromise; +} +export {}; +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/tokens/types.d.ts.map b/backend/node_modules/@clerk/backend/dist/tokens/types.d.ts.map new file mode 100644 index 000000000..21d674599 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/tokens/types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/tokens/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAChE,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,cAAc,CAAC;AAE1D,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,EAAE,mBAAmB,EAAE,QAAQ,EAAE,MAAM,QAAQ,CAAC;AAC/E,OAAO,KAAK,EACV,0BAA0B,EAC1B,UAAU,EACV,sBAAsB,EACtB,kBAAkB,EAClB,mBAAmB,EACnB,4BAA4B,EAC7B,MAAM,eAAe,CAAC;AACvB,OAAO,KAAK,EAAE,gBAAgB,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAChE,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,UAAU,CAAC;AAEnD;;GAEG;AACH,MAAM,MAAM,0BAA0B,GAAG;IACvC;;OAEG;IACH,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB;;OAEG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;;OAGG;IACH,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB;;OAEG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB;;OAEG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB;;OAEG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB;;;OAGG;IACH,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB;;;OAGG;IACH,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB;;;;OAIG;IACH,uBAAuB,CAAC,EAA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AAO,EAAE,WAAW,GAAG;QAAE,YAAY,EAAE,CAAC,CAAA;KAAE,GACzC,YAAY,CACX,6BAA6B,CAAC,CAAC,EAAE,iBAAiB,EAAE,iBAAiB,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,EAAE,gBAAgB,CAAC,CAAC,CAAC,GAC5G,sBAAsB,EACxB,cAAc,CACf,CAAC;IAEF;;;OAGG;IACH,CAAC,CAAC,SAAS,SAAS,EAClB,GAAG,EAAE,WAAW,EAChB,OAAO,EAAE,WAAW,GAAG;QAAE,YAAY,EAAE,CAAC,CAAA;KAAE,GACzC,YAAY,CACb,wBAAwB,CAAC,CAAC,EAAE,iBAAiB,EAAE,iBAAiB,CAAC,OAAO,CAAC,CAAC,EAAE,gBAAgB,CAAC,CAAC,CAAC,EAC/F,cAAc,CACf,CAAC;IAEF;;;OAGG;IACH,CAAC,GAAG,EAAE,WAAW,EAAE,OAAO,EAAE,WAAW,GAAG;QAAE,YAAY,EAAE,KAAK,CAAA;KAAE,GAAG,YAAY,CAAC,UAAU,EAAE,cAAc,CAAC,CAAC;IAE7G;;;OAGG;IACH,CAAC,GAAG,EAAE,WAAW,EAAE,OAAO,CAAC,EAAE,qBAAqB,GAAG,YAAY,CAAC,iBAAiB,EAAE,cAAc,CAAC,CAAC;CACtG"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/tokens/verify.d.ts b/backend/node_modules/@clerk/backend/dist/tokens/verify.d.ts new file mode 100644 index 000000000..91e52d015 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/tokens/verify.d.ts @@ -0,0 +1,118 @@ +import type { JwtPayload } from '@clerk/types'; +import type { APIKey, IdPOAuthAccessToken, M2MToken } from '../api'; +import { MachineTokenVerificationError, TokenVerificationError } from '../errors'; +import type { VerifyJwtOptions } from '../jwt'; +import type { JwtReturnType } from '../jwt/types'; +import type { LoadClerkJWKFromRemoteOptions } from './keys'; +import type { MachineTokenType } from './tokenTypes'; +/** + * @interface + */ +export type VerifyTokenOptions = Omit & Omit & { + /** + * Used to verify the session token in a networkless manner. Supply the PEM public key from the **[**API keys**](https://dashboard.clerk.com/last-active?path=api-keys) page -> Show JWT public key -> PEM Public Key** section in the Clerk Dashboard. **It's recommended to use [the environment variable](https://clerk.com/docs/deployments/clerk-environment-variables) instead.** For more information, refer to [Manual JWT verification](https://clerk.com/docs/backend-requests/manual-jwt). + */ + jwtKey?: string; +}; +/** + * > [!WARNING] + * > This is a lower-level method intended for more advanced use-cases. It's recommended to use [`authenticateRequest()`](https://clerk.com/docs/references/backend/authenticate-request), which fully authenticates a token passed from the `request` object. + * + * Verifies a Clerk-generated token signature. Networkless if the `jwtKey` is provided. Otherwise, performs a network call to retrieve the JWKS from the [Backend API](https://clerk.com/docs/reference/backend-api/tag/JWKS#operation/GetJWKS){{ target: '_blank' }}. + * + * @param token - The token to verify. + * @param options - Options for verifying the token. + * + * @displayFunctionSignature + * + * @paramExtension + * + * ### `VerifyTokenOptions` + * + * It is recommended to set these options as [environment variables](/docs/deployments/clerk-environment-variables#api-and-sdk-configuration) where possible, and then pass them to the function. For example, you can set the `secretKey` option using the `CLERK_SECRET_KEY` environment variable, and then pass it to the function like this: `createClerkClient({ secretKey: process.env.CLERK_SECRET_KEY })`. + * + * > [!WARNING] + * You must provide either `jwtKey` or `secretKey`. + * + * + * + * @example + * + * The following example demonstrates how to use the [JavaScript Backend SDK](https://clerk.com/docs/references/backend/overview) to verify the token signature. + * + * In the following example: + * + * 1. The **JWKS Public Key** from the Clerk Dashboard is set in the environment variable `CLERK_JWT_KEY`. + * 1. The session token is retrieved from the `__session` cookie or the Authorization header. + * 1. The token is verified in a networkless manner by passing the `jwtKey` prop. + * 1. The `authorizedParties` prop is passed to verify that the session token is generated from the expected frontend application. + * 1. If the token is valid, the response contains the verified token. + * + * ```ts + * import { verifyToken } from '@clerk/backend' + * import { cookies } from 'next/headers' + * + * export async function GET(request: Request) { + * const cookieStore = cookies() + * const sessToken = cookieStore.get('__session')?.value + * const bearerToken = request.headers.get('Authorization')?.replace('Bearer ', '') + * const token = sessToken || bearerToken + * + * if (!token) { + * return Response.json({ error: 'Token not found. User must sign in.' }, { status: 401 }) + * } + * + * try { + * const verifiedToken = await verifyToken(token, { + * jwtKey: process.env.CLERK_JWT_KEY, + * authorizedParties: ['http://localhost:3001', 'api.example.com'], // Replace with your authorized parties + * }) + * + * return Response.json({ verifiedToken }) + * } catch (error) { + * return Response.json({ error: 'Token not verified.' }, { status: 401 }) + * } + * } + * ``` + * + * If the token is valid, the response will contain a JSON object that looks something like this: + * + * ```json + * { + * "verifiedToken": { + * "azp": "http://localhost:3000", + * "exp": 1687906422, + * "iat": 1687906362, + * "iss": "https://magical-marmoset-51.clerk.accounts.dev", + * "nbf": 1687906352, + * "sid": "sess_2Ro7e2IxrffdqBboq8KfB6eGbIy", + * "sub": "user_2RfWKJREkjKbHZy0Wqa5qrHeAnb" + * } + * } + * ``` + */ +export declare function verifyToken(token: string, options: VerifyTokenOptions): Promise>; +/** + * Verifies any type of machine token by detecting its type from the prefix. + * + * @param token - The token to verify (e.g. starts with "m2m_", "oauth_", "api_key_", etc.) + * @param options - Options including secretKey for BAPI authorization + */ +export declare function verifyMachineAuthToken(token: string, options: VerifyTokenOptions): Promise<{ + data?: undefined; + tokenType: MachineTokenType; + errors: [MachineTokenVerificationError]; +} | { + data: M2MToken; + tokenType: MachineTokenType; + errors?: undefined; +} | { + data: IdPOAuthAccessToken; + tokenType: MachineTokenType; + errors?: undefined; +} | { + data: APIKey; + tokenType: MachineTokenType; + errors?: undefined; +}>; +//# sourceMappingURL=verify.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/tokens/verify.d.ts.map b/backend/node_modules/@clerk/backend/dist/tokens/verify.d.ts.map new file mode 100644 index 000000000..7c65f1717 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/tokens/verify.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"verify.d.ts","sourceRoot":"","sources":["../../src/tokens/verify.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAE/C,OAAO,KAAK,EAAE,MAAM,EAAE,mBAAmB,EAAE,QAAQ,EAAE,MAAM,QAAQ,CAAC;AAEpE,OAAO,EACL,6BAA6B,EAE7B,sBAAsB,EAGvB,MAAM,WAAW,CAAC;AACnB,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,QAAQ,CAAC;AAC/C,OAAO,KAAK,EAAE,aAAa,EAA0B,MAAM,cAAc,CAAC;AAE1E,OAAO,KAAK,EAAE,6BAA6B,EAAE,MAAM,QAAQ,CAAC;AAG5D,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAGrD;;GAEG;AACH,MAAM,MAAM,kBAAkB,GAAG,IAAI,CAAC,gBAAgB,EAAE,KAAK,CAAC,GAC5D,IAAI,CAAC,6BAA6B,EAAE,KAAK,CAAC,GAAG;IAC3C;;OAEG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB,CAAC;AAEJ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4EG;AACH,wBAAsB,WAAW,CAC/B,KAAK,EAAE,MAAM,EACb,OAAO,EAAE,kBAAkB,GAC1B,OAAO,CAAC,aAAa,CAAC,UAAU,EAAE,sBAAsB,CAAC,CAAC,CAiC5D;AAgGD;;;;;GAKG;AACH,wBAAsB,sBAAsB,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,kBAAkB;;;;;;;;;;;;;;;;GAYtF"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/util/decorateObjectWithResources.d.ts b/backend/node_modules/@clerk/backend/dist/util/decorateObjectWithResources.d.ts new file mode 100644 index 000000000..0a8a438ea --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/util/decorateObjectWithResources.d.ts @@ -0,0 +1,22 @@ +import type { CreateBackendApiOptions, Organization, Session, User } from '../api'; +import type { AuthObject } from '../tokens/authObjects'; +type DecorateAuthWithResourcesOptions = { + loadSession?: boolean; + loadUser?: boolean; + loadOrganization?: boolean; +}; +type WithResources = T & { + session?: Session | null; + user?: User | null; + organization?: Organization | null; +}; +/** + * @internal + */ +export declare const decorateObjectWithResources: (obj: T, authObj: AuthObject, opts: CreateBackendApiOptions & DecorateAuthWithResourcesOptions) => Promise>; +/** + * @internal + */ +export declare function stripPrivateDataFromObject>(authObject: T): T; +export {}; +//# sourceMappingURL=decorateObjectWithResources.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/util/decorateObjectWithResources.d.ts.map b/backend/node_modules/@clerk/backend/dist/util/decorateObjectWithResources.d.ts.map new file mode 100644 index 000000000..c60f59e77 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/util/decorateObjectWithResources.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"decorateObjectWithResources.d.ts","sourceRoot":"","sources":["../../src/util/decorateObjectWithResources.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,uBAAuB,EAAE,YAAY,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,QAAQ,CAAC;AAEnF,OAAO,KAAK,EAAE,UAAU,EAA2C,MAAM,uBAAuB,CAAC;AAEjG,KAAK,gCAAgC,GAAG;IACtC,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,gBAAgB,CAAC,EAAE,OAAO,CAAC;CAC5B,CAAC;AAEF,KAAK,aAAa,CAAC,CAAC,IAAI,CAAC,GAAG;IAC1B,OAAO,CAAC,EAAE,OAAO,GAAG,IAAI,CAAC;IACzB,IAAI,CAAC,EAAE,IAAI,GAAG,IAAI,CAAC;IACnB,YAAY,CAAC,EAAE,YAAY,GAAG,IAAI,CAAC;CACpC,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,2BAA2B,GAAU,CAAC,SAAS,MAAM,EAChE,KAAK,CAAC,EACN,SAAS,UAAU,EACnB,MAAM,uBAAuB,GAAG,gCAAgC,KAC/D,OAAO,CAAC,aAAa,CAAC,CAAC,CAAC,CAkB1B,CAAC;AAEF;;GAEG;AACH,wBAAgB,0BAA0B,CAAC,CAAC,SAAS,aAAa,CAAC,MAAM,CAAC,EAAE,UAAU,EAAE,CAAC,GAAG,CAAC,CAM5F"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/util/mergePreDefinedOptions.d.ts b/backend/node_modules/@clerk/backend/dist/util/mergePreDefinedOptions.d.ts new file mode 100644 index 000000000..01025d8d6 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/util/mergePreDefinedOptions.d.ts @@ -0,0 +1,2 @@ +export declare function mergePreDefinedOptions>(preDefinedOptions: T, options: Partial): T; +//# sourceMappingURL=mergePreDefinedOptions.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/util/mergePreDefinedOptions.d.ts.map b/backend/node_modules/@clerk/backend/dist/util/mergePreDefinedOptions.d.ts.map new file mode 100644 index 000000000..81dd2e53e --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/util/mergePreDefinedOptions.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"mergePreDefinedOptions.d.ts","sourceRoot":"","sources":["../../src/util/mergePreDefinedOptions.ts"],"names":[],"mappings":"AAAA,wBAAgB,sBAAsB,CAAC,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EAAE,iBAAiB,EAAE,CAAC,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,CAOlH"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/util/optionsAssertions.d.ts b/backend/node_modules/@clerk/backend/dist/util/optionsAssertions.d.ts new file mode 100644 index 000000000..0d0d05606 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/util/optionsAssertions.d.ts @@ -0,0 +1,3 @@ +export declare function assertValidSecretKey(val: unknown): asserts val is string; +export declare function assertValidPublishableKey(val: unknown): asserts val is string; +//# sourceMappingURL=optionsAssertions.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/util/optionsAssertions.d.ts.map b/backend/node_modules/@clerk/backend/dist/util/optionsAssertions.d.ts.map new file mode 100644 index 000000000..a66869572 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/util/optionsAssertions.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"optionsAssertions.d.ts","sourceRoot":"","sources":["../../src/util/optionsAssertions.ts"],"names":[],"mappings":"AAEA,wBAAgB,oBAAoB,CAAC,GAAG,EAAE,OAAO,GAAG,OAAO,CAAC,GAAG,IAAI,MAAM,CAMxE;AAED,wBAAgB,yBAAyB,CAAC,GAAG,EAAE,OAAO,GAAG,OAAO,CAAC,GAAG,IAAI,MAAM,CAE7E"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/util/path.d.ts b/backend/node_modules/@clerk/backend/dist/util/path.d.ts new file mode 100644 index 000000000..c45c13ce4 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/util/path.d.ts @@ -0,0 +1,4 @@ +type PathString = string | null | undefined; +export declare function joinPaths(...args: PathString[]): string; +export {}; +//# sourceMappingURL=path.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/util/path.d.ts.map b/backend/node_modules/@clerk/backend/dist/util/path.d.ts.map new file mode 100644 index 000000000..786848d29 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/util/path.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"path.d.ts","sourceRoot":"","sources":["../../src/util/path.ts"],"names":[],"mappings":"AAGA,KAAK,UAAU,GAAG,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC;AAE5C,wBAAgB,SAAS,CAAC,GAAG,IAAI,EAAE,UAAU,EAAE,GAAG,MAAM,CAKvD"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/util/rfc4648.d.ts b/backend/node_modules/@clerk/backend/dist/util/rfc4648.d.ts new file mode 100644 index 000000000..e02995270 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/util/rfc4648.d.ts @@ -0,0 +1,26 @@ +/** + * The base64url helper was extracted from the rfc4648 package + * in order to resolve CSJ/ESM interoperability issues + * + * https://github.com/swansontec/rfc4648.js + * + * For more context please refer to: + * - https://github.com/evanw/esbuild/issues/1719 + * - https://github.com/evanw/esbuild/issues/532 + * - https://github.com/swansontec/rollup-plugin-mjs-entry + */ +export declare const base64url: { + parse(string: string, opts?: ParseOptions): Uint8Array; + stringify(data: ArrayLike, opts?: StringifyOptions): string; +}; +interface ParseOptions { + loose?: boolean; + out?: new (size: number) => { + [index: number]: number; + }; +} +interface StringifyOptions { + pad?: boolean; +} +export {}; +//# sourceMappingURL=rfc4648.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/util/rfc4648.d.ts.map b/backend/node_modules/@clerk/backend/dist/util/rfc4648.d.ts.map new file mode 100644 index 000000000..5bef9ff27 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/util/rfc4648.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"rfc4648.d.ts","sourceRoot":"","sources":["../../src/util/rfc4648.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,eAAO,MAAM,SAAS;kBACN,MAAM,SAAS,YAAY,GAAG,UAAU;oBAItC,SAAS,CAAC,MAAM,CAAC,SAAS,gBAAgB,GAAG,MAAM;CAGpE,CAAC;AAaF,UAAU,YAAY;IACpB,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,GAAG,CAAC,EAAE,KAAK,IAAI,EAAE,MAAM,KAAK;QAAE,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAAA;KAAE,CAAC;CACzD;AAED,UAAU,gBAAgB;IACxB,GAAG,CAAC,EAAE,OAAO,CAAC;CACf"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/util/shared.d.ts b/backend/node_modules/@clerk/backend/dist/util/shared.d.ts new file mode 100644 index 000000000..7c39948c3 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/util/shared.d.ts @@ -0,0 +1,7 @@ +export { addClerkPrefix, getScriptUrl, getClerkJsMajorVersionOrTag } from '@clerk/shared/url'; +export { retry } from '@clerk/shared/retry'; +export { isDevelopmentFromSecretKey, isProductionFromSecretKey, parsePublishableKey, getCookieSuffix, getSuffixedCookieName, } from '@clerk/shared/keys'; +export { deprecated, deprecatedProperty } from '@clerk/shared/deprecated'; +export declare const errorThrower: import("@clerk/shared/error").ErrorThrower; +export declare const isDevOrStagingUrl: (url: string | URL) => boolean; +//# sourceMappingURL=shared.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/util/shared.d.ts.map b/backend/node_modules/@clerk/backend/dist/util/shared.d.ts.map new file mode 100644 index 000000000..02d9d1bd3 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/util/shared.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"shared.d.ts","sourceRoot":"","sources":["../../src/util/shared.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,2BAA2B,EAAE,MAAM,mBAAmB,CAAC;AAC9F,OAAO,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAC;AAC5C,OAAO,EACL,0BAA0B,EAC1B,yBAAyB,EACzB,mBAAmB,EACnB,eAAe,EACf,qBAAqB,GACtB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,UAAU,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAK1E,eAAO,MAAM,YAAY,4CAAuD,CAAC;AAEjF,eAAO,MAAQ,iBAAiB,gCAAiC,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/webhooks.d.ts b/backend/node_modules/@clerk/backend/dist/webhooks.d.ts new file mode 100644 index 000000000..83227a3a6 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/webhooks.d.ts @@ -0,0 +1,45 @@ +import type { WebhookEvent } from './api/resources/Webhooks'; +/** + * @inline + */ +export type VerifyWebhookOptions = { + /** + * The signing secret for the webhook. It's recommended to use the [`CLERK_WEBHOOK_SIGNING_SECRET` environment variable](https://clerk.com/docs/deployments/clerk-environment-variables#webhooks) instead. + */ + signingSecret?: string; +}; +export * from './api/resources/Webhooks'; +/** + * Verifies the authenticity of a webhook request using Standard Webhooks. Returns a promise that resolves to the verified webhook event data. + * + * @param request - The request object. + * @param options - Optional configuration object. + * + * @displayFunctionSignature + * + * @example + * See the [guide on syncing data](https://clerk.com/docs/webhooks/sync-data) for more comprehensive and framework-specific examples that you can copy and paste into your app. + * + * ```ts + * try { + * const evt = await verifyWebhook(request) + * + * // Access the event data + * const { id } = evt.data + * const eventType = evt.type + * + * // Handle specific event types + * if (evt.type === 'user.created') { + * console.log('New user created:', evt.data.id) + * // Handle user creation + * } + * + * return new Response('Success', { status: 200 }) + * } catch (err) { + * console.error('Webhook verification failed:', err) + * return new Response('Webhook verification failed', { status: 400 }) + * } + * ``` + */ +export declare function verifyWebhook(request: Request, options?: VerifyWebhookOptions): Promise; +//# sourceMappingURL=webhooks.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/webhooks.d.ts.map b/backend/node_modules/@clerk/backend/dist/webhooks.d.ts.map new file mode 100644 index 000000000..32d4da92e --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/webhooks.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"webhooks.d.ts","sourceRoot":"","sources":["../src/webhooks.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC;AAE7D;;GAEG;AACH,MAAM,MAAM,oBAAoB,GAAG;IACjC;;OAEG;IACH,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB,CAAC;AAYF,cAAc,0BAA0B,CAAC;AA0BzC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,wBAAsB,aAAa,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,GAAE,oBAAyB,GAAG,OAAO,CAAC,YAAY,CAAC,CAoD/G"} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/webhooks.js b/backend/node_modules/@clerk/backend/dist/webhooks.js new file mode 100644 index 000000000..add917103 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/webhooks.js @@ -0,0 +1,104 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/webhooks.ts +var webhooks_exports = {}; +__export(webhooks_exports, { + verifyWebhook: () => verifyWebhook +}); +module.exports = __toCommonJS(webhooks_exports); +var import_getEnvVariable = require("@clerk/shared/getEnvVariable"); + +// src/util/shared.ts +var import_url = require("@clerk/shared/url"); +var import_retry = require("@clerk/shared/retry"); +var import_keys = require("@clerk/shared/keys"); +var import_deprecated = require("@clerk/shared/deprecated"); +var import_error = require("@clerk/shared/error"); +var import_keys2 = require("@clerk/shared/keys"); +var errorThrower = (0, import_error.buildErrorThrower)({ packageName: "@clerk/backend" }); +var { isDevOrStagingUrl } = (0, import_keys2.createDevOrStagingUrlCache)(); + +// src/webhooks.ts +var import_standardwebhooks = require("standardwebhooks"); +var STANDARD_WEBHOOK_ID_HEADER = "webhook-id"; +var STANDARD_WEBHOOK_TIMESTAMP_HEADER = "webhook-timestamp"; +var STANDARD_WEBHOOK_SIGNATURE_HEADER = "webhook-signature"; +var SVIX_ID_HEADER = "svix-id"; +var SVIX_TIMESTAMP_HEADER = "svix-timestamp"; +var SVIX_SIGNATURE_HEADER = "svix-signature"; +function createStandardWebhookHeaders(request) { + const headers = {}; + const svixId = request.headers.get(SVIX_ID_HEADER)?.trim(); + const svixTimestamp = request.headers.get(SVIX_TIMESTAMP_HEADER)?.trim(); + const svixSignature = request.headers.get(SVIX_SIGNATURE_HEADER)?.trim(); + if (svixId) { + headers[STANDARD_WEBHOOK_ID_HEADER] = svixId; + } + if (svixTimestamp) { + headers[STANDARD_WEBHOOK_TIMESTAMP_HEADER] = svixTimestamp; + } + if (svixSignature) { + headers[STANDARD_WEBHOOK_SIGNATURE_HEADER] = svixSignature; + } + return headers; +} +async function verifyWebhook(request, options = {}) { + const secret = options.signingSecret ?? (0, import_getEnvVariable.getEnvVariable)("CLERK_WEBHOOK_SIGNING_SECRET"); + if (!secret) { + return errorThrower.throw( + "Missing webhook signing secret. Set the CLERK_WEBHOOK_SIGNING_SECRET environment variable with the webhook secret from the Clerk Dashboard." + ); + } + const webhookId = request.headers.get(SVIX_ID_HEADER)?.trim(); + const webhookTimestamp = request.headers.get(SVIX_TIMESTAMP_HEADER)?.trim(); + const webhookSignature = request.headers.get(SVIX_SIGNATURE_HEADER)?.trim(); + if (!webhookId || !webhookTimestamp || !webhookSignature) { + const missingHeaders = []; + if (!webhookId) { + missingHeaders.push(SVIX_ID_HEADER); + } + if (!webhookTimestamp) { + missingHeaders.push(SVIX_TIMESTAMP_HEADER); + } + if (!webhookSignature) { + missingHeaders.push(SVIX_SIGNATURE_HEADER); + } + return errorThrower.throw(`Missing required webhook headers: ${missingHeaders.join(", ")}`); + } + const body = await request.text(); + const standardHeaders = createStandardWebhookHeaders(request); + const webhook = new import_standardwebhooks.Webhook(secret); + try { + const payload = webhook.verify(body, standardHeaders); + return { + type: payload.type, + object: "event", + data: payload.data, + event_attributes: payload.event_attributes + }; + } catch (e) { + return errorThrower.throw(`Unable to verify incoming webhook: ${e instanceof Error ? e.message : "Unknown error"}`); + } +} +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + verifyWebhook +}); +//# sourceMappingURL=webhooks.js.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/webhooks.js.map b/backend/node_modules/@clerk/backend/dist/webhooks.js.map new file mode 100644 index 000000000..85f07b8ab --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/webhooks.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../src/webhooks.ts","../src/util/shared.ts"],"sourcesContent":["import { getEnvVariable } from '@clerk/shared/getEnvVariable';\nimport { errorThrower } from 'src/util/shared';\nimport { Webhook } from 'standardwebhooks';\n\nimport type { WebhookEvent } from './api/resources/Webhooks';\n\n/**\n * @inline\n */\nexport type VerifyWebhookOptions = {\n /**\n * The signing secret for the webhook. It's recommended to use the [`CLERK_WEBHOOK_SIGNING_SECRET` environment variable](https://clerk.com/docs/deployments/clerk-environment-variables#webhooks) instead.\n */\n signingSecret?: string;\n};\n\n// Standard Webhooks header names\nconst STANDARD_WEBHOOK_ID_HEADER = 'webhook-id';\nconst STANDARD_WEBHOOK_TIMESTAMP_HEADER = 'webhook-timestamp';\nconst STANDARD_WEBHOOK_SIGNATURE_HEADER = 'webhook-signature';\n\n// Svix header names (for mapping)\nconst SVIX_ID_HEADER = 'svix-id';\nconst SVIX_TIMESTAMP_HEADER = 'svix-timestamp';\nconst SVIX_SIGNATURE_HEADER = 'svix-signature';\n\nexport * from './api/resources/Webhooks';\n\n/**\n * Maps Svix headers to Standard Webhooks headers for compatibility\n */\nfunction createStandardWebhookHeaders(request: Request): Record {\n const headers: Record = {};\n\n // Map Svix headers to Standard Webhooks headers\n const svixId = request.headers.get(SVIX_ID_HEADER)?.trim();\n const svixTimestamp = request.headers.get(SVIX_TIMESTAMP_HEADER)?.trim();\n const svixSignature = request.headers.get(SVIX_SIGNATURE_HEADER)?.trim();\n\n if (svixId) {\n headers[STANDARD_WEBHOOK_ID_HEADER] = svixId;\n }\n if (svixTimestamp) {\n headers[STANDARD_WEBHOOK_TIMESTAMP_HEADER] = svixTimestamp;\n }\n if (svixSignature) {\n headers[STANDARD_WEBHOOK_SIGNATURE_HEADER] = svixSignature;\n }\n\n return headers;\n}\n\n/**\n * Verifies the authenticity of a webhook request using Standard Webhooks. Returns a promise that resolves to the verified webhook event data.\n *\n * @param request - The request object.\n * @param options - Optional configuration object.\n *\n * @displayFunctionSignature\n *\n * @example\n * See the [guide on syncing data](https://clerk.com/docs/webhooks/sync-data) for more comprehensive and framework-specific examples that you can copy and paste into your app.\n *\n * ```ts\n * try {\n * const evt = await verifyWebhook(request)\n *\n * // Access the event data\n * const { id } = evt.data\n * const eventType = evt.type\n *\n * // Handle specific event types\n * if (evt.type === 'user.created') {\n * console.log('New user created:', evt.data.id)\n * // Handle user creation\n * }\n *\n * return new Response('Success', { status: 200 })\n * } catch (err) {\n * console.error('Webhook verification failed:', err)\n * return new Response('Webhook verification failed', { status: 400 })\n * }\n * ```\n */\nexport async function verifyWebhook(request: Request, options: VerifyWebhookOptions = {}): Promise {\n const secret = options.signingSecret ?? getEnvVariable('CLERK_WEBHOOK_SIGNING_SECRET');\n\n if (!secret) {\n return errorThrower.throw(\n 'Missing webhook signing secret. Set the CLERK_WEBHOOK_SIGNING_SECRET environment variable with the webhook secret from the Clerk Dashboard.',\n );\n }\n\n // Check for required Svix headers\n const webhookId = request.headers.get(SVIX_ID_HEADER)?.trim();\n const webhookTimestamp = request.headers.get(SVIX_TIMESTAMP_HEADER)?.trim();\n const webhookSignature = request.headers.get(SVIX_SIGNATURE_HEADER)?.trim();\n\n if (!webhookId || !webhookTimestamp || !webhookSignature) {\n const missingHeaders = [];\n\n if (!webhookId) {\n missingHeaders.push(SVIX_ID_HEADER);\n }\n if (!webhookTimestamp) {\n missingHeaders.push(SVIX_TIMESTAMP_HEADER);\n }\n if (!webhookSignature) {\n missingHeaders.push(SVIX_SIGNATURE_HEADER);\n }\n\n return errorThrower.throw(`Missing required webhook headers: ${missingHeaders.join(', ')}`);\n }\n\n const body = await request.text();\n\n // Create Standard Webhooks compatible headers mapping\n const standardHeaders = createStandardWebhookHeaders(request);\n\n // Initialize Standard Webhooks verifier\n const webhook = new Webhook(secret);\n\n try {\n // Verify using Standard Webhooks - this provides constant-time comparison\n // and proper signature format handling\n const payload = webhook.verify(body, standardHeaders) as Record;\n\n return {\n type: payload.type,\n object: 'event',\n data: payload.data,\n event_attributes: payload.event_attributes,\n } as WebhookEvent;\n } catch (e) {\n return errorThrower.throw(`Unable to verify incoming webhook: ${e instanceof Error ? e.message : 'Unknown error'}`);\n }\n}\n","export { addClerkPrefix, getScriptUrl, getClerkJsMajorVersionOrTag } from '@clerk/shared/url';\nexport { retry } from '@clerk/shared/retry';\nexport {\n isDevelopmentFromSecretKey,\n isProductionFromSecretKey,\n parsePublishableKey,\n getCookieSuffix,\n getSuffixedCookieName,\n} from '@clerk/shared/keys';\nexport { deprecated, deprecatedProperty } from '@clerk/shared/deprecated';\n\nimport { buildErrorThrower } from '@clerk/shared/error';\nimport { createDevOrStagingUrlCache } from '@clerk/shared/keys';\n// TODO: replace packageName with `${PACKAGE_NAME}@${PACKAGE_VERSION}` from tsup.config.ts\nexport const errorThrower = buildErrorThrower({ packageName: '@clerk/backend' });\n\nexport const { isDevOrStagingUrl } = createDevOrStagingUrlCache();\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,4BAA+B;;;ACA/B,iBAA0E;AAC1E,mBAAsB;AACtB,kBAMO;AACP,wBAA+C;AAE/C,mBAAkC;AAClC,IAAAA,eAA2C;AAEpC,IAAM,mBAAe,gCAAkB,EAAE,aAAa,iBAAiB,CAAC;AAExE,IAAM,EAAE,kBAAkB,QAAI,yCAA2B;;;ADdhE,8BAAwB;AAexB,IAAM,6BAA6B;AACnC,IAAM,oCAAoC;AAC1C,IAAM,oCAAoC;AAG1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hC,QAAM,kBAAkB,6BAA6B,OAAO;AAG5D,QAAM,UAAU,IAAI,gCAAQ,MAAM;AAElC,MAAI;AAGF,UAAM,UAAU,QAAQ,OAAO,MAAM,eAAe;AAEpD,WAAO;AAAA,MACL,MAAM,QAAQ;AAAA,MACd,QAAQ;AAAA,MACR,MAAM,QAAQ;AAAA,MACd,kBAAkB,QAAQ;AAAA,IAC5B;AAAA,EACF,SAAS,GAAG;AACV,WAAO,aAAa,MAAM,sCAAsC,aAAa,QAAQ,EAAE,UAAU,eAAe,EAAE;AAAA,EACpH;AACF;","names":["import_keys"]} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/webhooks.mjs b/backend/node_modules/@clerk/backend/dist/webhooks.mjs new file mode 100644 index 000000000..8eb346303 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/webhooks.mjs @@ -0,0 +1,72 @@ +import { + errorThrower +} from "./chunk-LWOXHF4E.mjs"; +import "./chunk-RPS7XK5K.mjs"; + +// src/webhooks.ts +import { getEnvVariable } from "@clerk/shared/getEnvVariable"; +import { Webhook } from "standardwebhooks"; +var STANDARD_WEBHOOK_ID_HEADER = "webhook-id"; +var STANDARD_WEBHOOK_TIMESTAMP_HEADER = "webhook-timestamp"; +var STANDARD_WEBHOOK_SIGNATURE_HEADER = "webhook-signature"; +var SVIX_ID_HEADER = "svix-id"; +var SVIX_TIMESTAMP_HEADER = "svix-timestamp"; +var SVIX_SIGNATURE_HEADER = "svix-signature"; +function createStandardWebhookHeaders(request) { + const headers = {}; + const svixId = request.headers.get(SVIX_ID_HEADER)?.trim(); + const svixTimestamp = request.headers.get(SVIX_TIMESTAMP_HEADER)?.trim(); + const svixSignature = request.headers.get(SVIX_SIGNATURE_HEADER)?.trim(); + if (svixId) { + headers[STANDARD_WEBHOOK_ID_HEADER] = svixId; + } + if (svixTimestamp) { + headers[STANDARD_WEBHOOK_TIMESTAMP_HEADER] = svixTimestamp; + } + if (svixSignature) { + headers[STANDARD_WEBHOOK_SIGNATURE_HEADER] = svixSignature; + } + return headers; +} +async function verifyWebhook(request, options = {}) { + const secret = options.signingSecret ?? getEnvVariable("CLERK_WEBHOOK_SIGNING_SECRET"); + if (!secret) { + return errorThrower.throw( + "Missing webhook signing secret. Set the CLERK_WEBHOOK_SIGNING_SECRET environment variable with the webhook secret from the Clerk Dashboard." + ); + } + const webhookId = request.headers.get(SVIX_ID_HEADER)?.trim(); + const webhookTimestamp = request.headers.get(SVIX_TIMESTAMP_HEADER)?.trim(); + const webhookSignature = request.headers.get(SVIX_SIGNATURE_HEADER)?.trim(); + if (!webhookId || !webhookTimestamp || !webhookSignature) { + const missingHeaders = []; + if (!webhookId) { + missingHeaders.push(SVIX_ID_HEADER); + } + if (!webhookTimestamp) { + missingHeaders.push(SVIX_TIMESTAMP_HEADER); + } + if (!webhookSignature) { + missingHeaders.push(SVIX_SIGNATURE_HEADER); + } + return errorThrower.throw(`Missing required webhook headers: ${missingHeaders.join(", ")}`); + } + const body = await request.text(); + const standardHeaders = createStandardWebhookHeaders(request); + const webhook = new Webhook(secret); + try { + const payload = webhook.verify(body, standardHeaders); + return { + type: payload.type, + object: "event", + data: payload.data, + event_attributes: payload.event_attributes + }; + } catch (e) { + return errorThrower.throw(`Unable to verify incoming webhook: ${e instanceof Error ? e.message : "Unknown error"}`); + } +} +export { + verifyWebhook +}; +//# sourceMappingURL=webhooks.mjs.map \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/dist/webhooks.mjs.map b/backend/node_modules/@clerk/backend/dist/webhooks.mjs.map new file mode 100644 index 000000000..e674b44e4 --- /dev/null +++ b/backend/node_modules/@clerk/backend/dist/webhooks.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../src/webhooks.ts"],"sourcesContent":["import { getEnvVariable } from '@clerk/shared/getEnvVariable';\nimport { errorThrower } from 'src/util/shared';\nimport { Webhook } from 'standardwebhooks';\n\nimport type { WebhookEvent } from './api/resources/Webhooks';\n\n/**\n * @inline\n */\nexport type VerifyWebhookOptions = {\n /**\n * The signing secret for the webhook. It's recommended to use the [`CLERK_WEBHOOK_SIGNING_SECRET` environment variable](https://clerk.com/docs/deployments/clerk-environment-variables#webhooks) instead.\n */\n signingSecret?: string;\n};\n\n// Standard Webhooks header names\nconst STANDARD_WEBHOOK_ID_HEADER = 'webhook-id';\nconst STANDARD_WEBHOOK_TIMESTAMP_HEADER = 'webhook-timestamp';\nconst STANDARD_WEBHOOK_SIGNATURE_HEADER = 'webhook-signature';\n\n// Svix header names (for mapping)\nconst SVIX_ID_HEADER = 'svix-id';\nconst SVIX_TIMESTAMP_HEADER = 'svix-timestamp';\nconst SVIX_SIGNATURE_HEADER = 'svix-signature';\n\nexport * from './api/resources/Webhooks';\n\n/**\n * Maps Svix headers to Standard Webhooks headers for compatibility\n */\nfunction createStandardWebhookHeaders(request: Request): Record {\n const headers: Record = {};\n\n // Map Svix headers to Standard Webhooks headers\n const svixId = request.headers.get(SVIX_ID_HEADER)?.trim();\n const svixTimestamp = request.headers.get(SVIX_TIMESTAMP_HEADER)?.trim();\n const svixSignature = request.headers.get(SVIX_SIGNATURE_HEADER)?.trim();\n\n if (svixId) {\n headers[STANDARD_WEBHOOK_ID_HEADER] = svixId;\n }\n if (svixTimestamp) {\n headers[STANDARD_WEBHOOK_TIMESTAMP_HEADER] = svixTimestamp;\n }\n if (svixSignature) {\n headers[STANDARD_WEBHOOK_SIGNATURE_HEADER] = svixSignature;\n }\n\n return headers;\n}\n\n/**\n * Verifies the authenticity of a webhook request using Standard Webhooks. Returns a promise that resolves to the verified webhook event data.\n *\n * @param request - The request object.\n * @param options - Optional configuration object.\n *\n * @displayFunctionSignature\n *\n * @example\n * See the [guide on syncing data](https://clerk.com/docs/webhooks/sync-data) for more comprehensive and framework-specific examples that you can copy and paste into your app.\n *\n * ```ts\n * try {\n * const evt = await verifyWebhook(request)\n *\n * // Access the event data\n * const { id } = evt.data\n * const eventType = evt.type\n *\n * // Handle specific event types\n * if (evt.type === 'user.created') {\n * console.log('New user created:', evt.data.id)\n * // Handle user creation\n * }\n *\n * return new Response('Success', { status: 200 })\n * } catch (err) {\n * console.error('Webhook verification failed:', err)\n * return new Response('Webhook verification failed', { status: 400 })\n * }\n * ```\n */\nexport async function verifyWebhook(request: Request, options: VerifyWebhookOptions = {}): Promise {\n const secret = options.signingSecret ?? getEnvVariable('CLERK_WEBHOOK_SIGNING_SECRET');\n\n if (!secret) {\n return errorThrower.throw(\n 'Missing webhook signing secret. Set the CLERK_WEBHOOK_SIGNING_SECRET environment variable with the webhook secret from the Clerk Dashboard.',\n );\n }\n\n // Check for required Svix headers\n const webhookId = request.headers.get(SVIX_ID_HEADER)?.trim();\n const webhookTimestamp = request.headers.get(SVIX_TIMESTAMP_HEADER)?.trim();\n const webhookSignature = request.headers.get(SVIX_SIGNATURE_HEADER)?.trim();\n\n if (!webhookId || !webhookTimestamp || !webhookSignature) {\n const missingHeaders = [];\n\n if (!webhookId) {\n missingHeaders.push(SVIX_ID_HEADER);\n }\n if (!webhookTimestamp) {\n missingHeaders.push(SVIX_TIMESTAMP_HEADER);\n }\n if (!webhookSignature) {\n missingHeaders.push(SVIX_SIGNATURE_HEADER);\n }\n\n return errorThrower.throw(`Missing required webhook headers: ${missingHeaders.join(', ')}`);\n }\n\n const body = await request.text();\n\n // Create Standard Webhooks compatible headers mapping\n const standardHeaders = createStandardWebhookHeaders(request);\n\n // Initialize Standard Webhooks verifier\n const webhook = new Webhook(secret);\n\n try {\n // Verify using Standard Webhooks - this provides constant-time comparison\n // and proper signature format handling\n const payload = webhook.verify(body, standardHeaders) as Record;\n\n return {\n type: payload.type,\n object: 'event',\n data: payload.data,\n event_attributes: payload.event_attributes,\n } as WebhookEvent;\n } catch (e) {\n return errorThrower.throw(`Unable to verify incoming webhook: ${e instanceof Error ? e.message : 'Unknown error'}`);\n }\n}\n"],"mappings":";;;;;;AAAA,SAAS,sBAAsB;AAE/B,SAAS,eAAe;AAexB,IAAM,6BAA6B;AACnC,IAAM,oCAAoC;AAC1C,IAA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AQ,KAAK;AAGhC,QAAM,kBAAkB,6BAA6B,OAAO;AAG5D,QAAM,UAAU,IAAI,QAAQ,MAAM;AAElC,MAAI;AAGF,UAAM,UAAU,QAAQ,OAAO,MAAM,eAAe;AAEpD,WAAO;AAAA,MACL,MAAM,QAAQ;AAAA,MACd,QAAQ;AAAA,MACR,MAAM,QAAQ;AAAA,MACd,kBAAkB,QAAQ;AAAA,IAC5B;AAAA,EACF,SAAS,GAAG;AACV,WAAO,aAAa,MAAM,sCAAsC,aAAa,QAAQ,EAAE,UAAU,eAAe,EAAE;AAAA,EACpH;AACF;","names":[]} \ No newline at end of file diff --git a/backend/node_modules/@clerk/backend/errors/package.json b/backend/node_modules/@clerk/backend/errors/package.json new file mode 100644 index 000000000..61ac22953 --- /dev/null +++ b/backend/node_modules/@clerk/backend/errors/package.json @@ -0,0 +1,5 @@ +{ + "main": "../dist/errors.js", + "module": "../dist/errors.mjs", + "types": "../dist/errors.d.ts" +} diff --git a/backend/node_modules/@clerk/backend/internal/package.json b/backend/node_modules/@clerk/backend/internal/package.json new file mode 100644 index 000000000..9dacb15eb --- /dev/null +++ b/backend/node_modules/@clerk/backend/internal/package.json @@ -0,0 +1,5 @@ +{ + "main": "../dist/internal.js", + "module": "../dist/internal.mjs", + "types": "../dist/internal.d.ts" +} diff --git a/backend/node_modules/@clerk/backend/jwt/package.json b/backend/node_modules/@clerk/backend/jwt/package.json new file mode 100644 index 000000000..1375b2569 --- /dev/null +++ b/backend/node_modules/@clerk/backend/jwt/package.json @@ -0,0 +1,5 @@ +{ + "main": "../dist/jwt/index.js", + "module": "../dist/jwt/index.mjs", + "types": "../dist/jwt/index.d.ts" +} diff --git a/backend/node_modules/@clerk/backend/node_modules/cookie/LICENSE b/backend/node_modules/@clerk/backend/node_modules/cookie/LICENSE new file mode 100644 index 000000000..058b6b4ef --- /dev/null +++ b/backend/node_modules/@clerk/backend/node_modules/cookie/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2012-2014 Roman Shtylman +Copyright (c) 2015 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + diff --git a/backend/node_modules/@clerk/backend/node_modules/cookie/README.md b/backend/node_modules/@clerk/backend/node_modules/cookie/README.md new file mode 100644 index 000000000..54e1cdae9 --- /dev/null +++ b/backend/node_modules/@clerk/backend/node_modules/cookie/README.md @@ -0,0 +1,248 @@ +# cookie + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Build Status][ci-image]][ci-url] +[![Coverage Status][coverage-image]][coverage-url] + +Basic HTTP cookie parser and serializer for HTTP servers. + +## Installation + +```sh +$ npm install cookie +``` + +## API + +```js +const cookie = require("cookie"); +// import * as cookie from 'cookie'; +``` + +### cookie.parse(str, options) + +Parse a HTTP `Cookie` header string and returning an object of all cookie name-value pairs. +The `str` argument is the string representing a `Cookie` header value and `options` is an +optional object containing additional parsing options. + +```js +const cookies = cookie.parse("foo=bar; equation=E%3Dmc%5E2"); +// { foo: 'bar', equation: 'E=mc^2' } +``` + +#### Options + +`cookie.parse` accepts these properties in the options object. + +##### decode + +Specifies a function that will be used to decode a [cookie-value](https://datatracker.ietf.org/doc/html/rfc6265#section-4.1.1). +Since the value of a cookie has a limited character set (and must be a simple string), this function can be used to decode +a previously-encoded cookie value into a JavaScript string. + +The default function is the global `decodeURIComponent`, wrapped in a `try..catch`. If an error +is thrown it will return the cookie's original value. If you provide your own encode/decode +scheme you must ensure errors are appropriately handled. + +### cookie.serialize(name, value, options) + +Serialize a cookie name-value pair into a `Set-Cookie` header string. The `name` argument is the +name for the cookie, the `value` argument is the value to set the cookie to, and the `options` +argument is an optional object containing additional serialization options. + +```js +const setCookie = cookie.serialize("foo", "bar"); +// foo=bar +``` + +#### Options + +`cookie.serialize` accepts these properties in the options object. + +##### encode + +Specifies a function that will be used to encode a [cookie-value](https://datatracker.ietf.org/doc/html/rfc6265#section-4.1.1). +Since value of a cookie has a limited character set (and must be a simple string), this function can be used to encode +a value into a string suited for a cookie's value, and should mirror `decode` when parsing. + +The default function is the global `encodeURIComponent`. + +##### maxAge + +Specifies the `number` (in seconds) to be the value for the [`Max-Age` `Set-Cookie` attribute](https://tools.ietf.org/html/rfc6265#section-5.2.2). + +The [cookie storage model specification](https://tools.ietf.org/html/rfc6265#section-5.3) states that if both `expires` and +`maxAge` are set, then `maxAge` takes precedence, but it is possible not all clients by obey this, +so if both are set, they should point to the same date and time. + +##### expires + +Specifies the `Date` object to be the value for the [`Expires` `Set-Cookie` attribute](https://tools.ietf.org/html/rfc6265#section-5.2.1). +When no expiration is set clients consider this a "non-persistent cookie" and delete it the current session is over. + +The [cookie storage model specification](https://tools.ietf.org/html/rfc6265#section-5.3) states that if both `expires` and +`maxAge` are set, then `maxAge` takes precedence, but it is possible not all clients by obey this, +so if both are set, they should point to the same date and time. + +##### domain + +Specifies the value for the [`Domain` `Set-Cookie` attribute](https://tools.ietf.org/html/rfc6265#section-5.2.3). +When no domain is set clients consider the cookie to apply to the current domain only. + +##### path + +Specifies the value for the [`Path` `Set-Cookie` attribute](https://tools.ietf.org/html/rfc6265#section-5.2.4). +When no path is set, the path is considered the ["default path"](https://tools.ietf.org/html/rfc6265#section-5.1.4). + +##### httpOnly + +Enables the [`HttpOnly` `Set-Cookie` attribute](https://tools.ietf.org/html/rfc6265#section-5.2.6). +When enabled, clients will not allow client-side JavaScript to see the cookie in `document.cookie`. + +##### secure + +Enables the [`Secure` `Set-Cookie` attribute](https://tools.ietf.org/html/rfc6265#section-5.2.5). +When enabled, clients will only send the cookie back if the browser has a HTTPS connection. + +##### partitioned + +Enables the [`Partitioned` `Set-Cookie` attribute](https://tools.ietf.org/html/draft-cutler-httpbis-partitioned-cookies/). +When enabled, clients will only send the cookie back when the current domain _and_ top-level domain matches. + +This is an attribute that has not yet been fully standardized, and may change in the future. +This also means clients may ignore this attribute until they understand it. More information +about can be found in [the proposal](https://github.com/privacycg/CHIPS). + +##### priority + +Specifies the value for the [`Priority` `Set-Cookie` attribute](https://tools.ietf.org/html/draft-west-cookie-priority-00#section-4.1). + +- `'low'` will set the `Priority` attribute to `Low`. +- `'medium'` will set the `Priority` attribute to `Medium`, the default priority when not set. +- `'high'` will set the `Priority` attribute to `High`. + +More information about priority levels can be found in [the specification](https://tools.ietf.org/html/draft-west-cookie-priority-00#section-4.1). + +##### sameSite + +Specifies the value for the [`SameSite` `Set-Cookie` attribute](https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-09#section-5.4.7). + +- `true` will set the `SameSite` attribute to `Strict` for strict same site enforcement. +- `'lax'` will set the `SameSite` attribute to `Lax` for lax same site enforcement. +- `'none'` will set the `SameSite` attribute to `None` for an explicit cross-site cookie. +- `'strict'` will set the `SameSite` attribute to `Strict` for strict same site enforcement. + +More information about enforcement levels can be found in [the specification](https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-09#section-5.4.7). + +## Example + +The following example uses this module in conjunction with the Node.js core HTTP server +to prompt a user for their name and display it back on future visits. + +```js +var cookie = require("cookie"); +var escapeHtml = require("escape-html"); +var http = require("http"); +var url = require("url"); + +function onRequest(req, res) { + // Parse the query string + var query = url.parse(req.url, true, true).query; + + if (query && query.name) { + // Set a new cookie with the name + res.setHeader( + "Set-Cookie", + cookie.serialize("name", String(query.name), { + httpOnly: true, + maxAge: 60 * 60 * 24 * 7, // 1 week + }), + ); + + // Redirect back after setting cookie + res.statusCode = 302; + res.setHeader("Location", req.headers.referer || "/"); + res.end(); + return; + } + + // Parse the cookies on the request + var cookies = cookie.parse(req.headers.cookie || ""); + + // Get the visitor name set in the cookie + var name = cookies.name; + + res.setHeader("Content-Type", "text/html; charset=UTF-8"); + + if (name) { + res.write("

Welcome back, " + escapeHtml(name) + "!

"); + } else { + res.write("

Hello, new visitor!

"); + } + + res.write('
'); + res.write( + ' ', + ); + res.end("
"); +} + +http.createServer(onRequest).listen(3000); +``` + +## Testing + +```sh +npm test +``` + +## Benchmark + +```sh +npm run bench +``` + +``` + name hz min max mean p75 p99 p995 p999 rme samples + · simple 8,566,313.09 0.0000 0.3694 0.0001 0.0001 0.0002 0.0002 0.0003 ±0.64% 4283157 fastest + · decode 3,834,348.85 0.0001 0.2465 0.0003 0.0003 0.0003 0.0004 0.0006 ±0.38% 1917175 + · unquote 8,315,355.96 0.0000 0.3824 0.0001 0.0001 0.0002 0.0002 0.0003 ±0.72% 4157880 + · duplicates 1,944,765.97 0.0004 0.2959 0.0005 0.0005 0.0006 0.0006 0.0008 ±0.24% 972384 + · 10 cookies 675,345.67 0.0012 0.4328 0.0015 0.0015 0.0019 0.0020 0.0058 ±0.75% 337673 + · 100 cookies 61,040.71 0.0152 0.4092 0.0164 0.0160 0.0196 0.0228 0.2260 ±0.71% 30521 slowest + ✓ parse top-sites (15) 22945ms + name hz min max mean p75 p99 p995 p999 rme samples + · parse accounts.google.com 7,164,349.17 0.0000 0.0929 0.0001 0.0002 0.0002 0.0002 0.0003 ±0.09% 3582184 + · parse apple.com 7,817,686.84 0.0000 0.6048 0.0001 0.0001 0.0002 0.0002 0.0003 ±1.05% 3908844 + · parse cloudflare.com 7,189,841.70 0.0000 0.0390 0.0001 0.0002 0.0002 0.0002 0.0003 ±0.06% 3594921 + · parse docs.google.com 7,051,765.61 0.0000 0.0296 0.0001 0.0002 0.0002 0.0002 0.0003 ±0.06% 3525883 + · parse drive.google.com 7,349,104.77 0.0000 0.0368 0.0001 0.0001 0.0002 0.0002 0.0003 ±0.05% 3674553 + · parse en.wikipedia.org 1,929,909.49 0.0004 0.3598 0.0005 0.0005 0.0007 0.0007 0.0012 ±0.16% 964955 + · parse linkedin.com 2,225,658.01 0.0003 0.0595 0.0004 0.0005 0.0005 0.0005 0.0006 ±0.06% 1112830 + · parse maps.google.com 4,423,511.68 0.0001 0.0942 0.0002 0.0003 0.0003 0.0003 0.0005 ±0.08% 2211756 + · parse microsoft.com 3,387,601.88 0.0002 0.0725 0.0003 0.0003 0.0004 0.0004 0.0005 ±0.09% 1693801 + · parse play.google.com 7,375,980.86 0.0000 0.1994 0.0001 0.0001 0.0002 0.0002 0.0003 ±0.12% 3687991 + · parse support.google.com 4,912,267.94 0.0001 2.8958 0.0002 0.0002 0.0003 0.0003 0.0005 ±1.28% 2456134 + · parse www.google.com 3,443,035.87 0.0002 0.2783 0.0003 0.0003 0.0004 0.0004 0.0007 ±0.51% 1721518 + · parse youtu.be 1,910,492.87 0.0004 0.3490 0.0005 0.0005 0.0007 0.0007 0.0011 ±0.46% 955247 + · parse youtube.com 1,895,082.62 0.0004 0.7454 0.0005 0.0005 0.0006 0.0007 0.0013 ±0.64% 947542 slowest + · parse example.com 21,582,835.27 0.0000 0.1095 0.0000 0.0000 0.0001 0.0001 0.0001 ±0.13% 10791418 +``` + +## References + +- [RFC 6265: HTTP State Management Mechanism](https://tools.ietf.org/html/rfc6265) +- [Same-site Cookies](https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-09#section-5.4.7) + +## License + +[MIT](LICENSE) + +[ci-image]: https://img.shields.io/github/actions/workflow/status/jshttp/cookie/ci.yml +[ci-url]: https://github.com/jshttp/cookie/actions/workflows/ci.yml?query=branch%3Amaster +[coverage-image]: https://img.shields.io/codecov/c/github/jshttp/cookie/master +[coverage-url]: https://app.codecov.io/gh/jshttp/cookie +[npm-downloads-image]: https://img.shields.io/npm/dm/cookie +[npm-url]: https://npmjs.org/package/cookie +[npm-version-image]: https://img.shields.io/npm/v/cookie diff --git a/backend/node_modules/@clerk/backend/node_modules/cookie/dist/index.d.ts b/backend/node_modules/@clerk/backend/node_modules/cookie/dist/index.d.ts new file mode 100644 index 000000000..784b0dbd6 --- /dev/null +++ b/backend/node_modules/@clerk/backend/node_modules/cookie/dist/index.d.ts @@ -0,0 +1,114 @@ +/** + * Parse options. + */ +export interface ParseOptions { + /** + * Specifies a function that will be used to decode a [cookie-value](https://datatracker.ietf.org/doc/html/rfc6265#section-4.1.1). + * Since the value of a cookie has a limited character set (and must be a simple string), this function can be used to decode + * a previously-encoded cookie value into a JavaScript string. + * + * The default function is the global `decodeURIComponent`, wrapped in a `try..catch`. If an error + * is thrown it will return the cookie's original value. If you provide your own encode/decode + * scheme you must ensure errors are appropriately handled. + * + * @default decode + */ + decode?: (str: string) => string | undefined; +} +/** + * Parse a cookie header. + * + * Parse the given cookie header string into an object + * The object has the various cookies as keys(names) => values + */ +export declare function parse(str: string, options?: ParseOptions): Record; +/** + * Serialize options. + */ +export interface SerializeOptions { + /** + * Specifies a function that will be used to encode a [cookie-value](https://datatracker.ietf.org/doc/html/rfc6265#section-4.1.1). + * Since value of a cookie has a limited character set (and must be a simple string), this function can be used to encode + * a value into a string suited for a cookie's value, and should mirror `decode` when parsing. + * + * @default encodeURIComponent + */ + encode?: (str: string) => string; + /** + * Specifies the `number` (in seconds) to be the value for the [`Max-Age` `Set-Cookie` attribute](https://tools.ietf.org/html/rfc6265#section-5.2.2). + * + * The [cookie storage model specification](https://tools.ietf.org/html/rfc6265#section-5.3) states that if both `expires` and + * `maxAge` are set, then `maxAge` takes precedence, but it is possible not all clients by obey this, + * so if both are set, they should point to the same date and time. + */ + maxAge?: number; + /** + * Specifies the `Date` object to be the value for the [`Expires` `Set-Cookie` attribute](https://tools.ietf.org/html/rfc6265#section-5.2.1). + * When no expiration is set clients consider this a "non-persistent cookie" and delete it the current session is over. + * + * The [cookie storage model specification](https://tools.ietf.org/html/rfc6265#section-5.3) states that if both `expires` and + * `maxAge` are set, then `maxAge` takes precedence, but it is possible not all clients by obey this, + * so if both are set, they should point to the same date and time. + */ + expires?: Date; + /** + * Specifies the value for the [`Domain` `Set-Cookie` attribute](https://tools.ietf.org/html/rfc6265#section-5.2.3). + * When no domain is set clients consider the cookie to apply to the current domain only. + */ + domain?: string; + /** + * Specifies the value for the [`Path` `Set-Cookie` attribute](https://tools.ietf.org/html/rfc6265#section-5.2.4). + * When no path is set, the path is considered the ["default path"](https://tools.ietf.org/html/rfc6265#section-5.1.4). + */ + path?: string; + /** + * Enables the [`HttpOnly` `Set-Cookie` attribute](https://tools.ietf.org/html/rfc6265#section-5.2.6). + * When enabled, clients will not allow client-side JavaScript to see the cookie in `document.cookie`. + */ + httpOnly?: boolean; + /** + * Enables the [`Secure` `Set-Cookie` attribute](https://tools.ietf.org/html/rfc6265#section-5.2.5). + * When enabled, clients will only send the cookie back if the browser has a HTTPS connection. + */ + secure?: boolean; + /** + * Enables the [`Partitioned` `Set-Cookie` attribute](https://tools.ietf.org/html/draft-cutler-httpbis-partitioned-cookies/). + * When enabled, clients will only send the cookie back when the current domain _and_ top-level domain matches. + * + * This is an attribute that has not yet been fully standardized, and may change in the future. + * This also means clients may ignore this attribute until they understand it. More information + * about can be found in [the proposal](https://github.com/privacycg/CHIPS). + */ + partitioned?: boolean; + /** + * Specifies the value for the [`Priority` `Set-Cookie` attribute](https://tools.ietf.org/html/draft-west-cookie-priority-00#section-4.1). + * + * - `'low'` will set the `Priority` attribute to `Low`. + * - `'medium'` will set the `Priority` attribute to `Medium`, the default priority when not set. + * - `'high'` will set the `Priority` attribute to `High`. + * + * More information about priority levels can be found in [the specification](https://tools.ietf.org/html/draft-west-cookie-priority-00#section-4.1). + */ + priority?: "low" | "medium" | "high"; + /** + * Specifies the value for the [`SameSite` `Set-Cookie` attribute](https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-09#section-5.4.7). + * + * - `true` will set the `SameSite` attribute to `Strict` for strict same site enforcement. + * - `'lax'` will set the `SameSite` attribute to `Lax` for lax same site enforcement. + * - `'none'` will set the `SameSite` attribute to `None` for an explicit cross-site cookie. + * - `'strict'` will set the `SameSite` attribute to `Strict` for strict same site enforcement. + * + * More information about enforcement levels can be found in [the specification](https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-09#section-5.4.7). + */ + sameSite?: boolean | "lax" | "strict" | "none"; +} +/** + * Serialize data into a cookie header. + * + * Serialize a name value pair into a cookie string suitable for + * http headers. An optional options object specifies cookie parameters. + * + * serialize('foo', 'bar', { httpOnly: true }) + * => "foo=bar; httpOnly" + */ +export declare function serialize(name: string, val: string, options?: SerializeOptions): string; diff --git a/backend/node_modules/@clerk/backend/node_modules/cookie/dist/index.js b/backend/node_modules/@clerk/backend/node_modules/cookie/dist/index.js new file mode 100644 index 000000000..423acb4e7 --- /dev/null +++ b/backend/node_modules/@clerk/backend/node_modules/cookie/dist/index.js @@ -0,0 +1,239 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parse = parse; +exports.serialize = serialize; +/** + * RegExp to match cookie-name in RFC 6265 sec 4.1.1 + * This refers out to the obsoleted definition of token in RFC 2616 sec 2.2 + * which has been replaced by the token definition in RFC 7230 appendix B. + * + * cookie-name = token + * token = 1*tchar + * tchar = "!" / "#" / "$" / "%" / "&" / "'" / + * "*" / "+" / "-" / "." / "^" / "_" / + * "`" / "|" / "~" / DIGIT / ALPHA + * + * Note: Allowing more characters - https://github.com/jshttp/cookie/issues/191 + * Allow same range as cookie value, except `=`, which delimits end of name. + */ +const cookieNameRegExp = /^[\u0021-\u003A\u003C\u003E-\u007E]+$/; +/** + * RegExp to match cookie-value in RFC 6265 sec 4.1.1 + * + * cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE ) + * cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E + * ; US-ASCII characters excluding CTLs, + * ; whitespace DQUOTE, comma, semicolon, + * ; and backslash + * + * Allowing more characters: https://github.com/jshttp/cookie/issues/191 + * Comma, backslash, and DQUOTE are not part of the parsing algorithm. + */ +const cookieValueRegExp = /^[\u0021-\u003A\u003C-\u007E]*$/; +/** + * RegExp to match domain-value in RFC 6265 sec 4.1.1 + * + * domain-value = + * ; defined in [RFC1034], Section 3.5, as + * ; enhanced by [RFC1123], Section 2.1 + * =