@prosopo/better-auth-procaptcha-plugin 0.0.0-stage → 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/.turbo/turbo-build$colon$types.log +54 -0
  2. package/LICENSE +201 -0
  3. package/coverage/base.css +362 -0
  4. package/coverage/block-navigation.js +82 -0
  5. package/coverage/client.ts.html +316 -0
  6. package/coverage/clover.xml +151 -0
  7. package/coverage/constants.ts.html +190 -0
  8. package/coverage/coverage-final.json +6 -0
  9. package/coverage/favicon.png +0 -0
  10. package/coverage/index.html +176 -0
  11. package/coverage/index.ts.html +706 -0
  12. package/coverage/path.ts.html +355 -0
  13. package/coverage/prettify.css +101 -0
  14. package/coverage/prettify.js +937 -0
  15. package/coverage/siteverify.ts.html +559 -0
  16. package/coverage/sort-arrow-sprite.png +0 -0
  17. package/coverage/sorter.js +205 -0
  18. package/dist/cjs/client.cjs +32 -0
  19. package/dist/cjs/constants.cjs +22 -0
  20. package/dist/cjs/index.cjs +80 -0
  21. package/dist/cjs/path.cjs +41 -0
  22. package/dist/cjs/siteverify.cjs +68 -0
  23. package/dist/esm/_virtual/_rolldown/runtime.js +3 -0
  24. package/dist/esm/client.js +31 -0
  25. package/dist/esm/constants.js +18 -0
  26. package/dist/esm/index.js +75 -0
  27. package/dist/esm/path.js +40 -0
  28. package/dist/esm/siteverify.js +68 -0
  29. package/dist/types/client.d.ts +19 -0
  30. package/dist/types/client.d.ts.map +1 -0
  31. package/dist/types/constants.d.ts +12 -0
  32. package/dist/types/constants.d.ts.map +1 -0
  33. package/dist/types/index.d.ts +28 -0
  34. package/dist/types/index.d.ts.map +1 -0
  35. package/dist/types/path.d.ts +4 -0
  36. package/dist/types/path.d.ts.map +1 -0
  37. package/dist/types/siteverify.d.ts +40 -0
  38. package/dist/types/siteverify.d.ts.map +1 -0
  39. package/dist/types/tests/client.unit.test.d.ts +2 -0
  40. package/dist/types/tests/client.unit.test.d.ts.map +1 -0
  41. package/dist/types/tests/path.unit.test.d.ts +2 -0
  42. package/dist/types/tests/path.unit.test.d.ts.map +1 -0
  43. package/dist/types/tests/procaptcha.unit.test.d.ts +2 -0
  44. package/dist/types/tests/procaptcha.unit.test.d.ts.map +1 -0
  45. package/dist/types/tests/siteVerifyMock.d.ts +17 -0
  46. package/dist/types/tests/siteVerifyMock.d.ts.map +1 -0
  47. package/dist/types/tests/siteverify.unit.test.d.ts +2 -0
  48. package/dist/types/tests/siteverify.unit.test.d.ts.map +1 -0
  49. package/package.json +68 -3
  50. package/readme.md +145 -0
  51. package/vite.cjs.config.ts +24 -0
  52. package/vite.esm.config.ts +23 -0
  53. package/vite.test.config.ts +19 -0
  54. package/README.md +0 -3
@@ -0,0 +1,205 @@
1
+ /* eslint-disable */
2
+ var addSorting = (function () {
3
+ "use strict";
4
+ var cols,
5
+ currentSort = {
6
+ index: 0,
7
+ desc: false,
8
+ };
9
+
10
+ // returns the summary table element
11
+ function getTable() {
12
+ return document.querySelector(".coverage-summary");
13
+ }
14
+ // returns the thead element of the summary table
15
+ function getTableHeader() {
16
+ return getTable().querySelector("thead tr");
17
+ }
18
+ // returns the tbody element of the summary table
19
+ function getTableBody() {
20
+ return getTable().querySelector("tbody");
21
+ }
22
+ // returns the th element for nth column
23
+ function getNthColumn(n) {
24
+ return getTableHeader().querySelectorAll("th")[n];
25
+ }
26
+
27
+ function onFilterInput() {
28
+ const searchValue = document.getElementById("fileSearch").value;
29
+ const rows = document.getElementsByTagName("tbody")[0].children;
30
+
31
+ // Try to create a RegExp from the searchValue. If it fails (invalid regex),
32
+ // it will be treated as a plain text search
33
+ let searchRegex;
34
+ try {
35
+ searchRegex = new RegExp(searchValue, "i"); // 'i' for case-insensitive
36
+ } catch (error) {
37
+ searchRegex = null;
38
+ }
39
+
40
+ for (let i = 0; i < rows.length; i++) {
41
+ const row = rows[i];
42
+ let isMatch = false;
43
+
44
+ if (searchRegex) {
45
+ // If a valid regex was created, use it for matching
46
+ isMatch = searchRegex.test(row.textContent);
47
+ } else {
48
+ // Otherwise, fall back to the original plain text search
49
+ isMatch = row.textContent.toLowerCase().includes(searchValue.toLowerCase());
50
+ }
51
+
52
+ row.style.display = isMatch ? "" : "none";
53
+ }
54
+ }
55
+
56
+ // loads the search box
57
+ function addSearchBox() {
58
+ var template = document.getElementById("filterTemplate");
59
+ var templateClone = template.content.cloneNode(true);
60
+ templateClone.getElementById("fileSearch").oninput = onFilterInput;
61
+ template.parentElement.appendChild(templateClone);
62
+ }
63
+
64
+ // loads all columns
65
+ function loadColumns() {
66
+ var colNodes = getTableHeader().querySelectorAll("th"),
67
+ colNode,
68
+ cols = [],
69
+ col,
70
+ i;
71
+
72
+ for (i = 0; i < colNodes.length; i += 1) {
73
+ colNode = colNodes[i];
74
+ col = {
75
+ key: colNode.getAttribute("data-col"),
76
+ sortable: !colNode.getAttribute("data-nosort"),
77
+ type: colNode.getAttribute("data-type") || "string",
78
+ };
79
+ cols.push(col);
80
+ if (col.sortable) {
81
+ col.defaultDescSort = col.type === "number";
82
+ colNode.innerHTML = colNode.innerHTML + '<span class="sorter"></span>';
83
+ }
84
+ }
85
+ return cols;
86
+ }
87
+ // attaches a data attribute to every tr element with an object
88
+ // of data values keyed by column name
89
+ function loadRowData(tableRow) {
90
+ var tableCols = tableRow.querySelectorAll("td"),
91
+ colNode,
92
+ col,
93
+ data = {},
94
+ i,
95
+ val;
96
+ for (i = 0; i < tableCols.length; i += 1) {
97
+ colNode = tableCols[i];
98
+ col = cols[i];
99
+ val = colNode.getAttribute("data-value");
100
+ if (col.type === "number") {
101
+ val = Number(val);
102
+ }
103
+ data[col.key] = val;
104
+ }
105
+ return data;
106
+ }
107
+ // loads all row data
108
+ function loadData() {
109
+ var rows = getTableBody().querySelectorAll("tr"),
110
+ i;
111
+
112
+ for (i = 0; i < rows.length; i += 1) {
113
+ rows[i].data = loadRowData(rows[i]);
114
+ }
115
+ }
116
+ // sorts the table using the data for the ith column
117
+ function sortByIndex(index, desc) {
118
+ var key = cols[index].key,
119
+ sorter = function (a, b) {
120
+ a = a.data[key];
121
+ b = b.data[key];
122
+ return a < b ? -1 : a > b ? 1 : 0;
123
+ },
124
+ finalSorter = sorter,
125
+ tableBody = document.querySelector(".coverage-summary tbody"),
126
+ rowNodes = tableBody.querySelectorAll("tr"),
127
+ rows = [],
128
+ i;
129
+
130
+ if (desc) {
131
+ finalSorter = function (a, b) {
132
+ return -1 * sorter(a, b);
133
+ };
134
+ }
135
+
136
+ for (i = 0; i < rowNodes.length; i += 1) {
137
+ rows.push(rowNodes[i]);
138
+ tableBody.removeChild(rowNodes[i]);
139
+ }
140
+
141
+ rows.sort(finalSorter);
142
+
143
+ for (i = 0; i < rows.length; i += 1) {
144
+ tableBody.appendChild(rows[i]);
145
+ }
146
+ }
147
+ // removes sort indicators for current column being sorted
148
+ function removeSortIndicators() {
149
+ var col = getNthColumn(currentSort.index),
150
+ cls = col.className;
151
+
152
+ cls = cls.replace(/ sorted$/, "").replace(/ sorted-desc$/, "");
153
+ col.className = cls;
154
+ }
155
+ // adds sort indicators for current column being sorted
156
+ function addSortIndicators() {
157
+ getNthColumn(currentSort.index).className += currentSort.desc ? " sorted-desc" : " sorted";
158
+ }
159
+ // adds event listeners for all sorter widgets
160
+ function enableUI() {
161
+ var i,
162
+ el,
163
+ ithSorter = function ithSorter(i) {
164
+ var col = cols[i];
165
+
166
+ return function () {
167
+ var desc = col.defaultDescSort;
168
+
169
+ if (currentSort.index === i) {
170
+ desc = !currentSort.desc;
171
+ }
172
+ sortByIndex(i, desc);
173
+ removeSortIndicators();
174
+ currentSort.index = i;
175
+ currentSort.desc = desc;
176
+ addSortIndicators();
177
+ };
178
+ };
179
+ for (i = 0; i < cols.length; i += 1) {
180
+ if (cols[i].sortable) {
181
+ // add the click event handler on the th so users
182
+ // dont have to click on those tiny arrows
183
+ el = getNthColumn(i).querySelector(".sorter").parentElement;
184
+ if (el.addEventListener) {
185
+ el.addEventListener("click", ithSorter(i));
186
+ } else {
187
+ el.attachEvent("onclick", ithSorter(i));
188
+ }
189
+ }
190
+ }
191
+ }
192
+ // adds sorting functionality to the UI
193
+ return function () {
194
+ if (!getTable()) {
195
+ return;
196
+ }
197
+ cols = loadColumns();
198
+ loadData();
199
+ addSearchBox();
200
+ addSortIndicators();
201
+ enableUI();
202
+ };
203
+ })();
204
+
205
+ window.addEventListener("load", addSorting);
@@ -0,0 +1,32 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_constants = require("./constants.cjs");
3
+ const require_path = require("./path.cjs");
4
+ //#region src/client.ts
5
+ var procaptchaHeaders = (token, headerName = require_constants.PROCAPTCHA_HEADER) => ({ [headerName]: token });
6
+ var authPathOf = (url, baseURL) => {
7
+ const requestURL = new URL(url, "http://localhost");
8
+ const basePath = baseURL ? new URL(baseURL, requestURL).pathname : "";
9
+ return require_path.normalizeAuthPath(requestURL.pathname, basePath);
10
+ };
11
+ var procaptchaClient = (options = {}) => {
12
+ const { getToken } = options;
13
+ const headerName = options.headerName ?? "x-captcha-response";
14
+ const isProtected = require_path.createPathMatcher(options.endpoints?.length ? options.endpoints : require_constants.DEFAULT_ENDPOINTS);
15
+ return {
16
+ id: "procaptcha",
17
+ $InferServerPlugin: {},
18
+ fetchPlugins: getToken ? [{
19
+ id: "procaptcha",
20
+ name: "procaptcha",
21
+ hooks: { onRequest: async (context) => {
22
+ if (context.headers.has(headerName) || !isProtected(authPathOf(context.url, context.baseURL))) return context;
23
+ const token = await getToken();
24
+ if (token) context.headers.set(headerName, token);
25
+ return context;
26
+ } }
27
+ }] : []
28
+ };
29
+ };
30
+ //#endregion
31
+ exports.procaptchaClient = procaptchaClient;
32
+ exports.procaptchaHeaders = procaptchaHeaders;
@@ -0,0 +1,22 @@
1
+ let better_auth = require("better-auth");
2
+ //#region src/constants.ts
3
+ var PROCAPTCHA_SITEVERIFY_URL = "https://api.prosopo.io/siteverify";
4
+ var PROCAPTCHA_HEADER = "x-captcha-response";
5
+ var DEFAULT_ENDPOINTS = [
6
+ "/sign-up/email",
7
+ "/sign-in/email",
8
+ "/request-password-reset"
9
+ ];
10
+ var DEFAULT_TIMEOUT_MS = 1e4;
11
+ var PROCAPTCHA_ERROR_CODES = (0, better_auth.defineErrorCodes)({
12
+ PROCAPTCHA_MISSING_RESPONSE: "Missing Procaptcha response",
13
+ PROCAPTCHA_VERIFICATION_FAILED: "Procaptcha verification failed",
14
+ PROCAPTCHA_SERVICE_UNAVAILABLE: "Procaptcha service unavailable",
15
+ PROCAPTCHA_UNKNOWN_ERROR: "Something went wrong"
16
+ });
17
+ //#endregion
18
+ exports.DEFAULT_ENDPOINTS = DEFAULT_ENDPOINTS;
19
+ exports.DEFAULT_TIMEOUT_MS = DEFAULT_TIMEOUT_MS;
20
+ exports.PROCAPTCHA_ERROR_CODES = PROCAPTCHA_ERROR_CODES;
21
+ exports.PROCAPTCHA_HEADER = PROCAPTCHA_HEADER;
22
+ exports.PROCAPTCHA_SITEVERIFY_URL = PROCAPTCHA_SITEVERIFY_URL;
@@ -0,0 +1,80 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_constants = require("./constants.cjs");
3
+ const require_path = require("./path.cjs");
4
+ const require_siteverify = require("./siteverify.cjs");
5
+ let better_auth_api = require("better-auth/api");
6
+ //#region src/index.ts
7
+ var errorResponse = (code, status) => ({ response: Response.json({
8
+ code,
9
+ message: require_constants.PROCAPTCHA_ERROR_CODES[code].message
10
+ }, { status }) });
11
+ var resolveClientIP = (request, options) => (0, better_auth_api.getIP)(request, {
12
+ ...options,
13
+ advanced: {
14
+ ...options.advanced,
15
+ ipAddress: {
16
+ ...options.advanced?.ipAddress,
17
+ ipv6Subnet: 128
18
+ }
19
+ }
20
+ }) ?? void 0;
21
+ var readEmailDomain = async (request) => {
22
+ if (!request.headers.get("content-type")?.includes("application/json")) return;
23
+ try {
24
+ const body = await request.clone().json();
25
+ if (typeof body !== "object" || body === null || !("email" in body)) return;
26
+ const { email } = body;
27
+ if (typeof email !== "string") return;
28
+ const domain = email.slice(email.lastIndexOf("@") + 1).trim();
29
+ return email.includes("@") && domain ? domain.toLowerCase() : void 0;
30
+ } catch {
31
+ return;
32
+ }
33
+ };
34
+ var procaptcha = (options) => {
35
+ const isProtected = require_path.createPathMatcher(options.endpoints?.length ? options.endpoints : require_constants.DEFAULT_ENDPOINTS);
36
+ const headerName = options.headerName ?? "x-captcha-response";
37
+ return {
38
+ id: "procaptcha",
39
+ $ERROR_CODES: require_constants.PROCAPTCHA_ERROR_CODES,
40
+ onRequest: async (request, ctx) => {
41
+ const path = require_path.normalizeAuthPath(new URL(request.url).pathname, ctx.options.basePath ?? "/api/auth");
42
+ if (!isProtected(path)) return;
43
+ if (!options.secretKey) {
44
+ ctx.logger.error("Procaptcha: secretKey is not configured");
45
+ return errorResponse("PROCAPTCHA_UNKNOWN_ERROR", 500);
46
+ }
47
+ const token = request.headers.get(headerName);
48
+ if (!token) return errorResponse("PROCAPTCHA_MISSING_RESPONSE", 400);
49
+ const ip = options.sendIP === false ? void 0 : resolveClientIP(request, ctx.options);
50
+ const email = options.sendEmailDomain ? await readEmailDomain(request) : void 0;
51
+ const result = await require_siteverify.verifyProcaptchaToken({
52
+ secretKey: options.secretKey,
53
+ token,
54
+ ...ip ? { ip } : {},
55
+ ...email ? { email } : {},
56
+ siteVerifyURL: options.siteVerifyURL ?? "https://api.prosopo.io/siteverify",
57
+ timeoutMs: options.timeoutMs ?? 1e4,
58
+ ...options.fetch ? { fetch: options.fetch } : {}
59
+ });
60
+ if (result.outcome === "error") {
61
+ ctx.logger.error("Procaptcha siteverify failed", {
62
+ status: result.status,
63
+ key: result.key,
64
+ message: result.message
65
+ });
66
+ return result.transient ? errorResponse("PROCAPTCHA_SERVICE_UNAVAILABLE", 503) : errorResponse("PROCAPTCHA_UNKNOWN_ERROR", 500);
67
+ }
68
+ if (result.outcome === "rejected") return errorResponse("PROCAPTCHA_VERIFICATION_FAILED", 403);
69
+ if (options.maxScore !== void 0 && result.score !== void 0 && result.score > options.maxScore) return errorResponse("PROCAPTCHA_VERIFICATION_FAILED", 403);
70
+ },
71
+ options
72
+ };
73
+ };
74
+ //#endregion
75
+ exports.DEFAULT_ENDPOINTS = require_constants.DEFAULT_ENDPOINTS;
76
+ exports.PROCAPTCHA_ERROR_CODES = require_constants.PROCAPTCHA_ERROR_CODES;
77
+ exports.PROCAPTCHA_HEADER = require_constants.PROCAPTCHA_HEADER;
78
+ exports.PROCAPTCHA_SITEVERIFY_URL = require_constants.PROCAPTCHA_SITEVERIFY_URL;
79
+ exports.procaptcha = procaptcha;
80
+ exports.verifyProcaptchaToken = require_siteverify.verifyProcaptchaToken;
@@ -0,0 +1,41 @@
1
+ //#region src/path.ts
2
+ var normalizeAuthPath = (pathname, basePath) => {
3
+ const collapsed = `/${basePath && pathname.startsWith(basePath) ? pathname.slice(basePath.length) : pathname}`.replace(/\/{2,}/g, "/");
4
+ return collapsed.length > 1 ? collapsed.replace(/\/$/, "") : collapsed;
5
+ };
6
+ var matchesSegment = (pattern, segment) => {
7
+ const parts = pattern.split("*");
8
+ if (parts.length === 1) return pattern === segment;
9
+ const first = parts[0] ?? "";
10
+ const last = parts[parts.length - 1] ?? "";
11
+ if (segment.length < first.length + last.length || !segment.startsWith(first) || !segment.endsWith(last)) return false;
12
+ let cursor = first.length;
13
+ const end = segment.length - last.length;
14
+ for (const part of parts.slice(1, -1)) {
15
+ const found = segment.indexOf(part, cursor);
16
+ if (found === -1 || found + part.length > end) return false;
17
+ cursor = found + part.length;
18
+ }
19
+ return true;
20
+ };
21
+ var matchesSegments = (patterns, segments) => {
22
+ const [pattern, ...restPatterns] = patterns;
23
+ if (pattern === void 0) return segments.length === 0;
24
+ if (pattern === "**") {
25
+ for (let skip = 0; skip <= segments.length; skip++) if (matchesSegments(restPatterns, segments.slice(skip))) return true;
26
+ return false;
27
+ }
28
+ const [segment, ...restSegments] = segments;
29
+ return segment !== void 0 && matchesSegment(pattern, segment) && matchesSegments(restPatterns, restSegments);
30
+ };
31
+ var createPathMatcher = (endpoints) => {
32
+ const matchers = endpoints.map((endpoint) => {
33
+ if (!endpoint.includes("*")) return (path) => path === endpoint;
34
+ const patterns = endpoint.split("/");
35
+ return (path) => matchesSegments(patterns, path.split("/"));
36
+ });
37
+ return (path) => matchers.some((matches) => matches(path));
38
+ };
39
+ //#endregion
40
+ exports.createPathMatcher = createPathMatcher;
41
+ exports.normalizeAuthPath = normalizeAuthPath;
@@ -0,0 +1,68 @@
1
+ const require_constants = require("./constants.cjs");
2
+ //#region src/siteverify.ts
3
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
4
+ var isSiteVerifyResponse = (value) => isRecord(value) && typeof value.status === "string" && typeof value.verified === "boolean" && (value.score === void 0 || typeof value.score === "number") && (value.reason === void 0 || typeof value.reason === "string");
5
+ var isSiteVerifyErrorResponse = (value) => isRecord(value) && isRecord(value.error) && typeof value.error.key === "string";
6
+ var readJson = async (response) => {
7
+ try {
8
+ return await response.json();
9
+ } catch {
10
+ return;
11
+ }
12
+ };
13
+ var isTransientStatus = (status) => status === 429 || status >= 500;
14
+ var verifyProcaptchaToken = async ({ secretKey, token, ip, email, siteVerifyURL = require_constants.PROCAPTCHA_SITEVERIFY_URL, timeoutMs = require_constants.DEFAULT_TIMEOUT_MS, fetch: fetchImpl = fetch }) => {
15
+ const body = {
16
+ secret: secretKey,
17
+ token,
18
+ ...ip ? { ip } : {},
19
+ ...email ? { email } : {}
20
+ };
21
+ let response;
22
+ try {
23
+ response = await fetchImpl(siteVerifyURL, {
24
+ method: "POST",
25
+ headers: {
26
+ "Content-Type": "application/json",
27
+ Accept: "application/json"
28
+ },
29
+ body: JSON.stringify(body),
30
+ signal: AbortSignal.timeout(timeoutMs)
31
+ });
32
+ } catch (error) {
33
+ return {
34
+ outcome: "error",
35
+ transient: true,
36
+ message: error instanceof Error ? error.message : String(error)
37
+ };
38
+ }
39
+ const payload = await readJson(response);
40
+ if (!response.ok) {
41
+ const errorBody = isSiteVerifyErrorResponse(payload) ? payload.error : void 0;
42
+ return {
43
+ outcome: "error",
44
+ transient: isTransientStatus(response.status),
45
+ status: response.status,
46
+ ...errorBody ? { key: errorBody.key } : {},
47
+ message: typeof errorBody?.message === "string" ? errorBody.message : `siteverify responded with HTTP ${response.status}`
48
+ };
49
+ }
50
+ if (!isSiteVerifyResponse(payload)) return {
51
+ outcome: "error",
52
+ transient: true,
53
+ status: response.status,
54
+ message: "siteverify returned an unexpected response body"
55
+ };
56
+ const score = payload.score === void 0 ? {} : { score: payload.score };
57
+ if (!payload.verified) return {
58
+ outcome: "rejected",
59
+ ...payload.reason ? { reason: payload.reason } : {},
60
+ ...score
61
+ };
62
+ return {
63
+ outcome: "verified",
64
+ ...score
65
+ };
66
+ };
67
+ //#endregion
68
+ exports.verifyProcaptchaToken = verifyProcaptchaToken;
@@ -0,0 +1,3 @@
1
+ import "node:module";
2
+ //#endregion
3
+ export {};
@@ -0,0 +1,31 @@
1
+ import "./_virtual/_rolldown/runtime.js";
2
+ import { DEFAULT_ENDPOINTS, PROCAPTCHA_HEADER } from "./constants.js";
3
+ import { createPathMatcher, normalizeAuthPath } from "./path.js";
4
+ //#region src/client.ts
5
+ var procaptchaHeaders = (token, headerName = PROCAPTCHA_HEADER) => ({ [headerName]: token });
6
+ var authPathOf = (url, baseURL) => {
7
+ const requestURL = new URL(url, "http://localhost");
8
+ const basePath = baseURL ? new URL(baseURL, requestURL).pathname : "";
9
+ return normalizeAuthPath(requestURL.pathname, basePath);
10
+ };
11
+ var procaptchaClient = (options = {}) => {
12
+ const { getToken } = options;
13
+ const headerName = options.headerName ?? "x-captcha-response";
14
+ const isProtected = createPathMatcher(options.endpoints?.length ? options.endpoints : DEFAULT_ENDPOINTS);
15
+ return {
16
+ id: "procaptcha",
17
+ $InferServerPlugin: {},
18
+ fetchPlugins: getToken ? [{
19
+ id: "procaptcha",
20
+ name: "procaptcha",
21
+ hooks: { onRequest: async (context) => {
22
+ if (context.headers.has(headerName) || !isProtected(authPathOf(context.url, context.baseURL))) return context;
23
+ const token = await getToken();
24
+ if (token) context.headers.set(headerName, token);
25
+ return context;
26
+ } }
27
+ }] : []
28
+ };
29
+ };
30
+ //#endregion
31
+ export { procaptchaClient, procaptchaHeaders };
@@ -0,0 +1,18 @@
1
+ import { defineErrorCodes } from "better-auth";
2
+ //#region src/constants.ts
3
+ var PROCAPTCHA_SITEVERIFY_URL = "https://api.prosopo.io/siteverify";
4
+ var PROCAPTCHA_HEADER = "x-captcha-response";
5
+ var DEFAULT_ENDPOINTS = [
6
+ "/sign-up/email",
7
+ "/sign-in/email",
8
+ "/request-password-reset"
9
+ ];
10
+ var DEFAULT_TIMEOUT_MS = 1e4;
11
+ var PROCAPTCHA_ERROR_CODES = defineErrorCodes({
12
+ PROCAPTCHA_MISSING_RESPONSE: "Missing Procaptcha response",
13
+ PROCAPTCHA_VERIFICATION_FAILED: "Procaptcha verification failed",
14
+ PROCAPTCHA_SERVICE_UNAVAILABLE: "Procaptcha service unavailable",
15
+ PROCAPTCHA_UNKNOWN_ERROR: "Something went wrong"
16
+ });
17
+ //#endregion
18
+ export { DEFAULT_ENDPOINTS, DEFAULT_TIMEOUT_MS, PROCAPTCHA_ERROR_CODES, PROCAPTCHA_HEADER, PROCAPTCHA_SITEVERIFY_URL };
@@ -0,0 +1,75 @@
1
+ import "./_virtual/_rolldown/runtime.js";
2
+ import { DEFAULT_ENDPOINTS, PROCAPTCHA_ERROR_CODES, PROCAPTCHA_HEADER, PROCAPTCHA_SITEVERIFY_URL } from "./constants.js";
3
+ import { createPathMatcher, normalizeAuthPath } from "./path.js";
4
+ import { verifyProcaptchaToken } from "./siteverify.js";
5
+ import { getIP } from "better-auth/api";
6
+ //#region src/index.ts
7
+ var errorResponse = (code, status) => ({ response: Response.json({
8
+ code,
9
+ message: PROCAPTCHA_ERROR_CODES[code].message
10
+ }, { status }) });
11
+ var resolveClientIP = (request, options) => getIP(request, {
12
+ ...options,
13
+ advanced: {
14
+ ...options.advanced,
15
+ ipAddress: {
16
+ ...options.advanced?.ipAddress,
17
+ ipv6Subnet: 128
18
+ }
19
+ }
20
+ }) ?? void 0;
21
+ var readEmailDomain = async (request) => {
22
+ if (!request.headers.get("content-type")?.includes("application/json")) return;
23
+ try {
24
+ const body = await request.clone().json();
25
+ if (typeof body !== "object" || body === null || !("email" in body)) return;
26
+ const { email } = body;
27
+ if (typeof email !== "string") return;
28
+ const domain = email.slice(email.lastIndexOf("@") + 1).trim();
29
+ return email.includes("@") && domain ? domain.toLowerCase() : void 0;
30
+ } catch {
31
+ return;
32
+ }
33
+ };
34
+ var procaptcha = (options) => {
35
+ const isProtected = createPathMatcher(options.endpoints?.length ? options.endpoints : DEFAULT_ENDPOINTS);
36
+ const headerName = options.headerName ?? "x-captcha-response";
37
+ return {
38
+ id: "procaptcha",
39
+ $ERROR_CODES: PROCAPTCHA_ERROR_CODES,
40
+ onRequest: async (request, ctx) => {
41
+ const path = normalizeAuthPath(new URL(request.url).pathname, ctx.options.basePath ?? "/api/auth");
42
+ if (!isProtected(path)) return;
43
+ if (!options.secretKey) {
44
+ ctx.logger.error("Procaptcha: secretKey is not configured");
45
+ return errorResponse("PROCAPTCHA_UNKNOWN_ERROR", 500);
46
+ }
47
+ const token = request.headers.get(headerName);
48
+ if (!token) return errorResponse("PROCAPTCHA_MISSING_RESPONSE", 400);
49
+ const ip = options.sendIP === false ? void 0 : resolveClientIP(request, ctx.options);
50
+ const email = options.sendEmailDomain ? await readEmailDomain(request) : void 0;
51
+ const result = await verifyProcaptchaToken({
52
+ secretKey: options.secretKey,
53
+ token,
54
+ ...ip ? { ip } : {},
55
+ ...email ? { email } : {},
56
+ siteVerifyURL: options.siteVerifyURL ?? "https://api.prosopo.io/siteverify",
57
+ timeoutMs: options.timeoutMs ?? 1e4,
58
+ ...options.fetch ? { fetch: options.fetch } : {}
59
+ });
60
+ if (result.outcome === "error") {
61
+ ctx.logger.error("Procaptcha siteverify failed", {
62
+ status: result.status,
63
+ key: result.key,
64
+ message: result.message
65
+ });
66
+ return result.transient ? errorResponse("PROCAPTCHA_SERVICE_UNAVAILABLE", 503) : errorResponse("PROCAPTCHA_UNKNOWN_ERROR", 500);
67
+ }
68
+ if (result.outcome === "rejected") return errorResponse("PROCAPTCHA_VERIFICATION_FAILED", 403);
69
+ if (options.maxScore !== void 0 && result.score !== void 0 && result.score > options.maxScore) return errorResponse("PROCAPTCHA_VERIFICATION_FAILED", 403);
70
+ },
71
+ options
72
+ };
73
+ };
74
+ //#endregion
75
+ export { DEFAULT_ENDPOINTS, PROCAPTCHA_ERROR_CODES, PROCAPTCHA_HEADER, PROCAPTCHA_SITEVERIFY_URL, procaptcha, verifyProcaptchaToken };
@@ -0,0 +1,40 @@
1
+ //#region src/path.ts
2
+ var normalizeAuthPath = (pathname, basePath) => {
3
+ const collapsed = `/${basePath && pathname.startsWith(basePath) ? pathname.slice(basePath.length) : pathname}`.replace(/\/{2,}/g, "/");
4
+ return collapsed.length > 1 ? collapsed.replace(/\/$/, "") : collapsed;
5
+ };
6
+ var matchesSegment = (pattern, segment) => {
7
+ const parts = pattern.split("*");
8
+ if (parts.length === 1) return pattern === segment;
9
+ const first = parts[0] ?? "";
10
+ const last = parts[parts.length - 1] ?? "";
11
+ if (segment.length < first.length + last.length || !segment.startsWith(first) || !segment.endsWith(last)) return false;
12
+ let cursor = first.length;
13
+ const end = segment.length - last.length;
14
+ for (const part of parts.slice(1, -1)) {
15
+ const found = segment.indexOf(part, cursor);
16
+ if (found === -1 || found + part.length > end) return false;
17
+ cursor = found + part.length;
18
+ }
19
+ return true;
20
+ };
21
+ var matchesSegments = (patterns, segments) => {
22
+ const [pattern, ...restPatterns] = patterns;
23
+ if (pattern === void 0) return segments.length === 0;
24
+ if (pattern === "**") {
25
+ for (let skip = 0; skip <= segments.length; skip++) if (matchesSegments(restPatterns, segments.slice(skip))) return true;
26
+ return false;
27
+ }
28
+ const [segment, ...restSegments] = segments;
29
+ return segment !== void 0 && matchesSegment(pattern, segment) && matchesSegments(restPatterns, restSegments);
30
+ };
31
+ var createPathMatcher = (endpoints) => {
32
+ const matchers = endpoints.map((endpoint) => {
33
+ if (!endpoint.includes("*")) return (path) => path === endpoint;
34
+ const patterns = endpoint.split("/");
35
+ return (path) => matchesSegments(patterns, path.split("/"));
36
+ });
37
+ return (path) => matchers.some((matches) => matches(path));
38
+ };
39
+ //#endregion
40
+ export { createPathMatcher, normalizeAuthPath };