@zarex/sveltekit 0.0.0-stage → 0.1.1

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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kodjogbe
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,107 @@
1
- # Temporary Holding Version
1
+ # @zarex/sveltekit
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Hook Zarex pour SvelteKit — protège votre application contre les bots, les abus de trafic, les injections (SQL, XSS, SSRF...) et les fuites de données sensibles, en quelques lignes.
4
+
5
+ Aucune dépendance à `@sveltejs/kit` à l'exécution.
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ npm install @zarex/sveltekit
11
+ ```
12
+
13
+ ## Démarrage rapide
14
+
15
+ ```ts
16
+ // src/hooks.server.ts
17
+ import { zarexHandle, shield, rateLimit } from "@zarex/sveltekit";
18
+
19
+ export const handle = zarexHandle({
20
+ key: process.env.ZAREX_KEY!,
21
+ rules: [shield(), rateLimit({ max: 100, window: "1m" })],
22
+ });
23
+ ```
24
+
25
+ Avec d'autres hooks (`sequence`) :
26
+
27
+ ```ts
28
+ import { sequence } from "@sveltejs/kit/hooks";
29
+ import { zarexHandle } from "@zarex/sveltekit";
30
+
31
+ export const handle = sequence(zarexHandle({ key, rules: [shield()] }), maHandle);
32
+ ```
33
+
34
+ Une requête refusée reçoit automatiquement `403 Forbidden` (ou `429 Too Many Requests` avec l'en-tête `retry-after` pour une limite de débit) — sans aucun code supplémentaire.
35
+
36
+ **Fail-open** : si Zarex est injoignable, lent ou répond de façon inattendue, la requête passe toujours. Une panne chez Zarex ne doit jamais faire tomber votre application.
37
+
38
+ ## L'adresse IP du visiteur
39
+
40
+ Par défaut (`ipSource` non renseigné), l'adaptateur utilise `event.getClientAddress()`, calculé par SvelteKit selon la configuration de **votre** adaptateur de déploiement (`adapter-node` : variables `ADDRESS_HEADER` et `XFF_DEPTH` ; `adapter-vercel`, etc. — voir la documentation de votre adaptateur). Un mauvais réglage ici fait passer tous vos visiteurs pour une seule adresse IP.
41
+
42
+ ## Options
43
+
44
+ ```ts
45
+ zarexHandle({
46
+ key: string, // obligatoire : clé API du projet
47
+ rules: Rule[], // obligatoire : 1 à 10 règles, voir ci-dessous
48
+ ipSource?: IpSource, // défaut "framework" (voir ci-dessus)
49
+ inspectBody?: boolean,
50
+ secureHeaders?: boolean | SecureHeadersOptions,
51
+ responseGuard?: boolean | ResponseGuardOptions,
52
+ onDeny?: (event, decision) => Response | undefined,
53
+ onDegraded?: (event, decision) => void,
54
+ call?: (event) => ProtectCall | undefined,
55
+ timeoutMs?: number, // défaut 500 ms
56
+ breaker?: BreakerOptions | false,
57
+ })
58
+ ```
59
+
60
+ ### En-têtes de sécurité et surveillance des réponses
61
+
62
+ ```ts
63
+ export const handle = zarexHandle({ ..., secureHeaders: true, responseGuard: true });
64
+ ```
65
+
66
+ Appliqués automatiquement à toute réponse (y compris celle que `resolve(event)` aurait produite) — aucun appel supplémentaire à faire, contrairement au middleware Next.js.
67
+
68
+ ### Identifiants personnalisés (`call`)
69
+
70
+ ```ts
71
+ export const handle = zarexHandle({
72
+ key,
73
+ rules: [rateLimit({ max: 100, window: "1m", characteristics: ["userId"] })],
74
+ call: (event) => ({ characteristics: { userId: event.locals.user?.id } }),
75
+ });
76
+ ```
77
+
78
+ Les valeurs sont hachées en SHA-256 avant l'envoi à Zarex. Une erreur dans cette fonction est silencieusement ignorée. `call` peut aussi fournir `tokensRequested`, `email`/`phone` ou `text` (voir [`@zarex/core`](https://www.npmjs.com/package/@zarex/core)).
79
+
80
+ ### Lire le résultat de la décision
81
+
82
+ ```ts
83
+ // dans une route +page.server.ts ou +server.ts
84
+ export function load({ locals }) {
85
+ console.log(locals.zarex?.verdict); // "ALLOW" | "DENY" | "ERROR"
86
+ }
87
+ ```
88
+
89
+ ## Règles disponibles
90
+
91
+ | Fonction | Résumé |
92
+ |---|---|
93
+ | `shield(opts?)` | Pare-feu applicatif : injection SQL, XSS, traversée de répertoires, SSRF, SSTI... |
94
+ | `rateLimit({ max, window, ... })` | Limite de requêtes par visiteur sur une fenêtre de temps. |
95
+ | `tokenBucket({ capacity, refillRate, interval })` | Budget de jetons avec pics autorisés. |
96
+ | `detectBot(opts?)` | Détecte les robots connus, avec vérification DNS inversée. |
97
+ | `requestFilter({ expressions, logic })` | Règles personnalisées sur IP, chemin, en-têtes, cookies, pays... |
98
+ | `sensitiveInfo(opts?)` | Refuse une requête contenant une donnée sensible (nécessite `inspectBody`). |
99
+ | `emailValidation(opts?)` | Valide un email donné via `call: () => ({ email })`. |
100
+ | `phoneValidation(opts?)` | Valide un numéro donné, orienté opérateurs africains (MTN, Moov, Orange, Wave...). |
101
+ | `promptInjection(opts?)` | Détecte les tentatives de manipulation d'un assistant IA, via `call: () => ({ text })`. |
102
+
103
+ Chaque règle accepte `mode: "LIVE" | "DRY_RUN" | "OFF"`. Détails complets des options : voir [`@zarex/core`](https://www.npmjs.com/package/@zarex/core).
104
+
105
+ ## Licence
106
+
107
+ MIT
package/dist/index.cjs ADDED
@@ -0,0 +1,101 @@
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/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ CLOUDFLARE_RANGES: () => import_core2.CLOUDFLARE_RANGES,
24
+ PRIVATE_NETWORKS: () => import_core2.PRIVATE_NETWORKS,
25
+ createZarex: () => import_core2.createZarex,
26
+ detectBot: () => import_core2.detectBot,
27
+ emailValidation: () => import_core2.emailValidation,
28
+ phoneValidation: () => import_core2.phoneValidation,
29
+ promptInjection: () => import_core2.promptInjection,
30
+ rateLimit: () => import_core2.rateLimit,
31
+ requestFilter: () => import_core2.requestFilter,
32
+ secureHeaders: () => import_core2.secureHeaders,
33
+ sensitiveInfo: () => import_core2.sensitiveInfo,
34
+ shield: () => import_core2.shield,
35
+ tokenBucket: () => import_core2.tokenBucket,
36
+ withSecureHeaders: () => import_core2.withSecureHeaders,
37
+ zarexHandle: () => zarexHandle
38
+ });
39
+ module.exports = __toCommonJS(index_exports);
40
+ var import_core = require("@zarex/core");
41
+ var import_core2 = require("@zarex/core");
42
+ function zarexHandle(options, extra = {}) {
43
+ const isInstance = typeof options.protect === "function";
44
+ const opts = isInstance ? extra : options;
45
+ const instance = isInstance ? options : (0, import_core.createZarex)({ ...options, ipSource: options.ipSource ?? "framework" });
46
+ const finalizer = (0, import_core.createWebFinalizer)({ secureHeaders: opts.secureHeaders, responseGuard: opts.responseGuard });
47
+ const finalize = async (res, request) => {
48
+ if (!finalizer || !(res instanceof Response)) return res;
49
+ try {
50
+ return await finalizer(res, request);
51
+ } catch {
52
+ return res;
53
+ }
54
+ };
55
+ return async function handle({ event, resolve }) {
56
+ try {
57
+ let frameworkIp;
58
+ try {
59
+ frameworkIp = event.getClientAddress();
60
+ } catch {
61
+ frameworkIp = void 0;
62
+ }
63
+ let call;
64
+ try {
65
+ call = opts.call?.(event);
66
+ } catch {
67
+ call = void 0;
68
+ }
69
+ const { decision, deny } = await (0, import_core.guardWebRequest)(instance, event.request, {
70
+ frameworkIp,
71
+ ...opts.inspectBody ? { inspectBody: true } : {},
72
+ ...opts.onDeny ? { onDeny: opts.onDeny } : {},
73
+ ...opts.onDegraded ? { onDegraded: opts.onDegraded } : {},
74
+ ...call ? { call } : {}
75
+ });
76
+ if (decision) event.locals["zarex"] = decision;
77
+ if (deny) return finalize(deny, event.request);
78
+ } catch {
79
+ }
80
+ return finalize(await resolve(event), event.request);
81
+ };
82
+ }
83
+ // Annotate the CommonJS export names for ESM import in node:
84
+ 0 && (module.exports = {
85
+ CLOUDFLARE_RANGES,
86
+ PRIVATE_NETWORKS,
87
+ createZarex,
88
+ detectBot,
89
+ emailValidation,
90
+ phoneValidation,
91
+ promptInjection,
92
+ rateLimit,
93
+ requestFilter,
94
+ secureHeaders,
95
+ sensitiveInfo,
96
+ shield,
97
+ tokenBucket,
98
+ withSecureHeaders,
99
+ zarexHandle
100
+ });
101
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import { createWebFinalizer, createZarex, guardWebRequest, type ResponseGuardOptions, type SecureHeadersOptions, type Decision, type ProtectCall, type WebGuardOptions, type Zarex, type ZarexOptions } from \"@zarex/core\";\r\n\r\n/** Ce dont on a besoin de l'évènement SvelteKit (types minimaux : pas de dépendance à @sveltejs/kit). */\r\nexport interface SvelteEventLike {\r\n request: Request;\r\n getClientAddress(): string;\r\n locals: Record<string, unknown>;\r\n}\r\n\r\nexport interface SvelteZarexOptions extends Omit<ZarexOptions, \"ipSource\"> {\r\n /**\r\n * Défaut : \"framework\" — l'adresse est celle de `event.getClientAddress()`, que SvelteKit calcule selon\r\n * la configuration de votre adaptateur (adapter-node : variables ADDRESS_HEADER et XFF_DEPTH ; adapter-vercel, etc.).\r\n */\r\n ipSource?: ZarexOptions[\"ipSource\"];\r\n inspectBody?: boolean;\r\n /** En-têtes de sécurité ajoutés à chaque réponse (true = défauts prudents). */\r\n secureHeaders?: SecureHeadersOptions | boolean;\r\n /** Surveille les réponses : masque les cartes bancaires, clés d'API, etc. */\r\n responseGuard?: ResponseGuardOptions | boolean;\r\n onDeny?: WebGuardOptions[\"onDeny\"];\r\n onDegraded?: WebGuardOptions[\"onDegraded\"];\r\n call?: (event: SvelteEventLike) => ProtectCall | undefined;\r\n}\r\n\r\n/**\r\n * // src/hooks.server.ts\r\n * export const handle = zarexHandle({ key, baseUrl, rules: [shield(), rateLimit({ max: 100, window: \"1m\" })] });\r\n * // ou avec d'autres hooks : export const handle = sequence(zarexHandle({...}), maHandle);\r\n *\r\n * La décision est dans `event.locals.zarex`.\r\n */\r\nexport function zarexHandle(options: SvelteZarexOptions | Zarex, extra: Pick<SvelteZarexOptions, \"inspectBody\" | \"onDeny\" | \"onDegraded\" | \"call\" | \"secureHeaders\" | \"responseGuard\"> = {}) {\r\n const isInstance = typeof (options as Zarex).protect === \"function\";\r\n const opts = (isInstance ? extra : options) as SvelteZarexOptions;\r\n const instance: Zarex = isInstance\r\n ? (options as Zarex)\r\n : createZarex({ ...(options as SvelteZarexOptions), ipSource: (options as SvelteZarexOptions).ipSource ?? \"framework\" });\r\n\r\n const finalizer = createWebFinalizer({ secureHeaders: opts.secureHeaders, responseGuard: opts.responseGuard });\r\n const finalize = async <T>(res: T, request: Request): Promise<T> => {\r\n if (!finalizer || !(res instanceof Response)) return res;\r\n try {\r\n return (await finalizer(res, request)) as T;\r\n } catch {\r\n return res;\r\n }\r\n };\r\n\r\n return async function handle<R>({ event, resolve }: { event: SvelteEventLike; resolve: (event: SvelteEventLike) => R | Promise<R> }): Promise<R | Response> {\r\n try {\r\n let frameworkIp: string | undefined;\r\n try {\r\n frameworkIp = event.getClientAddress(); // lève une erreur si l'adaptateur ne sait pas l'IP\r\n } catch {\r\n frameworkIp = undefined;\r\n }\r\n let call: ProtectCall | undefined;\r\n try {\r\n call = opts.call?.(event);\r\n } catch {\r\n call = undefined;\r\n }\r\n const { decision, deny } = await guardWebRequest(instance, event.request, {\r\n frameworkIp,\r\n ...(opts.inspectBody ? { inspectBody: true } : {}),\r\n ...(opts.onDeny ? { onDeny: opts.onDeny } : {}),\r\n ...(opts.onDegraded ? { onDegraded: opts.onDegraded } : {}),\r\n ...(call ? { call } : {}),\r\n });\r\n if (decision) event.locals[\"zarex\"] = decision;\r\n if (deny) return finalize(deny, event.request);\r\n } catch {\r\n /* fail-open */\r\n }\r\n return finalize(await resolve(event), event.request);\r\n };\r\n}\r\n\r\nexport {\r\n shield,\r\n rateLimit,\r\n tokenBucket,\r\n detectBot,\r\n requestFilter,\r\n sensitiveInfo,\r\n emailValidation,\r\n phoneValidation,\r\n promptInjection,\r\n secureHeaders,\r\n withSecureHeaders,\r\n createZarex,\r\n PRIVATE_NETWORKS,\r\n CLOUDFLARE_RANGES,\r\n} from \"@zarex/core\";\r\nexport type { SecureHeadersOptions, ResponseGuardOptions, ResponseGuardEvent } from \"@zarex/core\";\r\nexport type { Decision, Zarex, ZarexOptions, IpSource, Rule, ProtectCall } from \"@zarex/core\";"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,kBAA6M;AA+E7M,IAAAA,eAeO;AA9DA,SAAS,YAAY,SAAqC,QAAwH,CAAC,GAAG;AAC3L,QAAM,aAAa,OAAQ,QAAkB,YAAY;AACzD,QAAM,OAAQ,aAAa,QAAQ;AACnC,QAAM,WAAkB,aACnB,cACD,yBAAY,EAAE,GAAI,SAAgC,UAAW,QAA+B,YAAY,YAAY,CAAC;AAEzH,QAAM,gBAAY,gCAAmB,EAAE,eAAe,KAAK,eAAe,eAAe,KAAK,cAAc,CAAC;AAC7G,QAAM,WAAW,OAAU,KAAQ,YAAiC;AAClE,QAAI,CAAC,aAAa,EAAE,eAAe,UAAW,QAAO;AACrD,QAAI;AACF,aAAQ,MAAM,UAAU,KAAK,OAAO;AAAA,IACtC,QAAQ;AACN,aAAO;AAAA,IACT;AAAA,EACF;AAEA,SAAO,eAAe,OAAU,EAAE,OAAO,QAAQ,GAA2G;AAC1J,QAAI;AACF,UAAI;AACJ,UAAI;AACF,sBAAc,MAAM,iBAAiB;AAAA,MACvC,QAAQ;AACN,sBAAc;AAAA,MAChB;AACA,UAAI;AACJ,UAAI;AACF,eAAO,KAAK,OAAO,KAAK;AAAA,MAC1B,QAAQ;AACN,eAAO;AAAA,MACT;AACA,YAAM,EAAE,UAAU,KAAK,IAAI,UAAM,6BAAgB,UAAU,MAAM,SAAS;AAAA,QACxE;AAAA,QACA,GAAI,KAAK,cAAc,EAAE,aAAa,KAAK,IAAI,CAAC;AAAA,QAChD,GAAI,KAAK,SAAS,EAAE,QAAQ,KAAK,OAAO,IAAI,CAAC;AAAA,QAC7C,GAAI,KAAK,aAAa,EAAE,YAAY,KAAK,WAAW,IAAI,CAAC;AAAA,QACzD,GAAI,OAAO,EAAE,KAAK,IAAI,CAAC;AAAA,MACzB,CAAC;AACD,UAAI,SAAU,OAAM,OAAO,OAAO,IAAI;AACtC,UAAI,KAAM,QAAO,SAAS,MAAM,MAAM,OAAO;AAAA,IAC/C,QAAQ;AAAA,IAER;AACA,WAAO,SAAS,MAAM,QAAQ,KAAK,GAAG,MAAM,OAAO;AAAA,EACrD;AACF;","names":["import_core"]}
@@ -0,0 +1,37 @@
1
+ import { ZarexOptions, SecureHeadersOptions, ResponseGuardOptions, WebGuardOptions, ProtectCall, Zarex } from '@zarex/core';
2
+ export { CLOUDFLARE_RANGES, Decision, IpSource, PRIVATE_NETWORKS, ProtectCall, ResponseGuardEvent, ResponseGuardOptions, Rule, SecureHeadersOptions, Zarex, ZarexOptions, createZarex, detectBot, emailValidation, phoneValidation, promptInjection, rateLimit, requestFilter, secureHeaders, sensitiveInfo, shield, tokenBucket, withSecureHeaders } from '@zarex/core';
3
+
4
+ /** Ce dont on a besoin de l'évènement SvelteKit (types minimaux : pas de dépendance à @sveltejs/kit). */
5
+ interface SvelteEventLike {
6
+ request: Request;
7
+ getClientAddress(): string;
8
+ locals: Record<string, unknown>;
9
+ }
10
+ interface SvelteZarexOptions extends Omit<ZarexOptions, "ipSource"> {
11
+ /**
12
+ * Défaut : "framework" — l'adresse est celle de `event.getClientAddress()`, que SvelteKit calcule selon
13
+ * la configuration de votre adaptateur (adapter-node : variables ADDRESS_HEADER et XFF_DEPTH ; adapter-vercel, etc.).
14
+ */
15
+ ipSource?: ZarexOptions["ipSource"];
16
+ inspectBody?: boolean;
17
+ /** En-têtes de sécurité ajoutés à chaque réponse (true = défauts prudents). */
18
+ secureHeaders?: SecureHeadersOptions | boolean;
19
+ /** Surveille les réponses : masque les cartes bancaires, clés d'API, etc. */
20
+ responseGuard?: ResponseGuardOptions | boolean;
21
+ onDeny?: WebGuardOptions["onDeny"];
22
+ onDegraded?: WebGuardOptions["onDegraded"];
23
+ call?: (event: SvelteEventLike) => ProtectCall | undefined;
24
+ }
25
+ /**
26
+ * // src/hooks.server.ts
27
+ * export const handle = zarexHandle({ key, baseUrl, rules: [shield(), rateLimit({ max: 100, window: "1m" })] });
28
+ * // ou avec d'autres hooks : export const handle = sequence(zarexHandle({...}), maHandle);
29
+ *
30
+ * La décision est dans `event.locals.zarex`.
31
+ */
32
+ declare function zarexHandle(options: SvelteZarexOptions | Zarex, extra?: Pick<SvelteZarexOptions, "inspectBody" | "onDeny" | "onDegraded" | "call" | "secureHeaders" | "responseGuard">): <R>({ event, resolve }: {
33
+ event: SvelteEventLike;
34
+ resolve: (event: SvelteEventLike) => R | Promise<R>;
35
+ }) => Promise<R | Response>;
36
+
37
+ export { type SvelteEventLike, type SvelteZarexOptions, zarexHandle };
@@ -0,0 +1,37 @@
1
+ import { ZarexOptions, SecureHeadersOptions, ResponseGuardOptions, WebGuardOptions, ProtectCall, Zarex } from '@zarex/core';
2
+ export { CLOUDFLARE_RANGES, Decision, IpSource, PRIVATE_NETWORKS, ProtectCall, ResponseGuardEvent, ResponseGuardOptions, Rule, SecureHeadersOptions, Zarex, ZarexOptions, createZarex, detectBot, emailValidation, phoneValidation, promptInjection, rateLimit, requestFilter, secureHeaders, sensitiveInfo, shield, tokenBucket, withSecureHeaders } from '@zarex/core';
3
+
4
+ /** Ce dont on a besoin de l'évènement SvelteKit (types minimaux : pas de dépendance à @sveltejs/kit). */
5
+ interface SvelteEventLike {
6
+ request: Request;
7
+ getClientAddress(): string;
8
+ locals: Record<string, unknown>;
9
+ }
10
+ interface SvelteZarexOptions extends Omit<ZarexOptions, "ipSource"> {
11
+ /**
12
+ * Défaut : "framework" — l'adresse est celle de `event.getClientAddress()`, que SvelteKit calcule selon
13
+ * la configuration de votre adaptateur (adapter-node : variables ADDRESS_HEADER et XFF_DEPTH ; adapter-vercel, etc.).
14
+ */
15
+ ipSource?: ZarexOptions["ipSource"];
16
+ inspectBody?: boolean;
17
+ /** En-têtes de sécurité ajoutés à chaque réponse (true = défauts prudents). */
18
+ secureHeaders?: SecureHeadersOptions | boolean;
19
+ /** Surveille les réponses : masque les cartes bancaires, clés d'API, etc. */
20
+ responseGuard?: ResponseGuardOptions | boolean;
21
+ onDeny?: WebGuardOptions["onDeny"];
22
+ onDegraded?: WebGuardOptions["onDegraded"];
23
+ call?: (event: SvelteEventLike) => ProtectCall | undefined;
24
+ }
25
+ /**
26
+ * // src/hooks.server.ts
27
+ * export const handle = zarexHandle({ key, baseUrl, rules: [shield(), rateLimit({ max: 100, window: "1m" })] });
28
+ * // ou avec d'autres hooks : export const handle = sequence(zarexHandle({...}), maHandle);
29
+ *
30
+ * La décision est dans `event.locals.zarex`.
31
+ */
32
+ declare function zarexHandle(options: SvelteZarexOptions | Zarex, extra?: Pick<SvelteZarexOptions, "inspectBody" | "onDeny" | "onDegraded" | "call" | "secureHeaders" | "responseGuard">): <R>({ event, resolve }: {
33
+ event: SvelteEventLike;
34
+ resolve: (event: SvelteEventLike) => R | Promise<R>;
35
+ }) => Promise<R | Response>;
36
+
37
+ export { type SvelteEventLike, type SvelteZarexOptions, zarexHandle };
package/dist/index.js ADDED
@@ -0,0 +1,77 @@
1
+ // src/index.ts
2
+ import { createWebFinalizer, createZarex, guardWebRequest } from "@zarex/core";
3
+ import {
4
+ shield,
5
+ rateLimit,
6
+ tokenBucket,
7
+ detectBot,
8
+ requestFilter,
9
+ sensitiveInfo,
10
+ emailValidation,
11
+ phoneValidation,
12
+ promptInjection,
13
+ secureHeaders,
14
+ withSecureHeaders,
15
+ createZarex as createZarex2,
16
+ PRIVATE_NETWORKS,
17
+ CLOUDFLARE_RANGES
18
+ } from "@zarex/core";
19
+ function zarexHandle(options, extra = {}) {
20
+ const isInstance = typeof options.protect === "function";
21
+ const opts = isInstance ? extra : options;
22
+ const instance = isInstance ? options : createZarex({ ...options, ipSource: options.ipSource ?? "framework" });
23
+ const finalizer = createWebFinalizer({ secureHeaders: opts.secureHeaders, responseGuard: opts.responseGuard });
24
+ const finalize = async (res, request) => {
25
+ if (!finalizer || !(res instanceof Response)) return res;
26
+ try {
27
+ return await finalizer(res, request);
28
+ } catch {
29
+ return res;
30
+ }
31
+ };
32
+ return async function handle({ event, resolve }) {
33
+ try {
34
+ let frameworkIp;
35
+ try {
36
+ frameworkIp = event.getClientAddress();
37
+ } catch {
38
+ frameworkIp = void 0;
39
+ }
40
+ let call;
41
+ try {
42
+ call = opts.call?.(event);
43
+ } catch {
44
+ call = void 0;
45
+ }
46
+ const { decision, deny } = await guardWebRequest(instance, event.request, {
47
+ frameworkIp,
48
+ ...opts.inspectBody ? { inspectBody: true } : {},
49
+ ...opts.onDeny ? { onDeny: opts.onDeny } : {},
50
+ ...opts.onDegraded ? { onDegraded: opts.onDegraded } : {},
51
+ ...call ? { call } : {}
52
+ });
53
+ if (decision) event.locals["zarex"] = decision;
54
+ if (deny) return finalize(deny, event.request);
55
+ } catch {
56
+ }
57
+ return finalize(await resolve(event), event.request);
58
+ };
59
+ }
60
+ export {
61
+ CLOUDFLARE_RANGES,
62
+ PRIVATE_NETWORKS,
63
+ createZarex2 as createZarex,
64
+ detectBot,
65
+ emailValidation,
66
+ phoneValidation,
67
+ promptInjection,
68
+ rateLimit,
69
+ requestFilter,
70
+ secureHeaders,
71
+ sensitiveInfo,
72
+ shield,
73
+ tokenBucket,
74
+ withSecureHeaders,
75
+ zarexHandle
76
+ };
77
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import { createWebFinalizer, createZarex, guardWebRequest, type ResponseGuardOptions, type SecureHeadersOptions, type Decision, type ProtectCall, type WebGuardOptions, type Zarex, type ZarexOptions } from \"@zarex/core\";\r\n\r\n/** Ce dont on a besoin de l'évènement SvelteKit (types minimaux : pas de dépendance à @sveltejs/kit). */\r\nexport interface SvelteEventLike {\r\n request: Request;\r\n getClientAddress(): string;\r\n locals: Record<string, unknown>;\r\n}\r\n\r\nexport interface SvelteZarexOptions extends Omit<ZarexOptions, \"ipSource\"> {\r\n /**\r\n * Défaut : \"framework\" — l'adresse est celle de `event.getClientAddress()`, que SvelteKit calcule selon\r\n * la configuration de votre adaptateur (adapter-node : variables ADDRESS_HEADER et XFF_DEPTH ; adapter-vercel, etc.).\r\n */\r\n ipSource?: ZarexOptions[\"ipSource\"];\r\n inspectBody?: boolean;\r\n /** En-têtes de sécurité ajoutés à chaque réponse (true = défauts prudents). */\r\n secureHeaders?: SecureHeadersOptions | boolean;\r\n /** Surveille les réponses : masque les cartes bancaires, clés d'API, etc. */\r\n responseGuard?: ResponseGuardOptions | boolean;\r\n onDeny?: WebGuardOptions[\"onDeny\"];\r\n onDegraded?: WebGuardOptions[\"onDegraded\"];\r\n call?: (event: SvelteEventLike) => ProtectCall | undefined;\r\n}\r\n\r\n/**\r\n * // src/hooks.server.ts\r\n * export const handle = zarexHandle({ key, baseUrl, rules: [shield(), rateLimit({ max: 100, window: \"1m\" })] });\r\n * // ou avec d'autres hooks : export const handle = sequence(zarexHandle({...}), maHandle);\r\n *\r\n * La décision est dans `event.locals.zarex`.\r\n */\r\nexport function zarexHandle(options: SvelteZarexOptions | Zarex, extra: Pick<SvelteZarexOptions, \"inspectBody\" | \"onDeny\" | \"onDegraded\" | \"call\" | \"secureHeaders\" | \"responseGuard\"> = {}) {\r\n const isInstance = typeof (options as Zarex).protect === \"function\";\r\n const opts = (isInstance ? extra : options) as SvelteZarexOptions;\r\n const instance: Zarex = isInstance\r\n ? (options as Zarex)\r\n : createZarex({ ...(options as SvelteZarexOptions), ipSource: (options as SvelteZarexOptions).ipSource ?? \"framework\" });\r\n\r\n const finalizer = createWebFinalizer({ secureHeaders: opts.secureHeaders, responseGuard: opts.responseGuard });\r\n const finalize = async <T>(res: T, request: Request): Promise<T> => {\r\n if (!finalizer || !(res instanceof Response)) return res;\r\n try {\r\n return (await finalizer(res, request)) as T;\r\n } catch {\r\n return res;\r\n }\r\n };\r\n\r\n return async function handle<R>({ event, resolve }: { event: SvelteEventLike; resolve: (event: SvelteEventLike) => R | Promise<R> }): Promise<R | Response> {\r\n try {\r\n let frameworkIp: string | undefined;\r\n try {\r\n frameworkIp = event.getClientAddress(); // lève une erreur si l'adaptateur ne sait pas l'IP\r\n } catch {\r\n frameworkIp = undefined;\r\n }\r\n let call: ProtectCall | undefined;\r\n try {\r\n call = opts.call?.(event);\r\n } catch {\r\n call = undefined;\r\n }\r\n const { decision, deny } = await guardWebRequest(instance, event.request, {\r\n frameworkIp,\r\n ...(opts.inspectBody ? { inspectBody: true } : {}),\r\n ...(opts.onDeny ? { onDeny: opts.onDeny } : {}),\r\n ...(opts.onDegraded ? { onDegraded: opts.onDegraded } : {}),\r\n ...(call ? { call } : {}),\r\n });\r\n if (decision) event.locals[\"zarex\"] = decision;\r\n if (deny) return finalize(deny, event.request);\r\n } catch {\r\n /* fail-open */\r\n }\r\n return finalize(await resolve(event), event.request);\r\n };\r\n}\r\n\r\nexport {\r\n shield,\r\n rateLimit,\r\n tokenBucket,\r\n detectBot,\r\n requestFilter,\r\n sensitiveInfo,\r\n emailValidation,\r\n phoneValidation,\r\n promptInjection,\r\n secureHeaders,\r\n withSecureHeaders,\r\n createZarex,\r\n PRIVATE_NETWORKS,\r\n CLOUDFLARE_RANGES,\r\n} from \"@zarex/core\";\r\nexport type { SecureHeadersOptions, ResponseGuardOptions, ResponseGuardEvent } from \"@zarex/core\";\r\nexport type { Decision, Zarex, ZarexOptions, IpSource, Rule, ProtectCall } from \"@zarex/core\";"],"mappings":";AAAA,SAAS,oBAAoB,aAAa,uBAAmK;AA+E7M;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,eAAAA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AA9DA,SAAS,YAAY,SAAqC,QAAwH,CAAC,GAAG;AAC3L,QAAM,aAAa,OAAQ,QAAkB,YAAY;AACzD,QAAM,OAAQ,aAAa,QAAQ;AACnC,QAAM,WAAkB,aACnB,UACD,YAAY,EAAE,GAAI,SAAgC,UAAW,QAA+B,YAAY,YAAY,CAAC;AAEzH,QAAM,YAAY,mBAAmB,EAAE,eAAe,KAAK,eAAe,eAAe,KAAK,cAAc,CAAC;AAC7G,QAAM,WAAW,OAAU,KAAQ,YAAiC;AAClE,QAAI,CAAC,aAAa,EAAE,eAAe,UAAW,QAAO;AACrD,QAAI;AACF,aAAQ,MAAM,UAAU,KAAK,OAAO;AAAA,IACtC,QAAQ;AACN,aAAO;AAAA,IACT;AAAA,EACF;AAEA,SAAO,eAAe,OAAU,EAAE,OAAO,QAAQ,GAA2G;AAC1J,QAAI;AACF,UAAI;AACJ,UAAI;AACF,sBAAc,MAAM,iBAAiB;AAAA,MACvC,QAAQ;AACN,sBAAc;AAAA,MAChB;AACA,UAAI;AACJ,UAAI;AACF,eAAO,KAAK,OAAO,KAAK;AAAA,MAC1B,QAAQ;AACN,eAAO;AAAA,MACT;AACA,YAAM,EAAE,UAAU,KAAK,IAAI,MAAM,gBAAgB,UAAU,MAAM,SAAS;AAAA,QACxE;AAAA,QACA,GAAI,KAAK,cAAc,EAAE,aAAa,KAAK,IAAI,CAAC;AAAA,QAChD,GAAI,KAAK,SAAS,EAAE,QAAQ,KAAK,OAAO,IAAI,CAAC;AAAA,QAC7C,GAAI,KAAK,aAAa,EAAE,YAAY,KAAK,WAAW,IAAI,CAAC;AAAA,QACzD,GAAI,OAAO,EAAE,KAAK,IAAI,CAAC;AAAA,MACzB,CAAC;AACD,UAAI,SAAU,OAAM,OAAO,OAAO,IAAI;AACtC,UAAI,KAAM,QAAO,SAAS,MAAM,MAAM,OAAO;AAAA,IAC/C,QAAQ;AAAA,IAER;AACA,WAAO,SAAS,MAAM,QAAQ,KAAK,GAAG,MAAM,OAAO;AAAA,EACrD;AACF;","names":["createZarex"]}
package/package.json CHANGED
@@ -1,6 +1,43 @@
1
1
  {
2
2
  "name": "@zarex/sveltekit",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.1",
4
+ "description": "Zarex — SvelteKit (hook handle)",
5
+ "license": "MIT",
6
+ "publishConfig": {
7
+ "access": "public"
8
+ },
9
+ "type": "module",
10
+ "main": "./dist/index.cjs",
11
+ "module": "./dist/index.js",
12
+ "types": "./dist/index.d.ts",
13
+ "exports": {
14
+ ".": {
15
+ "import": {
16
+ "types": "./dist/index.d.ts",
17
+ "default": "./dist/index.js"
18
+ },
19
+ "require": {
20
+ "types": "./dist/index.d.cts",
21
+ "default": "./dist/index.cjs"
22
+ }
23
+ }
24
+ },
25
+ "files": [
26
+ "dist"
27
+ ],
28
+ "sideEffects": false,
29
+ "dependencies": {
30
+ "@zarex/core": "^0.1.1"
31
+ },
32
+ "peerDependencies": {
33
+ "@sveltejs/kit": ">=1"
34
+ },
35
+ "peerDependenciesMeta": {
36
+ "@sveltejs/kit": {
37
+ "optional": true
38
+ }
39
+ },
40
+ "scripts": {
41
+ "build": "tsup"
42
+ }
6
43
  }