@tansy/captcha 0.0.0-stage → 0.1.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.
- package/LICENSE +21 -0
- package/README.md +12 -2
- package/index.d.ts +20 -0
- package/index.js +82 -0
- package/messages.d.ts +43 -0
- package/messages.js +19 -0
- package/package.json +34 -4
- package/provider.d.ts +48 -0
- package/provider.js +32 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Mohamed Salah
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,13 @@
|
|
|
1
|
-
|
|
1
|
+
<!-- Generated by scripts/package-metadata.mjs. Change that script, not this file. -->
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
# @tansy/captcha
|
|
4
|
+
|
|
5
|
+
A CAPTCHA for Tansy's sign-in forms and any plugin's own forms. Add a provider package, such as @tansy/captcha-turnstile.
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install @tansy/captcha
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
Add it to `tansy.config.ts`. See [the captcha plugin documentation](https://github.com/mhmdsalahsebai/tansy/blob/main/docs/plugins/captcha.md) for what it adds and the options it takes.
|
|
12
|
+
|
|
13
|
+
A first-party plugin for [tansy](https://github.com/mhmdsalahsebai/tansy), a self-hosted, runtime-schema CMS for Next.js. MIT licensed.
|
package/index.d.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { type CaptchaAuthForm } from "tansy/plugin";
|
|
2
|
+
import type { CaptchaProvider } from "./provider";
|
|
3
|
+
export type { CaptchaProvider } from "./provider";
|
|
4
|
+
export interface CaptchaOptions {
|
|
5
|
+
/**
|
|
6
|
+
* The providers the site can use, each from its own package, such as `turnstile()`
|
|
7
|
+
* from @tansy/captcha-turnstile. Owners choose one under Extensions → CAPTCHA.
|
|
8
|
+
*/
|
|
9
|
+
providers: CaptchaProvider[];
|
|
10
|
+
/** Which of them is used until changed in the settings. The first when left out. */
|
|
11
|
+
provider?: string;
|
|
12
|
+
/** The sign-in forms that ask for it until changed in the settings. All three when left out. */
|
|
13
|
+
authForms?: CaptchaAuthForm[];
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Checks that a person, not a script, is filling in a form: the sign-in forms chosen in
|
|
17
|
+
* the settings, and any plugin's own forms through `context.captcha`, such as Forms. One
|
|
18
|
+
* adapter package per provider. See docs/plugins/captcha.md.
|
|
19
|
+
*/
|
|
20
|
+
export declare function captcha(options: CaptchaOptions): import("tansy/plugin").CmsPlugin;
|
package/index.js
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { definePlugin, mergeMessagesByLanguage } from "tansy/plugin";
|
|
3
|
+
import { messages } from "./messages";
|
|
4
|
+
const PROVIDER_ID = /^[a-z][a-z0-9]{0,19}$/;
|
|
5
|
+
const FORMS = ["signin", "signup", "forgot-password"];
|
|
6
|
+
const optionsSchema = z.strictObject({
|
|
7
|
+
providers: z.array(z.object({ id: z.string().regex(PROVIDER_ID, "A provider's id is lowercase letters and digits."), label: z.string().min(1) }).loose()).min(1, "Add at least one provider, such as turnstile() from @tansy/captcha-turnstile."),
|
|
8
|
+
provider: z.string(),
|
|
9
|
+
authForms: z.array(z.enum(FORMS)),
|
|
10
|
+
}).superRefine((value, issues) => {
|
|
11
|
+
const ids = value.providers.map((provider) => provider.id);
|
|
12
|
+
const twice = ids.find((id, index) => ids.indexOf(id) !== index);
|
|
13
|
+
if (twice)
|
|
14
|
+
issues.addIssue({ code: "custom", path: ["providers"], message: `The provider "${twice}" is listed twice.` });
|
|
15
|
+
if (!ids.includes(value.provider))
|
|
16
|
+
issues.addIssue({ code: "custom", path: ["provider"], message: `"${value.provider}" isn't one of the providers listed.` });
|
|
17
|
+
});
|
|
18
|
+
const settingsOf = async (context) => (await context.settings.get());
|
|
19
|
+
const sharedSettings = (value, providers) => [
|
|
20
|
+
{ name: "provider", type: "select", default: value.provider, label: "Provider", description: "Who checks that a person is filling in the form. Fill in that provider's keys below. Until they're set, forms go without a CAPTCHA.", options: providers.map((provider) => ({ value: provider.id, label: provider.label })) },
|
|
21
|
+
{ name: "signIn", type: "boolean", default: value.authForms.includes("signin"), label: "Ask on sign-in", description: "Slows down password guessing. Lockout after failed attempts applies either way." },
|
|
22
|
+
{ name: "signUp", type: "boolean", default: value.authForms.includes("signup"), label: "Ask on sign-up", description: "Keeps scripts from creating accounts." },
|
|
23
|
+
{ name: "passwordReset", type: "boolean", default: value.authForms.includes("forgot-password"), label: "Ask on password reset", description: "Keeps scripts from sending reset emails to people who didn't ask." },
|
|
24
|
+
];
|
|
25
|
+
/** Every setting's name starts with its provider's id, so two providers can't claim one. */
|
|
26
|
+
function providerSettings(providers) {
|
|
27
|
+
return providers.flatMap((provider) => provider.settings().map((field) => {
|
|
28
|
+
if (!field.name.startsWith(provider.id))
|
|
29
|
+
throw new Error(`CAPTCHA provider "${provider.id}": the setting "${field.name}" must start with "${provider.id}".`);
|
|
30
|
+
return field;
|
|
31
|
+
}));
|
|
32
|
+
}
|
|
33
|
+
/** Every installed provider's origins, as the provider can change without a rebuild. */
|
|
34
|
+
function cspOf(providers) {
|
|
35
|
+
const all = (key) => [...new Set(providers.flatMap((provider) => provider.csp[key] ?? []))];
|
|
36
|
+
return { frame: all("frame"), connect: all("connect"), img: all("img") };
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Checks that a person, not a script, is filling in a form: the sign-in forms chosen in
|
|
40
|
+
* the settings, and any plugin's own forms through `context.captcha`, such as Forms. One
|
|
41
|
+
* adapter package per provider. See docs/plugins/captcha.md.
|
|
42
|
+
*/
|
|
43
|
+
export function captcha(options) {
|
|
44
|
+
const value = optionsSchema.parse({ provider: options.providers?.[0]?.id, authForms: [...FORMS], ...Object.fromEntries(Object.entries(options).filter(([, option]) => option !== undefined)) });
|
|
45
|
+
const providers = options.providers;
|
|
46
|
+
const byId = new Map(providers.map((provider) => [provider.id, provider]));
|
|
47
|
+
/** The provider in use, once its keys are set. */
|
|
48
|
+
const current = async (context) => {
|
|
49
|
+
const settings = await settingsOf(context);
|
|
50
|
+
const provider = byId.get(settings.provider);
|
|
51
|
+
return provider?.ready(settings) ? { provider, settings } : null;
|
|
52
|
+
};
|
|
53
|
+
return definePlugin({
|
|
54
|
+
name: "captcha",
|
|
55
|
+
version: "0.1.0",
|
|
56
|
+
apiVersion: 1,
|
|
57
|
+
requires: { cms: "^0.1.0" },
|
|
58
|
+
options: { schema: optionsSchema, value },
|
|
59
|
+
messages: mergeMessagesByLanguage(messages, ...providers.map((provider) => provider.messages)),
|
|
60
|
+
settings: { fields: [...sharedSettings(value, providers), ...providerSettings(providers)] },
|
|
61
|
+
csp: cspOf(providers),
|
|
62
|
+
auth: {
|
|
63
|
+
captcha: {
|
|
64
|
+
ready: async (context) => (await current(context)) !== null,
|
|
65
|
+
async widget(context) {
|
|
66
|
+
const active = await current(context);
|
|
67
|
+
if (!active)
|
|
68
|
+
throw new Error("[captcha] The provider isn't set up.");
|
|
69
|
+
return { provider: active.provider.id, ...active.provider.widget(active.settings) };
|
|
70
|
+
},
|
|
71
|
+
async verify(answer, request, context) {
|
|
72
|
+
const active = await current(context);
|
|
73
|
+
return active ? active.provider.verify(answer, request, active.settings) : false;
|
|
74
|
+
},
|
|
75
|
+
async authForms(context) {
|
|
76
|
+
const settings = await settingsOf(context);
|
|
77
|
+
return FORMS.filter((form) => ({ signin: settings.signIn, signup: settings.signUp, "forgot-password": settings.passwordReset })[form] === true);
|
|
78
|
+
},
|
|
79
|
+
},
|
|
80
|
+
},
|
|
81
|
+
});
|
|
82
|
+
}
|
package/messages.d.ts
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/** The CAPTCHA plugin's dashboard words, read as `t("ext.captcha.<key>")`. Each provider package adds its own settings' words. */
|
|
2
|
+
export declare const messages: {
|
|
3
|
+
en: {
|
|
4
|
+
settings: {
|
|
5
|
+
provider: {
|
|
6
|
+
label: string;
|
|
7
|
+
description: string;
|
|
8
|
+
};
|
|
9
|
+
signIn: {
|
|
10
|
+
label: string;
|
|
11
|
+
description: string;
|
|
12
|
+
};
|
|
13
|
+
signUp: {
|
|
14
|
+
label: string;
|
|
15
|
+
description: string;
|
|
16
|
+
};
|
|
17
|
+
passwordReset: {
|
|
18
|
+
label: string;
|
|
19
|
+
description: string;
|
|
20
|
+
};
|
|
21
|
+
};
|
|
22
|
+
};
|
|
23
|
+
ar: {
|
|
24
|
+
settings: {
|
|
25
|
+
provider: {
|
|
26
|
+
label: string;
|
|
27
|
+
description: string;
|
|
28
|
+
};
|
|
29
|
+
signIn: {
|
|
30
|
+
label: string;
|
|
31
|
+
description: string;
|
|
32
|
+
};
|
|
33
|
+
signUp: {
|
|
34
|
+
label: string;
|
|
35
|
+
description: string;
|
|
36
|
+
};
|
|
37
|
+
passwordReset: {
|
|
38
|
+
label: string;
|
|
39
|
+
description: string;
|
|
40
|
+
};
|
|
41
|
+
};
|
|
42
|
+
};
|
|
43
|
+
};
|
package/messages.js
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/** The CAPTCHA plugin's dashboard words, read as `t("ext.captcha.<key>")`. Each provider package adds its own settings' words. */
|
|
2
|
+
export const messages = {
|
|
3
|
+
en: {
|
|
4
|
+
settings: {
|
|
5
|
+
provider: { label: "Provider", description: "Who checks that a person is filling in the form. Fill in that provider's keys below. Until they're set, forms go without a CAPTCHA." },
|
|
6
|
+
signIn: { label: "Ask on sign-in", description: "Slows down password guessing. Lockout after failed attempts applies either way." },
|
|
7
|
+
signUp: { label: "Ask on sign-up", description: "Keeps scripts from creating accounts." },
|
|
8
|
+
passwordReset: { label: "Ask on password reset", description: "Keeps scripts from sending reset emails to people who didn't ask." },
|
|
9
|
+
},
|
|
10
|
+
},
|
|
11
|
+
ar: {
|
|
12
|
+
settings: {
|
|
13
|
+
provider: { label: "المزوّد", description: "الجهة التي تتحقق من أن من يملأ النموذج إنسان. املأ مفاتيح ذلك المزوّد أدناه. حتى تُضبط، تعمل النماذج دون CAPTCHA." },
|
|
14
|
+
signIn: { label: "اطلبه عند تسجيل الدخول", description: "يبطئ تخمين كلمات المرور. القفل بعد المحاولات الفاشلة يعمل في الحالتين." },
|
|
15
|
+
signUp: { label: "اطلبه عند إنشاء حساب", description: "يمنع البرامج الآلية من إنشاء الحسابات." },
|
|
16
|
+
passwordReset: { label: "اطلبه عند إعادة تعيين كلمة المرور", description: "يمنع البرامج الآلية من إرسال رسائل إعادة التعيين لمن لم يطلبها." },
|
|
17
|
+
},
|
|
18
|
+
},
|
|
19
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,36 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tansy/captcha",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "A CAPTCHA for Tansy's sign-in forms and any plugin's own forms. Add a provider package, such as @tansy/captcha-turnstile.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"tansy",
|
|
7
|
+
"tansy-plugin",
|
|
8
|
+
"cms",
|
|
9
|
+
"nextjs"
|
|
10
|
+
],
|
|
11
|
+
"license": "MIT",
|
|
12
|
+
"author": "Mohamed Salah <mohamedsalahsebai@gmail.com>",
|
|
13
|
+
"homepage": "https://github.com/mhmdsalahsebai/tansy",
|
|
14
|
+
"repository": {
|
|
15
|
+
"type": "git",
|
|
16
|
+
"url": "git+https://github.com/mhmdsalahsebai/tansy.git",
|
|
17
|
+
"directory": "plugins/captcha"
|
|
18
|
+
},
|
|
19
|
+
"bugs": "https://github.com/mhmdsalahsebai/tansy/issues",
|
|
20
|
+
"exports": {
|
|
21
|
+
".": {
|
|
22
|
+
"types": "./index.d.ts",
|
|
23
|
+
"default": "./index.js"
|
|
24
|
+
},
|
|
25
|
+
"./provider": {
|
|
26
|
+
"types": "./provider.d.ts",
|
|
27
|
+
"default": "./provider.js"
|
|
28
|
+
}
|
|
29
|
+
},
|
|
30
|
+
"peerDependencies": {
|
|
31
|
+
"tansy": "^0.1.0"
|
|
32
|
+
},
|
|
33
|
+
"dependencies": {
|
|
34
|
+
"zod": "^4.6.7"
|
|
35
|
+
}
|
|
36
|
+
}
|
package/provider.d.ts
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import type { CaptchaWidgetConfig, CspAdditions, Messages, PluginSettingField } from "tansy/plugin";
|
|
2
|
+
/**
|
|
3
|
+
* What a CAPTCHA provider adapter implements, such as @tansy/captcha-turnstile. The
|
|
4
|
+
* CAPTCHA plugin keeps what providers share: choosing one, which forms ask for it, and
|
|
5
|
+
* handing it to core. An adapter only describes its widget and checks one answer. See
|
|
6
|
+
* docs/plugins/captcha.md.
|
|
7
|
+
*/
|
|
8
|
+
/** The CAPTCHA plugin's own settings, and each installed provider's, by name. */
|
|
9
|
+
export interface CaptchaSettings {
|
|
10
|
+
/** The id of the provider in use. */
|
|
11
|
+
provider: string;
|
|
12
|
+
signIn: boolean;
|
|
13
|
+
signUp: boolean;
|
|
14
|
+
passwordReset: boolean;
|
|
15
|
+
[name: string]: unknown;
|
|
16
|
+
}
|
|
17
|
+
export interface CaptchaProvider {
|
|
18
|
+
/** Lowercase letters and digits, such as "turnstile". Every setting's name starts with it. */
|
|
19
|
+
id: string;
|
|
20
|
+
label: string;
|
|
21
|
+
/** Its keys on the CAPTCHA plugin's settings. */
|
|
22
|
+
settings(): PluginSettingField[];
|
|
23
|
+
/**
|
|
24
|
+
* Its settings' words in other interface languages, by language code, as
|
|
25
|
+
* `{ ar: { settings: { <name>: { label, description } } } }`. CAPTCHA adds them to its own
|
|
26
|
+
* `messages`, and the setting's `label` and `description` cover any language missing.
|
|
27
|
+
*/
|
|
28
|
+
messages?: Record<string, Messages>;
|
|
29
|
+
/** Whether the keys it needs are set. */
|
|
30
|
+
ready(settings: CaptchaSettings): boolean;
|
|
31
|
+
/** What the browser shows. Public: never a secret. */
|
|
32
|
+
widget(settings: CaptchaSettings): Omit<CaptchaWidgetConfig, "provider">;
|
|
33
|
+
/** Asks the provider whether the answer is good. */
|
|
34
|
+
verify(answer: string, request: {
|
|
35
|
+
ip: string | null;
|
|
36
|
+
}, settings: CaptchaSettings): Promise<boolean>;
|
|
37
|
+
/** The origins its widget frames and calls, added to the Content Security Policy. */
|
|
38
|
+
csp: CspAdditions;
|
|
39
|
+
}
|
|
40
|
+
/** Types an adapter. */
|
|
41
|
+
export declare const defineCaptchaProvider: (provider: CaptchaProvider) => CaptchaProvider;
|
|
42
|
+
/**
|
|
43
|
+
* The siteverify call Turnstile, hCaptcha and reCAPTCHA share: a form post of the secret
|
|
44
|
+
* and the answer, answered with `{ success }`. Anything else, a redirect, a timeout or
|
|
45
|
+
* an error status, refuses. What the provider says beyond `success` is never logged.
|
|
46
|
+
*/
|
|
47
|
+
export declare function siteVerify(url: string, fields: Record<string, string | null | undefined>, fetcher?: typeof fetch): Promise<boolean>;
|
|
48
|
+
export declare const str: (value: unknown) => string;
|
package/provider.js
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/** Types an adapter. */
|
|
2
|
+
export const defineCaptchaProvider = (provider) => provider;
|
|
3
|
+
const TIMEOUT_MS = 10_000;
|
|
4
|
+
/**
|
|
5
|
+
* The siteverify call Turnstile, hCaptcha and reCAPTCHA share: a form post of the secret
|
|
6
|
+
* and the answer, answered with `{ success }`. Anything else, a redirect, a timeout or
|
|
7
|
+
* an error status, refuses. What the provider says beyond `success` is never logged.
|
|
8
|
+
*/
|
|
9
|
+
export async function siteVerify(url, fields, fetcher = fetch) {
|
|
10
|
+
const body = new URLSearchParams(Object.entries(fields).flatMap(([name, value]) => (value ? [[name, value]] : [])));
|
|
11
|
+
let response;
|
|
12
|
+
try {
|
|
13
|
+
response = await fetcher(url, { method: "POST", body, headers: { "content-type": "application/x-www-form-urlencoded" }, redirect: "error", signal: AbortSignal.timeout(TIMEOUT_MS) });
|
|
14
|
+
}
|
|
15
|
+
catch {
|
|
16
|
+
console.error(`[captcha] ${new URL(url).host} couldn't be reached`);
|
|
17
|
+
return false;
|
|
18
|
+
}
|
|
19
|
+
if (!response.ok) {
|
|
20
|
+
await response.body?.cancel().catch(() => { });
|
|
21
|
+
console.error(`[captcha] ${new URL(url).host} answered ${response.status}`);
|
|
22
|
+
return false;
|
|
23
|
+
}
|
|
24
|
+
try {
|
|
25
|
+
const answer = (await response.json());
|
|
26
|
+
return answer?.success === true;
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
return false;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
export const str = (value) => (typeof value === "string" ? value.trim() : "");
|