@bemedev/react-guardian 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.
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Encrypts an access code with AES-GCM.
3
+ *
4
+ * @param code - Code to encrypt.
5
+ *
6
+ * @returns The Base64 encoded initialization vector followed by the encrypted code.
7
+ */
8
+ export declare function encryptCode(code: string): Promise<string>;
9
+ /**
10
+ * Decrypts an access code encrypted by {@linkcode encryptCode}.
11
+ *
12
+ * @param value - Encrypted value read from `sessionStorage`.
13
+ *
14
+ * @returns The decrypted code, or `null` when the value cannot be decrypted.
15
+ */
16
+ export declare function decryptCode(value: string): Promise<string | null>;
17
+ //# sourceMappingURL=crypto.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"crypto.d.ts","names":[],"sources":["../src/crypto.ts"],"mappings":";;;;;;;wBA6EsB,YAAY,eAAe;;;;;;;;wBAwB3B,YAAY,gBAAgB"}
package/lib/crypto.js ADDED
@@ -0,0 +1,97 @@
1
+ import { ENCRYPTION_ALGORITHM, ENCRYPTION_SECRET } from "./constants.js";
2
+ // src/crypto.ts
3
+ /** Cached AES-GCM key derived from {@linkcode ENCRYPTION_SECRET}. */
4
+ let encryptionKey;
5
+ /**
6
+ * Returns the Web Crypto implementation.
7
+ *
8
+ * @returns The Web Crypto implementation.
9
+ *
10
+ * @throws {Error} When Web Crypto is not available in the current context.
11
+ */
12
+ function getCrypto() {
13
+ if (!globalThis.crypto?.subtle) throw new Error("[react-guardian] Web Crypto is required to encrypt the session code.");
14
+ return globalThis.crypto;
15
+ }
16
+ /**
17
+ * Derives and caches the AES-GCM key used to encrypt the session code.
18
+ *
19
+ * @returns The AES-GCM key.
20
+ */
21
+ function getEncryptionKey() {
22
+ encryptionKey ??= (async () => {
23
+ const secret = new TextEncoder().encode(ENCRYPTION_SECRET);
24
+ const digest = await getCrypto().subtle.digest("SHA-256", secret);
25
+ return getCrypto().subtle.importKey("raw", digest, { name: ENCRYPTION_ALGORITHM }, false, ["encrypt", "decrypt"]);
26
+ })();
27
+ return encryptionKey;
28
+ }
29
+ /**
30
+ * Encodes bytes as a Base64 string.
31
+ *
32
+ * @param bytes - Bytes to encode.
33
+ *
34
+ * @returns The Base64 encoded string.
35
+ */
36
+ function bytesToBase64(bytes) {
37
+ let binary = "";
38
+ for (const byte of bytes) binary += String.fromCharCode(byte);
39
+ return btoa(binary);
40
+ }
41
+ /**
42
+ * Decodes a Base64 string into bytes.
43
+ *
44
+ * @param value - Base64 encoded string.
45
+ *
46
+ * @returns The decoded bytes.
47
+ */
48
+ function base64ToBytes(value) {
49
+ return Uint8Array.from(atob(value), (char) => char.charCodeAt(0));
50
+ }
51
+ /**
52
+ * Encrypts an access code with AES-GCM.
53
+ *
54
+ * @param code - Code to encrypt.
55
+ *
56
+ * @returns The Base64 encoded initialization vector followed by the encrypted code.
57
+ */
58
+ async function encryptCode(code) {
59
+ const crypto = getCrypto();
60
+ const key = await getEncryptionKey();
61
+ const iv = crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(12));
62
+ const encrypted = await crypto.subtle.encrypt({
63
+ name: ENCRYPTION_ALGORITHM,
64
+ iv
65
+ }, key, new TextEncoder().encode(code));
66
+ const bytes = new Uint8Array(iv.length + encrypted.byteLength);
67
+ bytes.set(iv);
68
+ bytes.set(new Uint8Array(encrypted), iv.length);
69
+ return bytesToBase64(bytes);
70
+ }
71
+ /**
72
+ * Decrypts an access code encrypted by {@linkcode encryptCode}.
73
+ *
74
+ * @param value - Encrypted value read from `sessionStorage`.
75
+ *
76
+ * @returns The decrypted code, or `null` when the value cannot be decrypted.
77
+ */
78
+ async function decryptCode(value) {
79
+ try {
80
+ const crypto = getCrypto();
81
+ const bytes = base64ToBytes(value);
82
+ if (bytes.length <= 12) return null;
83
+ const iv = bytes.slice(0, 12);
84
+ const encrypted = bytes.slice(12);
85
+ const key = await getEncryptionKey();
86
+ const decrypted = await crypto.subtle.decrypt({
87
+ name: ENCRYPTION_ALGORITHM,
88
+ iv
89
+ }, key, encrypted);
90
+ return new TextDecoder().decode(decrypted);
91
+ } catch {
92
+ return null;
93
+ }
94
+ }
95
+ export { decryptCode, encryptCode };
96
+
97
+ //# sourceMappingURL=crypto.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"crypto.js","names":[],"sources":["../src/crypto.ts"],"sourcesContent":["import { ENCRYPTION_ALGORITHM, ENCRYPTION_SECRET, IV_LENGTH } from './constants';\n\n/** Cached AES-GCM key derived from {@linkcode ENCRYPTION_SECRET}. */\nlet encryptionKey: Promise<CryptoKey> | undefined;\n\n/**\n * Returns the Web Crypto implementation.\n *\n * @returns The Web Crypto implementation.\n *\n * @throws {Error} When Web Crypto is not available in the current context.\n */\nfunction getCrypto(): Crypto {\n if (!globalThis.crypto?.subtle) {\n throw new Error(\n '[react-guardian] Web Crypto is required to encrypt the session code.',\n );\n }\n\n return globalThis.crypto;\n}\n\n/**\n * Derives and caches the AES-GCM key used to encrypt the session code.\n *\n * @returns The AES-GCM key.\n */\nfunction getEncryptionKey(): Promise<CryptoKey> {\n encryptionKey ??= (async () => {\n const secret = new TextEncoder().encode(ENCRYPTION_SECRET);\n const digest = await getCrypto().subtle.digest('SHA-256', secret);\n\n return getCrypto().subtle.importKey(\n 'raw',\n digest,\n { name: ENCRYPTION_ALGORITHM },\n false,\n ['encrypt', 'decrypt'],\n );\n })();\n\n return encryptionKey;\n}\n\n/**\n * Encodes bytes as a Base64 string.\n *\n * @param bytes - Bytes to encode.\n *\n * @returns The Base64 encoded string.\n */\nfunction bytesToBase64(bytes: Uint8Array): string {\n let binary = '';\n\n for (const byte of bytes) binary += String.fromCharCode(byte);\n\n return btoa(binary);\n}\n\n/**\n * Decodes a Base64 string into bytes.\n *\n * @param value - Base64 encoded string.\n *\n * @returns The decoded bytes.\n */\nfunction base64ToBytes(value: string): Uint8Array {\n return Uint8Array.from(atob(value), char => char.charCodeAt(0));\n}\n\n/**\n * Encrypts an access code with AES-GCM.\n *\n * @param code - Code to encrypt.\n *\n * @returns The Base64 encoded initialization vector followed by the encrypted code.\n */\nexport async function encryptCode(code: string): Promise<string> {\n const crypto = getCrypto();\n const key = await getEncryptionKey();\n const iv = crypto.getRandomValues(new Uint8Array(IV_LENGTH));\n const encrypted = await crypto.subtle.encrypt(\n { name: ENCRYPTION_ALGORITHM, iv },\n key,\n new TextEncoder().encode(code),\n );\n\n const bytes = new Uint8Array(iv.length + encrypted.byteLength);\n bytes.set(iv);\n bytes.set(new Uint8Array(encrypted), iv.length);\n\n return bytesToBase64(bytes);\n}\n\n/**\n * Decrypts an access code encrypted by {@linkcode encryptCode}.\n *\n * @param value - Encrypted value read from `sessionStorage`.\n *\n * @returns The decrypted code, or `null` when the value cannot be decrypted.\n */\nexport async function decryptCode(value: string): Promise<string | null> {\n try {\n const crypto = getCrypto();\n const bytes = base64ToBytes(value);\n\n if (bytes.length <= IV_LENGTH) return null;\n\n const iv = bytes.slice(0, IV_LENGTH);\n const encrypted = bytes.slice(IV_LENGTH);\n const key = await getEncryptionKey();\n const decrypted = await crypto.subtle.decrypt(\n { name: ENCRYPTION_ALGORITHM, iv },\n key,\n encrypted,\n );\n\n return new TextDecoder().decode(decrypted);\n } catch {\n return null;\n }\n}\n"],"mappings":";;;AAGA,IAAI;;;;;;;;AASJ,SAAS,YAAoB;CAC3B,IAAI,CAAC,WAAW,QAAQ,QACtB,MAAM,IAAI,MACR,sEACF;CAGF,OAAO,WAAW;AACpB;;;;;;AAOA,SAAS,mBAAuC;CAC9C,mBAAmB,YAAY;EAC7B,MAAM,SAAS,IAAI,YAAY,CAAC,CAAC,OAAO,iBAAiB;EACzD,MAAM,SAAS,MAAM,UAAU,CAAC,CAAC,OAAO,OAAO,WAAW,MAAM;EAEhE,OAAO,UAAU,CAAC,CAAC,OAAO,UACxB,OACA,QACA,EAAE,MAAM,qBAAqB,GAC7B,OACA,CAAC,WAAW,SAAS,CACvB;CACF,EAAA,CAAG;CAEH,OAAO;AACT;;;;;;;;AASA,SAAS,cAAc,OAA2B;CAChD,IAAI,SAAS;CAEb,KAAK,MAAM,QAAQ,OAAO,UAAU,OAAO,aAAa,IAAI;CAE5D,OAAO,KAAK,MAAM;AACpB;;;;;;;;AASA,SAAS,cAAc,OAA2B;CAChD,OAAO,WAAW,KAAK,KAAK,KAAK,IAAG,SAAQ,KAAK,WAAW,CAAC,CAAC;AAChE;;;;;;;;AASA,eAAsB,YAAY,MAA+B;CAC/D,MAAM,SAAS,UAAU;CACzB,MAAM,MAAM,MAAM,iBAAiB;CACnC,MAAM,KAAK,OAAO,gCAAgB,IAAI,WAAA,EAAoB,CAAC;CAC3D,MAAM,YAAY,MAAM,OAAO,OAAO,QACpC;EAAE,MAAM;EAAsB;CAAG,GACjC,KACA,IAAI,YAAY,CAAC,CAAC,OAAO,IAAI,CAC/B;CAEA,MAAM,QAAQ,IAAI,WAAW,GAAG,SAAS,UAAU,UAAU;CAC7D,MAAM,IAAI,EAAE;CACZ,MAAM,IAAI,IAAI,WAAW,SAAS,GAAG,GAAG,MAAM;CAE9C,OAAO,cAAc,KAAK;AAC5B;;;;;;;;AASA,eAAsB,YAAY,OAAuC;CACvE,IAAI;EACF,MAAM,SAAS,UAAU;EACzB,MAAM,QAAQ,cAAc,KAAK;EAEjC,IAAI,MAAM,UAAA,IAAqB,OAAO;EAEtC,MAAM,KAAK,MAAM,MAAM,GAAA,EAAY;EACnC,MAAM,YAAY,MAAM,MAAA,EAAe;EACvC,MAAM,MAAM,MAAM,iBAAiB;EACnC,MAAM,YAAY,MAAM,OAAO,OAAO,QACpC;GAAE,MAAM;GAAsB;EAAG,GACjC,KACA,SACF;EAEA,OAAO,IAAI,YAAY,CAAC,CAAC,OAAO,SAAS;CAC3C,QAAQ;EACN,OAAO;CACT;AACF"}
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Options accepted by {@linkcode disconnect}.
3
+ */
4
+ export type DisconnectOptions = {
5
+ /**
6
+ * Page to open after disconnection.
7
+ *
8
+ * When omitted, the visitor stays on the current page.
9
+ */
10
+ redirectTo?: string;
11
+ /**
12
+ * Navigation implementation.
13
+ *
14
+ * Defaults to `window.location.replace`.
15
+ */
16
+ navigate?: (href: string) => void;
17
+ };
18
+ /**
19
+ * Disconnects the visitor by removing the access code from `sessionStorage`.
20
+ *
21
+ * @param options - Disconnection options.
22
+ *
23
+ * @see -- type {@linkcode DisconnectOptions}
24
+ */
25
+ export declare function disconnect(options?: DisconnectOptions): void;
26
+ //# sourceMappingURL=disconnect.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"disconnect.d.ts","names":[],"sources":["../src/disconnect.ts"],"mappings":";;;YAMY;;;;;;EAMV;;;;;;EAOA,YAAY;;;;;;;;;wBAUE,WAAW,UAAS"}
@@ -0,0 +1,18 @@
1
+ import { defaultNavigate } from "./browser.js";
2
+ import { clearCode } from "./session.js";
3
+ // src/disconnect.ts
4
+ /**
5
+ * Disconnects the visitor by removing the access code from `sessionStorage`.
6
+ *
7
+ * @param options - Disconnection options.
8
+ *
9
+ * @see -- type {@linkcode DisconnectOptions}
10
+ */
11
+ function disconnect(options = {}) {
12
+ clearCode();
13
+ if (!options.redirectTo) return;
14
+ (options.navigate ?? defaultNavigate)(options.redirectTo);
15
+ }
16
+ export { disconnect };
17
+
18
+ //# sourceMappingURL=disconnect.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"disconnect.js","names":[],"sources":["../src/disconnect.ts"],"sourcesContent":["import { defaultNavigate } from './browser';\nimport { clearCode } from './session';\n\n/**\n * Options accepted by {@linkcode disconnect}.\n */\nexport type DisconnectOptions = {\n /**\n * Page to open after disconnection.\n *\n * When omitted, the visitor stays on the current page.\n */\n redirectTo?: string;\n\n /**\n * Navigation implementation.\n *\n * Defaults to `window.location.replace`.\n */\n navigate?: (href: string) => void;\n};\n\n/**\n * Disconnects the visitor by removing the access code from `sessionStorage`.\n *\n * @param options - Disconnection options.\n *\n * @see -- type {@linkcode DisconnectOptions}\n */\nexport function disconnect(options: DisconnectOptions = {}): void {\n clearCode();\n\n if (!options.redirectTo) return;\n\n const navigate = options.navigate ?? defaultNavigate;\n\n navigate(options.redirectTo);\n}\n"],"mappings":";;;;;;;;;;AA6BA,SAAgB,WAAW,UAA6B,CAAC,GAAS;CAChE,UAAU;CAEV,IAAI,CAAC,QAAQ,YAAY;CAIzB,CAFiB,QAAQ,YAAY,gBAAA,CAE5B,QAAQ,UAAU;AAC7B"}
package/lib/env.d.ts ADDED
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Reads an environment variable from the Node.js runtime first, then from the
3
+ * bundler-provided `import.meta.env` object.
4
+ *
5
+ * The Node.js runtime is authoritative on the server, while `import.meta.env` is the
6
+ * only source available in a Vite client bundle.
7
+ *
8
+ * @param name - Name of the environment variable to read.
9
+ *
10
+ * @returns The environment variable value, or `undefined` when it is not defined.
11
+ */
12
+ export declare function readEnv(name: string): string | undefined;
13
+ //# sourceMappingURL=env.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"env.d.ts","names":[],"sources":["../src/env.ts"],"mappings":";;;;;;;;;;;wBAcgB,QAAQ"}
package/lib/env.js ADDED
@@ -0,0 +1,20 @@
1
+ // src/env.ts
2
+ /**
3
+ * Reads an environment variable from the Node.js runtime first, then from the
4
+ * bundler-provided `import.meta.env` object.
5
+ *
6
+ * The Node.js runtime is authoritative on the server, while `import.meta.env` is the
7
+ * only source available in a Vite client bundle.
8
+ *
9
+ * @param name - Name of the environment variable to read.
10
+ *
11
+ * @returns The environment variable value, or `undefined` when it is not defined.
12
+ */
13
+ function readEnv(name) {
14
+ const processEnv = globalThis.process?.env;
15
+ const viteEnv = import.meta.env;
16
+ return processEnv?.[name] ?? viteEnv?.[name];
17
+ }
18
+ export { readEnv };
19
+
20
+ //# sourceMappingURL=env.js.map
package/lib/env.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"env.js","names":[],"sources":["../src/env.ts"],"sourcesContent":["/** A simple record of environment variables. */\ntype EnvRecord = Record<string, string | undefined>;\n\n/**\n * Reads an environment variable from the Node.js runtime first, then from the\n * bundler-provided `import.meta.env` object.\n *\n * The Node.js runtime is authoritative on the server, while `import.meta.env` is the\n * only source available in a Vite client bundle.\n *\n * @param name - Name of the environment variable to read.\n *\n * @returns The environment variable value, or `undefined` when it is not defined.\n */\nexport function readEnv(name: string): string | undefined {\n const processEnv = (\n globalThis as typeof globalThis & { process?: { env?: EnvRecord } }\n ).process?.env;\n\n const viteEnv = (import.meta as ImportMeta & { env?: EnvRecord }).env;\n\n return processEnv?.[name] ?? viteEnv?.[name];\n}\n"],"mappings":";;;;;;;;;;;;AAcA,SAAgB,QAAQ,MAAkC;CACxD,MAAM,aACJ,WACA,SAAS;CAEX,MAAM,UAAW,YAAiD;CAElE,OAAO,aAAa,SAAS,UAAU;AACzC"}
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Headless guard for TanStack Start applications.
3
+ *
4
+ * Verifies the access code stored in `sessionStorage` against the server-only
5
+ * `BEMEDEV_CODE_ENV` environment variable. When the code is missing or invalid, the
6
+ * guard clears the session and throws a redirect to the connexion page identified by
7
+ * `to`, carrying the current URL in the `redirect` query parameter. When the code is
8
+ * valid, the guard returns and the requested page renders.
9
+ *
10
+ * `sessionStorage` only exists in the browser, so the guard must run client-side. It
11
+ * returns early during server rendering; protect server data with your own server
12
+ * checks as well.
13
+ *
14
+ * ```tsx
15
+ * export const Route = createFileRoute('/')({
16
+ * beforeLoad: () => reactGuardian('/connexion'),
17
+ * });
18
+ * ```
19
+ *
20
+ * @param to - Route or absolute URL of the connexion page used when the visitor is not
21
+ * connected.
22
+ *
23
+ * @throws A TanStack Router redirect to `to` when the access code is missing or
24
+ * invalid.
25
+ */
26
+ export declare function reactGuardian(to: string): Promise<void>;
27
+ //# sourceMappingURL=guardian.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"guardian.d.ts","names":[],"sources":["../src/guardian.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;wBA+BsB,cAAc,aAAa"}
@@ -0,0 +1,42 @@
1
+ import { redirect } from "@tanstack/react-router";
2
+ import { REDIRECT_PARAM } from "./constants.js";
3
+ import { clearCode, getCode } from "./session.js";
4
+ import { verifyCode } from "./verify.js";
5
+ // src/guardian.ts
6
+ /**
7
+ * Headless guard for TanStack Start applications.
8
+ *
9
+ * Verifies the access code stored in `sessionStorage` against the server-only
10
+ * `BEMEDEV_CODE_ENV` environment variable. When the code is missing or invalid, the
11
+ * guard clears the session and throws a redirect to the connexion page identified by
12
+ * `to`, carrying the current URL in the `redirect` query parameter. When the code is
13
+ * valid, the guard returns and the requested page renders.
14
+ *
15
+ * `sessionStorage` only exists in the browser, so the guard must run client-side. It
16
+ * returns early during server rendering; protect server data with your own server
17
+ * checks as well.
18
+ *
19
+ * ```tsx
20
+ * export const Route = createFileRoute('/')({
21
+ * beforeLoad: () => reactGuardian('/connexion'),
22
+ * });
23
+ * ```
24
+ *
25
+ * @param to - Route or absolute URL of the connexion page used when the visitor is not
26
+ * connected.
27
+ *
28
+ * @throws A TanStack Router redirect to `to` when the access code is missing or
29
+ * invalid.
30
+ */
31
+ async function reactGuardian(to) {
32
+ if (typeof window === "undefined") return;
33
+ const code = await getCode();
34
+ if (!!code && await verifyCode({ data: code })) return;
35
+ clearCode();
36
+ const connexion = new URL(to, window.location.origin);
37
+ if (!connexion.searchParams.has("redirect")) connexion.searchParams.set(REDIRECT_PARAM, window.location.href);
38
+ throw redirect({ href: connexion.toString() });
39
+ }
40
+ export { reactGuardian };
41
+
42
+ //# sourceMappingURL=guardian.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"guardian.js","names":[],"sources":["../src/guardian.ts"],"sourcesContent":["import { redirect } from '@tanstack/react-router';\n\nimport { REDIRECT_PARAM } from './constants';\nimport { clearCode, getCode } from './session';\nimport { verifyCode } from './verify';\n\n/**\n * Headless guard for TanStack Start applications.\n *\n * Verifies the access code stored in `sessionStorage` against the server-only\n * `BEMEDEV_CODE_ENV` environment variable. When the code is missing or invalid, the\n * guard clears the session and throws a redirect to the connexion page identified by\n * `to`, carrying the current URL in the `redirect` query parameter. When the code is\n * valid, the guard returns and the requested page renders.\n *\n * `sessionStorage` only exists in the browser, so the guard must run client-side. It\n * returns early during server rendering; protect server data with your own server\n * checks as well.\n *\n * ```tsx\n * export const Route = createFileRoute('/')({\n * beforeLoad: () => reactGuardian('/connexion'),\n * });\n * ```\n *\n * @param to - Route or absolute URL of the connexion page used when the visitor is not\n * connected.\n *\n * @throws A TanStack Router redirect to `to` when the access code is missing or\n * invalid.\n */\nexport async function reactGuardian(to: string): Promise<void> {\n if (typeof window === 'undefined') return;\n\n const code = await getCode();\n const valid = !!code && (await verifyCode({ data: code }));\n\n if (valid) return;\n\n clearCode();\n\n const connexion = new URL(to, window.location.origin);\n if (!connexion.searchParams.has(REDIRECT_PARAM)) {\n connexion.searchParams.set(REDIRECT_PARAM, window.location.href);\n }\n\n throw redirect({ href: connexion.toString() });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,eAAsB,cAAc,IAA2B;CAC7D,IAAI,OAAO,WAAW,aAAa;CAEnC,MAAM,OAAO,MAAM,QAAQ;CAG3B,IAFc,CAAC,CAAC,QAAS,MAAM,WAAW,EAAE,MAAM,KAAK,CAAC,GAE7C;CAEX,UAAU;CAEV,MAAM,YAAY,IAAI,IAAI,IAAI,OAAO,SAAS,MAAM;CACpD,IAAI,CAAC,UAAU,aAAa,IAAA,UAAkB,GAC5C,UAAU,aAAa,IAAI,gBAAgB,OAAO,SAAS,IAAI;CAGjE,MAAM,SAAS,EAAE,MAAM,UAAU,SAAS,EAAE,CAAC;AAC/C"}
package/lib/index.d.ts ADDED
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Public entry point of `@bemedev/react-guardian`.
3
+ *
4
+ * Re-exports the route guard, the connection helpers, the disconnection helper and the
5
+ * session utilities.
6
+ */
7
+ import { n as connect, t as ConnectOptions } from "./connect-Dc_Y4PVe.js";
8
+ import { DisconnectOptions, disconnect } from "./disconnect.js";
9
+ import { reactGuardian } from "./guardian.js";
10
+ import { clearCode, getCode, isConnected, setCode } from "./session.js";
11
+ export { type ConnectOptions, type DisconnectOptions, clearCode, connect, disconnect, getCode, isConnected, reactGuardian, setCode };
package/lib/index.js ADDED
@@ -0,0 +1,5 @@
1
+ import { t as connect } from "./connect-Bw2GVANX.js";
2
+ import { disconnect } from "./disconnect.js";
3
+ import { reactGuardian } from "./guardian.js";
4
+ import { clearCode, getCode, isConnected, setCode } from "./session.js";
5
+ export { clearCode, connect, disconnect, getCode, isConnected, reactGuardian, setCode };
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Returns the access code stored in `sessionStorage`.
3
+ *
4
+ * The stored value is AES-GCM encrypted; it is decrypted before being returned.
5
+ *
6
+ * @returns The decrypted code, or `null` when the visitor is not connected, session
7
+ * storage is not available, or the stored value cannot be decrypted.
8
+ */
9
+ export declare function getCode(): Promise<string | null>;
10
+ /**
11
+ * Tells whether an access code is stored in `sessionStorage`.
12
+ *
13
+ * This is a client-side check. It does not verify the code on the server; use
14
+ * `reactGuardian` for the full verification.
15
+ *
16
+ * @returns `true` when a code is stored, `false` otherwise.
17
+ */
18
+ export declare function isConnected(): Promise<boolean>;
19
+ /**
20
+ * Stores an access code in `sessionStorage`.
21
+ *
22
+ * The code is encrypted with AES-GCM before being persisted.
23
+ *
24
+ * @param code - Code to persist for the current browser session.
25
+ */
26
+ export declare function setCode(code: string): Promise<void>;
27
+ /**
28
+ * Removes the access code from `sessionStorage`.
29
+ */
30
+ export declare function clearCode(): void;
31
+ //# sourceMappingURL=session.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session.d.ts","names":[],"sources":["../src/session.ts"],"mappings":";;;;;;;;wBAYsB,WAAW;;;;;;;;;wBAqBX,eAAe;;;;;;;;wBAWf,QAAQ,eAAe;;;;wBAW7B"}
package/lib/session.js ADDED
@@ -0,0 +1,52 @@
1
+ import { getSessionStorage } from "./browser.js";
2
+ import { SESSION_KEY } from "./constants.js";
3
+ import { decryptCode, encryptCode } from "./crypto.js";
4
+ // src/session.ts
5
+ /**
6
+ * Returns the access code stored in `sessionStorage`.
7
+ *
8
+ * The stored value is AES-GCM encrypted; it is decrypted before being returned.
9
+ *
10
+ * @returns The decrypted code, or `null` when the visitor is not connected, session
11
+ * storage is not available, or the stored value cannot be decrypted.
12
+ */
13
+ async function getCode() {
14
+ const storage = getSessionStorage();
15
+ const stored = storage?.getItem(SESSION_KEY);
16
+ if (!stored) return null;
17
+ const code = await decryptCode(stored);
18
+ if (code === null) storage?.removeItem(SESSION_KEY);
19
+ return code;
20
+ }
21
+ /**
22
+ * Tells whether an access code is stored in `sessionStorage`.
23
+ *
24
+ * This is a client-side check. It does not verify the code on the server; use
25
+ * `reactGuardian` for the full verification.
26
+ *
27
+ * @returns `true` when a code is stored, `false` otherwise.
28
+ */
29
+ async function isConnected() {
30
+ return await getCode() !== null;
31
+ }
32
+ /**
33
+ * Stores an access code in `sessionStorage`.
34
+ *
35
+ * The code is encrypted with AES-GCM before being persisted.
36
+ *
37
+ * @param code - Code to persist for the current browser session.
38
+ */
39
+ async function setCode(code) {
40
+ const storage = getSessionStorage();
41
+ if (!storage) return;
42
+ storage.setItem(SESSION_KEY, await encryptCode(code));
43
+ }
44
+ /**
45
+ * Removes the access code from `sessionStorage`.
46
+ */
47
+ function clearCode() {
48
+ getSessionStorage()?.removeItem(SESSION_KEY);
49
+ }
50
+ export { clearCode, getCode, isConnected, setCode };
51
+
52
+ //# sourceMappingURL=session.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session.js","names":[],"sources":["../src/session.ts"],"sourcesContent":["import { getSessionStorage } from './browser';\nimport { SESSION_KEY } from './constants';\nimport { decryptCode, encryptCode } from './crypto';\n\n/**\n * Returns the access code stored in `sessionStorage`.\n *\n * The stored value is AES-GCM encrypted; it is decrypted before being returned.\n *\n * @returns The decrypted code, or `null` when the visitor is not connected, session\n * storage is not available, or the stored value cannot be decrypted.\n */\nexport async function getCode(): Promise<string | null> {\n const storage = getSessionStorage();\n const stored = storage?.getItem(SESSION_KEY);\n\n if (!stored) return null;\n\n const code = await decryptCode(stored);\n\n if (code === null) storage?.removeItem(SESSION_KEY);\n\n return code;\n}\n\n/**\n * Tells whether an access code is stored in `sessionStorage`.\n *\n * This is a client-side check. It does not verify the code on the server; use\n * `reactGuardian` for the full verification.\n *\n * @returns `true` when a code is stored, `false` otherwise.\n */\nexport async function isConnected(): Promise<boolean> {\n return (await getCode()) !== null;\n}\n\n/**\n * Stores an access code in `sessionStorage`.\n *\n * The code is encrypted with AES-GCM before being persisted.\n *\n * @param code - Code to persist for the current browser session.\n */\nexport async function setCode(code: string): Promise<void> {\n const storage = getSessionStorage();\n\n if (!storage) return;\n\n storage.setItem(SESSION_KEY, await encryptCode(code));\n}\n\n/**\n * Removes the access code from `sessionStorage`.\n */\nexport function clearCode(): void {\n getSessionStorage()?.removeItem(SESSION_KEY);\n}\n"],"mappings":";;;;;;;;;;;;AAYA,eAAsB,UAAkC;CACtD,MAAM,UAAU,kBAAkB;CAClC,MAAM,SAAS,SAAS,QAAQ,WAAW;CAE3C,IAAI,CAAC,QAAQ,OAAO;CAEpB,MAAM,OAAO,MAAM,YAAY,MAAM;CAErC,IAAI,SAAS,MAAM,SAAS,WAAW,WAAW;CAElD,OAAO;AACT;;;;;;;;;AAUA,eAAsB,cAAgC;CACpD,OAAQ,MAAM,QAAQ,MAAO;AAC/B;;;;;;;;AASA,eAAsB,QAAQ,MAA6B;CACzD,MAAM,UAAU,kBAAkB;CAElC,IAAI,CAAC,SAAS;CAEd,QAAQ,QAAQ,aAAa,MAAM,YAAY,IAAI,CAAC;AACtD;;;;AAKA,SAAgB,YAAkB;CAChC,kBAAkB,CAAC,EAAE,WAAW,WAAW;AAC7C"}
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Callable signature of the server function returned by {@linkcode verifyCode}.
3
+ */
4
+ export type VerifyCode = (options: {
5
+ data: string;
6
+ }) => Promise<boolean>;
7
+ /**
8
+ * Verifies an access code on the server.
9
+ *
10
+ * The expected code is read from the server-only `BEMEDEV_CODE_ENV` environment
11
+ * variable. When that variable is empty or missing, the website is considered open and
12
+ * every code is accepted.
13
+ *
14
+ * This server function must be transformed by the TanStack Start Vite plugin. When the
15
+ * library is consumed from `node_modules`, add it to `optimizeDeps.exclude` so the
16
+ * development server also transforms it.
17
+ */
18
+ export declare const verifyCode: VerifyCode;
19
+ //# sourceMappingURL=verify.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"verify.d.ts","names":[],"sources":["../src/verify.ts"],"mappings":";;;YAQY,cAAc;EAAW;MAAmB;;;;;;;;;;;;qBAa3C,YAAY"}
package/lib/verify.js ADDED
@@ -0,0 +1,23 @@
1
+ import { createServerFn } from "@tanstack/react-start";
2
+ import { CODE_ENV } from "./constants.js";
3
+ import { readEnv } from "./env.js";
4
+ // src/verify.ts
5
+ /**
6
+ * Verifies an access code on the server.
7
+ *
8
+ * The expected code is read from the server-only `BEMEDEV_CODE_ENV` environment
9
+ * variable. When that variable is empty or missing, the website is considered open and
10
+ * every code is accepted.
11
+ *
12
+ * This server function must be transformed by the TanStack Start Vite plugin. When the
13
+ * library is consumed from `node_modules`, add it to `optimizeDeps.exclude` so the
14
+ * development server also transforms it.
15
+ */
16
+ const verifyCode = createServerFn({ method: "POST" }).validator((code) => code).handler(async ({ data }) => {
17
+ const expected = readEnv(CODE_ENV);
18
+ if (!expected) return true;
19
+ return data === expected;
20
+ });
21
+ export { verifyCode };
22
+
23
+ //# sourceMappingURL=verify.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"verify.js","names":[],"sources":["../src/verify.ts"],"sourcesContent":["import { createServerFn } from '@tanstack/react-start';\n\nimport { CODE_ENV } from './constants';\nimport { readEnv } from './env';\n\n/**\n * Callable signature of the server function returned by {@linkcode verifyCode}.\n */\nexport type VerifyCode = (options: { data: string }) => Promise<boolean>;\n\n/**\n * Verifies an access code on the server.\n *\n * The expected code is read from the server-only `BEMEDEV_CODE_ENV` environment\n * variable. When that variable is empty or missing, the website is considered open and\n * every code is accepted.\n *\n * This server function must be transformed by the TanStack Start Vite plugin. When the\n * library is consumed from `node_modules`, add it to `optimizeDeps.exclude` so the\n * development server also transforms it.\n */\nexport const verifyCode: VerifyCode = createServerFn({ method: 'POST' })\n .validator((code: string) => code)\n .handler(async ({ data }) => {\n const expected = readEnv(CODE_ENV);\n\n if (!expected) return true;\n\n return data === expected;\n });\n"],"mappings":";;;;;;;;;;;;;;;AAqBA,MAAa,aAAyB,eAAe,EAAE,QAAQ,OAAO,CAAC,CAAC,CACrE,WAAW,SAAiB,IAAI,CAAC,CACjC,QAAQ,OAAO,EAAE,WAAW;CAC3B,MAAM,WAAW,QAAQ,QAAQ;CAEjC,IAAI,CAAC,UAAU,OAAO;CAEtB,OAAO,SAAS;AAClB,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,130 @@
1
1
  {
2
2
  "name": "@bemedev/react-guardian",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.1",
4
+ "description": "Headless TanStack Start guard that redirects visitors to the Bemedev connexion page.",
5
+ "keywords": [
6
+ "bemedev",
7
+ "guard",
8
+ "headless",
9
+ "react",
10
+ "redirect",
11
+ "tanstack-start"
12
+ ],
13
+ "author": {
14
+ "name": "chlbri",
15
+ "email": "bri_lvi@icloud.com",
16
+ "url": "https://bemedev.vercel.app"
17
+ },
18
+ "maintainers": [
19
+ {
20
+ "email": "bri_lvi@icloud.com",
21
+ "name": "chlbri",
22
+ "url": "https://bemedev.vercel.app"
23
+ }
24
+ ],
25
+ "contributors": [
26
+ {
27
+ "email": "bri_lvi@icloud.com",
28
+ "name": "chlbri",
29
+ "url": "https://bemedev.vercel.app"
30
+ }
31
+ ],
32
+ "repository": {
33
+ "type": "git",
34
+ "url": "git+https://github.com/chlbri/tan-react-utils.git",
35
+ "directory": "packages/react-guardian"
36
+ },
37
+ "homepage": "https://github.com/chlbri/tan-react-utils/tree/main/packages/react-guardian#readme",
38
+ "files": [
39
+ "lib",
40
+ "package.json",
41
+ "LICENSE",
42
+ "CHANGELOG.md"
43
+ ],
44
+ "type": "module",
45
+ "main": "lib/index.js",
46
+ "module": "lib/index.js",
47
+ "types": "lib/index.d.ts",
48
+ "exports": {
49
+ ".": {
50
+ "types": "./lib/index.d.ts",
51
+ "import": "./lib/index.js"
52
+ },
53
+ "./index": {
54
+ "types": "./lib/index.d.ts",
55
+ "import": "./lib/index.js"
56
+ },
57
+ "./browser": {
58
+ "types": "./lib/browser.d.ts",
59
+ "import": "./lib/browser.js"
60
+ },
61
+ "./connect": {
62
+ "types": "./lib/connect.d.ts",
63
+ "import": "./lib/connect.js"
64
+ },
65
+ "./constants": {
66
+ "types": "./lib/constants.d.ts",
67
+ "import": "./lib/constants.js"
68
+ },
69
+ "./crypto": {
70
+ "types": "./lib/crypto.d.ts",
71
+ "import": "./lib/crypto.js"
72
+ },
73
+ "./disconnect": {
74
+ "types": "./lib/disconnect.d.ts",
75
+ "import": "./lib/disconnect.js"
76
+ },
77
+ "./env": {
78
+ "types": "./lib/env.d.ts",
79
+ "import": "./lib/env.js"
80
+ },
81
+ "./guardian": {
82
+ "types": "./lib/guardian.d.ts",
83
+ "import": "./lib/guardian.js"
84
+ },
85
+ "./session": {
86
+ "types": "./lib/session.d.ts",
87
+ "import": "./lib/session.js"
88
+ },
89
+ "./verify": {
90
+ "types": "./lib/verify.d.ts",
91
+ "import": "./lib/verify.js"
92
+ },
93
+ "./package.json": "./package.json"
94
+ },
95
+ "sideEffects": false,
96
+ "peerDependencies": {
97
+ "@tanstack/react-router": "^1.170.0",
98
+ "@tanstack/react-start": "^1.170.0"
99
+ },
100
+ "devDependencies": {
101
+ "@bemedev/dev-utils": "^1.6.2",
102
+ "@size-limit/file": "^14.3.0",
103
+ "@tanstack/react-router": "^1.170.46",
104
+ "@tanstack/react-start": "^1.170.0",
105
+ "size-limit": "^14.3.0",
106
+ "typescript": "6.0.3",
107
+ "vite-plus": "1.9.0"
108
+ },
109
+ "size-limit": [
110
+ {
111
+ "path": "lib/**/*.js",
112
+ "limit": "20kb"
113
+ },
114
+ {
115
+ "path": "lib/**/*.d.ts",
116
+ "limit": "10kb"
117
+ }
118
+ ],
119
+ "scripts": {
120
+ "p-q": "pretty-quick",
121
+ "posttest": "vp fmt",
122
+ "pretest": "vp run pack",
123
+ "rm:lib": "vp dlx rimraf ./lib",
124
+ "publish:first": "vp run pretest && pnpm publish --access public --no-git-checks",
125
+ "test:coverage": "vp test run",
126
+ "test": "vp run test:coverage --no-coverage",
127
+ "test:only": "vp run test",
128
+ "test:watch": "vp test"
129
+ }
6
130
  }