@aiveth/nextjs 0.0.0-stage → 0.3.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/CHANGELOG.md ADDED
@@ -0,0 +1,14 @@
1
+ # Changelog
2
+
3
+ ## 0.3.0 — 2026-11-25 — first release
4
+
5
+ - `aivethProxy()` for `proxy.ts` (Next.js 16) or `middleware.ts` (15): answers `/auth/login`,
6
+ `/auth/callback`, `/auth/logout` and `/auth/session`; keeps the session alive (a new access token
7
+ a minute before it ends); sends signed-out people from `protect` paths to sign in.
8
+ - Sign-in on Aiveth's page: authorization code + PKCE (S256), `state`, `nonce`, the issuer checked
9
+ (RFC 9207); the ID token checked against Aiveth's keys.
10
+ - The session is ONE encrypted cookie (JWE `dir` + `A256GCM`), HttpOnly, SameSite=Lax, Secure on
11
+ https, split when big; signed out after a day without a visit and a week after signing in.
12
+ - Server: `getUser()`, `getSession()`, `requireUser()`, `getAccessToken()`.
13
+ - Browser (`@aiveth/nextjs/client`): `AivethProvider`, `useUser`, `SignedIn`, `SignedOut`,
14
+ `SignInButton`, `SignOutButton`, `UserButton`. No token ever reaches the browser.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,72 @@
1
- # Temporary Holding Version
1
+ # @aiveth/nextjs
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
+ Aiveth by Gooclaim for Next.js 15 and 16 (App Router). Sign-in happens on Aiveth's page; your app
4
+ keeps the session in one encrypted, HttpOnly cookie — no database.
5
+
6
+ ## Set up
7
+
8
+ 1. In the Aiveth console: **Apps → Register app → Server app**. Return address
9
+ `https://your-app.com/auth/callback`, sign-out address `https://your-app.com`. While you build,
10
+ use your Development environment and `http://localhost:3000`.
11
+ 2. Environment:
12
+
13
+ ```bash
14
+ AIVETH_BASE_URL=https://accounts.aiveth.com
15
+ AIVETH_CLIENT_ID=okc_...
16
+ AIVETH_CLIENT_SECRET=oks_...
17
+ AIVETH_COOKIE_SECRET=$(openssl rand -base64 32) # at least 32 characters
18
+ AIVETH_APP_URL=https://your-app.com
19
+ ```
20
+
21
+ 3. `proxy.ts` (Next.js 16) — or `middleware.ts` (15):
22
+
23
+ ```ts
24
+ import { aivethProxy } from '@aiveth/nextjs';
25
+
26
+ export default aivethProxy({ protect: ['/dashboard'] });
27
+ export const config = { matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'] };
28
+ ```
29
+
30
+ ## On the server
31
+
32
+ ```tsx
33
+ import { getAccessToken, requireUser } from '@aiveth/nextjs';
34
+
35
+ export default async function Dashboard() {
36
+ const user = await requireUser('/dashboard'); // not signed in → off to sign in, then back here
37
+ const token = await getAccessToken(); // for your API: Authorization: Bearer …
38
+ return <p>Hello {user.name}</p>;
39
+ }
40
+ ```
41
+
42
+ Check again where the data is (`requireUser()` in the page, the Route Handler, the Server
43
+ Action): the proxy is a convenience, not the lock.
44
+
45
+ ## In the browser
46
+
47
+ ```tsx
48
+ // app/layout.tsx
49
+ import { getUser } from '@aiveth/nextjs';
50
+ import { AivethProvider } from '@aiveth/nextjs/client';
51
+
52
+ export default async function RootLayout({ children }: { children: React.ReactNode }) {
53
+ return <html lang="en"><body><AivethProvider initialUser={await getUser()}>{children}</AivethProvider></body></html>;
54
+ }
55
+ ```
56
+
57
+ ```tsx
58
+ 'use client';
59
+ import { SignedIn, SignedOut, SignInButton, UserButton, useUser } from '@aiveth/nextjs/client';
60
+
61
+ <SignedOut><SignInButton returnTo="/dashboard" /></SignedOut>
62
+ <SignedIn><UserButton /></SignedIn>
63
+ ```
64
+
65
+ ## Routes the proxy answers
66
+
67
+ | Route | What it does |
68
+ |---|---|
69
+ | `/auth/login?returnTo=/path` | Sends the person to Aiveth to sign in |
70
+ | `/auth/callback` | Aiveth's answer: checks it and writes the session |
71
+ | `/auth/logout` | Clears the session, then signs out at Aiveth and comes back |
72
+ | `/auth/session` | `{ user }` for the browser — never a token |
@@ -0,0 +1,34 @@
1
+ import { type ReactNode } from 'react';
2
+ import type { User } from './session.js';
3
+ interface UseUser {
4
+ user: User | null;
5
+ loading: boolean;
6
+ reload: () => Promise<void>;
7
+ }
8
+ /** `initialUser`: pass `await getUser()` from a Server Component to skip the first fetch. */
9
+ export declare function AivethProvider({ children, initialUser }: {
10
+ children: ReactNode;
11
+ initialUser?: User | null;
12
+ }): import("react").JSX.Element;
13
+ export declare function useUser(): UseUser;
14
+ export declare function SignedIn({ children }: {
15
+ children: ReactNode;
16
+ }): import("react").JSX.Element | null;
17
+ export declare function SignedOut({ children }: {
18
+ children: ReactNode;
19
+ }): import("react").JSX.Element | null;
20
+ /** `returnTo`: where to come back after signing in (a path on this site). */
21
+ export declare function SignInButton({ children, returnTo, className }: {
22
+ children?: ReactNode;
23
+ returnTo?: string;
24
+ className?: string;
25
+ }): import("react").JSX.Element;
26
+ export declare function SignOutButton({ children, className }: {
27
+ children?: ReactNode;
28
+ className?: string;
29
+ }): import("react").JSX.Element;
30
+ /** The person's photo (or initial) and name, with a sign-out link. Style it with `className`. */
31
+ export declare function UserButton({ className }: {
32
+ className?: string;
33
+ }): import("react").JSX.Element | null;
34
+ export {};
package/dist/client.js ADDED
@@ -0,0 +1,61 @@
1
+ 'use client';
2
+ import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
3
+ /* The person in the browser. The profile comes from `/auth/session` (the cookie is HttpOnly: no
4
+ * token ever reaches the browser). Sign in and out are links to the proxy's routes. */
5
+ import { createContext, useCallback, useContext, useEffect, useState } from 'react';
6
+ import { ROUTES } from './config.js';
7
+ const Ctx = createContext(null);
8
+ /** `initialUser`: pass `await getUser()` from a Server Component to skip the first fetch. */
9
+ export function AivethProvider({ children, initialUser }) {
10
+ const [user, setUser] = useState(initialUser ?? null);
11
+ const [loading, setLoading] = useState(initialUser === undefined);
12
+ const reload = useCallback(async () => {
13
+ try {
14
+ const res = await fetch(ROUTES.session, { credentials: 'same-origin', cache: 'no-store' });
15
+ setUser(res.ok ? (await res.json()).user : null);
16
+ }
17
+ catch {
18
+ setUser(null);
19
+ }
20
+ finally {
21
+ setLoading(false);
22
+ }
23
+ }, []);
24
+ useEffect(() => {
25
+ if (initialUser === undefined)
26
+ void reload();
27
+ }, [initialUser, reload]);
28
+ return _jsx(Ctx.Provider, { value: { user, loading, reload }, children: children });
29
+ }
30
+ export function useUser() {
31
+ const found = useContext(Ctx);
32
+ if (!found)
33
+ throw new Error('useUser needs <AivethProvider> around your app.');
34
+ return found;
35
+ }
36
+ export function SignedIn({ children }) {
37
+ const { user } = useUser();
38
+ return user ? _jsx(_Fragment, { children: children }) : null;
39
+ }
40
+ export function SignedOut({ children }) {
41
+ const { user, loading } = useUser();
42
+ return !loading && !user ? _jsx(_Fragment, { children: children }) : null;
43
+ }
44
+ /** `returnTo`: where to come back after signing in (a path on this site). */
45
+ export function SignInButton({ children = 'Sign in', returnTo, className }) {
46
+ const href = returnTo ? `${ROUTES.login}?${new URLSearchParams({ returnTo })}` : ROUTES.login;
47
+ return _jsx("a", { href: href, className: className, children: children });
48
+ }
49
+ export function SignOutButton({ children = 'Sign out', className }) {
50
+ return _jsx("a", { href: ROUTES.logout, className: className, children: children });
51
+ }
52
+ /** The person's photo (or initial) and name, with a sign-out link. Style it with `className`. */
53
+ export function UserButton({ className }) {
54
+ const { user } = useUser();
55
+ if (!user)
56
+ return null;
57
+ const name = user.name || user.email || 'Signed in';
58
+ return (_jsxs("span", { className: className, style: { display: 'inline-flex', alignItems: 'center', gap: 8 }, children: [user.picture
59
+ ? _jsx("img", { src: user.picture, alt: "", width: 28, height: 28, style: { borderRadius: '50%' } })
60
+ : _jsx("span", { "aria-hidden": "true", style: { width: 28, height: 28, borderRadius: '50%', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', background: '#e5e7eb', color: '#111827', fontWeight: 600 }, children: name.charAt(0).toUpperCase() }), _jsx("span", { children: name }), _jsx(SignOutButton, {})] }));
61
+ }
@@ -0,0 +1,30 @@
1
+ export interface AivethNextConfig {
2
+ /** Your Aiveth address, e.g. https://accounts.aiveth.com */
3
+ baseUrl: string;
4
+ /** A SERVER app's client id (Apps → Register app → Server app). */
5
+ clientId: string;
6
+ clientSecret: string;
7
+ /** At least 32 characters: the key of the session cookie. Never commit it. */
8
+ cookieSecret: string;
9
+ /** Your app's own address, e.g. https://app.acme.com — `${appUrl}/auth/callback` must be one of
10
+ * the app's return addresses, and `appUrl` its sign-out address. */
11
+ appUrl: string;
12
+ /** Space-separated. `offline_access` keeps the person signed in past the access token. */
13
+ scope: string;
14
+ /** For tests, or a runtime without a global fetch. */
15
+ fetch?: typeof fetch;
16
+ }
17
+ export declare const ROUTES: {
18
+ readonly login: "/auth/login";
19
+ readonly callback: "/auth/callback";
20
+ readonly logout: "/auth/logout";
21
+ readonly session: "/auth/session";
22
+ };
23
+ /** Use these settings instead of the environment's (or on top of them). */
24
+ export declare function configureAiveth(settings: Partial<AivethNextConfig>): void;
25
+ export declare function config(): AivethNextConfig;
26
+ /** Forget the settings (tests). */
27
+ export declare function resetConfig(): void;
28
+ export declare function redirectUri(c: AivethNextConfig): string;
29
+ /** A path on this site only — never `//other.example` or a full address (no open redirect). */
30
+ export declare function safeReturnTo(value: string | null | undefined): string;
package/dist/config.js ADDED
@@ -0,0 +1,68 @@
1
+ /* The app's settings: read once from the environment (or handed in with `configureAiveth`). */
2
+ export const ROUTES = {
3
+ login: '/auth/login',
4
+ callback: '/auth/callback',
5
+ logout: '/auth/logout',
6
+ session: '/auth/session',
7
+ };
8
+ const DEFAULT_SCOPE = 'openid profile email offline_access';
9
+ let current = null;
10
+ function trimmed(url) {
11
+ return url.replace(/\/+$/, '');
12
+ }
13
+ /** https, or http only for this machine (development). */
14
+ function checkedUrl(name, url) {
15
+ let parsed;
16
+ try {
17
+ parsed = new URL(url);
18
+ }
19
+ catch {
20
+ throw new Error(`${name} must be a full address, like https://example.com`);
21
+ }
22
+ const local = ['localhost', '127.0.0.1', '[::1]'].includes(parsed.hostname);
23
+ if (parsed.protocol !== 'https:' && !(parsed.protocol === 'http:' && local)) {
24
+ throw new Error(`${name} must use https (http only for localhost).`);
25
+ }
26
+ return trimmed(url);
27
+ }
28
+ function checked(c) {
29
+ for (const [name, value] of Object.entries({ AIVETH_CLIENT_ID: c.clientId, AIVETH_CLIENT_SECRET: c.clientSecret })) {
30
+ if (!value)
31
+ throw new Error(`${name} is not set.`);
32
+ }
33
+ if (!c.cookieSecret || c.cookieSecret.length < 32)
34
+ throw new Error('AIVETH_COOKIE_SECRET must be at least 32 characters.');
35
+ return { ...c, baseUrl: checkedUrl('AIVETH_BASE_URL', c.baseUrl), appUrl: checkedUrl('AIVETH_APP_URL', c.appUrl) };
36
+ }
37
+ /** Use these settings instead of the environment's (or on top of them). */
38
+ export function configureAiveth(settings) {
39
+ current = checked({ ...fromEnv(), ...settings });
40
+ }
41
+ function fromEnv() {
42
+ const env = typeof process === 'undefined' ? {} : process.env;
43
+ return {
44
+ baseUrl: env.AIVETH_BASE_URL ?? '',
45
+ clientId: env.AIVETH_CLIENT_ID ?? '',
46
+ clientSecret: env.AIVETH_CLIENT_SECRET ?? '',
47
+ cookieSecret: env.AIVETH_COOKIE_SECRET ?? '',
48
+ appUrl: env.AIVETH_APP_URL ?? '',
49
+ scope: env.AIVETH_SCOPES || DEFAULT_SCOPE,
50
+ };
51
+ }
52
+ export function config() {
53
+ current ??= checked(fromEnv());
54
+ return current;
55
+ }
56
+ /** Forget the settings (tests). */
57
+ export function resetConfig() {
58
+ current = null;
59
+ }
60
+ export function redirectUri(c) {
61
+ return `${c.appUrl}${ROUTES.callback}`;
62
+ }
63
+ /** A path on this site only — never `//other.example` or a full address (no open redirect). */
64
+ export function safeReturnTo(value) {
65
+ if (!value || !value.startsWith('/') || value.startsWith('//') || value.startsWith('/\\'))
66
+ return '/';
67
+ return value;
68
+ }
@@ -0,0 +1,10 @@
1
+ import { NextResponse, type NextRequest } from 'next/server';
2
+ import { type AivethNextConfig } from './config.js';
3
+ import { type CookieToSet } from './session.js';
4
+ export declare const secureFor: (c: AivethNextConfig) => boolean;
5
+ export declare function write(res: NextResponse, cookies: CookieToSet[]): NextResponse;
6
+ export declare function login(req: NextRequest, c: AivethNextConfig): Promise<NextResponse>;
7
+ export declare function callback(req: NextRequest, c: AivethNextConfig): Promise<NextResponse>;
8
+ export declare function logout(req: NextRequest, c: AivethNextConfig): Promise<NextResponse>;
9
+ /** Who is signed in, for the browser (`AivethProvider`): the profile only, never a token. */
10
+ export declare function sessionJson(req: NextRequest, c: AivethNextConfig): Promise<NextResponse>;
@@ -0,0 +1,62 @@
1
+ /* The routes the proxy answers: /auth/login, /auth/callback, /auth/logout, /auth/session. */
2
+ import { NextResponse } from 'next/server';
3
+ import { ROUTES, safeReturnTo } from './config.js';
4
+ import { AivethAuthError, authorizeUrl, challengeOf, exchangeCode, logoutUrl, randomValue } from './oidc.js';
5
+ import { TX_COOKIE, TX_SECONDS, clearedSessionCookies, readSession, seal, sessionCookies, txCookie, unseal, } from './session.js';
6
+ export const secureFor = (c) => c.appUrl.startsWith('https://');
7
+ export function write(res, cookies) {
8
+ for (const { name, value, options } of cookies)
9
+ res.cookies.set(name, value, options);
10
+ return res;
11
+ }
12
+ function failed(why, status = 400) {
13
+ const page = `<!doctype html><meta charset="utf-8"><title>Sign-in failed</title>` +
14
+ `<p>${why.replace(/[<>&]/g, '')}</p><p><a href="${ROUTES.login}">Try again</a></p>`;
15
+ return new NextResponse(page, { status, headers: { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' } });
16
+ }
17
+ export async function login(req, c) {
18
+ const tx = {
19
+ state: randomValue(), nonce: randomValue(), verifier: randomValue(),
20
+ returnTo: safeReturnTo(req.nextUrl.searchParams.get('returnTo')),
21
+ };
22
+ const to = await authorizeUrl(c, {
23
+ state: tx.state, nonce: tx.nonce, challenge: await challengeOf(tx.verifier),
24
+ loginHint: req.nextUrl.searchParams.get('login_hint') ?? undefined,
25
+ });
26
+ return write(NextResponse.redirect(to), [txCookie(await seal(tx, c.cookieSecret, TX_SECONDS), secureFor(c))]);
27
+ }
28
+ export async function callback(req, c) {
29
+ const q = req.nextUrl.searchParams;
30
+ const tx = await unseal(req.cookies.get(TX_COOKIE)?.value, c.cookieSecret);
31
+ if (!tx)
32
+ return failed('This sign-in took too long or started in another browser.');
33
+ if (q.get('state') !== tx.state)
34
+ return failed('This sign-in does not belong to this browser.');
35
+ const iss = q.get('iss');
36
+ if (iss && iss.replace(/\/+$/, '') !== c.baseUrl)
37
+ return failed('The answer came from another issuer.');
38
+ if (q.get('error'))
39
+ return failed(q.get('error_description') ?? 'Aiveth did not sign you in.');
40
+ const code = q.get('code');
41
+ if (!code)
42
+ return failed('Aiveth sent no code.');
43
+ try {
44
+ const session = await exchangeCode(c, code, tx.verifier, tx.nonce);
45
+ const res = NextResponse.redirect(new URL(tx.returnTo, c.appUrl));
46
+ res.cookies.set(TX_COOKIE, '', { path: '/', maxAge: 0 });
47
+ return write(res, await sessionCookies(session, c.cookieSecret, secureFor(c), req.cookies));
48
+ }
49
+ catch (exc) {
50
+ return failed(exc instanceof AivethAuthError ? exc.message : 'Sign-in failed.', 502);
51
+ }
52
+ }
53
+ export async function logout(req, c) {
54
+ const session = await readSession(req.cookies, c.cookieSecret);
55
+ const res = NextResponse.redirect(await logoutUrl(c, session?.idToken));
56
+ return write(res, clearedSessionCookies(secureFor(c), req.cookies));
57
+ }
58
+ /** Who is signed in, for the browser (`AivethProvider`): the profile only, never a token. */
59
+ export async function sessionJson(req, c) {
60
+ const session = await readSession(req.cookies, c.cookieSecret);
61
+ return NextResponse.json({ user: session?.user ?? null }, { headers: { 'Cache-Control': 'no-store' } });
62
+ }
@@ -0,0 +1,5 @@
1
+ export { aivethProxy, REFRESH_BEFORE_SECONDS, type AivethProxyOptions, type Protect } from './proxy.js';
2
+ export { getAccessToken, getSession, getUser, requireUser } from './server.js';
3
+ export { configureAiveth, ROUTES, type AivethNextConfig } from './config.js';
4
+ export { AivethAuthError } from './oidc.js';
5
+ export type { Session, User } from './session.js';
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export { aivethProxy, REFRESH_BEFORE_SECONDS } from './proxy.js';
2
+ export { getAccessToken, getSession, getUser, requireUser } from './server.js';
3
+ export { configureAiveth, ROUTES } from './config.js';
4
+ export { AivethAuthError } from './oidc.js';
package/dist/oidc.d.ts ADDED
@@ -0,0 +1,39 @@
1
+ import { type AivethNextConfig } from './config.js';
2
+ import { type Session, type User } from './session.js';
3
+ interface Discovery {
4
+ issuer: string;
5
+ authorization_endpoint: string;
6
+ token_endpoint: string;
7
+ jwks_uri: string;
8
+ end_session_endpoint?: string;
9
+ }
10
+ interface TokenAnswer {
11
+ access_token: string;
12
+ id_token?: string;
13
+ refresh_token?: string;
14
+ expires_in?: number;
15
+ }
16
+ /** Aiveth said no (a code used twice, a refresh token that ended…). */
17
+ export declare class AivethAuthError extends Error {
18
+ readonly status?: number | undefined;
19
+ constructor(message: string, status?: number | undefined);
20
+ }
21
+ export declare function discover(c: AivethNextConfig): Promise<Discovery>;
22
+ /** Forget discovery and keys (tests). */
23
+ export declare function forgetAiveth(): void;
24
+ export declare function randomValue(): string;
25
+ export declare function challengeOf(verifier: string): Promise<string>;
26
+ export declare function authorizeUrl(c: AivethNextConfig, a: {
27
+ state: string;
28
+ nonce: string;
29
+ challenge: string;
30
+ loginHint?: string;
31
+ }): Promise<string>;
32
+ /** The ID token's claims: signed by Aiveth, for this app, live — and, on sign-in, this nonce. */
33
+ export declare function verifyIdToken(c: AivethNextConfig, idToken: string, nonce?: string): Promise<User>;
34
+ export declare function sessionFrom(t: TokenAnswer, user: User, idToken: string, createdAt?: number): Session;
35
+ export declare function exchangeCode(c: AivethNextConfig, code: string, verifier: string, nonce: string): Promise<Session>;
36
+ /** A new access token (and, as Aiveth turns them, a new refresh token). */
37
+ export declare function refreshSession(c: AivethNextConfig, s: Session): Promise<Session>;
38
+ export declare function logoutUrl(c: AivethNextConfig, idToken: string | undefined): Promise<string>;
39
+ export {};
package/dist/oidc.js ADDED
@@ -0,0 +1,132 @@
1
+ /* Talking to Aiveth: discovery, the authorization address (PKCE S256, state, nonce), the code and
2
+ * refresh exchanges (the app's secret, `client_secret_post`), and the ID token check against
3
+ * Aiveth's keys (fetched once, cached, fetched again for a new key id). */
4
+ import { createLocalJWKSet, jwtVerify } from 'jose';
5
+ import { redirectUri } from './config.js';
6
+ import { now } from './session.js';
7
+ /** Aiveth said no (a code used twice, a refresh token that ended…). */
8
+ export class AivethAuthError extends Error {
9
+ status;
10
+ constructor(message, status) {
11
+ super(message);
12
+ this.status = status;
13
+ this.name = 'AivethAuthError';
14
+ }
15
+ }
16
+ const KEYS_FOR_SECONDS = 600;
17
+ const found = new Map();
18
+ const keySets = new Map();
19
+ const fetcher = (c) => c.fetch ?? globalThis.fetch.bind(globalThis);
20
+ export function discover(c) {
21
+ let known = found.get(c.baseUrl);
22
+ if (!known) {
23
+ known = (async () => {
24
+ const res = await fetcher(c)(`${c.baseUrl}/.well-known/openid-configuration`);
25
+ if (!res.ok)
26
+ throw new AivethAuthError(`Aiveth's discovery answered ${res.status}.`, res.status);
27
+ const doc = (await res.json());
28
+ if (doc.issuer.replace(/\/+$/, '') !== c.baseUrl)
29
+ throw new AivethAuthError('Discovery names another issuer than AIVETH_BASE_URL.');
30
+ return doc;
31
+ })();
32
+ known.catch(() => found.delete(c.baseUrl));
33
+ found.set(c.baseUrl, known);
34
+ }
35
+ return known;
36
+ }
37
+ /** Forget discovery and keys (tests). */
38
+ export function forgetAiveth() {
39
+ found.clear();
40
+ keySets.clear();
41
+ }
42
+ const b64url = (bytes) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
43
+ export function randomValue() {
44
+ return b64url(crypto.getRandomValues(new Uint8Array(32)));
45
+ }
46
+ export async function challengeOf(verifier) {
47
+ return b64url(new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier))));
48
+ }
49
+ export async function authorizeUrl(c, a) {
50
+ const d = await discover(c);
51
+ const q = new URLSearchParams({
52
+ response_type: 'code', client_id: c.clientId, redirect_uri: redirectUri(c), scope: c.scope,
53
+ state: a.state, nonce: a.nonce, code_challenge: a.challenge, code_challenge_method: 'S256',
54
+ });
55
+ if (a.loginHint)
56
+ q.set('login_hint', a.loginHint);
57
+ return `${d.authorization_endpoint}?${q}`;
58
+ }
59
+ async function token(c, form) {
60
+ const d = await discover(c);
61
+ const res = await fetcher(c)(d.token_endpoint, {
62
+ method: 'POST',
63
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' },
64
+ body: new URLSearchParams({ ...form, client_id: c.clientId, client_secret: c.clientSecret }),
65
+ });
66
+ const body = (await res.json().catch(() => ({})));
67
+ if (!res.ok || typeof body.access_token !== 'string') {
68
+ throw new AivethAuthError(body.error_description ?? `Aiveth answered ${res.status}.`, res.status);
69
+ }
70
+ return body;
71
+ }
72
+ async function keySet(c, fresh) {
73
+ const held = keySets.get(c.baseUrl);
74
+ if (held && !fresh && Date.now() / 1000 - held.at < KEYS_FOR_SECONDS)
75
+ return held.set;
76
+ const res = await fetcher(c)((await discover(c)).jwks_uri);
77
+ if (!res.ok)
78
+ throw new AivethAuthError(`Aiveth's keys answered ${res.status}.`, res.status);
79
+ const set = createLocalJWKSet((await res.json()));
80
+ keySets.set(c.baseUrl, { set, at: Date.now() / 1000 });
81
+ return set;
82
+ }
83
+ /** The ID token's claims: signed by Aiveth, for this app, live — and, on sign-in, this nonce. */
84
+ export async function verifyIdToken(c, idToken, nonce) {
85
+ const d = await discover(c);
86
+ const check = async (fresh) => jwtVerify(idToken, await keySet(c, fresh), { issuer: d.issuer, audience: c.clientId, clockTolerance: 60, algorithms: ['RS256'] });
87
+ let claims;
88
+ try {
89
+ claims = (await check(false)).payload;
90
+ }
91
+ catch (exc) {
92
+ if (exc.code !== 'ERR_JWKS_NO_MATCHING_KEY')
93
+ throw new AivethAuthError('The ID token did not check out.');
94
+ claims = (await check(true)).payload; // a new key id: Aiveth turned its keys
95
+ }
96
+ if (nonce !== undefined && claims.nonce !== nonce)
97
+ throw new AivethAuthError('The ID token was not made for this sign-in.');
98
+ if (typeof claims.sub !== 'string' || typeof claims.org_id !== 'string')
99
+ throw new AivethAuthError('Not an Aiveth ID token.');
100
+ const { iss: _i, aud: _a, exp: _e, iat: _t, nonce: _n, auth_time: _at, at_hash: _h, sid: _s, ...user } = claims;
101
+ return user;
102
+ }
103
+ export function sessionFrom(t, user, idToken, createdAt = now()) {
104
+ return {
105
+ user, idToken, accessToken: t.access_token, refreshToken: t.refresh_token ?? null,
106
+ expiresAt: now() + (t.expires_in ?? 300), createdAt,
107
+ };
108
+ }
109
+ export async function exchangeCode(c, code, verifier, nonce) {
110
+ const t = await token(c, { grant_type: 'authorization_code', code, redirect_uri: redirectUri(c), code_verifier: verifier });
111
+ if (!t.id_token)
112
+ throw new AivethAuthError('Aiveth sent no ID token: the scope needs openid.');
113
+ return sessionFrom(t, await verifyIdToken(c, t.id_token, nonce), t.id_token);
114
+ }
115
+ /** A new access token (and, as Aiveth turns them, a new refresh token). */
116
+ export async function refreshSession(c, s) {
117
+ if (!s.refreshToken)
118
+ throw new AivethAuthError('No refresh token: ask for offline_access.');
119
+ const t = await token(c, { grant_type: 'refresh_token', refresh_token: s.refreshToken });
120
+ const idToken = t.id_token ?? s.idToken;
121
+ const user = t.id_token ? await verifyIdToken(c, t.id_token) : s.user;
122
+ return { ...sessionFrom(t, user, idToken, s.createdAt), refreshToken: t.refresh_token ?? s.refreshToken };
123
+ }
124
+ export async function logoutUrl(c, idToken) {
125
+ const d = await discover(c);
126
+ if (!d.end_session_endpoint)
127
+ return c.appUrl;
128
+ const q = new URLSearchParams({ client_id: c.clientId, post_logout_redirect_uri: c.appUrl });
129
+ if (idToken)
130
+ q.set('id_token_hint', idToken);
131
+ return `${d.end_session_endpoint}?${q}`;
132
+ }
@@ -0,0 +1,12 @@
1
+ import { NextResponse, type NextRequest } from 'next/server';
2
+ import { type AivethNextConfig } from './config.js';
3
+ export type Protect = (string | RegExp)[] | ((path: string) => boolean);
4
+ export interface AivethProxyOptions {
5
+ /** Paths that need a signed-in person: `'/dashboard'` covers `/dashboard` and below. */
6
+ protect?: Protect;
7
+ /** Settings instead of the environment's. */
8
+ config?: AivethNextConfig;
9
+ }
10
+ /** A new access token this long before the old one ends. */
11
+ export declare const REFRESH_BEFORE_SECONDS = 60;
12
+ export declare function aivethProxy(options?: AivethProxyOptions): (req: NextRequest) => Promise<NextResponse>;
package/dist/proxy.js ADDED
@@ -0,0 +1,67 @@
1
+ /* `proxy.ts` (Next.js 16) or `middleware.ts` (15): `export default aivethProxy({ protect: [...] })`.
2
+ * It answers /auth/*, keeps the session alive (a new access token a minute before it ends, the
3
+ * cookie renewed on every visit) and sends signed-out people from protected paths to sign in.
4
+ * 🔴 It is a convenience, not the lock: check again where the data is (`requireUser()` in the
5
+ * page, the Route Handler, the Server Action) — CVE-2025-29927 slipped past middleware alone. */
6
+ import { NextResponse } from 'next/server';
7
+ import { ROUTES, config } from './config.js';
8
+ import { callback, login, logout, secureFor, sessionJson, write } from './handlers.js';
9
+ import { refreshSession } from './oidc.js';
10
+ import { clearedSessionCookies, now, readSession, sessionCookies } from './session.js';
11
+ /** A new access token this long before the old one ends. */
12
+ export const REFRESH_BEFORE_SECONDS = 60;
13
+ function isProtected(path, protect) {
14
+ if (!protect)
15
+ return false;
16
+ if (typeof protect === 'function')
17
+ return protect(path);
18
+ return protect.some((p) => (typeof p === 'string' ? path === p || path.startsWith(`${p.replace(/\/+$/, '')}/`) : p.test(path)));
19
+ }
20
+ /** The request carries the new cookies too, so the page rendering now reads the fresh session. */
21
+ function nextWith(req, cookies) {
22
+ const jar = new Map(req.cookies.getAll().map((k) => [k.name, k.value]));
23
+ for (const { name, value } of cookies) {
24
+ if (value)
25
+ jar.set(name, value);
26
+ else
27
+ jar.delete(name);
28
+ }
29
+ const headers = new Headers(req.headers);
30
+ headers.set('cookie', [...jar].map(([n, v]) => `${n}=${v}`).join('; '));
31
+ return write(NextResponse.next({ request: { headers } }), cookies);
32
+ }
33
+ export function aivethProxy(options = {}) {
34
+ return async function proxy(req) {
35
+ const c = options.config ?? config();
36
+ const path = req.nextUrl.pathname;
37
+ if (path === ROUTES.login)
38
+ return login(req, c);
39
+ if (path === ROUTES.callback)
40
+ return callback(req, c);
41
+ if (path === ROUTES.logout)
42
+ return logout(req, c);
43
+ if (path === ROUTES.session)
44
+ return sessionJson(req, c);
45
+ let session = await readSession(req.cookies, c.cookieSecret);
46
+ let cookies = [];
47
+ if (session) {
48
+ if (session.expiresAt - now() < REFRESH_BEFORE_SECONDS && session.refreshToken) {
49
+ try {
50
+ session = await refreshSession(c, session);
51
+ }
52
+ catch {
53
+ session = null; // Aiveth no longer stands behind it: signed out, suspended, ended
54
+ }
55
+ }
56
+ cookies = session
57
+ ? await sessionCookies(session, c.cookieSecret, secureFor(c), req.cookies)
58
+ : clearedSessionCookies(secureFor(c), req.cookies);
59
+ }
60
+ if (!session && isProtected(path, options.protect)) {
61
+ const to = new URL(ROUTES.login, c.appUrl);
62
+ to.searchParams.set('returnTo', `${path}${req.nextUrl.search}`);
63
+ return write(NextResponse.redirect(to), cookies);
64
+ }
65
+ return nextWith(req, cookies);
66
+ };
67
+ }
@@ -0,0 +1,9 @@
1
+ import { type Session, type User } from './session.js';
2
+ export declare function getSession(): Promise<Session | null>;
3
+ export declare function getUser(): Promise<User | null>;
4
+ /** The person, or off to sign in (and back to `returnTo` after). */
5
+ export declare function requireUser(returnTo?: string): Promise<User>;
6
+ /** A live access token for your API (null when nobody is signed in). Renewed a minute before it
7
+ * ends; the new session is written where Next lets a cookie be written (Route Handlers, Server
8
+ * Actions) — in a Server Component it is used for this render, and the proxy writes it next time. */
9
+ export declare function getAccessToken(): Promise<string | null>;
package/dist/server.js ADDED
@@ -0,0 +1,44 @@
1
+ /* The person on the server: Server Components, Route Handlers and Server Actions. Each call reads
2
+ * and checks the cookie itself — never trusting that the proxy ran. */
3
+ import { cookies } from 'next/headers';
4
+ import { redirect } from 'next/navigation';
5
+ import { ROUTES, config, safeReturnTo } from './config.js';
6
+ import { secureFor } from './handlers.js';
7
+ import { refreshSession } from './oidc.js';
8
+ import { REFRESH_BEFORE_SECONDS } from './proxy.js';
9
+ import { now, readSession, sessionCookies } from './session.js';
10
+ export async function getSession() {
11
+ return readSession(await cookies(), config().cookieSecret);
12
+ }
13
+ export async function getUser() {
14
+ return (await getSession())?.user ?? null;
15
+ }
16
+ /** The person, or off to sign in (and back to `returnTo` after). */
17
+ export async function requireUser(returnTo) {
18
+ const user = await getUser();
19
+ if (!user)
20
+ redirect(`${ROUTES.login}?${new URLSearchParams({ returnTo: safeReturnTo(returnTo) })}`);
21
+ return user;
22
+ }
23
+ /** A live access token for your API (null when nobody is signed in). Renewed a minute before it
24
+ * ends; the new session is written where Next lets a cookie be written (Route Handlers, Server
25
+ * Actions) — in a Server Component it is used for this render, and the proxy writes it next time. */
26
+ export async function getAccessToken() {
27
+ const c = config();
28
+ const jar = await cookies();
29
+ let session = await readSession(jar, c.cookieSecret);
30
+ if (!session)
31
+ return null;
32
+ if (session.expiresAt - now() < REFRESH_BEFORE_SECONDS && session.refreshToken) {
33
+ session = await refreshSession(c, session);
34
+ try {
35
+ for (const { name, value, options } of await sessionCookies(session, c.cookieSecret, secureFor(c), jar)) {
36
+ jar.set(name, value, options);
37
+ }
38
+ }
39
+ catch {
40
+ // A Server Component: cookies are read-only while rendering.
41
+ }
42
+ }
43
+ return session.accessToken;
44
+ }
@@ -0,0 +1,60 @@
1
+ export interface User {
2
+ sub: string;
3
+ org_id: string;
4
+ email?: string;
5
+ email_verified?: boolean;
6
+ name?: string | null;
7
+ given_name?: string | null;
8
+ family_name?: string | null;
9
+ picture?: string;
10
+ role?: string;
11
+ permissions?: string[];
12
+ feature_flags?: string[];
13
+ [claim: string]: unknown;
14
+ }
15
+ export interface Session {
16
+ user: User;
17
+ idToken: string;
18
+ accessToken: string;
19
+ refreshToken: string | null;
20
+ /** When the access token ends (seconds since 1970). */
21
+ expiresAt: number;
22
+ /** When the person signed in (seconds since 1970): the session never outlives `ABSOLUTE_SECONDS`. */
23
+ createdAt: number;
24
+ }
25
+ export declare const SESSION_COOKIE = "aiveth-session";
26
+ export declare const TX_COOKIE = "aiveth-tx";
27
+ /** Signed out after a day without a visit (the cookie's age, renewed on every visit)… */
28
+ export declare const IDLE_SECONDS: number;
29
+ /** …and a week after signing in, whatever happens. */
30
+ export declare const ABSOLUTE_SECONDS: number;
31
+ /** The sign-in round trip has this long. */
32
+ export declare const TX_SECONDS: number;
33
+ /** Room for one cookie's value (browsers keep ~4096 bytes per cookie, name and options included). */
34
+ export declare const CHUNK = 3800;
35
+ export interface CookieJar {
36
+ get(name: string): {
37
+ value: string;
38
+ } | undefined;
39
+ }
40
+ export interface CookieToSet {
41
+ name: string;
42
+ value: string;
43
+ options: {
44
+ httpOnly: true;
45
+ secure: boolean;
46
+ sameSite: 'lax';
47
+ path: '/';
48
+ maxAge: number;
49
+ };
50
+ }
51
+ export declare const now: () => number;
52
+ export declare function seal(data: object, secret: string, seconds: number): Promise<string>;
53
+ /** The sealed value, or null: changed, sealed with another secret, or past its time. */
54
+ export declare function unseal<T>(token: string | undefined, secret: string): Promise<T | null>;
55
+ /** The session's cookies to write — and every part left from a bigger one, emptied. */
56
+ export declare function sessionCookies(session: Session, secret: string, secure: boolean, jar?: CookieJar): Promise<CookieToSet[]>;
57
+ /** Every session part, emptied (sign out, or a session Aiveth no longer stands behind). */
58
+ export declare function clearedSessionCookies(secure: boolean, jar: CookieJar): CookieToSet[];
59
+ export declare function readSession(jar: CookieJar, secret: string): Promise<Session | null>;
60
+ export declare function txCookie(value: string, secure: boolean): CookieToSet;
@@ -0,0 +1,86 @@
1
+ /* The session: ONE encrypted cookie (JWE, dir + A256GCM; the key is SHA-256 of the cookie secret),
2
+ * split into numbered parts when it is too big for one cookie. HttpOnly, SameSite=Lax, Secure on
3
+ * https. Nothing is kept on a server. Web Crypto only, so it runs where Next runs it. */
4
+ import { EncryptJWT, jwtDecrypt } from 'jose';
5
+ export const SESSION_COOKIE = 'aiveth-session';
6
+ export const TX_COOKIE = 'aiveth-tx';
7
+ /** Signed out after a day without a visit (the cookie's age, renewed on every visit)… */
8
+ export const IDLE_SECONDS = 24 * 3600;
9
+ /** …and a week after signing in, whatever happens. */
10
+ export const ABSOLUTE_SECONDS = 7 * 24 * 3600;
11
+ /** The sign-in round trip has this long. */
12
+ export const TX_SECONDS = 10 * 60;
13
+ /** Room for one cookie's value (browsers keep ~4096 bytes per cookie, name and options included). */
14
+ export const CHUNK = 3800;
15
+ const MOST_CHUNKS = 10;
16
+ const keys = new Map();
17
+ async function keyOf(secret) {
18
+ let key = keys.get(secret);
19
+ if (!key) {
20
+ key = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(secret)));
21
+ keys.set(secret, key);
22
+ }
23
+ return key;
24
+ }
25
+ export const now = () => Math.floor(Date.now() / 1000);
26
+ export async function seal(data, secret, seconds) {
27
+ return new EncryptJWT({ d: data }).setProtectedHeader({ alg: 'dir', enc: 'A256GCM' })
28
+ .setIssuedAt().setExpirationTime(now() + seconds).encrypt(await keyOf(secret));
29
+ }
30
+ /** The sealed value, or null: changed, sealed with another secret, or past its time. */
31
+ export async function unseal(token, secret) {
32
+ if (!token)
33
+ return null;
34
+ try {
35
+ const { payload } = await jwtDecrypt(token, await keyOf(secret));
36
+ return payload.d ?? null;
37
+ }
38
+ catch {
39
+ return null;
40
+ }
41
+ }
42
+ function options(secure, maxAge) {
43
+ return { httpOnly: true, secure, sameSite: 'lax', path: '/', maxAge };
44
+ }
45
+ /** The session's cookies to write — and every part left from a bigger one, emptied. */
46
+ export async function sessionCookies(session, secret, secure, jar) {
47
+ const left = session.createdAt + ABSOLUTE_SECONDS - now();
48
+ const age = Math.max(Math.min(IDLE_SECONDS, left), 0);
49
+ const value = await seal(session, secret, age);
50
+ const parts = [];
51
+ for (let i = 0; i < value.length; i += CHUNK)
52
+ parts.push(value.slice(i, i + CHUNK));
53
+ if (parts.length > MOST_CHUNKS)
54
+ throw new Error('The session is too big for cookies (ask for fewer scopes).');
55
+ const out = parts.map((part, i) => ({ name: `${SESSION_COOKIE}.${i}`, value: part, options: options(secure, age) }));
56
+ for (let i = parts.length; i < MOST_CHUNKS; i++) {
57
+ if (jar?.get(`${SESSION_COOKIE}.${i}`))
58
+ out.push({ name: `${SESSION_COOKIE}.${i}`, value: '', options: options(secure, 0) });
59
+ }
60
+ return out;
61
+ }
62
+ /** Every session part, emptied (sign out, or a session Aiveth no longer stands behind). */
63
+ export function clearedSessionCookies(secure, jar) {
64
+ const out = [];
65
+ for (let i = 0; i < MOST_CHUNKS; i++) {
66
+ if (i === 0 || jar.get(`${SESSION_COOKIE}.${i}`))
67
+ out.push({ name: `${SESSION_COOKIE}.${i}`, value: '', options: options(secure, 0) });
68
+ }
69
+ return out;
70
+ }
71
+ export async function readSession(jar, secret) {
72
+ let value = '';
73
+ for (let i = 0; i < MOST_CHUNKS; i++) {
74
+ const part = jar.get(`${SESSION_COOKIE}.${i}`)?.value;
75
+ if (!part)
76
+ break;
77
+ value += part;
78
+ }
79
+ const session = await unseal(value || undefined, secret);
80
+ if (!session || typeof session.user?.sub !== 'string' || session.createdAt + ABSOLUTE_SECONDS <= now())
81
+ return null;
82
+ return session;
83
+ }
84
+ export function txCookie(value, secure) {
85
+ return { name: TX_COOKIE, value, options: options(secure, TX_SECONDS) };
86
+ }
package/package.json CHANGED
@@ -1,6 +1,35 @@
1
1
  {
2
2
  "name": "@aiveth/nextjs",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.3.0",
4
+ "description": "Aiveth by Gooclaim for Next.js: sign in on Aiveth's page, an encrypted session cookie, the user on the server and in the browser.",
5
+ "license": "Apache-2.0",
6
+ "author": "Gooclaim",
7
+ "keywords": ["aiveth", "gooclaim", "nextjs", "next", "auth", "authentication", "oidc", "pkce", "sso"],
8
+ "type": "module",
9
+ "main": "./dist/index.js",
10
+ "types": "./dist/index.d.ts",
11
+ "exports": {
12
+ ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" },
13
+ "./client": { "types": "./dist/client.d.ts", "import": "./dist/client.js" }
14
+ },
15
+ "files": ["dist", "LICENSE", "README.md", "CHANGELOG.md"],
16
+ "sideEffects": false,
17
+ "publishConfig": { "access": "public" },
18
+ "scripts": {
19
+ "build": "tsc -p tsconfig.build.json",
20
+ "typecheck": "tsc -p tsconfig.json --noEmit",
21
+ "test": "vitest run",
22
+ "prepublishOnly": "npm run typecheck && npm test && npm run build"
23
+ },
24
+ "dependencies": { "jose": "5.9.6" },
25
+ "peerDependencies": { "next": ">=15", "react": ">=19" },
26
+ "devDependencies": {
27
+ "@types/node": "20.17.10",
28
+ "@types/react": "19.3.0",
29
+ "next": "16.4.6",
30
+ "react": "19.3.1",
31
+ "react-dom": "19.3.1",
32
+ "typescript": "5.6.3",
33
+ "vitest": "2.1.8"
34
+ }
35
+ }