@bemedev/react-guardian 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +181 -2
- package/lib/index.d.ts +147 -0
- package/lib/index.d.ts.map +1 -0
- package/lib/index.js +342 -0
- package/lib/index.js.map +1 -0
- package/package.json +77 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2022 chlbri
|
|
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,182 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @bemedev/react-guardian
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Headless access gate for [TanStack Start](https://tanstack.com/start) React
|
|
4
|
+
applications. Client websites are protected by an access code stored encrypted
|
|
5
|
+
(AES-GCM) in `sessionStorage` and verified on the server against the
|
|
6
|
+
`BEMEDEV_CODE_ENV` environment variable.
|
|
7
|
+
|
|
8
|
+
The package provides:
|
|
9
|
+
|
|
10
|
+
- `reactGuardian(to)` — guard a route and redirect disconnected visitors to the
|
|
11
|
+
connexion page.
|
|
12
|
+
- `connect({ password })` — connect with a password.
|
|
13
|
+
- `connect()` / `connectSeamless()` — connect without a password from the `code`
|
|
14
|
+
query parameter (seamless redirect).
|
|
15
|
+
- `connectWithPassword(password)` — explicit password helper.
|
|
16
|
+
- `disconnect()` — clear the session.
|
|
17
|
+
|
|
18
|
+
<br/>
|
|
19
|
+
|
|
20
|
+
## Installation
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
pnpm add @bemedev/react-guardian
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
<br/>
|
|
27
|
+
|
|
28
|
+
## Configuration
|
|
29
|
+
|
|
30
|
+
Add the expected access code to `.env`. It stays on the server:
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
BEMEDEV_CODE_ENV=my-secret-code
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
When `BEMEDEV_CODE_ENV` is missing or empty, the website is considered open and every
|
|
37
|
+
visitor is accepted.
|
|
38
|
+
|
|
39
|
+
The server function must be transformed by the TanStack Start Vite plugin. When the
|
|
40
|
+
library is consumed from `node_modules`, exclude it from dependency pre-bundling in
|
|
41
|
+
development:
|
|
42
|
+
|
|
43
|
+
```ts
|
|
44
|
+
// vite.config.ts
|
|
45
|
+
export default defineConfig({
|
|
46
|
+
optimizeDeps: { exclude: ['@bemedev/react-guardian'] },
|
|
47
|
+
plugins: [tanstackStart(), viteReact()],
|
|
48
|
+
});
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
<br/>
|
|
52
|
+
|
|
53
|
+
## Guard a route
|
|
54
|
+
|
|
55
|
+
```tsx
|
|
56
|
+
import { reactGuardian } from '@bemedev/react-guardian';
|
|
57
|
+
import { createFileRoute } from '@tanstack/react-router';
|
|
58
|
+
|
|
59
|
+
export const Route = createFileRoute('/')({
|
|
60
|
+
beforeLoad: () => reactGuardian('/connexion'),
|
|
61
|
+
});
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
When the code stored in `sessionStorage` is missing or invalid, the guard redirects
|
|
65
|
+
to `/connexion?redirect=<current-url>`. When it is valid, the requested page renders.
|
|
66
|
+
|
|
67
|
+
`sessionStorage` only exists in the browser, so the guard returns early during server
|
|
68
|
+
rendering. Protect server data with your own server checks as well.
|
|
69
|
+
|
|
70
|
+
<br/>
|
|
71
|
+
|
|
72
|
+
## Connect with a password
|
|
73
|
+
|
|
74
|
+
On the connexion page, verify the password entered by the visitor:
|
|
75
|
+
|
|
76
|
+
```tsx
|
|
77
|
+
import { connectWithPassword } from '@bemedev/react-guardian';
|
|
78
|
+
|
|
79
|
+
async function onSubmit(password: string) {
|
|
80
|
+
const connected = await connectWithPassword(password, { redirectTo: '/' });
|
|
81
|
+
|
|
82
|
+
if (!connected) {
|
|
83
|
+
// Show an error message.
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
The password is verified on the server, stored in `sessionStorage`, and the visitor
|
|
89
|
+
is sent to `redirectTo`. You can also read the page to open from the `redirect` query
|
|
90
|
+
parameter by omitting `redirectTo`.
|
|
91
|
+
|
|
92
|
+
<br/>
|
|
93
|
+
|
|
94
|
+
## Connect without a password (seamless redirect)
|
|
95
|
+
|
|
96
|
+
When the connexion page sends the visitor back with a `code` query parameter, connect
|
|
97
|
+
seamlessly:
|
|
98
|
+
|
|
99
|
+
```tsx
|
|
100
|
+
import { connectSeamless } from '@bemedev/react-guardian';
|
|
101
|
+
|
|
102
|
+
await connectSeamless();
|
|
103
|
+
// Reads /?code=<code>&redirect=<page>, verifies the code on the server,
|
|
104
|
+
// stores it in sessionStorage, and opens <page>.
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
`connect()` behaves the same way when no `password` is provided:
|
|
108
|
+
|
|
109
|
+
```ts
|
|
110
|
+
await connect({ redirectTo: '/dashboard' });
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
<br/>
|
|
114
|
+
|
|
115
|
+
## Disconnect
|
|
116
|
+
|
|
117
|
+
```ts
|
|
118
|
+
import { disconnect } from '@bemedev/react-guardian';
|
|
119
|
+
|
|
120
|
+
disconnect({ redirectTo: '/connexion' });
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
This clears the code from `sessionStorage` and optionally opens a page.
|
|
124
|
+
|
|
125
|
+
<br/>
|
|
126
|
+
|
|
127
|
+
## API
|
|
128
|
+
|
|
129
|
+
### `reactGuardian(to)`
|
|
130
|
+
|
|
131
|
+
Verifies the session code on the server. Redirects to `to` when the visitor is not
|
|
132
|
+
connected. `to` can be an internal route or an absolute URL.
|
|
133
|
+
|
|
134
|
+
### `connect(options?)`
|
|
135
|
+
|
|
136
|
+
- `options.password` — Password variant. Verified on the server.
|
|
137
|
+
- `options.redirectTo` — Page to open after a successful connection. Defaults to the
|
|
138
|
+
`redirect` query parameter, then `/`.
|
|
139
|
+
- `options.navigate` — Navigation implementation. Defaults to
|
|
140
|
+
`window.location.replace`.
|
|
141
|
+
|
|
142
|
+
Returns `true` when connected, `false` otherwise.
|
|
143
|
+
|
|
144
|
+
### `connectWithPassword(password, options?)`
|
|
145
|
+
|
|
146
|
+
Password variant of `connect`.
|
|
147
|
+
|
|
148
|
+
### `connectSeamless(options?)`
|
|
149
|
+
|
|
150
|
+
Seamless variant of `connect`. Reads the code from the `code` query parameter.
|
|
151
|
+
|
|
152
|
+
### `disconnect(options?)`
|
|
153
|
+
|
|
154
|
+
Clears the session code. `options.redirectTo` optionally opens a page, and
|
|
155
|
+
`options.navigate` overrides navigation.
|
|
156
|
+
|
|
157
|
+
### Session helpers
|
|
158
|
+
|
|
159
|
+
- `getCode()` — decrypted code from `sessionStorage`, or `null`.
|
|
160
|
+
- `isConnected()` — whether a valid code is stored.
|
|
161
|
+
- `setCode(code)` — encrypt with AES-GCM and persist the code.
|
|
162
|
+
- `clearCode()` — remove the code.
|
|
163
|
+
|
|
164
|
+
<br/>
|
|
165
|
+
|
|
166
|
+
## Licence
|
|
167
|
+
|
|
168
|
+
MIT
|
|
169
|
+
|
|
170
|
+
## CHANGE_LOG
|
|
171
|
+
|
|
172
|
+
Read [CHANGELOG.md](CHANGELOG.md) for more details about the changes.
|
|
173
|
+
|
|
174
|
+
<br/>
|
|
175
|
+
|
|
176
|
+
## Auteur
|
|
177
|
+
|
|
178
|
+
chlbri (bri_lvi@icloud.com)
|
|
179
|
+
|
|
180
|
+
[My github](https://github.com/chlbri?tab=repositories)
|
|
181
|
+
|
|
182
|
+
[<svg width="98" height="96" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" clip-rule="evenodd" d="M48.854 0C21.839 0 0 22 0 49.217c0 21.756 13.993 40.172 33.405 46.69 2.427.49 3.316-1.059 3.316-2.362 0-1.141-.08-5.052-.08-9.127-13.59 2.934-16.42-5.867-16.42-5.867-2.184-5.704-5.42-7.17-5.42-7.17-4.448-3.015.324-3.015.324-3.015 4.934.326 7.523 5.052 7.523 5.052 4.367 7.496 11.404 5.378 14.235 4.074.404-3.178 1.699-5.378 3.074-6.6-10.839-1.141-22.243-5.378-22.243-24.283 0-5.378 1.94-9.778 5.014-13.2-.485-1.222-2.184-6.275.486-13.038 0 0 4.125-1.304 13.426 5.052a46.97 46.97 0 0 1 12.214-1.63c4.125 0 8.33.571 12.213 1.63 9.302-6.356 13.427-5.052 13.427-5.052 2.67 6.763.97 11.816.485 13.038 3.155 3.422 5.015 7.822 5.015 13.2 0 18.905-11.404 23.06-22.324 24.283 1.78 1.548 3.316 4.481 3.316 9.126 0 6.6-.08 11.897-.08 13.526 0 1.304.89 2.853 3.316 2.364 19.412-6.52 33.405-24.935 33.405-46.691C97.707 22 75.788 0 48.854 0z" fill="#24292f"/></svg>](https://github.com/chlbri?tab=repositories)
|
package/lib/index.d.ts
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Options accepted by {@linkcode connect}.
|
|
3
|
+
*/
|
|
4
|
+
type ConnectOptions = {
|
|
5
|
+
/**
|
|
6
|
+
* Password entered by the visitor.
|
|
7
|
+
*
|
|
8
|
+
* When omitted, {@linkcode connect} runs the seamless variant and reads the code
|
|
9
|
+
* from the `code` query parameter.
|
|
10
|
+
*/
|
|
11
|
+
password?: string;
|
|
12
|
+
/**
|
|
13
|
+
* Page to open after a successful connection.
|
|
14
|
+
*
|
|
15
|
+
* Defaults to the `redirect` query parameter, then to `/`.
|
|
16
|
+
*/
|
|
17
|
+
redirectTo?: string;
|
|
18
|
+
/**
|
|
19
|
+
* Navigation implementation.
|
|
20
|
+
*
|
|
21
|
+
* Defaults to `window.location.replace`.
|
|
22
|
+
*/
|
|
23
|
+
navigate?: (href: string) => void;
|
|
24
|
+
};
|
|
25
|
+
/**
|
|
26
|
+
* Connects the visitor with or without a password.
|
|
27
|
+
*
|
|
28
|
+
* - With `options.password`, the entered password is verified on the server.
|
|
29
|
+
* - Without `options.password`, the `code` query parameter is read from the current
|
|
30
|
+
* URL and verified on the server. This is the seamless redirect variant used when a
|
|
31
|
+
* connexion page sends the visitor back to the client website.
|
|
32
|
+
*
|
|
33
|
+
* On success the verified code is stored in `sessionStorage`, the visitor is sent to
|
|
34
|
+
* the requested page, and the function resolves to `true`. On failure nothing is
|
|
35
|
+
* stored or navigated, and the function resolves to `false`.
|
|
36
|
+
*
|
|
37
|
+
* @param options - Connection options.
|
|
38
|
+
*
|
|
39
|
+
* @returns `true` when the visitor is connected, `false` otherwise.
|
|
40
|
+
*
|
|
41
|
+
* @see -- type {@linkcode ConnectOptions}
|
|
42
|
+
*/
|
|
43
|
+
export declare function connect(options?: ConnectOptions): Promise<boolean>;
|
|
44
|
+
/**
|
|
45
|
+
* Connects the visitor with a password.
|
|
46
|
+
*
|
|
47
|
+
* @param password - Password entered by the visitor.
|
|
48
|
+
* @param options - Connection options without the password.
|
|
49
|
+
*
|
|
50
|
+
* @returns `true` when the visitor is connected, `false` otherwise.
|
|
51
|
+
*
|
|
52
|
+
* @see {@linkcode connect}
|
|
53
|
+
*/
|
|
54
|
+
export declare function connectWithPassword(password: string, options?: Omit<ConnectOptions, 'password'>): Promise<boolean>;
|
|
55
|
+
/**
|
|
56
|
+
* Connects the visitor seamlessly from the `code` query parameter.
|
|
57
|
+
*
|
|
58
|
+
* @param options - Connection options without the password.
|
|
59
|
+
*
|
|
60
|
+
* @returns `true` when the visitor is connected, `false` otherwise.
|
|
61
|
+
*
|
|
62
|
+
* @see {@linkcode connect}
|
|
63
|
+
*/
|
|
64
|
+
export declare function connectSeamless(options?: Omit<ConnectOptions, 'password'>): Promise<boolean>;
|
|
65
|
+
/**
|
|
66
|
+
* Options accepted by {@linkcode disconnect}.
|
|
67
|
+
*/
|
|
68
|
+
type DisconnectOptions = {
|
|
69
|
+
/**
|
|
70
|
+
* Page to open after disconnection.
|
|
71
|
+
*
|
|
72
|
+
* When omitted, the visitor stays on the current page.
|
|
73
|
+
*/
|
|
74
|
+
redirectTo?: string;
|
|
75
|
+
/**
|
|
76
|
+
* Navigation implementation.
|
|
77
|
+
*
|
|
78
|
+
* Defaults to `window.location.replace`.
|
|
79
|
+
*/
|
|
80
|
+
navigate?: (href: string) => void;
|
|
81
|
+
};
|
|
82
|
+
/**
|
|
83
|
+
* Disconnects the visitor by removing the access code from `sessionStorage`.
|
|
84
|
+
*
|
|
85
|
+
* @param options - Disconnection options.
|
|
86
|
+
*
|
|
87
|
+
* @see -- type {@linkcode DisconnectOptions}
|
|
88
|
+
*/
|
|
89
|
+
export declare function disconnect(options?: DisconnectOptions): void;
|
|
90
|
+
/**
|
|
91
|
+
* Headless guard for TanStack Start applications.
|
|
92
|
+
*
|
|
93
|
+
* Verifies the access code stored in `sessionStorage` against the server-only
|
|
94
|
+
* `BEMEDEV_CODE_ENV` environment variable. When the code is missing or invalid, the
|
|
95
|
+
* guard clears the session and throws a redirect to the connexion page identified by
|
|
96
|
+
* `to`, carrying the current URL in the `redirect` query parameter. When the code is
|
|
97
|
+
* valid, the guard returns and the requested page renders.
|
|
98
|
+
*
|
|
99
|
+
* `sessionStorage` only exists in the browser, so the guard must run client-side. It
|
|
100
|
+
* returns early during server rendering; protect server data with your own server
|
|
101
|
+
* checks as well.
|
|
102
|
+
*
|
|
103
|
+
* ```tsx
|
|
104
|
+
* export const Route = createFileRoute('/')({
|
|
105
|
+
* beforeLoad: () => reactGuardian('/connexion'),
|
|
106
|
+
* });
|
|
107
|
+
* ```
|
|
108
|
+
*
|
|
109
|
+
* @param to - Route or absolute URL of the connexion page used when the visitor is not
|
|
110
|
+
* connected.
|
|
111
|
+
*
|
|
112
|
+
* @throws A TanStack Router redirect to `to` when the access code is missing or
|
|
113
|
+
* invalid.
|
|
114
|
+
*/
|
|
115
|
+
export declare function reactGuardian(to: string): Promise<void>;
|
|
116
|
+
/**
|
|
117
|
+
* Returns the access code stored in `sessionStorage`.
|
|
118
|
+
*
|
|
119
|
+
* The stored value is AES-GCM encrypted; it is decrypted before being returned.
|
|
120
|
+
*
|
|
121
|
+
* @returns The decrypted code, or `null` when the visitor is not connected, session
|
|
122
|
+
* storage is not available, or the stored value cannot be decrypted.
|
|
123
|
+
*/
|
|
124
|
+
export declare function getCode(): Promise<string | null>;
|
|
125
|
+
/**
|
|
126
|
+
* Tells whether an access code is stored in `sessionStorage`.
|
|
127
|
+
*
|
|
128
|
+
* This is a client-side check. It does not verify the code on the server; use
|
|
129
|
+
* `reactGuardian` for the full verification.
|
|
130
|
+
*
|
|
131
|
+
* @returns `true` when a code is stored, `false` otherwise.
|
|
132
|
+
*/
|
|
133
|
+
export declare function isConnected(): Promise<boolean>;
|
|
134
|
+
/**
|
|
135
|
+
* Stores an access code in `sessionStorage`.
|
|
136
|
+
*
|
|
137
|
+
* The code is encrypted with AES-GCM before being persisted.
|
|
138
|
+
*
|
|
139
|
+
* @param code - Code to persist for the current browser session.
|
|
140
|
+
*/
|
|
141
|
+
export declare function setCode(code: string): Promise<void>;
|
|
142
|
+
/**
|
|
143
|
+
* Removes the access code from `sessionStorage`.
|
|
144
|
+
*/
|
|
145
|
+
export declare function clearCode(): void;
|
|
146
|
+
export type { ConnectOptions, DisconnectOptions };
|
|
147
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/connect.ts","../src/disconnect.ts","../src/guardian.ts","../src/session.ts"],"mappings":";;;KAQY;;;;;;;EAOV;;;;;;EAOA;;;;;;EAOA,YAAY;;;;;;;;;;;;;;;;;;;;wBAqBQ,QAAQ,UAAS,iBAAsB;;;;;;;;;;;wBA0B7C,oBACd,kBACA,UAAS,KAAK,8BACb;;;;;;;;;;wBAaa,gBACd,UAAS,KAAK,8BACb;;;;KCxFS;;;;;;EAMV;;;;;;EAOA,YAAY;;;;;;;;;wBAUE,WAAW,UAAS;;;;;;;;;;;;;;;;;;;;;;;;;;wBCEd,cAAc,aAAa;;;;;;;;;wBCnB3B,WAAW;;;;;;;;;wBAqBX,eAAe;;;;;;;;wBAWf,QAAQ,eAAe;;;;wBAW7B"}
|
package/lib/index.js
ADDED
|
@@ -0,0 +1,342 @@
|
|
|
1
|
+
import { createServerFn } from "@tanstack/react-start";
|
|
2
|
+
import { redirect } from "@tanstack/react-router";
|
|
3
|
+
// src/constants.ts
|
|
4
|
+
/** Name of the `.env` variable holding the expected access code. */
|
|
5
|
+
const CODE_ENV = "BEMEDEV_CODE_ENV";
|
|
6
|
+
/** Key used to persist the access code in `sessionStorage`. */
|
|
7
|
+
const SESSION_KEY = "bemedev:react-guardian:code";
|
|
8
|
+
/** Query parameter carrying the page to open after a connection. */
|
|
9
|
+
const REDIRECT_PARAM = "redirect";
|
|
10
|
+
/** Secret used to derive the AES-GCM session key. */
|
|
11
|
+
const ENCRYPTION_SECRET = "bemedev:react-guardian:v1";
|
|
12
|
+
/** AES-GCM encryption algorithm. */
|
|
13
|
+
const ENCRYPTION_ALGORITHM = "AES-GCM";
|
|
14
|
+
// src/browser.ts
|
|
15
|
+
/**
|
|
16
|
+
* Returns the browser session storage, when available.
|
|
17
|
+
*
|
|
18
|
+
* @returns The session storage, or `undefined` during server rendering.
|
|
19
|
+
*/
|
|
20
|
+
function getSessionStorage() {
|
|
21
|
+
if (typeof window === "undefined") return void 0;
|
|
22
|
+
try {
|
|
23
|
+
return window.sessionStorage;
|
|
24
|
+
} catch {
|
|
25
|
+
return;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Returns the current browser URL, when available.
|
|
30
|
+
*
|
|
31
|
+
* @returns The current URL, or `undefined` during server rendering.
|
|
32
|
+
*/
|
|
33
|
+
function getCurrentUrl() {
|
|
34
|
+
if (typeof window === "undefined") return void 0;
|
|
35
|
+
return new URL(window.location.href);
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Default navigation implementation.
|
|
39
|
+
*
|
|
40
|
+
* Uses `window.location.replace` so a successful connection does not leave the
|
|
41
|
+
* connexion page in the browser history.
|
|
42
|
+
*
|
|
43
|
+
* @param href - Absolute or relative URL to open.
|
|
44
|
+
*/
|
|
45
|
+
function defaultNavigate(href) {
|
|
46
|
+
if (typeof window !== "undefined") window.location.replace(href);
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Reads the code from the `code` query parameter of the current URL.
|
|
50
|
+
*
|
|
51
|
+
* @returns The code, or `undefined` when it is not present.
|
|
52
|
+
*/
|
|
53
|
+
function readUrlCode() {
|
|
54
|
+
return getCurrentUrl()?.searchParams.get("code") ?? void 0;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Reads the page to open from the `redirect` query parameter of the current URL.
|
|
58
|
+
*
|
|
59
|
+
* @returns The requested page, or `undefined` when it is not present.
|
|
60
|
+
*/
|
|
61
|
+
function readUrlRedirect() {
|
|
62
|
+
return getCurrentUrl()?.searchParams.get("redirect") ?? void 0;
|
|
63
|
+
}
|
|
64
|
+
// src/crypto.ts
|
|
65
|
+
/** Cached AES-GCM key derived from {@linkcode ENCRYPTION_SECRET}. */
|
|
66
|
+
let encryptionKey;
|
|
67
|
+
/**
|
|
68
|
+
* Returns the Web Crypto implementation.
|
|
69
|
+
*
|
|
70
|
+
* @returns The Web Crypto implementation.
|
|
71
|
+
*
|
|
72
|
+
* @throws {Error} When Web Crypto is not available in the current context.
|
|
73
|
+
*/
|
|
74
|
+
function getCrypto() {
|
|
75
|
+
if (!globalThis.crypto?.subtle) throw new Error("[react-guardian] Web Crypto is required to encrypt the session code.");
|
|
76
|
+
return globalThis.crypto;
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Derives and caches the AES-GCM key used to encrypt the session code.
|
|
80
|
+
*
|
|
81
|
+
* @returns The AES-GCM key.
|
|
82
|
+
*/
|
|
83
|
+
function getEncryptionKey() {
|
|
84
|
+
encryptionKey ??= (async () => {
|
|
85
|
+
const secret = new TextEncoder().encode(ENCRYPTION_SECRET);
|
|
86
|
+
const digest = await getCrypto().subtle.digest("SHA-256", secret);
|
|
87
|
+
return getCrypto().subtle.importKey("raw", digest, { name: ENCRYPTION_ALGORITHM }, false, ["encrypt", "decrypt"]);
|
|
88
|
+
})();
|
|
89
|
+
return encryptionKey;
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Encodes bytes as a Base64 string.
|
|
93
|
+
*
|
|
94
|
+
* @param bytes - Bytes to encode.
|
|
95
|
+
*
|
|
96
|
+
* @returns The Base64 encoded string.
|
|
97
|
+
*/
|
|
98
|
+
function bytesToBase64(bytes) {
|
|
99
|
+
let binary = "";
|
|
100
|
+
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
101
|
+
return btoa(binary);
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Decodes a Base64 string into bytes.
|
|
105
|
+
*
|
|
106
|
+
* @param value - Base64 encoded string.
|
|
107
|
+
*
|
|
108
|
+
* @returns The decoded bytes.
|
|
109
|
+
*/
|
|
110
|
+
function base64ToBytes(value) {
|
|
111
|
+
return Uint8Array.from(atob(value), (char) => char.charCodeAt(0));
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Encrypts an access code with AES-GCM.
|
|
115
|
+
*
|
|
116
|
+
* @param code - Code to encrypt.
|
|
117
|
+
*
|
|
118
|
+
* @returns The Base64 encoded initialization vector followed by the encrypted code.
|
|
119
|
+
*/
|
|
120
|
+
async function encryptCode(code) {
|
|
121
|
+
const crypto = getCrypto();
|
|
122
|
+
const key = await getEncryptionKey();
|
|
123
|
+
const iv = crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(12));
|
|
124
|
+
const encrypted = await crypto.subtle.encrypt({
|
|
125
|
+
name: ENCRYPTION_ALGORITHM,
|
|
126
|
+
iv
|
|
127
|
+
}, key, new TextEncoder().encode(code));
|
|
128
|
+
const bytes = new Uint8Array(iv.length + encrypted.byteLength);
|
|
129
|
+
bytes.set(iv);
|
|
130
|
+
bytes.set(new Uint8Array(encrypted), iv.length);
|
|
131
|
+
return bytesToBase64(bytes);
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Decrypts an access code encrypted by {@linkcode encryptCode}.
|
|
135
|
+
*
|
|
136
|
+
* @param value - Encrypted value read from `sessionStorage`.
|
|
137
|
+
*
|
|
138
|
+
* @returns The decrypted code, or `null` when the value cannot be decrypted.
|
|
139
|
+
*/
|
|
140
|
+
async function decryptCode(value) {
|
|
141
|
+
try {
|
|
142
|
+
const crypto = getCrypto();
|
|
143
|
+
const bytes = base64ToBytes(value);
|
|
144
|
+
if (bytes.length <= 12) return null;
|
|
145
|
+
const iv = bytes.slice(0, 12);
|
|
146
|
+
const encrypted = bytes.slice(12);
|
|
147
|
+
const key = await getEncryptionKey();
|
|
148
|
+
const decrypted = await crypto.subtle.decrypt({
|
|
149
|
+
name: ENCRYPTION_ALGORITHM,
|
|
150
|
+
iv
|
|
151
|
+
}, key, encrypted);
|
|
152
|
+
return new TextDecoder().decode(decrypted);
|
|
153
|
+
} catch {
|
|
154
|
+
return null;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
// src/session.ts
|
|
158
|
+
/**
|
|
159
|
+
* Returns the access code stored in `sessionStorage`.
|
|
160
|
+
*
|
|
161
|
+
* The stored value is AES-GCM encrypted; it is decrypted before being returned.
|
|
162
|
+
*
|
|
163
|
+
* @returns The decrypted code, or `null` when the visitor is not connected, session
|
|
164
|
+
* storage is not available, or the stored value cannot be decrypted.
|
|
165
|
+
*/
|
|
166
|
+
async function getCode() {
|
|
167
|
+
const storage = getSessionStorage();
|
|
168
|
+
const stored = storage?.getItem(SESSION_KEY);
|
|
169
|
+
if (!stored) return null;
|
|
170
|
+
const code = await decryptCode(stored);
|
|
171
|
+
if (code === null) storage?.removeItem(SESSION_KEY);
|
|
172
|
+
return code;
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* Tells whether an access code is stored in `sessionStorage`.
|
|
176
|
+
*
|
|
177
|
+
* This is a client-side check. It does not verify the code on the server; use
|
|
178
|
+
* `reactGuardian` for the full verification.
|
|
179
|
+
*
|
|
180
|
+
* @returns `true` when a code is stored, `false` otherwise.
|
|
181
|
+
*/
|
|
182
|
+
async function isConnected() {
|
|
183
|
+
return await getCode() !== null;
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* Stores an access code in `sessionStorage`.
|
|
187
|
+
*
|
|
188
|
+
* The code is encrypted with AES-GCM before being persisted.
|
|
189
|
+
*
|
|
190
|
+
* @param code - Code to persist for the current browser session.
|
|
191
|
+
*/
|
|
192
|
+
async function setCode(code) {
|
|
193
|
+
const storage = getSessionStorage();
|
|
194
|
+
if (!storage) return;
|
|
195
|
+
storage.setItem(SESSION_KEY, await encryptCode(code));
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* Removes the access code from `sessionStorage`.
|
|
199
|
+
*/
|
|
200
|
+
function clearCode() {
|
|
201
|
+
getSessionStorage()?.removeItem(SESSION_KEY);
|
|
202
|
+
}
|
|
203
|
+
// src/env.ts
|
|
204
|
+
/**
|
|
205
|
+
* Reads an environment variable from the Node.js runtime first, then from the
|
|
206
|
+
* bundler-provided `import.meta.env` object.
|
|
207
|
+
*
|
|
208
|
+
* The Node.js runtime is authoritative on the server, while `import.meta.env` is the
|
|
209
|
+
* only source available in a Vite client bundle.
|
|
210
|
+
*
|
|
211
|
+
* @param name - Name of the environment variable to read.
|
|
212
|
+
*
|
|
213
|
+
* @returns The environment variable value, or `undefined` when it is not defined.
|
|
214
|
+
*/
|
|
215
|
+
function readEnv(name) {
|
|
216
|
+
const processEnv = globalThis.process?.env;
|
|
217
|
+
const viteEnv = import.meta.env;
|
|
218
|
+
return processEnv?.[name] ?? viteEnv?.[name];
|
|
219
|
+
}
|
|
220
|
+
// src/verify.ts
|
|
221
|
+
/**
|
|
222
|
+
* Verifies an access code on the server.
|
|
223
|
+
*
|
|
224
|
+
* The expected code is read from the server-only `BEMEDEV_CODE_ENV` environment
|
|
225
|
+
* variable. When that variable is empty or missing, the website is considered open and
|
|
226
|
+
* every code is accepted.
|
|
227
|
+
*
|
|
228
|
+
* This server function must be transformed by the TanStack Start Vite plugin. When the
|
|
229
|
+
* library is consumed from `node_modules`, add it to `optimizeDeps.exclude` so the
|
|
230
|
+
* development server also transforms it.
|
|
231
|
+
*/
|
|
232
|
+
const verifyCode = createServerFn({ method: "POST" }).validator((code) => code).handler(async ({ data }) => {
|
|
233
|
+
const expected = readEnv(CODE_ENV);
|
|
234
|
+
if (!expected) return true;
|
|
235
|
+
return data === expected;
|
|
236
|
+
});
|
|
237
|
+
// src/connect.ts
|
|
238
|
+
/**
|
|
239
|
+
* Connects the visitor with or without a password.
|
|
240
|
+
*
|
|
241
|
+
* - With `options.password`, the entered password is verified on the server.
|
|
242
|
+
* - Without `options.password`, the `code` query parameter is read from the current
|
|
243
|
+
* URL and verified on the server. This is the seamless redirect variant used when a
|
|
244
|
+
* connexion page sends the visitor back to the client website.
|
|
245
|
+
*
|
|
246
|
+
* On success the verified code is stored in `sessionStorage`, the visitor is sent to
|
|
247
|
+
* the requested page, and the function resolves to `true`. On failure nothing is
|
|
248
|
+
* stored or navigated, and the function resolves to `false`.
|
|
249
|
+
*
|
|
250
|
+
* @param options - Connection options.
|
|
251
|
+
*
|
|
252
|
+
* @returns `true` when the visitor is connected, `false` otherwise.
|
|
253
|
+
*
|
|
254
|
+
* @see -- type {@linkcode ConnectOptions}
|
|
255
|
+
*/
|
|
256
|
+
async function connect(options = {}) {
|
|
257
|
+
const code = options.password ?? readUrlCode() ?? "";
|
|
258
|
+
if (!await verifyCode({ data: code })) return false;
|
|
259
|
+
await setCode(code || "bemedev:open");
|
|
260
|
+
const target = options.redirectTo ?? readUrlRedirect() ?? "/";
|
|
261
|
+
(options.navigate ?? defaultNavigate)(target);
|
|
262
|
+
return true;
|
|
263
|
+
}
|
|
264
|
+
/**
|
|
265
|
+
* Connects the visitor with a password.
|
|
266
|
+
*
|
|
267
|
+
* @param password - Password entered by the visitor.
|
|
268
|
+
* @param options - Connection options without the password.
|
|
269
|
+
*
|
|
270
|
+
* @returns `true` when the visitor is connected, `false` otherwise.
|
|
271
|
+
*
|
|
272
|
+
* @see {@linkcode connect}
|
|
273
|
+
*/
|
|
274
|
+
function connectWithPassword(password, options = {}) {
|
|
275
|
+
return connect({
|
|
276
|
+
...options,
|
|
277
|
+
password
|
|
278
|
+
});
|
|
279
|
+
}
|
|
280
|
+
/**
|
|
281
|
+
* Connects the visitor seamlessly from the `code` query parameter.
|
|
282
|
+
*
|
|
283
|
+
* @param options - Connection options without the password.
|
|
284
|
+
*
|
|
285
|
+
* @returns `true` when the visitor is connected, `false` otherwise.
|
|
286
|
+
*
|
|
287
|
+
* @see {@linkcode connect}
|
|
288
|
+
*/
|
|
289
|
+
function connectSeamless(options = {}) {
|
|
290
|
+
return connect(options);
|
|
291
|
+
}
|
|
292
|
+
// src/disconnect.ts
|
|
293
|
+
/**
|
|
294
|
+
* Disconnects the visitor by removing the access code from `sessionStorage`.
|
|
295
|
+
*
|
|
296
|
+
* @param options - Disconnection options.
|
|
297
|
+
*
|
|
298
|
+
* @see -- type {@linkcode DisconnectOptions}
|
|
299
|
+
*/
|
|
300
|
+
function disconnect(options = {}) {
|
|
301
|
+
clearCode();
|
|
302
|
+
if (!options.redirectTo) return;
|
|
303
|
+
(options.navigate ?? defaultNavigate)(options.redirectTo);
|
|
304
|
+
}
|
|
305
|
+
// src/guardian.ts
|
|
306
|
+
/**
|
|
307
|
+
* Headless guard for TanStack Start applications.
|
|
308
|
+
*
|
|
309
|
+
* Verifies the access code stored in `sessionStorage` against the server-only
|
|
310
|
+
* `BEMEDEV_CODE_ENV` environment variable. When the code is missing or invalid, the
|
|
311
|
+
* guard clears the session and throws a redirect to the connexion page identified by
|
|
312
|
+
* `to`, carrying the current URL in the `redirect` query parameter. When the code is
|
|
313
|
+
* valid, the guard returns and the requested page renders.
|
|
314
|
+
*
|
|
315
|
+
* `sessionStorage` only exists in the browser, so the guard must run client-side. It
|
|
316
|
+
* returns early during server rendering; protect server data with your own server
|
|
317
|
+
* checks as well.
|
|
318
|
+
*
|
|
319
|
+
* ```tsx
|
|
320
|
+
* export const Route = createFileRoute('/')({
|
|
321
|
+
* beforeLoad: () => reactGuardian('/connexion'),
|
|
322
|
+
* });
|
|
323
|
+
* ```
|
|
324
|
+
*
|
|
325
|
+
* @param to - Route or absolute URL of the connexion page used when the visitor is not
|
|
326
|
+
* connected.
|
|
327
|
+
*
|
|
328
|
+
* @throws A TanStack Router redirect to `to` when the access code is missing or
|
|
329
|
+
* invalid.
|
|
330
|
+
*/
|
|
331
|
+
async function reactGuardian(to) {
|
|
332
|
+
if (typeof window === "undefined") return;
|
|
333
|
+
const code = await getCode();
|
|
334
|
+
if (!!code && await verifyCode({ data: code })) return;
|
|
335
|
+
clearCode();
|
|
336
|
+
const connexion = new URL(to, window.location.origin);
|
|
337
|
+
if (!connexion.searchParams.has("redirect")) connexion.searchParams.set(REDIRECT_PARAM, window.location.href);
|
|
338
|
+
throw redirect({ href: connexion.toString() });
|
|
339
|
+
}
|
|
340
|
+
export { clearCode, connect, connectSeamless, connectWithPassword, disconnect, getCode, isConnected, reactGuardian, setCode };
|
|
341
|
+
|
|
342
|
+
//# sourceMappingURL=index.js.map
|
package/lib/index.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/constants.ts","../src/browser.ts","../src/crypto.ts","../src/session.ts","../src/env.ts","../src/verify.ts","../src/connect.ts","../src/disconnect.ts","../src/guardian.ts"],"sourcesContent":["/** Name of the `.env` variable holding the expected access code. */\nexport const CODE_ENV = 'BEMEDEV_CODE_ENV';\n\n/** Key used to persist the access code in `sessionStorage`. */\nexport const SESSION_KEY = 'bemedev:react-guardian:code';\n\n/** Query parameter carrying the code during a seamless connection. */\nexport const CODE_PARAM = 'code';\n\n/** Query parameter carrying the page to open after a connection. */\nexport const REDIRECT_PARAM = 'redirect';\n\n/** Value stored when the website has no access code configured. */\nexport const OPEN_CODE = 'bemedev:open';\n\n/** Default page opened after a successful connection. */\nexport const DEFAULT_REDIRECT = '/';\n\n/** Secret used to derive the AES-GCM session key. */\nexport const ENCRYPTION_SECRET = 'bemedev:react-guardian:v1';\n\n/** AES-GCM encryption algorithm. */\nexport const ENCRYPTION_ALGORITHM = 'AES-GCM';\n\n/** Length of the AES-GCM initialization vector, in bytes. */\nexport const IV_LENGTH = 12;\n","import { CODE_PARAM, REDIRECT_PARAM } from './constants';\n\n/**\n * Returns the browser session storage, when available.\n *\n * @returns The session storage, or `undefined` during server rendering.\n */\nexport function getSessionStorage(): Storage | undefined {\n if (typeof window === 'undefined') return undefined;\n\n try {\n return window.sessionStorage;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Returns the current browser URL, when available.\n *\n * @returns The current URL, or `undefined` during server rendering.\n */\nexport function getCurrentUrl(): URL | undefined {\n if (typeof window === 'undefined') return undefined;\n\n return new URL(window.location.href);\n}\n\n/**\n * Default navigation implementation.\n *\n * Uses `window.location.replace` so a successful connection does not leave the\n * connexion page in the browser history.\n *\n * @param href - Absolute or relative URL to open.\n */\nexport function defaultNavigate(href: string): void {\n if (typeof window !== 'undefined') window.location.replace(href);\n}\n\n/**\n * Reads the code from the `code` query parameter of the current URL.\n *\n * @returns The code, or `undefined` when it is not present.\n */\nexport function readUrlCode(): string | undefined {\n return getCurrentUrl()?.searchParams.get(CODE_PARAM) ?? undefined;\n}\n\n/**\n * Reads the page to open from the `redirect` query parameter of the current URL.\n *\n * @returns The requested page, or `undefined` when it is not present.\n */\nexport function readUrlRedirect(): string | undefined {\n return getCurrentUrl()?.searchParams.get(REDIRECT_PARAM) ?? undefined;\n}\n","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","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","/** 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","import { createServerFn } from '@tanstack/react-start';\n\nimport { CODE_ENV } from './constants';\nimport { readEnv } from './env';\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 = 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","import { defaultNavigate, readUrlCode, readUrlRedirect } from './browser';\nimport { DEFAULT_REDIRECT, OPEN_CODE } from './constants';\nimport { setCode } from './session';\nimport { verifyCode } from './verify';\n\n/**\n * Options accepted by {@linkcode connect}.\n */\nexport type ConnectOptions = {\n /**\n * Password entered by the visitor.\n *\n * When omitted, {@linkcode connect} runs the seamless variant and reads the code\n * from the `code` query parameter.\n */\n password?: string;\n\n /**\n * Page to open after a successful connection.\n *\n * Defaults to the `redirect` query parameter, then to `/`.\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 * Connects the visitor with or without a password.\n *\n * - With `options.password`, the entered password is verified on the server.\n * - Without `options.password`, the `code` query parameter is read from the current\n * URL and verified on the server. This is the seamless redirect variant used when a\n * connexion page sends the visitor back to the client website.\n *\n * On success the verified code is stored in `sessionStorage`, the visitor is sent to\n * the requested page, and the function resolves to `true`. On failure nothing is\n * stored or navigated, and the function resolves to `false`.\n *\n * @param options - Connection options.\n *\n * @returns `true` when the visitor is connected, `false` otherwise.\n *\n * @see -- type {@linkcode ConnectOptions}\n */\nexport async function connect(options: ConnectOptions = {}): Promise<boolean> {\n const code = options.password ?? readUrlCode() ?? '';\n const valid = await verifyCode({ data: code });\n\n if (!valid) return false;\n\n await setCode(code || OPEN_CODE);\n\n const target = options.redirectTo ?? readUrlRedirect() ?? DEFAULT_REDIRECT;\n const navigate = options.navigate ?? defaultNavigate;\n\n navigate(target);\n\n return true;\n}\n\n/**\n * Connects the visitor with a password.\n *\n * @param password - Password entered by the visitor.\n * @param options - Connection options without the password.\n *\n * @returns `true` when the visitor is connected, `false` otherwise.\n *\n * @see {@linkcode connect}\n */\nexport function connectWithPassword(\n password: string,\n options: Omit<ConnectOptions, 'password'> = {},\n): Promise<boolean> {\n return connect({ ...options, password });\n}\n\n/**\n * Connects the visitor seamlessly from the `code` query parameter.\n *\n * @param options - Connection options without the password.\n *\n * @returns `true` when the visitor is connected, `false` otherwise.\n *\n * @see {@linkcode connect}\n */\nexport function connectSeamless(\n options: Omit<ConnectOptions, 'password'> = {},\n): Promise<boolean> {\n return connect(options);\n}\n","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","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":"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"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,80 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bemedev/react-guardian",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0",
|
|
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": "https://github.com/chlbri/react-guardian"
|
|
35
|
+
},
|
|
36
|
+
"homepage": "https://github.com/chlbri/react-guardian#readme",
|
|
37
|
+
"files": [
|
|
38
|
+
"lib",
|
|
39
|
+
"package.json"
|
|
40
|
+
],
|
|
41
|
+
"type": "module",
|
|
42
|
+
"main": "lib/index.js",
|
|
43
|
+
"module": "lib/index.js",
|
|
44
|
+
"types": "lib/index.d.ts",
|
|
45
|
+
"sideEffects": false,
|
|
46
|
+
"peerDependencies": {
|
|
47
|
+
"@tanstack/react-router": "^1.170.0",
|
|
48
|
+
"@tanstack/react-start": "^1.170.0"
|
|
49
|
+
},
|
|
50
|
+
"devDependencies": {
|
|
51
|
+
"@bemedev/dev-utils": "^1.6.2",
|
|
52
|
+
"@size-limit/file": "^14.3.0",
|
|
53
|
+
"@tanstack/react-router": "^1.170.46",
|
|
54
|
+
"@tanstack/react-start": "^1.170.0",
|
|
55
|
+
"size-limit": "^14.3.0",
|
|
56
|
+
"typescript": "6.0.3",
|
|
57
|
+
"vite-plus": "1.9.0"
|
|
58
|
+
},
|
|
59
|
+
"size-limit": [
|
|
60
|
+
{
|
|
61
|
+
"path": "lib/**/*.js",
|
|
62
|
+
"limit": "20kb"
|
|
63
|
+
},
|
|
64
|
+
{
|
|
65
|
+
"path": "lib/**/*.d.ts",
|
|
66
|
+
"limit": "10kb"
|
|
67
|
+
}
|
|
68
|
+
],
|
|
69
|
+
"scripts": {
|
|
70
|
+
"p-q": "pretty-quick",
|
|
71
|
+
"posttest": "vp fmt",
|
|
72
|
+
"pretest": "vp run pack",
|
|
73
|
+
"rm:lib": "vp dlx rimraf ./lib",
|
|
74
|
+
"publish:first": "vp run pretest && pnpm publish --access public --no-git-checks",
|
|
75
|
+
"test:coverage": "vp test run",
|
|
76
|
+
"test": "vp run test:coverage --no-coverage",
|
|
77
|
+
"test:only": "vp run test",
|
|
78
|
+
"test:watch": "vp test"
|
|
79
|
+
}
|
|
6
80
|
}
|