@xlock/node 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 +112 -0
- package/dist/core-D4eszYbi.d.mts +23 -0
- package/dist/core-D4eszYbi.d.ts +23 -0
- package/dist/express.d.mts +15 -0
- package/dist/express.d.ts +15 -0
- package/dist/express.js +95 -0
- package/dist/express.js.map +1 -0
- package/dist/express.mjs +68 -0
- package/dist/express.mjs.map +1 -0
- package/dist/fastify.d.mts +19 -0
- package/dist/fastify.d.ts +19 -0
- package/dist/fastify.js +106 -0
- package/dist/fastify.js.map +1 -0
- package/dist/fastify.mjs +79 -0
- package/dist/fastify.mjs.map +1 -0
- package/dist/hono.d.mts +15 -0
- package/dist/hono.d.ts +15 -0
- package/dist/hono.js +91 -0
- package/dist/hono.js.map +1 -0
- package/dist/hono.mjs +64 -0
- package/dist/hono.mjs.map +1 -0
- package/dist/index.d.mts +4 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +179 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +148 -0
- package/dist/index.mjs.map +1 -0
- package/dist/koa.d.mts +19 -0
- package/dist/koa.d.ts +19 -0
- package/dist/koa.js +108 -0
- package/dist/koa.js.map +1 -0
- package/dist/koa.mjs +81 -0
- package/dist/koa.mjs.map +1 -0
- package/dist/next.d.mts +24 -0
- package/dist/next.d.ts +24 -0
- package/dist/next.js +101 -0
- package/dist/next.js.map +1 -0
- package/dist/next.mjs +74 -0
- package/dist/next.mjs.map +1 -0
- package/package.json +94 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 x-lock
|
|
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
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
# @xlock/node
|
|
2
|
+
|
|
3
|
+
Invisible bot protection middleware for Node.js. Drop-in replacement for reCAPTCHA, Turnstile, and hCaptcha — no visual challenges, no user friction.
|
|
4
|
+
|
|
5
|
+
Supports **Express**, **Fastify**, **Koa**, **Next.js**, and **Hono**.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm install @xlock/node
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Quick Start
|
|
14
|
+
|
|
15
|
+
### Express
|
|
16
|
+
|
|
17
|
+
```js
|
|
18
|
+
import { xlockMiddleware } from "@xlock/node/express";
|
|
19
|
+
|
|
20
|
+
app.use("/api/auth", xlockMiddleware({ siteKey: "sk_..." }));
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
### Fastify
|
|
24
|
+
|
|
25
|
+
```js
|
|
26
|
+
import { xlockPlugin } from "@xlock/node/fastify";
|
|
27
|
+
|
|
28
|
+
fastify.register(xlockPlugin, {
|
|
29
|
+
siteKey: "sk_...",
|
|
30
|
+
routes: ["/api/auth/*"],
|
|
31
|
+
});
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
### Next.js
|
|
35
|
+
|
|
36
|
+
```ts
|
|
37
|
+
// middleware.ts
|
|
38
|
+
import { withXlock } from "@xlock/node/next";
|
|
39
|
+
|
|
40
|
+
export const middleware = withXlock({
|
|
41
|
+
siteKey: process.env.NEXT_PUBLIC_XLOCK_SITE_KEY!,
|
|
42
|
+
protectedPaths: ["/api/auth/callback"],
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
export const config = { matcher: ["/api/:path*"] };
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
### Hono
|
|
49
|
+
|
|
50
|
+
```ts
|
|
51
|
+
import { xlockMiddleware } from "@xlock/node/hono";
|
|
52
|
+
|
|
53
|
+
app.use("/api/auth/*", xlockMiddleware({ siteKey: "sk_..." }));
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
### Koa
|
|
57
|
+
|
|
58
|
+
```js
|
|
59
|
+
import { xlockMiddleware } from "@xlock/node/koa";
|
|
60
|
+
|
|
61
|
+
router.post("/api/auth/login", xlockMiddleware({ siteKey: "sk_..." }), loginHandler);
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
### Direct Verification
|
|
65
|
+
|
|
66
|
+
```js
|
|
67
|
+
import { verify } from "@xlock/node";
|
|
68
|
+
|
|
69
|
+
const result = await verify("https://api.x-lock.dev", "sk_...", token, "/api/login");
|
|
70
|
+
if (result.blocked) {
|
|
71
|
+
console.log("Blocked:", result.reason);
|
|
72
|
+
}
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
## Configuration
|
|
76
|
+
|
|
77
|
+
All middleware accepts these options:
|
|
78
|
+
|
|
79
|
+
| Option | Type | Default | Description |
|
|
80
|
+
|--------|------|---------|-------------|
|
|
81
|
+
| `siteKey` | `string` | `XLOCK_SITE_KEY` env | Your x-lock site key |
|
|
82
|
+
| `apiUrl` | `string` | `https://api.x-lock.dev` | x-lock API endpoint |
|
|
83
|
+
| `failOpen` | `boolean` | `true` | Allow requests through on API errors |
|
|
84
|
+
|
|
85
|
+
## How It Works
|
|
86
|
+
|
|
87
|
+
1. Your frontend loads the x-lock script (invisible to users)
|
|
88
|
+
2. x-lock runs proof-of-work + behavioral analysis in the background
|
|
89
|
+
3. The script attaches a token to requests via the `x-lock` header
|
|
90
|
+
4. This middleware verifies the token server-side before your route handler runs
|
|
91
|
+
|
|
92
|
+
No CAPTCHAs. No clicking fire hydrants. No Google tracking.
|
|
93
|
+
|
|
94
|
+
## Migrating from reCAPTCHA
|
|
95
|
+
|
|
96
|
+
```diff
|
|
97
|
+
- const { RecaptchaEnterpriseServiceClient } = require("@google-cloud/recaptcha-enterprise");
|
|
98
|
+
+ import { xlockMiddleware } from "@xlock/node/express";
|
|
99
|
+
|
|
100
|
+
- app.post("/login", async (req, res) => {
|
|
101
|
+
- const score = await recaptcha.assessToken(req.body.token);
|
|
102
|
+
- if (score < 0.5) return res.status(403).json({ error: "Bot detected" });
|
|
103
|
+
- // handle login
|
|
104
|
+
- });
|
|
105
|
+
+ app.post("/login", xlockMiddleware({ siteKey: "sk_..." }), (req, res) => {
|
|
106
|
+
+ // handle login — x-lock already verified the request
|
|
107
|
+
+ });
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
## License
|
|
111
|
+
|
|
112
|
+
MIT
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Core x-lock enforcement logic shared across all framework adapters.
|
|
3
|
+
*/
|
|
4
|
+
declare const DEFAULT_API_URL = "https://api.x-lock.dev";
|
|
5
|
+
interface XLockConfig {
|
|
6
|
+
/** Your x-lock site key (or set XLOCK_SITE_KEY env var) */
|
|
7
|
+
siteKey?: string;
|
|
8
|
+
/** x-lock API URL (default: https://api.x-lock.dev) */
|
|
9
|
+
apiUrl?: string;
|
|
10
|
+
/** Allow requests through on API errors (default: true) */
|
|
11
|
+
failOpen?: boolean;
|
|
12
|
+
}
|
|
13
|
+
interface EnforceResult {
|
|
14
|
+
blocked: boolean;
|
|
15
|
+
reason?: string;
|
|
16
|
+
error?: boolean;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Call the x-lock enforcement API to verify a token.
|
|
20
|
+
*/
|
|
21
|
+
declare function enforce(apiUrl: string, siteKey: string, token: string, path?: string): Promise<EnforceResult>;
|
|
22
|
+
|
|
23
|
+
export { DEFAULT_API_URL as D, type EnforceResult as E, type XLockConfig as X, enforce as e };
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Core x-lock enforcement logic shared across all framework adapters.
|
|
3
|
+
*/
|
|
4
|
+
declare const DEFAULT_API_URL = "https://api.x-lock.dev";
|
|
5
|
+
interface XLockConfig {
|
|
6
|
+
/** Your x-lock site key (or set XLOCK_SITE_KEY env var) */
|
|
7
|
+
siteKey?: string;
|
|
8
|
+
/** x-lock API URL (default: https://api.x-lock.dev) */
|
|
9
|
+
apiUrl?: string;
|
|
10
|
+
/** Allow requests through on API errors (default: true) */
|
|
11
|
+
failOpen?: boolean;
|
|
12
|
+
}
|
|
13
|
+
interface EnforceResult {
|
|
14
|
+
blocked: boolean;
|
|
15
|
+
reason?: string;
|
|
16
|
+
error?: boolean;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Call the x-lock enforcement API to verify a token.
|
|
20
|
+
*/
|
|
21
|
+
declare function enforce(apiUrl: string, siteKey: string, token: string, path?: string): Promise<EnforceResult>;
|
|
22
|
+
|
|
23
|
+
export { DEFAULT_API_URL as D, type EnforceResult as E, type XLockConfig as X, enforce as e };
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { X as XLockConfig } from './core-D4eszYbi.mjs';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* x-lock middleware for Express.js
|
|
5
|
+
*
|
|
6
|
+
* @example
|
|
7
|
+
* ```js
|
|
8
|
+
* import { xlockMiddleware } from "@xlock/node/express";
|
|
9
|
+
* app.use("/api/auth", xlockMiddleware({ siteKey: "sk_..." }));
|
|
10
|
+
* ```
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
declare function xlockMiddleware(options?: XLockConfig): (_req: any, _res: any, next: () => void) => void;
|
|
14
|
+
|
|
15
|
+
export { XLockConfig, xlockMiddleware };
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { X as XLockConfig } from './core-D4eszYbi.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* x-lock middleware for Express.js
|
|
5
|
+
*
|
|
6
|
+
* @example
|
|
7
|
+
* ```js
|
|
8
|
+
* import { xlockMiddleware } from "@xlock/node/express";
|
|
9
|
+
* app.use("/api/auth", xlockMiddleware({ siteKey: "sk_..." }));
|
|
10
|
+
* ```
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
declare function xlockMiddleware(options?: XLockConfig): (_req: any, _res: any, next: () => void) => void;
|
|
14
|
+
|
|
15
|
+
export { XLockConfig, xlockMiddleware };
|
package/dist/express.js
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/express.ts
|
|
21
|
+
var express_exports = {};
|
|
22
|
+
__export(express_exports, {
|
|
23
|
+
xlockMiddleware: () => xlockMiddleware
|
|
24
|
+
});
|
|
25
|
+
module.exports = __toCommonJS(express_exports);
|
|
26
|
+
|
|
27
|
+
// src/core.ts
|
|
28
|
+
var DEFAULT_API_URL = "https://api.x-lock.dev";
|
|
29
|
+
async function enforce(apiUrl, siteKey, token, path) {
|
|
30
|
+
let enforceUrl;
|
|
31
|
+
let body;
|
|
32
|
+
if (token.startsWith("v3.")) {
|
|
33
|
+
const sessionId = token.split(".")[1];
|
|
34
|
+
enforceUrl = `${apiUrl}/v3/session/enforce`;
|
|
35
|
+
body = { sessionId, siteKey };
|
|
36
|
+
if (path) body.path = path;
|
|
37
|
+
} else {
|
|
38
|
+
enforceUrl = `${apiUrl}/v1/enforce`;
|
|
39
|
+
body = { token, siteKey };
|
|
40
|
+
if (path) body.path = path;
|
|
41
|
+
}
|
|
42
|
+
const response = await fetch(enforceUrl, {
|
|
43
|
+
method: "POST",
|
|
44
|
+
headers: { "Content-Type": "application/json" },
|
|
45
|
+
body: JSON.stringify(body)
|
|
46
|
+
});
|
|
47
|
+
if (response.status === 403) {
|
|
48
|
+
const data = await response.json();
|
|
49
|
+
return { blocked: true, reason: data.reason };
|
|
50
|
+
}
|
|
51
|
+
if (!response.ok) {
|
|
52
|
+
return { blocked: false, error: true };
|
|
53
|
+
}
|
|
54
|
+
return { blocked: false };
|
|
55
|
+
}
|
|
56
|
+
function resolveSiteKey(siteKey) {
|
|
57
|
+
return siteKey || process.env.XLOCK_SITE_KEY;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// src/express.ts
|
|
61
|
+
function xlockMiddleware(options = {}) {
|
|
62
|
+
const apiUrl = options.apiUrl || DEFAULT_API_URL;
|
|
63
|
+
const siteKey = resolveSiteKey(options.siteKey);
|
|
64
|
+
const failOpen = options.failOpen !== false;
|
|
65
|
+
if (!siteKey) {
|
|
66
|
+
console.warn("[x-lock] No site key configured \u2014 skipping enforcement");
|
|
67
|
+
return (_req, _res, next) => next();
|
|
68
|
+
}
|
|
69
|
+
return async (req, res, next) => {
|
|
70
|
+
const token = req.headers["x-lock"];
|
|
71
|
+
if (!token) {
|
|
72
|
+
return res.status(403).json({ error: "Blocked by x-lock: missing token" });
|
|
73
|
+
}
|
|
74
|
+
try {
|
|
75
|
+
const result = await enforce(apiUrl, siteKey, token, req.originalUrl || req.url);
|
|
76
|
+
if (result.blocked) {
|
|
77
|
+
return res.status(403).json({ error: "Blocked by x-lock", reason: result.reason });
|
|
78
|
+
}
|
|
79
|
+
if (result.error && !failOpen) {
|
|
80
|
+
return res.status(403).json({ error: "x-lock verification failed" });
|
|
81
|
+
}
|
|
82
|
+
} catch (err) {
|
|
83
|
+
console.error("[x-lock] Enforcement error:", err.message);
|
|
84
|
+
if (!failOpen) {
|
|
85
|
+
return res.status(403).json({ error: "x-lock verification failed" });
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
next();
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
92
|
+
0 && (module.exports = {
|
|
93
|
+
xlockMiddleware
|
|
94
|
+
});
|
|
95
|
+
//# sourceMappingURL=express.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/express.ts","../src/core.ts"],"sourcesContent":["/**\n * x-lock middleware for Express.js\n *\n * @example\n * ```js\n * import { xlockMiddleware } from \"@xlock/node/express\";\n * app.use(\"/api/auth\", xlockMiddleware({ siteKey: \"sk_...\" }));\n * ```\n */\n\nimport { enforce, resolveSiteKey, DEFAULT_API_URL, type XLockConfig } from \"./core\";\n\nexport type { XLockConfig };\n\nexport function xlockMiddleware(options: XLockConfig = {}) {\n const apiUrl = options.apiUrl || DEFAULT_API_URL;\n const siteKey = resolveSiteKey(options.siteKey);\n const failOpen = options.failOpen !== false;\n\n if (!siteKey) {\n console.warn(\"[x-lock] No site key configured — skipping enforcement\");\n return (_req: any, _res: any, next: () => void) => next();\n }\n\n return async (req: any, res: any, next: () => void) => {\n const token = req.headers[\"x-lock\"];\n\n if (!token) {\n return res.status(403).json({ error: \"Blocked by x-lock: missing token\" });\n }\n\n try {\n const result = await enforce(apiUrl, siteKey, token, req.originalUrl || req.url);\n\n if (result.blocked) {\n return res.status(403).json({ error: \"Blocked by x-lock\", reason: result.reason });\n }\n\n if (result.error && !failOpen) {\n return res.status(403).json({ error: \"x-lock verification failed\" });\n }\n } catch (err: any) {\n console.error(\"[x-lock] Enforcement error:\", err.message);\n if (!failOpen) {\n return res.status(403).json({ error: \"x-lock verification failed\" });\n }\n }\n\n next();\n };\n}\n","/**\n * Core x-lock enforcement logic shared across all framework adapters.\n */\n\nexport const DEFAULT_API_URL = \"https://api.x-lock.dev\";\n\nexport interface XLockConfig {\n /** Your x-lock site key (or set XLOCK_SITE_KEY env var) */\n siteKey?: string;\n /** x-lock API URL (default: https://api.x-lock.dev) */\n apiUrl?: string;\n /** Allow requests through on API errors (default: true) */\n failOpen?: boolean;\n}\n\nexport interface EnforceResult {\n blocked: boolean;\n reason?: string;\n error?: boolean;\n}\n\n/**\n * Call the x-lock enforcement API to verify a token.\n */\nexport async function enforce(\n apiUrl: string,\n siteKey: string,\n token: string,\n path?: string\n): Promise<EnforceResult> {\n let enforceUrl: string;\n let body: Record<string, string>;\n\n if (token.startsWith(\"v3.\")) {\n const sessionId = token.split(\".\")[1];\n enforceUrl = `${apiUrl}/v3/session/enforce`;\n body = { sessionId, siteKey };\n if (path) body.path = path;\n } else {\n enforceUrl = `${apiUrl}/v1/enforce`;\n body = { token, siteKey };\n if (path) body.path = path;\n }\n\n const response = await fetch(enforceUrl, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(body),\n });\n\n if (response.status === 403) {\n const data = (await response.json()) as { reason?: string };\n return { blocked: true, reason: data.reason };\n }\n\n if (!response.ok) {\n return { blocked: false, error: true };\n }\n\n return { blocked: false };\n}\n\n/**\n * Resolve site key from options or environment.\n */\nexport function resolveSiteKey(siteKey?: string): string | undefined {\n return siteKey || process.env.XLOCK_SITE_KEY;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACIO,IAAM,kBAAkB;AAoB/B,eAAsB,QACpB,QACA,SACA,OACA,MACwB;AACxB,MAAI;AACJ,MAAI;AAEJ,MAAI,MAAM,WAAW,KAAK,GAAG;AAC3B,UAAM,YAAY,MAAM,MAAM,GAAG,EAAE,CAAC;AACpC,iBAAa,GAAG,MAAM;AACtB,WAAO,EAAE,WAAW,QAAQ;AAC5B,QAAI,KAAM,MAAK,OAAO;AAAA,EACxB,OAAO;AACL,iBAAa,GAAG,MAAM;AACtB,WAAO,EAAE,OAAO,QAAQ;AACxB,QAAI,KAAM,MAAK,OAAO;AAAA,EACxB;AAEA,QAAM,WAAW,MAAM,MAAM,YAAY;AAAA,IACvC,QAAQ;AAAA,IACR,SAAS,EAAE,gBAAgB,mBAAmB;AAAA,IAC9C,MAAM,KAAK,UAAU,IAAI;AAAA,EAC3B,CAAC;AAED,MAAI,SAAS,WAAW,KAAK;AAC3B,UAAM,OAAQ,MAAM,SAAS,KAAK;AAClC,WAAO,EAAE,SAAS,MAAM,QAAQ,KAAK,OAAO;AAAA,EAC9C;AAEA,MAAI,CAAC,SAAS,IAAI;AAChB,WAAO,EAAE,SAAS,OAAO,OAAO,KAAK;AAAA,EACvC;AAEA,SAAO,EAAE,SAAS,MAAM;AAC1B;AAKO,SAAS,eAAe,SAAsC;AACnE,SAAO,WAAW,QAAQ,IAAI;AAChC;;;ADrDO,SAAS,gBAAgB,UAAuB,CAAC,GAAG;AACzD,QAAM,SAAS,QAAQ,UAAU;AACjC,QAAM,UAAU,eAAe,QAAQ,OAAO;AAC9C,QAAM,WAAW,QAAQ,aAAa;AAEtC,MAAI,CAAC,SAAS;AACZ,YAAQ,KAAK,6DAAwD;AACrE,WAAO,CAAC,MAAW,MAAW,SAAqB,KAAK;AAAA,EAC1D;AAEA,SAAO,OAAO,KAAU,KAAU,SAAqB;AACrD,UAAM,QAAQ,IAAI,QAAQ,QAAQ;AAElC,QAAI,CAAC,OAAO;AACV,aAAO,IAAI,OAAO,GAAG,EAAE,KAAK,EAAE,OAAO,mCAAmC,CAAC;AAAA,IAC3E;AAEA,QAAI;AACF,YAAM,SAAS,MAAM,QAAQ,QAAQ,SAAS,OAAO,IAAI,eAAe,IAAI,GAAG;AAE/E,UAAI,OAAO,SAAS;AAClB,eAAO,IAAI,OAAO,GAAG,EAAE,KAAK,EAAE,OAAO,qBAAqB,QAAQ,OAAO,OAAO,CAAC;AAAA,MACnF;AAEA,UAAI,OAAO,SAAS,CAAC,UAAU;AAC7B,eAAO,IAAI,OAAO,GAAG,EAAE,KAAK,EAAE,OAAO,6BAA6B,CAAC;AAAA,MACrE;AAAA,IACF,SAAS,KAAU;AACjB,cAAQ,MAAM,+BAA+B,IAAI,OAAO;AACxD,UAAI,CAAC,UAAU;AACb,eAAO,IAAI,OAAO,GAAG,EAAE,KAAK,EAAE,OAAO,6BAA6B,CAAC;AAAA,MACrE;AAAA,IACF;AAEA,SAAK;AAAA,EACP;AACF;","names":[]}
|
package/dist/express.mjs
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
// src/core.ts
|
|
2
|
+
var DEFAULT_API_URL = "https://api.x-lock.dev";
|
|
3
|
+
async function enforce(apiUrl, siteKey, token, path) {
|
|
4
|
+
let enforceUrl;
|
|
5
|
+
let body;
|
|
6
|
+
if (token.startsWith("v3.")) {
|
|
7
|
+
const sessionId = token.split(".")[1];
|
|
8
|
+
enforceUrl = `${apiUrl}/v3/session/enforce`;
|
|
9
|
+
body = { sessionId, siteKey };
|
|
10
|
+
if (path) body.path = path;
|
|
11
|
+
} else {
|
|
12
|
+
enforceUrl = `${apiUrl}/v1/enforce`;
|
|
13
|
+
body = { token, siteKey };
|
|
14
|
+
if (path) body.path = path;
|
|
15
|
+
}
|
|
16
|
+
const response = await fetch(enforceUrl, {
|
|
17
|
+
method: "POST",
|
|
18
|
+
headers: { "Content-Type": "application/json" },
|
|
19
|
+
body: JSON.stringify(body)
|
|
20
|
+
});
|
|
21
|
+
if (response.status === 403) {
|
|
22
|
+
const data = await response.json();
|
|
23
|
+
return { blocked: true, reason: data.reason };
|
|
24
|
+
}
|
|
25
|
+
if (!response.ok) {
|
|
26
|
+
return { blocked: false, error: true };
|
|
27
|
+
}
|
|
28
|
+
return { blocked: false };
|
|
29
|
+
}
|
|
30
|
+
function resolveSiteKey(siteKey) {
|
|
31
|
+
return siteKey || process.env.XLOCK_SITE_KEY;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// src/express.ts
|
|
35
|
+
function xlockMiddleware(options = {}) {
|
|
36
|
+
const apiUrl = options.apiUrl || DEFAULT_API_URL;
|
|
37
|
+
const siteKey = resolveSiteKey(options.siteKey);
|
|
38
|
+
const failOpen = options.failOpen !== false;
|
|
39
|
+
if (!siteKey) {
|
|
40
|
+
console.warn("[x-lock] No site key configured \u2014 skipping enforcement");
|
|
41
|
+
return (_req, _res, next) => next();
|
|
42
|
+
}
|
|
43
|
+
return async (req, res, next) => {
|
|
44
|
+
const token = req.headers["x-lock"];
|
|
45
|
+
if (!token) {
|
|
46
|
+
return res.status(403).json({ error: "Blocked by x-lock: missing token" });
|
|
47
|
+
}
|
|
48
|
+
try {
|
|
49
|
+
const result = await enforce(apiUrl, siteKey, token, req.originalUrl || req.url);
|
|
50
|
+
if (result.blocked) {
|
|
51
|
+
return res.status(403).json({ error: "Blocked by x-lock", reason: result.reason });
|
|
52
|
+
}
|
|
53
|
+
if (result.error && !failOpen) {
|
|
54
|
+
return res.status(403).json({ error: "x-lock verification failed" });
|
|
55
|
+
}
|
|
56
|
+
} catch (err) {
|
|
57
|
+
console.error("[x-lock] Enforcement error:", err.message);
|
|
58
|
+
if (!failOpen) {
|
|
59
|
+
return res.status(403).json({ error: "x-lock verification failed" });
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
next();
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
export {
|
|
66
|
+
xlockMiddleware
|
|
67
|
+
};
|
|
68
|
+
//# sourceMappingURL=express.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core.ts","../src/express.ts"],"sourcesContent":["/**\n * Core x-lock enforcement logic shared across all framework adapters.\n */\n\nexport const DEFAULT_API_URL = \"https://api.x-lock.dev\";\n\nexport interface XLockConfig {\n /** Your x-lock site key (or set XLOCK_SITE_KEY env var) */\n siteKey?: string;\n /** x-lock API URL (default: https://api.x-lock.dev) */\n apiUrl?: string;\n /** Allow requests through on API errors (default: true) */\n failOpen?: boolean;\n}\n\nexport interface EnforceResult {\n blocked: boolean;\n reason?: string;\n error?: boolean;\n}\n\n/**\n * Call the x-lock enforcement API to verify a token.\n */\nexport async function enforce(\n apiUrl: string,\n siteKey: string,\n token: string,\n path?: string\n): Promise<EnforceResult> {\n let enforceUrl: string;\n let body: Record<string, string>;\n\n if (token.startsWith(\"v3.\")) {\n const sessionId = token.split(\".\")[1];\n enforceUrl = `${apiUrl}/v3/session/enforce`;\n body = { sessionId, siteKey };\n if (path) body.path = path;\n } else {\n enforceUrl = `${apiUrl}/v1/enforce`;\n body = { token, siteKey };\n if (path) body.path = path;\n }\n\n const response = await fetch(enforceUrl, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(body),\n });\n\n if (response.status === 403) {\n const data = (await response.json()) as { reason?: string };\n return { blocked: true, reason: data.reason };\n }\n\n if (!response.ok) {\n return { blocked: false, error: true };\n }\n\n return { blocked: false };\n}\n\n/**\n * Resolve site key from options or environment.\n */\nexport function resolveSiteKey(siteKey?: string): string | undefined {\n return siteKey || process.env.XLOCK_SITE_KEY;\n}\n","/**\n * x-lock middleware for Express.js\n *\n * @example\n * ```js\n * import { xlockMiddleware } from \"@xlock/node/express\";\n * app.use(\"/api/auth\", xlockMiddleware({ siteKey: \"sk_...\" }));\n * ```\n */\n\nimport { enforce, resolveSiteKey, DEFAULT_API_URL, type XLockConfig } from \"./core\";\n\nexport type { XLockConfig };\n\nexport function xlockMiddleware(options: XLockConfig = {}) {\n const apiUrl = options.apiUrl || DEFAULT_API_URL;\n const siteKey = resolveSiteKey(options.siteKey);\n const failOpen = options.failOpen !== false;\n\n if (!siteKey) {\n console.warn(\"[x-lock] No site key configured — skipping enforcement\");\n return (_req: any, _res: any, next: () => void) => next();\n }\n\n return async (req: any, res: any, next: () => void) => {\n const token = req.headers[\"x-lock\"];\n\n if (!token) {\n return res.status(403).json({ error: \"Blocked by x-lock: missing token\" });\n }\n\n try {\n const result = await enforce(apiUrl, siteKey, token, req.originalUrl || req.url);\n\n if (result.blocked) {\n return res.status(403).json({ error: \"Blocked by x-lock\", reason: result.reason });\n }\n\n if (result.error && !failOpen) {\n return res.status(403).json({ error: \"x-lock verification failed\" });\n }\n } catch (err: any) {\n console.error(\"[x-lock] Enforcement error:\", err.message);\n if (!failOpen) {\n return res.status(403).json({ error: \"x-lock verification failed\" });\n }\n }\n\n next();\n };\n}\n"],"mappings":";AAIO,IAAM,kBAAkB;AAoB/B,eAAsB,QACpB,QACA,SACA,OACA,MACwB;AACxB,MAAI;AACJ,MAAI;AAEJ,MAAI,MAAM,WAAW,KAAK,GAAG;AAC3B,UAAM,YAAY,MAAM,MAAM,GAAG,EAAE,CAAC;AACpC,iBAAa,GAAG,MAAM;AACtB,WAAO,EAAE,WAAW,QAAQ;AAC5B,QAAI,KAAM,MAAK,OAAO;AAAA,EACxB,OAAO;AACL,iBAAa,G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AAC7B,eAAO,IAAI,OAAO,GAAG,EAAE,KAAK,EAAE,OAAO,6BAA6B,CAAC;AAAA,MACrE;AAAA,IACF,SAAS,KAAU;AACjB,cAAQ,MAAM,+BAA+B,IAAI,OAAO;AACxD,UAAI,CAAC,UAAU;AACb,eAAO,IAAI,OAAO,GAAG,EAAE,KAAK,EAAE,OAAO,6BAA6B,CAAC;AAAA,MACrE;AAAA,IACF;AAEA,SAAK;AAAA,EACP;AACF;","names":[]}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { X as XLockConfig } from './core-D4eszYbi.mjs';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* x-lock plugin for Fastify
|
|
5
|
+
*
|
|
6
|
+
* @example
|
|
7
|
+
* ```js
|
|
8
|
+
* import { xlockPlugin } from "@xlock/node/fastify";
|
|
9
|
+
* fastify.register(xlockPlugin, { siteKey: "sk_...", routes: ["/api/auth/*"] });
|
|
10
|
+
* ```
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
interface XLockFastifyConfig extends XLockConfig {
|
|
14
|
+
/** Route patterns to protect (supports trailing /*) */
|
|
15
|
+
routes?: string[];
|
|
16
|
+
}
|
|
17
|
+
declare function xlockPlugin(fastify: any, options: XLockFastifyConfig): Promise<void>;
|
|
18
|
+
|
|
19
|
+
export { type XLockFastifyConfig, xlockPlugin };
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { X as XLockConfig } from './core-D4eszYbi.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* x-lock plugin for Fastify
|
|
5
|
+
*
|
|
6
|
+
* @example
|
|
7
|
+
* ```js
|
|
8
|
+
* import { xlockPlugin } from "@xlock/node/fastify";
|
|
9
|
+
* fastify.register(xlockPlugin, { siteKey: "sk_...", routes: ["/api/auth/*"] });
|
|
10
|
+
* ```
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
interface XLockFastifyConfig extends XLockConfig {
|
|
14
|
+
/** Route patterns to protect (supports trailing /*) */
|
|
15
|
+
routes?: string[];
|
|
16
|
+
}
|
|
17
|
+
declare function xlockPlugin(fastify: any, options: XLockFastifyConfig): Promise<void>;
|
|
18
|
+
|
|
19
|
+
export { type XLockFastifyConfig, xlockPlugin };
|
package/dist/fastify.js
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/fastify.ts
|
|
21
|
+
var fastify_exports = {};
|
|
22
|
+
__export(fastify_exports, {
|
|
23
|
+
xlockPlugin: () => xlockPlugin
|
|
24
|
+
});
|
|
25
|
+
module.exports = __toCommonJS(fastify_exports);
|
|
26
|
+
|
|
27
|
+
// src/core.ts
|
|
28
|
+
var DEFAULT_API_URL = "https://api.x-lock.dev";
|
|
29
|
+
async function enforce(apiUrl, siteKey, token, path) {
|
|
30
|
+
let enforceUrl;
|
|
31
|
+
let body;
|
|
32
|
+
if (token.startsWith("v3.")) {
|
|
33
|
+
const sessionId = token.split(".")[1];
|
|
34
|
+
enforceUrl = `${apiUrl}/v3/session/enforce`;
|
|
35
|
+
body = { sessionId, siteKey };
|
|
36
|
+
if (path) body.path = path;
|
|
37
|
+
} else {
|
|
38
|
+
enforceUrl = `${apiUrl}/v1/enforce`;
|
|
39
|
+
body = { token, siteKey };
|
|
40
|
+
if (path) body.path = path;
|
|
41
|
+
}
|
|
42
|
+
const response = await fetch(enforceUrl, {
|
|
43
|
+
method: "POST",
|
|
44
|
+
headers: { "Content-Type": "application/json" },
|
|
45
|
+
body: JSON.stringify(body)
|
|
46
|
+
});
|
|
47
|
+
if (response.status === 403) {
|
|
48
|
+
const data = await response.json();
|
|
49
|
+
return { blocked: true, reason: data.reason };
|
|
50
|
+
}
|
|
51
|
+
if (!response.ok) {
|
|
52
|
+
return { blocked: false, error: true };
|
|
53
|
+
}
|
|
54
|
+
return { blocked: false };
|
|
55
|
+
}
|
|
56
|
+
function resolveSiteKey(siteKey) {
|
|
57
|
+
return siteKey || process.env.XLOCK_SITE_KEY;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// src/fastify.ts
|
|
61
|
+
async function xlockPlugin(fastify, options) {
|
|
62
|
+
const apiUrl = options.apiUrl || DEFAULT_API_URL;
|
|
63
|
+
const siteKey = resolveSiteKey(options.siteKey);
|
|
64
|
+
const failOpen = options.failOpen !== false;
|
|
65
|
+
const routes = options.routes || [];
|
|
66
|
+
if (!siteKey) {
|
|
67
|
+
fastify.log.warn("[x-lock] No site key configured \u2014 skipping enforcement");
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
function matchesRoute(path) {
|
|
71
|
+
return routes.some((pattern) => {
|
|
72
|
+
if (pattern.endsWith("/*")) {
|
|
73
|
+
return path.startsWith(pattern.slice(0, -2));
|
|
74
|
+
}
|
|
75
|
+
return path === pattern;
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
fastify.addHook("preHandler", async (request, reply) => {
|
|
79
|
+
if (routes.length > 0 && !matchesRoute(request.url)) return;
|
|
80
|
+
const token = request.headers["x-lock"];
|
|
81
|
+
if (!token) {
|
|
82
|
+
return reply.code(403).send({ error: "Blocked by x-lock: missing token" });
|
|
83
|
+
}
|
|
84
|
+
try {
|
|
85
|
+
const result = await enforce(apiUrl, siteKey, token, request.url);
|
|
86
|
+
if (result.blocked) {
|
|
87
|
+
return reply.code(403).send({ error: "Blocked by x-lock", reason: result.reason });
|
|
88
|
+
}
|
|
89
|
+
if (result.error && !failOpen) {
|
|
90
|
+
return reply.code(403).send({ error: "x-lock verification failed" });
|
|
91
|
+
}
|
|
92
|
+
} catch (err) {
|
|
93
|
+
request.log.error("[x-lock] Enforcement error:", err.message);
|
|
94
|
+
if (!failOpen) {
|
|
95
|
+
return reply.code(403).send({ error: "x-lock verification failed" });
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
xlockPlugin[/* @__PURE__ */ Symbol.for("skip-override")] = true;
|
|
101
|
+
xlockPlugin[/* @__PURE__ */ Symbol.for("fastify.display-name")] = "x-lock";
|
|
102
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
103
|
+
0 && (module.exports = {
|
|
104
|
+
xlockPlugin
|
|
105
|
+
});
|
|
106
|
+
//# sourceMappingURL=fastify.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/fastify.ts","../src/core.ts"],"sourcesContent":["/**\n * x-lock plugin for Fastify\n *\n * @example\n * ```js\n * import { xlockPlugin } from \"@xlock/node/fastify\";\n * fastify.register(xlockPlugin, { siteKey: \"sk_...\", routes: [\"/api/auth/*\"] });\n * ```\n */\n\nimport { enforce, resolveSiteKey, DEFAULT_API_URL, type XLockConfig } from \"./core\";\n\nexport interface XLockFastifyConfig extends XLockConfig {\n /** Route patterns to protect (supports trailing /*) */\n routes?: string[];\n}\n\nexport async function xlockPlugin(fastify: any, options: XLockFastifyConfig) {\n const apiUrl = options.apiUrl || DEFAULT_API_URL;\n const siteKey = resolveSiteKey(options.siteKey);\n const failOpen = options.failOpen !== false;\n const routes = options.routes || [];\n\n if (!siteKey) {\n fastify.log.warn(\"[x-lock] No site key configured — skipping enforcement\");\n return;\n }\n\n function matchesRoute(path: string): boolean {\n return routes.some((pattern) => {\n if (pattern.endsWith(\"/*\")) {\n return path.startsWith(pattern.slice(0, -2));\n }\n return path === pattern;\n });\n }\n\n fastify.addHook(\"preHandler\", async (request: any, reply: any) => {\n if (routes.length > 0 && !matchesRoute(request.url)) return;\n\n const token = request.headers[\"x-lock\"];\n\n if (!token) {\n return reply.code(403).send({ error: \"Blocked by x-lock: missing token\" });\n }\n\n try {\n const result = await enforce(apiUrl, siteKey, token, request.url);\n\n if (result.blocked) {\n return reply.code(403).send({ error: \"Blocked by x-lock\", reason: result.reason });\n }\n\n if (result.error && !failOpen) {\n return reply.code(403).send({ error: \"x-lock verification failed\" });\n }\n } catch (err: any) {\n request.log.error(\"[x-lock] Enforcement error:\", err.message);\n if (!failOpen) {\n return reply.code(403).send({ error: \"x-lock verification failed\" });\n }\n }\n });\n}\n\n// Fastify plugin metadata\n(xlockPlugin as any)[Symbol.for(\"skip-override\")] = true;\n(xlockPlugin as any)[Symbol.for(\"fastify.display-name\")] = \"x-lock\";\n","/**\n * Core x-lock enforcement logic shared across all framework adapters.\n */\n\nexport const DEFAULT_API_URL = \"https://api.x-lock.dev\";\n\nexport interface XLockConfig {\n /** Your x-lock site key (or set XLOCK_SITE_KEY env var) */\n siteKey?: string;\n /** x-lock API URL (default: https://api.x-lock.dev) */\n apiUrl?: string;\n /** Allow requests through on API errors (default: true) */\n failOpen?: boolean;\n}\n\nexport interface EnforceResult {\n blocked: boolean;\n reason?: string;\n error?: boolean;\n}\n\n/**\n * Call the x-lock enforcement API to verify a token.\n */\nexport async function enforce(\n apiUrl: string,\n siteKey: string,\n token: string,\n path?: string\n): Promise<EnforceResult> {\n let enforceUrl: string;\n let body: Record<string, string>;\n\n if (token.startsWith(\"v3.\")) {\n const sessionId = token.split(\".\")[1];\n enforceUrl = `${apiUrl}/v3/session/enforce`;\n body = { sessionId, siteKey };\n if (path) body.path = path;\n } else {\n enforceUrl = `${apiUrl}/v1/enforce`;\n body = { token, siteKey };\n if (path) body.path = path;\n }\n\n const response = await fetch(enforceUrl, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(body),\n });\n\n if (response.status === 403) {\n const data = (await response.json()) as { reason?: string };\n return { blocked: true, reason: data.reason };\n }\n\n if (!response.ok) {\n return { blocked: false, error: true };\n }\n\n return { blocked: false };\n}\n\n/**\n * Resolve site key from options or environment.\n */\nexport function resolveSiteKey(siteKey?: string): string | undefined {\n return siteKey || process.env.XLOCK_SITE_KEY;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACIO,IAAM,kBAAkB;AAoB/B,eAAsB,QACpB,QACA,SACA,OACA,MACwB;AACxB,MAAI;AACJ,MAAI;AAEJ,MAAI,MAAM,WAAW,KAAK,GAAG;AAC3B,UAAM,YAAY,MAAM,MAAM,GAAG,EAAE,CAAC;AACpC,iBAAa,GAAG,MAAM;AACtB,WAAO,EAAE,WAAW,QAAQ;AAC5B,QAAI,KAAM,MAAK,OAAO;AAAA,EACxB,OAAO;AACL,iBAAa,GAAG,MAAM;AACtB,WAAO,EAAE,OAAO,QAAQ;AACxB,QAAI,KAAM,MAAK,OAAO;AAAA,EACxB;AAEA,QAAM,WAAW,MAAM,MAAM,YAAY;AAAA,IACvC,QAAQ;AAAA,IACR,SAAS,EAAE,gBAAgB,mBAAmB;AAAA,IAC9C,MAAM,KAAK,UAAU,IAAI;AAAA,EAC3B,CAAC;AAED,MAAI,SAAS,WAAW,KAAK;AAC3B,UAAM,OAAQ,MAAM,SAAS,KAAK;AAClC,WAAO,EAAE,SAAS,MAAM,QAAQ,KAAK,OAAO;AAAA,EAC9C;AAEA,MAAI,CAAC,SAAS,IAAI;AAChB,WAAO,EAAE,SAAS,OAAO,OAAO,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AAI,CAAC,UAAU;AACb,eAAO,MAAM,KAAK,GAAG,EAAE,KAAK,EAAE,OAAO,6BAA6B,CAAC;AAAA,MACrE;AAAA,IACF;AAAA,EACF,CAAC;AACH;AAGC,YAAoB,uBAAO,IAAI,eAAe,CAAC,IAAI;AACnD,YAAoB,uBAAO,IAAI,sBAAsB,CAAC,IAAI;","names":[]}
|
package/dist/fastify.mjs
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
// src/core.ts
|
|
2
|
+
var DEFAULT_API_URL = "https://api.x-lock.dev";
|
|
3
|
+
async function enforce(apiUrl, siteKey, token, path) {
|
|
4
|
+
let enforceUrl;
|
|
5
|
+
let body;
|
|
6
|
+
if (token.startsWith("v3.")) {
|
|
7
|
+
const sessionId = token.split(".")[1];
|
|
8
|
+
enforceUrl = `${apiUrl}/v3/session/enforce`;
|
|
9
|
+
body = { sessionId, siteKey };
|
|
10
|
+
if (path) body.path = path;
|
|
11
|
+
} else {
|
|
12
|
+
enforceUrl = `${apiUrl}/v1/enforce`;
|
|
13
|
+
body = { token, siteKey };
|
|
14
|
+
if (path) body.path = path;
|
|
15
|
+
}
|
|
16
|
+
const response = await fetch(enforceUrl, {
|
|
17
|
+
method: "POST",
|
|
18
|
+
headers: { "Content-Type": "application/json" },
|
|
19
|
+
body: JSON.stringify(body)
|
|
20
|
+
});
|
|
21
|
+
if (response.status === 403) {
|
|
22
|
+
const data = await response.json();
|
|
23
|
+
return { blocked: true, reason: data.reason };
|
|
24
|
+
}
|
|
25
|
+
if (!response.ok) {
|
|
26
|
+
return { blocked: false, error: true };
|
|
27
|
+
}
|
|
28
|
+
return { blocked: false };
|
|
29
|
+
}
|
|
30
|
+
function resolveSiteKey(siteKey) {
|
|
31
|
+
return siteKey || process.env.XLOCK_SITE_KEY;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// src/fastify.ts
|
|
35
|
+
async function xlockPlugin(fastify, options) {
|
|
36
|
+
const apiUrl = options.apiUrl || DEFAULT_API_URL;
|
|
37
|
+
const siteKey = resolveSiteKey(options.siteKey);
|
|
38
|
+
const failOpen = options.failOpen !== false;
|
|
39
|
+
const routes = options.routes || [];
|
|
40
|
+
if (!siteKey) {
|
|
41
|
+
fastify.log.warn("[x-lock] No site key configured \u2014 skipping enforcement");
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
function matchesRoute(path) {
|
|
45
|
+
return routes.some((pattern) => {
|
|
46
|
+
if (pattern.endsWith("/*")) {
|
|
47
|
+
return path.startsWith(pattern.slice(0, -2));
|
|
48
|
+
}
|
|
49
|
+
return path === pattern;
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
fastify.addHook("preHandler", async (request, reply) => {
|
|
53
|
+
if (routes.length > 0 && !matchesRoute(request.url)) return;
|
|
54
|
+
const token = request.headers["x-lock"];
|
|
55
|
+
if (!token) {
|
|
56
|
+
return reply.code(403).send({ error: "Blocked by x-lock: missing token" });
|
|
57
|
+
}
|
|
58
|
+
try {
|
|
59
|
+
const result = await enforce(apiUrl, siteKey, token, request.url);
|
|
60
|
+
if (result.blocked) {
|
|
61
|
+
return reply.code(403).send({ error: "Blocked by x-lock", reason: result.reason });
|
|
62
|
+
}
|
|
63
|
+
if (result.error && !failOpen) {
|
|
64
|
+
return reply.code(403).send({ error: "x-lock verification failed" });
|
|
65
|
+
}
|
|
66
|
+
} catch (err) {
|
|
67
|
+
request.log.error("[x-lock] Enforcement error:", err.message);
|
|
68
|
+
if (!failOpen) {
|
|
69
|
+
return reply.code(403).send({ error: "x-lock verification failed" });
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
xlockPlugin[/* @__PURE__ */ Symbol.for("skip-override")] = true;
|
|
75
|
+
xlockPlugin[/* @__PURE__ */ Symbol.for("fastify.display-name")] = "x-lock";
|
|
76
|
+
export {
|
|
77
|
+
xlockPlugin
|
|
78
|
+
};
|
|
79
|
+
//# sourceMappingURL=fastify.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core.ts","../src/fastify.ts"],"sourcesContent":["/**\n * Core x-lock enforcement logic shared across all framework adapters.\n */\n\nexport const DEFAULT_API_URL = \"https://api.x-lock.dev\";\n\nexport interface XLockConfig {\n /** Your x-lock site key (or set XLOCK_SITE_KEY env var) */\n siteKey?: string;\n /** x-lock API URL (default: https://api.x-lock.dev) */\n apiUrl?: string;\n /** Allow requests through on API errors (default: true) */\n failOpen?: boolean;\n}\n\nexport interface EnforceResult {\n blocked: boolean;\n reason?: string;\n error?: boolean;\n}\n\n/**\n * Call the x-lock enforcement API to verify a token.\n */\nexport async function enforce(\n apiUrl: string,\n siteKey: string,\n token: string,\n path?: string\n): Promise<EnforceResult> {\n let enforceUrl: string;\n let body: Record<string, string>;\n\n if (token.startsWith(\"v3.\")) {\n const sessionId = token.split(\".\")[1];\n enforceUrl = `${apiUrl}/v3/session/enforce`;\n body = { sessionId, siteKey };\n if (path) body.path = path;\n } else {\n enforceUrl = `${apiUrl}/v1/enforce`;\n body = { token, siteKey };\n if (path) body.path = path;\n }\n\n const response = await fetch(enforceUrl, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(body),\n });\n\n if (response.status === 403) {\n const data = (await response.json()) as { reason?: string };\n return { blocked: true, reason: data.reason };\n }\n\n if (!response.ok) {\n return { blocked: false, error: true };\n }\n\n return { blocked: false };\n}\n\n/**\n * Resolve site key from options or environment.\n */\nexport function resolveSiteKey(siteKey?: string): string | undefined {\n return siteKey || process.env.XLOCK_SITE_KEY;\n}\n","/**\n * x-lock plugin for Fastify\n *\n * @example\n * ```js\n * import { xlockPlugin } from \"@xlock/node/fastify\";\n * fastify.register(xlockPlugin, { siteKey: \"sk_...\", routes: [\"/api/auth/*\"] });\n * ```\n */\n\nimport { enforce, resolveSiteKey, DEFAULT_API_URL, type XLockConfig } from \"./core\";\n\nexport interface XLockFastifyConfig extends XLockConfig {\n /** Route patterns to protect (supports trailing /*) */\n routes?: string[];\n}\n\nexport async function xlockPlugin(fastify: any, options: XLockFastifyConfig) {\n const apiUrl = options.apiUrl || DEFAULT_API_URL;\n const siteKey = resolveSiteKey(options.siteKey);\n const failOpen = options.failOpen !== false;\n const routes = options.routes || [];\n\n if (!siteKey) {\n fastify.log.warn(\"[x-lock] No site key configured — skipping enforcement\");\n return;\n }\n\n function matchesRoute(path: string): boolean {\n return routes.some((pattern) => {\n if (pattern.endsWith(\"/*\")) {\n return path.startsWith(pattern.slice(0, -2));\n }\n return path === pattern;\n });\n }\n\n fastify.addHook(\"preHandler\", async (request: any, reply: any) => {\n if (routes.length > 0 && !matchesRoute(request.url)) return;\n\n const token = request.headers[\"x-lock\"];\n\n if (!token) {\n return reply.code(403).send({ error: \"Blocked by x-lock: missing token\" });\n }\n\n try {\n const result = await enforce(apiUrl, siteKey, token, request.url);\n\n if (result.blocked) {\n return reply.code(403).send({ error: \"Blocked by x-lock\", reason: result.reason });\n }\n\n if (result.error && !failOpen) {\n return reply.code(403).send({ error: \"x-lock verification failed\" });\n }\n } catch (err: any) {\n request.log.error(\"[x-lock] Enforcement error:\", err.message);\n if (!failOpen) {\n return reply.code(403).send({ error: \"x-lock verification failed\" });\n }\n }\n });\n}\n\n// Fastify plugin metadata\n(xlockPlugin as any)[Symbol.for(\"skip-override\")] = true;\n(xlockPlugin as any)[Symbol.for(\"fastify.display-name\")] = \"x-lock\";\n"],"mappings":";AAIO,IAAM,kBAAkB;AAoB/B,eAAsB,QACpB,QACA,SACA,OACA,MACwB;AACxB,MAAI;AACJ,MAAI;AAEJ,MAAI,MAAM,WAAW,KAAK,GAAG;AAC3B,UAAM,YAAY,MAAM,MAAM,GAAG,EAAE,CAAC;AACpC,iBAAa,GAAG,MAAM;AACtB,WAAO,EAAE,WAAW,QAAQ;AAC5B,QAAI,KAAM,MAAK,OAAO;AAAA,EACxB,OAAO;AACL,iBAAa,GAAG,MAAM;AACtB,WAAO,EAAE,OAAO,QAAQ;A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