@henosia/app-next 1.0.6 → 1.0.8
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/.agents/skills/henosia-app-next/SKILL.md +10 -11
- package/.agents/skills/henosia-app-next/assets/template/components/sign-in.tsx +1 -1
- package/README.md +6 -11
- package/dist/api/auth.d.mts +1 -3
- package/dist/api/auth.mjs +3 -33
- package/dist/api/platform.mjs +7 -43
- package/dist/auth/middleware.d.mts +21 -6
- package/dist/auth/middleware.mjs +128 -43
- package/dist/auth/server-guards.d.mts +1 -1
- package/dist/auth/server-guards.mjs +3 -3
- package/dist/auth/server.d.mts +81 -2
- package/dist/auth/server.mjs +2 -174
- package/dist/index.d.mts +49 -3
- package/dist/index.mjs +3 -4
- package/dist/platform/app-switcher.d.mts +10 -7
- package/dist/platform/app-switcher.mjs +4 -4
- package/dist/server-DvvkIB4j.mjs +232 -0
- package/dist/shared-Cddy8ptu.d.mts +19 -0
- package/dist/shared.d.mts +2 -2
- package/dist/shared.mjs +2 -11
- package/package.json +1 -1
- package/dist/middleware-shared-CZbIZuBw.mjs +0 -140
- package/dist/server-DfD6Dc91.d.mts +0 -112
- package/dist/session-sync-Cva_oreV.mjs +0 -114
- package/dist/shared-BWPBaubT.d.mts +0 -30
package/dist/auth/server.mjs
CHANGED
|
@@ -1,175 +1,3 @@
|
|
|
1
1
|
/*! Copyright (c) 2026 Henosia ApS. Licensed under the Henosia Commercial Source License v1.0. See LICENSE */
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
import { APIError, betterAuth } from "better-auth";
|
|
5
|
-
import { createAuthMiddleware } from "better-auth/api";
|
|
6
|
-
import { bearer, genericOAuth, jwt } from "better-auth/plugins";
|
|
7
|
-
import { nextCookies } from "better-auth/next-js";
|
|
8
|
-
import { verifyAccessToken } from "better-auth/oauth2";
|
|
9
|
-
import { parseSetCookieHeader } from "better-auth/cookies";
|
|
10
|
-
import { AsyncLocalStorage } from "node:async_hooks";
|
|
11
|
-
//#region src/auth/server.ts
|
|
12
|
-
/**
|
|
13
|
-
* Environment-provided configuration for Henosia Auth.
|
|
14
|
-
* When the consuming app runs in the Henosia preview, the env vars are provided by the runtime environment and should not be
|
|
15
|
-
* hard-coded or present in the `.env.local` file. The Henosia Publish feature automatically sets production versions of
|
|
16
|
-
* the values on the deployed app. For self-publish flows or local development, see the `Environment settings`
|
|
17
|
-
* in the Henosia builder navbar for the relevant values. The preview values cannot be used for production deployments.
|
|
18
|
-
*/
|
|
19
|
-
const henosiaAuthConfig = {
|
|
20
|
-
provider: "henosia",
|
|
21
|
-
baseURL: getRequiredEnvValue((env) => env.BETTER_AUTH_URL),
|
|
22
|
-
secret: getRequiredEnvValue((env) => env.BETTER_AUTH_SECRET),
|
|
23
|
-
henosiaAuthPlatformServiceBaseUrl: getRequiredEnvValue((env) => env.HENOSIA_AUTH_SERVICE_BASE_URL),
|
|
24
|
-
henosiaAuthSupabaseProvider: getRequiredEnvValue((env) => env.HENOSIA_AUTH_SUPABASE_PROVIDER, "custom:henosia-auth:platform"),
|
|
25
|
-
clientSecret: getRequiredEnvValue((env) => env.HENOSIA_AUTH_CLIENT_SECRET),
|
|
26
|
-
clientId: getRequiredEnvValue((env) => env.HENOSIA_AUTH_CLIENT_ID),
|
|
27
|
-
projectId: getRequiredEnvValue((env) => env.HENOSIA_AUTH_PROJECT_ID)
|
|
28
|
-
};
|
|
29
|
-
/**
|
|
30
|
-
* Gets whether the specified request is allowed to spend the single-use OIDC refresh token to obtain a new
|
|
31
|
-
* access token.
|
|
32
|
-
*
|
|
33
|
-
*/
|
|
34
|
-
function isPageOrRefreshTokenRequest(request) {
|
|
35
|
-
if (isPageRequest(request)) return true;
|
|
36
|
-
return new URL(request.url).pathname === HENOSIA_AUTH_GET_SESSION_PATH_NAME;
|
|
37
|
-
}
|
|
38
|
-
const currentRequestStorage = new AsyncLocalStorage();
|
|
39
|
-
let henosiaOAuthProviderInitialized = false;
|
|
40
|
-
const authInstance = betterAuth({
|
|
41
|
-
baseURL: henosiaAuthConfig.baseURL.get(),
|
|
42
|
-
secret: henosiaAuthConfig.secret.get(),
|
|
43
|
-
advanced: { cookiePrefix },
|
|
44
|
-
plugins: [
|
|
45
|
-
bearer(),
|
|
46
|
-
jwt(),
|
|
47
|
-
genericOAuth({ config: [{
|
|
48
|
-
providerId: henosiaAuthConfig.provider,
|
|
49
|
-
discoveryUrl: `${henosiaAuthConfig.henosiaAuthPlatformServiceBaseUrl.get()}/.well-known/openid-configuration`,
|
|
50
|
-
clientId: henosiaAuthConfig.clientId.get(),
|
|
51
|
-
clientSecret: henosiaAuthConfig.clientSecret.get(),
|
|
52
|
-
scopes: [
|
|
53
|
-
"openid",
|
|
54
|
-
"profile",
|
|
55
|
-
"email",
|
|
56
|
-
"offline_access"
|
|
57
|
-
],
|
|
58
|
-
pkce: true,
|
|
59
|
-
mapProfileToUser: (profile) => {
|
|
60
|
-
if (!profile.name) profile.name = profile.email;
|
|
61
|
-
return profile;
|
|
62
|
-
}
|
|
63
|
-
}] }),
|
|
64
|
-
nextCookies()
|
|
65
|
-
],
|
|
66
|
-
hooks: { before: createAuthMiddleware(async (ctx) => {
|
|
67
|
-
if (henosiaOAuthProviderInitialized) return;
|
|
68
|
-
for (const provider of ctx.context.socialProviders) {
|
|
69
|
-
const { refreshAccessToken } = provider;
|
|
70
|
-
if (!refreshAccessToken || provider.id !== henosiaAuthConfig.provider) continue;
|
|
71
|
-
provider.refreshAccessToken = async (refreshToken) => {
|
|
72
|
-
const request = currentRequestStorage.getStore();
|
|
73
|
-
if (!request) throw new APIError("INTERNAL_SERVER_ERROR", { message: `Expected a current request during refreshAccessToken` });
|
|
74
|
-
if (!isPageOrRefreshTokenRequest(request)) throw new APIError("UNAUTHORIZED", {
|
|
75
|
-
statusCode: 401,
|
|
76
|
-
message: "Fetching a refresh access token is only allowed for page or refresh token requests"
|
|
77
|
-
});
|
|
78
|
-
return await refreshAccessToken(refreshToken);
|
|
79
|
-
};
|
|
80
|
-
henosiaOAuthProviderInitialized = true;
|
|
81
|
-
break;
|
|
82
|
-
}
|
|
83
|
-
}) },
|
|
84
|
-
session: { cookieCache: {
|
|
85
|
-
enabled: true,
|
|
86
|
-
version: "1",
|
|
87
|
-
maxAge: 720 * 60 * 60,
|
|
88
|
-
strategy: "jwe",
|
|
89
|
-
refreshCache: true
|
|
90
|
-
} },
|
|
91
|
-
account: {
|
|
92
|
-
storeStateStrategy: "cookie",
|
|
93
|
-
storeAccountCookie: true
|
|
94
|
-
},
|
|
95
|
-
databaseHooks: { user: { create: { before: async (data) => {
|
|
96
|
-
const stableId = data.sub;
|
|
97
|
-
if (!stableId) throw new APIError("INTERNAL_SERVER_ERROR", { message: `Expected '.sub' to be defined but got '${stableId}' for '${data.email}'` });
|
|
98
|
-
return { data: {
|
|
99
|
-
...data,
|
|
100
|
-
id: stableId
|
|
101
|
-
} };
|
|
102
|
-
} } } },
|
|
103
|
-
trustedOrigins: [henosiaAuthConfig.henosiaAuthPlatformServiceBaseUrl.get()]
|
|
104
|
-
});
|
|
105
|
-
/**
|
|
106
|
-
* The Henosia Auth instance.
|
|
107
|
-
*
|
|
108
|
-
* Typed as the minimal {@link Auth} type from better-auth (which is parameterised on the default
|
|
109
|
-
* {@link BetterAuthOptions}) rather than the deeply-inferred concrete type returned by {@link betterAuth}.
|
|
110
|
-
* The deeply-inferred graph references non-portable internals from `better-auth` and `zod` that cannot be
|
|
111
|
-
* named in published declarations (TS2883).
|
|
112
|
-
*/
|
|
113
|
-
const auth = authInstance;
|
|
114
|
-
/**
|
|
115
|
-
* Verifies the Henosia Auth JWT on the current request, or throws in case it's missing or invalid.
|
|
116
|
-
* This method must be called before allowing access to any protected pages or routes,
|
|
117
|
-
* and before accessing data in server side page methods or actions.
|
|
118
|
-
* @param request the current request which provides auth headers
|
|
119
|
-
* @return the better-auth `getAccessToken` response, the verified token `payload` (a {@link HenosiaAuthTokenClaims}),
|
|
120
|
-
* the `Set-Cookie` headers produced while obtaining/refreshing the token, and a
|
|
121
|
-
* `transferBetterAuthCookiesToNext` helper that forwards those cookies onto a Next.js request/response pair
|
|
122
|
-
* @throws APIError when the current credentials are missing or invalid
|
|
123
|
-
*/
|
|
124
|
-
async function verifyHenosiaAuthToken(request) {
|
|
125
|
-
return await currentRequestStorage.run(request, async () => {
|
|
126
|
-
const { response: accessTokenResponse, headers: accessTokenResponseHeaders } = await authInstance.api.getAccessToken({
|
|
127
|
-
body: { providerId: henosiaAuthConfig.provider },
|
|
128
|
-
headers: request.headers,
|
|
129
|
-
returnHeaders: true
|
|
130
|
-
});
|
|
131
|
-
if (!accessTokenResponse.idToken) throw new APIError("UNAUTHORIZED", { message: "No id_token returned for openid scope" });
|
|
132
|
-
const payload = await verifyAccessToken(accessTokenResponse.idToken, {
|
|
133
|
-
jwksUrl: `${henosiaAuthConfig.henosiaAuthPlatformServiceBaseUrl.get()}/api/auth/jwks`,
|
|
134
|
-
verifyOptions: {
|
|
135
|
-
audience: henosiaAuthConfig.clientId.get(),
|
|
136
|
-
issuer: `${henosiaAuthConfig.henosiaAuthPlatformServiceBaseUrl.get()}/api/auth`
|
|
137
|
-
}
|
|
138
|
-
});
|
|
139
|
-
const { "https://henosia.com/project": projectId } = payload;
|
|
140
|
-
if (!projectId) throw new APIError("UNAUTHORIZED", { message: "token does not grant access" });
|
|
141
|
-
if (!henosiaAuthConfig.projectId) throw new APIError("INTERNAL_SERVER_ERROR", { message: "HENOSIA_AUTH_PROJECT_ID env var has not been set" });
|
|
142
|
-
if (henosiaAuthConfig.projectId.get() !== projectId) throw new APIError("UNAUTHORIZED", { message: "token has invalid projectId" });
|
|
143
|
-
const setCookieHeaders = accessTokenResponseHeaders.getSetCookie();
|
|
144
|
-
const transferBetterAuthCookiesToNext = (nextRequest, response) => {
|
|
145
|
-
for (const cookie of setCookieHeaders) parseSetCookieHeader(cookie).forEach((attributes, name) => {
|
|
146
|
-
const { value, ...betterOptions } = attributes;
|
|
147
|
-
const options = {
|
|
148
|
-
...betterOptions,
|
|
149
|
-
maxAge: betterOptions["max-age"],
|
|
150
|
-
httpOnly: betterOptions.httponly,
|
|
151
|
-
sameSite: betterOptions.samesite
|
|
152
|
-
};
|
|
153
|
-
nextRequest.cookies.set(name, value);
|
|
154
|
-
response.cookies.set(name, value, options);
|
|
155
|
-
});
|
|
156
|
-
};
|
|
157
|
-
return {
|
|
158
|
-
accessTokenResponse,
|
|
159
|
-
payload,
|
|
160
|
-
setCookieHeaders,
|
|
161
|
-
transferBetterAuthCookiesToNext
|
|
162
|
-
};
|
|
163
|
-
});
|
|
164
|
-
}
|
|
165
|
-
const unauthorizedExceptionCodes = new Set(["ACCOUNT_NOT_FOUND", "FAILED_TO_GET_ACCESS_TOKEN"]);
|
|
166
|
-
/**
|
|
167
|
-
* Determines whether the specified exception should start the sign-in flow to authenticate the user
|
|
168
|
-
* @param error the error thrown by `verifyHenosiaAuthToken`
|
|
169
|
-
*/
|
|
170
|
-
function isUnauthorizedException(error) {
|
|
171
|
-
const apiError = error ?? {};
|
|
172
|
-
return unauthorizedExceptionCodes.has(apiError.body?.code ?? "") || apiError.status === "UNAUTHORIZED" || apiError.statusCode === 401;
|
|
173
|
-
}
|
|
174
|
-
//#endregion
|
|
175
|
-
export { HENOSIA_AUTH_MIDDLEWARE_UNAUTHENTICATED_PATH_NAMES, HENOSIA_AUTH_MIDDLEWARE_UNAUTHENTICATED_PATH_NAME_PREFIXES, auth, cookiePrefix, henosiaAuthConfig, isPageOrRefreshTokenRequest, isPageRequest, isUnauthorizedException, verifyHenosiaAuthToken };
|
|
2
|
+
import { a as isPageRequest, i as isPageOrRefreshTokenRequest, n as HENOSIA_AUTH_MIDDLEWARE_UNAUTHENTICATED_PATH_NAME_PREFIXES, o as isUnauthorizedException, r as getAuth, s as verifyHenosiaAuthToken, t as HENOSIA_AUTH_MIDDLEWARE_UNAUTHENTICATED_PATH_NAMES } from "../server-DvvkIB4j.mjs";
|
|
3
|
+
export { HENOSIA_AUTH_MIDDLEWARE_UNAUTHENTICATED_PATH_NAMES, HENOSIA_AUTH_MIDDLEWARE_UNAUTHENTICATED_PATH_NAME_PREFIXES, getAuth, isPageOrRefreshTokenRequest, isPageRequest, isUnauthorizedException, verifyHenosiaAuthToken };
|
package/dist/index.d.mts
CHANGED
|
@@ -1,5 +1,51 @@
|
|
|
1
1
|
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
2
|
+
import { i as HenosiaOrganizationContext, n as HENOSIA_AUTH_SIGN_IN_PATH_NAME, r as HENOSIA_ORGANIZATION_CTX_COOKIE, t as HENOSIA_AUTH_GET_SESSION_PATH_NAME } from "./shared-Cddy8ptu.mjs";
|
|
3
|
+
import { HENOSIA_AUTH_MIDDLEWARE_UNAUTHENTICATED_PATH_NAMES, HENOSIA_AUTH_MIDDLEWARE_UNAUTHENTICATED_PATH_NAME_PREFIXES, HenosiaAuthTokenClaims, getAuth, isPageOrRefreshTokenRequest, isPageRequest, isUnauthorizedException, verifyHenosiaAuthToken } from "./auth/server.mjs";
|
|
4
4
|
import { HenosiaAuthContext, getHenosiaAuth, requireHenosiaAuth, routeWithHenosiaAuth } from "./auth/server-guards.mjs";
|
|
5
|
-
|
|
5
|
+
|
|
6
|
+
//#region src/auth/configuration.d.ts
|
|
7
|
+
/**
|
|
8
|
+
* A lazy accessor for an environment-derived string value. Reading is deferred until {@link get} is invoked,
|
|
9
|
+
* so the underlying `process.env` lookup only happens at call time rather than at module load.
|
|
10
|
+
*/
|
|
11
|
+
type EnvLiveGetString = {
|
|
12
|
+
get(): string;
|
|
13
|
+
};
|
|
14
|
+
interface HenosiaAuthConfig {
|
|
15
|
+
/** Name of the Henosia Auth OAuth2 provider */
|
|
16
|
+
provider: 'henosia';
|
|
17
|
+
/** The consuming app's own deployment or preview browser URL. Used as the better-auth base url */
|
|
18
|
+
baseURL: EnvLiveGetString;
|
|
19
|
+
/** The consuming app's own deployment or preview auth secret. Used as the better-auth secret */
|
|
20
|
+
secret: EnvLiveGetString;
|
|
21
|
+
/** OAuth client ID from HenosiaAuthClientService */
|
|
22
|
+
clientId: EnvLiveGetString;
|
|
23
|
+
/** OAuth client secret from HenosiaAuthClientService */
|
|
24
|
+
clientSecret: EnvLiveGetString;
|
|
25
|
+
/** The Henosia auth and platform service base URL, under which the OAuth client is registered */
|
|
26
|
+
henosiaAuthPlatformServiceBaseUrl: EnvLiveGetString;
|
|
27
|
+
/** The provider identifier that Henosia Auth is registered with as a OIDC-based Custom Provider in Supabase Auth */
|
|
28
|
+
henosiaAuthSupabaseProvider: EnvLiveGetString;
|
|
29
|
+
/**
|
|
30
|
+
* The project id that the JWT project claim should match in HenosiaAuthTokenClaims.
|
|
31
|
+
* Ensures that signed-in Henosia users cannot access projects that they have not been granted access to,
|
|
32
|
+
* for example that User A from Org A cannot access User B from Org B's project.
|
|
33
|
+
* */
|
|
34
|
+
projectId: EnvLiveGetString;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Environment-provided configuration for Henosia Auth.
|
|
38
|
+
* When the consuming app runs in the Henosia preview, the env vars are provided by the runtime environment and should not be
|
|
39
|
+
* hard-coded or present in the `.env.local` file. The Henosia Publish feature automatically sets production versions of
|
|
40
|
+
* the values on the deployed app. For self-publish flows or local development, see the `Environment settings`
|
|
41
|
+
* in the Henosia builder navbar for the relevant values. The preview values cannot be used for production deployments.
|
|
42
|
+
*/
|
|
43
|
+
declare const henosiaAuthConfig: HenosiaAuthConfig;
|
|
44
|
+
/**
|
|
45
|
+
* Project-scoped cookie prefix used by Henosia Auth.
|
|
46
|
+
*/
|
|
47
|
+
declare const cookiePrefix: {
|
|
48
|
+
get: () => `henosia-auth-${string}`;
|
|
49
|
+
};
|
|
50
|
+
//#endregion
|
|
51
|
+
export { HENOSIA_AUTH_GET_SESSION_PATH_NAME, HENOSIA_AUTH_MIDDLEWARE_UNAUTHENTICATED_PATH_NAMES, HENOSIA_AUTH_MIDDLEWARE_UNAUTHENTICATED_PATH_NAME_PREFIXES, HENOSIA_AUTH_SIGN_IN_PATH_NAME, HENOSIA_ORGANIZATION_CTX_COOKIE, type HenosiaAuthConfig, type HenosiaAuthContext, type HenosiaAuthTokenClaims, type HenosiaOrganizationContext, cookiePrefix, getAuth, getHenosiaAuth, henosiaAuthConfig, isPageOrRefreshTokenRequest, isPageRequest, isUnauthorizedException, requireHenosiaAuth, routeWithHenosiaAuth, verifyHenosiaAuthToken };
|
package/dist/index.mjs
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
/*! Copyright (c) 2026 Henosia ApS. Licensed under the Henosia Commercial Source License v1.0. See LICENSE */
|
|
2
|
-
import { HENOSIA_AUTH_GET_SESSION_PATH_NAME,
|
|
3
|
-
import {
|
|
4
|
-
import { auth, henosiaAuthConfig, isPageOrRefreshTokenRequest, isUnauthorizedException, verifyHenosiaAuthToken } from "./auth/server.mjs";
|
|
2
|
+
import { HENOSIA_AUTH_GET_SESSION_PATH_NAME, HENOSIA_AUTH_SIGN_IN_PATH_NAME, HENOSIA_ORGANIZATION_CTX_COOKIE } from "./shared.mjs";
|
|
3
|
+
import { a as isPageRequest, c as cookiePrefix, i as isPageOrRefreshTokenRequest, l as henosiaAuthConfig, n as HENOSIA_AUTH_MIDDLEWARE_UNAUTHENTICATED_PATH_NAME_PREFIXES, o as isUnauthorizedException, r as getAuth, s as verifyHenosiaAuthToken, t as HENOSIA_AUTH_MIDDLEWARE_UNAUTHENTICATED_PATH_NAMES } from "./server-DvvkIB4j.mjs";
|
|
5
4
|
import { getHenosiaAuth, requireHenosiaAuth, routeWithHenosiaAuth } from "./auth/server-guards.mjs";
|
|
6
|
-
export { HENOSIA_AUTH_GET_SESSION_PATH_NAME,
|
|
5
|
+
export { HENOSIA_AUTH_GET_SESSION_PATH_NAME, HENOSIA_AUTH_MIDDLEWARE_UNAUTHENTICATED_PATH_NAMES, HENOSIA_AUTH_MIDDLEWARE_UNAUTHENTICATED_PATH_NAME_PREFIXES, HENOSIA_AUTH_SIGN_IN_PATH_NAME, HENOSIA_ORGANIZATION_CTX_COOKIE, cookiePrefix, getAuth, getHenosiaAuth, henosiaAuthConfig, isPageOrRefreshTokenRequest, isPageRequest, isUnauthorizedException, requireHenosiaAuth, routeWithHenosiaAuth, verifyHenosiaAuthToken };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
|
|
2
|
-
import {
|
|
2
|
+
import { i as HenosiaOrganizationContext } from "../shared-Cddy8ptu.mjs";
|
|
3
3
|
|
|
4
4
|
//#region src/platform/app-switcher.d.ts
|
|
5
5
|
/**
|
|
@@ -23,7 +23,10 @@ interface AppSwitcherAppGroup {
|
|
|
23
23
|
*/
|
|
24
24
|
interface AppSwitcherSuccessResponse {
|
|
25
25
|
groupedApps: AppSwitcherAppGroup[];
|
|
26
|
-
organization:
|
|
26
|
+
organization: {
|
|
27
|
+
id: string;
|
|
28
|
+
name: string;
|
|
29
|
+
};
|
|
27
30
|
}
|
|
28
31
|
/**
|
|
29
32
|
* Error response shape returned by `/api/henosia-platform/v1/app-switcher`.
|
|
@@ -48,8 +51,8 @@ interface UseAppSwitcherOptions {
|
|
|
48
51
|
*/
|
|
49
52
|
interface UseAppSwitcherResult {
|
|
50
53
|
/**
|
|
51
|
-
* The current organization context, derived from the
|
|
52
|
-
*
|
|
54
|
+
* The current organization context, derived from the {@link HENOSIA_ORGANIZATION_CTX_COOKIE} cookie set by the
|
|
55
|
+
* Henosia Auth middleware. `null` until the cookie has been read (or if no organization is in context).
|
|
53
56
|
*/
|
|
54
57
|
organization: HenosiaOrganizationContext;
|
|
55
58
|
/**
|
|
@@ -68,9 +71,9 @@ interface UseAppSwitcherResult {
|
|
|
68
71
|
/**
|
|
69
72
|
* React hook backing the Henosia app-switcher UI.
|
|
70
73
|
*
|
|
71
|
-
* Reads the
|
|
72
|
-
* Henosia Platform `app-switcher` endpoint mounted at `/api/henosia-platform/v1/app-switcher` (provided by
|
|
73
|
-
* `@henosia/app-next/api/platform`).
|
|
74
|
+
* Reads the current organization context from the {@link HENOSIA_ORGANIZATION_CTX_COOKIE} cookie and queries
|
|
75
|
+
* the Henosia Platform `app-switcher` endpoint mounted at `/api/henosia-platform/v1/app-switcher` (provided by
|
|
76
|
+
* `@henosia/app-next/api/platform`).
|
|
74
77
|
*
|
|
75
78
|
*
|
|
76
79
|
* @example
|
|
@@ -24,9 +24,9 @@ async function fetchAppSwitcher() {
|
|
|
24
24
|
/**
|
|
25
25
|
* React hook backing the Henosia app-switcher UI.
|
|
26
26
|
*
|
|
27
|
-
* Reads the
|
|
28
|
-
* Henosia Platform `app-switcher` endpoint mounted at `/api/henosia-platform/v1/app-switcher` (provided by
|
|
29
|
-
* `@henosia/app-next/api/platform`).
|
|
27
|
+
* Reads the current organization context from the {@link HENOSIA_ORGANIZATION_CTX_COOKIE} cookie and queries
|
|
28
|
+
* the Henosia Platform `app-switcher` endpoint mounted at `/api/henosia-platform/v1/app-switcher` (provided by
|
|
29
|
+
* `@henosia/app-next/api/platform`).
|
|
30
30
|
*
|
|
31
31
|
*
|
|
32
32
|
* @example
|
|
@@ -64,7 +64,7 @@ function useAppSwitcher(options) {
|
|
|
64
64
|
enabled
|
|
65
65
|
});
|
|
66
66
|
return {
|
|
67
|
-
organization
|
|
67
|
+
organization,
|
|
68
68
|
groupedApps: data?.groupedApps ?? [],
|
|
69
69
|
error,
|
|
70
70
|
isLoading
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
/*! Copyright (c) 2026 Henosia ApS. Licensed under the Henosia Commercial Source License v1.0. See LICENSE */
|
|
2
|
+
import { HENOSIA_AUTH_GET_SESSION_PATH_NAME, HENOSIA_AUTH_SIGN_IN_PATH_NAME } from "./shared.mjs";
|
|
3
|
+
import { APIError, betterAuth } from "better-auth";
|
|
4
|
+
import { createAuthMiddleware } from "better-auth/api";
|
|
5
|
+
import { bearer, genericOAuth, jwt } from "better-auth/plugins";
|
|
6
|
+
import { nextCookies } from "better-auth/next-js";
|
|
7
|
+
import { verifyAccessToken } from "better-auth/oauth2";
|
|
8
|
+
import { parseSetCookieHeader } from "better-auth/cookies";
|
|
9
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
10
|
+
import { headers } from "next/headers.js";
|
|
11
|
+
//#region src/auth/configuration.ts
|
|
12
|
+
const requiredEnvProxy = new Proxy(process.env, { get(target, property, receiver) {
|
|
13
|
+
const value = Reflect.get(target, property, receiver);
|
|
14
|
+
if (!value || typeof value !== "string") throw new Error(`[Henosia Auth] Missing required env var: ${property.toString()}`);
|
|
15
|
+
return value;
|
|
16
|
+
} });
|
|
17
|
+
function getRequiredEnvValue(getter, fallback) {
|
|
18
|
+
try {
|
|
19
|
+
return { get: () => getter(requiredEnvProxy) };
|
|
20
|
+
} catch (e) {
|
|
21
|
+
if (fallback) return { get: () => fallback };
|
|
22
|
+
console.log(e.message);
|
|
23
|
+
throw e;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Environment-provided configuration for Henosia Auth.
|
|
28
|
+
* When the consuming app runs in the Henosia preview, the env vars are provided by the runtime environment and should not be
|
|
29
|
+
* hard-coded or present in the `.env.local` file. The Henosia Publish feature automatically sets production versions of
|
|
30
|
+
* the values on the deployed app. For self-publish flows or local development, see the `Environment settings`
|
|
31
|
+
* in the Henosia builder navbar for the relevant values. The preview values cannot be used for production deployments.
|
|
32
|
+
*/
|
|
33
|
+
const henosiaAuthConfig = {
|
|
34
|
+
provider: "henosia",
|
|
35
|
+
baseURL: getRequiredEnvValue((env) => env.BETTER_AUTH_URL),
|
|
36
|
+
secret: getRequiredEnvValue((env) => env.BETTER_AUTH_SECRET),
|
|
37
|
+
henosiaAuthPlatformServiceBaseUrl: getRequiredEnvValue((env) => env.HENOSIA_AUTH_SERVICE_BASE_URL),
|
|
38
|
+
henosiaAuthSupabaseProvider: getRequiredEnvValue((env) => env.HENOSIA_AUTH_SUPABASE_PROVIDER, "custom:henosia-auth:platform"),
|
|
39
|
+
clientSecret: getRequiredEnvValue((env) => env.HENOSIA_AUTH_CLIENT_SECRET),
|
|
40
|
+
clientId: getRequiredEnvValue((env) => env.HENOSIA_AUTH_CLIENT_ID),
|
|
41
|
+
projectId: getRequiredEnvValue((env) => env.HENOSIA_AUTH_PROJECT_ID)
|
|
42
|
+
};
|
|
43
|
+
/**
|
|
44
|
+
* Project-scoped cookie prefix used by Henosia Auth.
|
|
45
|
+
*/
|
|
46
|
+
const cookiePrefix = { get: () => `henosia-auth-${henosiaAuthConfig.projectId.get()}` };
|
|
47
|
+
//#endregion
|
|
48
|
+
//#region src/auth/server.ts
|
|
49
|
+
/**
|
|
50
|
+
* URL pathname values that should not check for auth in middleware, e.g. the sign-in page.
|
|
51
|
+
* Additional pathname values can be added for public paths, but ONLY if they should not be intercepted by the
|
|
52
|
+
* middleware auth pre-check and redirect.
|
|
53
|
+
*/
|
|
54
|
+
const HENOSIA_AUTH_MIDDLEWARE_UNAUTHENTICATED_PATH_NAMES = new Set([HENOSIA_AUTH_SIGN_IN_PATH_NAME]);
|
|
55
|
+
if (HENOSIA_AUTH_MIDDLEWARE_UNAUTHENTICATED_PATH_NAMES.has("/")) throw new Error(`[Henosia Auth] Invalid path name '/'. Values must be non-root paths`);
|
|
56
|
+
/**
|
|
57
|
+
* URL pathname prefixes that should not be blocked by auth in middleware, e.g. the better-auth API routes used to sign in.
|
|
58
|
+
* Additional pathname prefixes can be added for public paths, but ONLY if they should not be intercepted by the
|
|
59
|
+
* middleware auth pre-check and redirect. Include the relevant `/` ending character to prevent unexpected partial
|
|
60
|
+
* route matches.
|
|
61
|
+
*/
|
|
62
|
+
const HENOSIA_AUTH_MIDDLEWARE_UNAUTHENTICATED_PATH_NAME_PREFIXES = ["/api/auth/", "/.well-known/"];
|
|
63
|
+
if (HENOSIA_AUTH_MIDDLEWARE_UNAUTHENTICATED_PATH_NAME_PREFIXES.find((p) => p === "/" || !p.trim() || !p.endsWith("/"))) throw new Error("[Henosia Auth] Invalid path name prefixes. Values must be non-empty sub paths ending with slash");
|
|
64
|
+
/**
|
|
65
|
+
* Gets whether the specified request is for a page (a top level page or iframe page)
|
|
66
|
+
*/
|
|
67
|
+
function isPageRequest(request) {
|
|
68
|
+
const { headers } = request;
|
|
69
|
+
const dest = headers.get("X-Henosia-Fetch-Dest") ?? headers.get("Sec-Fetch-Dest");
|
|
70
|
+
if (dest === "document" || dest === "iframe" || dest === "fencedframe") return true;
|
|
71
|
+
const isRsc = request.headers.get("RSC") === "1";
|
|
72
|
+
const isPrefetch = request.headers.get("Next-Router-Prefetch") === "1";
|
|
73
|
+
return isRsc && !isPrefetch;
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Gets whether the specified request is allowed to spend the single-use OIDC refresh token to obtain a new
|
|
77
|
+
* access token.
|
|
78
|
+
*
|
|
79
|
+
*/
|
|
80
|
+
function isPageOrRefreshTokenRequest(request) {
|
|
81
|
+
if (isPageRequest(request)) return true;
|
|
82
|
+
return new URL(request.url).pathname === HENOSIA_AUTH_GET_SESSION_PATH_NAME;
|
|
83
|
+
}
|
|
84
|
+
const currentRequestStorage = new AsyncLocalStorage();
|
|
85
|
+
let henosiaOAuthProviderInitialized = false;
|
|
86
|
+
const createAuthInstance = () => betterAuth({
|
|
87
|
+
baseURL: henosiaAuthConfig.baseURL.get(),
|
|
88
|
+
secret: henosiaAuthConfig.secret.get(),
|
|
89
|
+
advanced: { cookiePrefix: cookiePrefix.get() },
|
|
90
|
+
plugins: [
|
|
91
|
+
bearer(),
|
|
92
|
+
jwt(),
|
|
93
|
+
genericOAuth({ config: [{
|
|
94
|
+
providerId: henosiaAuthConfig.provider,
|
|
95
|
+
discoveryUrl: `${henosiaAuthConfig.henosiaAuthPlatformServiceBaseUrl.get()}/.well-known/openid-configuration`,
|
|
96
|
+
clientId: henosiaAuthConfig.clientId.get(),
|
|
97
|
+
clientSecret: henosiaAuthConfig.clientSecret.get(),
|
|
98
|
+
scopes: [
|
|
99
|
+
"openid",
|
|
100
|
+
"profile",
|
|
101
|
+
"email",
|
|
102
|
+
"offline_access"
|
|
103
|
+
],
|
|
104
|
+
pkce: true,
|
|
105
|
+
mapProfileToUser: (profile) => {
|
|
106
|
+
if (!profile.name) profile.name = profile.email;
|
|
107
|
+
return profile;
|
|
108
|
+
}
|
|
109
|
+
}] }),
|
|
110
|
+
nextCookies()
|
|
111
|
+
],
|
|
112
|
+
hooks: { before: createAuthMiddleware(async (ctx) => {
|
|
113
|
+
if (henosiaOAuthProviderInitialized) return;
|
|
114
|
+
for (const provider of ctx.context.socialProviders) {
|
|
115
|
+
const { refreshAccessToken } = provider;
|
|
116
|
+
if (!refreshAccessToken || provider.id !== henosiaAuthConfig.provider) continue;
|
|
117
|
+
provider.refreshAccessToken = async (refreshToken) => {
|
|
118
|
+
const request = currentRequestStorage.getStore();
|
|
119
|
+
if (!request) throw new APIError("INTERNAL_SERVER_ERROR", { message: `Expected a current request during refreshAccessToken` });
|
|
120
|
+
if (!isPageOrRefreshTokenRequest(request)) throw new APIError("UNAUTHORIZED", {
|
|
121
|
+
statusCode: 401,
|
|
122
|
+
message: "Fetching a refresh access token is only allowed for page or refresh token requests"
|
|
123
|
+
});
|
|
124
|
+
return await refreshAccessToken(refreshToken);
|
|
125
|
+
};
|
|
126
|
+
henosiaOAuthProviderInitialized = true;
|
|
127
|
+
break;
|
|
128
|
+
}
|
|
129
|
+
}) },
|
|
130
|
+
session: { cookieCache: {
|
|
131
|
+
enabled: true,
|
|
132
|
+
version: "1",
|
|
133
|
+
maxAge: 720 * 60 * 60,
|
|
134
|
+
strategy: "jwe",
|
|
135
|
+
refreshCache: true
|
|
136
|
+
} },
|
|
137
|
+
account: {
|
|
138
|
+
storeStateStrategy: "cookie",
|
|
139
|
+
storeAccountCookie: true
|
|
140
|
+
},
|
|
141
|
+
databaseHooks: { user: { create: { before: async (data) => {
|
|
142
|
+
const stableId = data.sub;
|
|
143
|
+
if (!stableId) throw new APIError("INTERNAL_SERVER_ERROR", { message: `Expected '.sub' to be defined but got '${stableId}' for '${data.email}'` });
|
|
144
|
+
return { data: {
|
|
145
|
+
...data,
|
|
146
|
+
id: stableId
|
|
147
|
+
} };
|
|
148
|
+
} } } },
|
|
149
|
+
trustedOrigins: [henosiaAuthConfig.henosiaAuthPlatformServiceBaseUrl.get()]
|
|
150
|
+
});
|
|
151
|
+
let authInstance = null;
|
|
152
|
+
/**
|
|
153
|
+
* Returns the singleton Henosia Auth instance, creating it on first call.
|
|
154
|
+
*
|
|
155
|
+
* The instance is created lazily so that importing this module does not eagerly read the required
|
|
156
|
+
* environment variables (see {@link henosiaAuthConfig}). This means modules that only need the
|
|
157
|
+
* configuration or shared helpers can be imported in environments where the full set of `BETTER_AUTH_*` /
|
|
158
|
+
* `HENOSIA_AUTH_*` env vars is not yet populated, and only call sites that actually invoke `getAuth()`
|
|
159
|
+
* will require them to be set.
|
|
160
|
+
*
|
|
161
|
+
* Subsequent calls return the same underlying better-auth instance.
|
|
162
|
+
*
|
|
163
|
+
* The return type is the minimal {@link Auth} type from better-auth (which is parameterised on the default
|
|
164
|
+
* `BetterAuthOptions`) rather than the deeply-inferred concrete type returned by {@link betterAuth}.
|
|
165
|
+
* The deeply-inferred graph references non-portable internals from `better-auth` and `zod` that cannot be
|
|
166
|
+
* named in published declarations (TS2883).
|
|
167
|
+
*/
|
|
168
|
+
const getAuth = () => {
|
|
169
|
+
if (!authInstance) authInstance = createAuthInstance();
|
|
170
|
+
return authInstance;
|
|
171
|
+
};
|
|
172
|
+
/**
|
|
173
|
+
* Verifies the Henosia Auth JWT on the current request, or throws in case it's missing or invalid.
|
|
174
|
+
* This method must be called before allowing access to any protected pages or routes,
|
|
175
|
+
* and before accessing data in server side page methods or actions.
|
|
176
|
+
* @param request the current request which provides auth headers
|
|
177
|
+
* @return the better-auth `getAccessToken` response, the verified token `payload` (a {@link HenosiaAuthTokenClaims}),
|
|
178
|
+
* the `Set-Cookie` headers produced while obtaining/refreshing the token, and a
|
|
179
|
+
* `transferBetterAuthCookiesToNext` helper that forwards those cookies onto a Next.js request/response pair
|
|
180
|
+
* @throws APIError when the current credentials are missing or invalid
|
|
181
|
+
*/
|
|
182
|
+
async function verifyHenosiaAuthToken(request) {
|
|
183
|
+
currentRequestStorage.enterWith(request);
|
|
184
|
+
const { response: accessTokenResponse, headers: accessTokenResponseHeaders } = await getAuth().api.getAccessToken({
|
|
185
|
+
body: { providerId: henosiaAuthConfig.provider },
|
|
186
|
+
headers: await headers(),
|
|
187
|
+
returnHeaders: true
|
|
188
|
+
});
|
|
189
|
+
if (!accessTokenResponse.idToken) throw new APIError("UNAUTHORIZED", { message: "No id_token returned for openid scope" });
|
|
190
|
+
const payload = await verifyAccessToken(accessTokenResponse.idToken, {
|
|
191
|
+
jwksUrl: `${henosiaAuthConfig.henosiaAuthPlatformServiceBaseUrl.get()}/api/auth/jwks`,
|
|
192
|
+
verifyOptions: {
|
|
193
|
+
audience: henosiaAuthConfig.clientId.get(),
|
|
194
|
+
issuer: `${henosiaAuthConfig.henosiaAuthPlatformServiceBaseUrl.get()}/api/auth`
|
|
195
|
+
}
|
|
196
|
+
});
|
|
197
|
+
const { "https://henosia.com/project": projectId } = payload;
|
|
198
|
+
if (!projectId) throw new APIError("UNAUTHORIZED", { message: "token does not grant access" });
|
|
199
|
+
if (!henosiaAuthConfig.projectId) throw new APIError("INTERNAL_SERVER_ERROR", { message: "HENOSIA_AUTH_PROJECT_ID env var has not been set" });
|
|
200
|
+
if (henosiaAuthConfig.projectId.get() !== projectId) throw new APIError("UNAUTHORIZED", { message: "token has invalid projectId" });
|
|
201
|
+
const setCookieHeaders = accessTokenResponseHeaders.getSetCookie();
|
|
202
|
+
const transferBetterAuthCookiesToNext = (nextRequest, response) => {
|
|
203
|
+
for (const cookie of setCookieHeaders) parseSetCookieHeader(cookie).forEach((attributes, name) => {
|
|
204
|
+
const { value, ...betterOptions } = attributes;
|
|
205
|
+
const options = {
|
|
206
|
+
...betterOptions,
|
|
207
|
+
maxAge: betterOptions["max-age"],
|
|
208
|
+
httpOnly: betterOptions.httponly,
|
|
209
|
+
sameSite: betterOptions.samesite
|
|
210
|
+
};
|
|
211
|
+
nextRequest.cookies.set(name, value);
|
|
212
|
+
response.cookies.set(name, value, options);
|
|
213
|
+
});
|
|
214
|
+
};
|
|
215
|
+
return {
|
|
216
|
+
accessTokenResponse,
|
|
217
|
+
payload,
|
|
218
|
+
setCookieHeaders,
|
|
219
|
+
transferBetterAuthCookiesToNext
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
const unauthorizedExceptionCodes = new Set(["ACCOUNT_NOT_FOUND", "FAILED_TO_GET_ACCESS_TOKEN"]);
|
|
223
|
+
/**
|
|
224
|
+
* Determines whether the specified exception should start the sign-in flow to authenticate the user
|
|
225
|
+
* @param error the error thrown by `verifyHenosiaAuthToken`
|
|
226
|
+
*/
|
|
227
|
+
function isUnauthorizedException(error) {
|
|
228
|
+
const apiError = error ?? {};
|
|
229
|
+
return unauthorizedExceptionCodes.has(apiError.body?.code ?? "") || apiError.status === "UNAUTHORIZED" || apiError.statusCode === 401;
|
|
230
|
+
}
|
|
231
|
+
//#endregion
|
|
232
|
+
export { isPageRequest as a, cookiePrefix as c, isPageOrRefreshTokenRequest as i, henosiaAuthConfig as l, HENOSIA_AUTH_MIDDLEWARE_UNAUTHENTICATED_PATH_NAME_PREFIXES as n, isUnauthorizedException as o, getAuth as r, verifyHenosiaAuthToken as s, HENOSIA_AUTH_MIDDLEWARE_UNAUTHENTICATED_PATH_NAMES as t };
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
|
|
2
|
+
//#region src/shared.d.ts
|
|
3
|
+
declare const HENOSIA_AUTH_SIGN_IN_PATH_NAME = "/sign-in";
|
|
4
|
+
/**
|
|
5
|
+
* The pathname for better-auth's `/get-session` endpoint, used by the React `useSession` hook.
|
|
6
|
+
*
|
|
7
|
+
* `useSession` automatically refetches this endpoint on browser tab focus (and optionally on a polling
|
|
8
|
+
* interval), which we leverage as a built-in keep-alive for the OIDC access/refresh tokens — see
|
|
9
|
+
* `isPageOrRefreshTokenRequest` and the middleware special-case for this path.
|
|
10
|
+
*/
|
|
11
|
+
declare const HENOSIA_AUTH_GET_SESSION_PATH_NAME = "/api/auth/get-session";
|
|
12
|
+
type HenosiaOrganizationContext = {
|
|
13
|
+
id: string;
|
|
14
|
+
name: string;
|
|
15
|
+
logoUrl: string | null;
|
|
16
|
+
} | null;
|
|
17
|
+
declare const HENOSIA_ORGANIZATION_CTX_COOKIE = "henosia.org";
|
|
18
|
+
//#endregion
|
|
19
|
+
export { HenosiaOrganizationContext as i, HENOSIA_AUTH_SIGN_IN_PATH_NAME as n, HENOSIA_ORGANIZATION_CTX_COOKIE as r, HENOSIA_AUTH_GET_SESSION_PATH_NAME as t };
|
package/dist/shared.d.mts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
|
|
2
|
-
import {
|
|
3
|
-
export { HENOSIA_AUTH_GET_SESSION_PATH_NAME,
|
|
2
|
+
import { i as HenosiaOrganizationContext, n as HENOSIA_AUTH_SIGN_IN_PATH_NAME, r as HENOSIA_ORGANIZATION_CTX_COOKIE, t as HENOSIA_AUTH_GET_SESSION_PATH_NAME } from "./shared-Cddy8ptu.mjs";
|
|
3
|
+
export { HENOSIA_AUTH_GET_SESSION_PATH_NAME, HENOSIA_AUTH_SIGN_IN_PATH_NAME, HENOSIA_ORGANIZATION_CTX_COOKIE, HenosiaOrganizationContext };
|
package/dist/shared.mjs
CHANGED
|
@@ -6,18 +6,9 @@ const HENOSIA_AUTH_SIGN_IN_PATH_NAME = "/sign-in";
|
|
|
6
6
|
*
|
|
7
7
|
* `useSession` automatically refetches this endpoint on browser tab focus (and optionally on a polling
|
|
8
8
|
* interval), which we leverage as a built-in keep-alive for the OIDC access/refresh tokens — see
|
|
9
|
-
* `isPageOrRefreshTokenRequest` and the middleware-
|
|
9
|
+
* `isPageOrRefreshTokenRequest` and the middleware special-case for this path.
|
|
10
10
|
*/
|
|
11
11
|
const HENOSIA_AUTH_GET_SESSION_PATH_NAME = "/api/auth/get-session";
|
|
12
|
-
/**
|
|
13
|
-
* Internal route used by the Edge middleware to delegate server-only token refresh and downstream session sync
|
|
14
|
-
* without importing the Better Auth server graph into the middleware bundle.
|
|
15
|
-
*/
|
|
16
|
-
const HENOSIA_AUTH_SESSION_SYNC_PATH_NAME = "/api/auth/henosia-session-sync";
|
|
17
|
-
const HENOSIA_AUTH_SESSION_SYNC_ORIGINAL_URL_HEADER = "x-henosia-auth-original-url";
|
|
18
|
-
const HENOSIA_AUTH_SESSION_SYNC_ORIGINAL_METHOD_HEADER = "x-henosia-auth-original-method";
|
|
19
|
-
const HENOSIA_AUTH_SESSION_SYNC_ORIGINAL_FETCH_DEST_HEADER = "x-henosia-auth-original-fetch-dest";
|
|
20
12
|
const HENOSIA_ORGANIZATION_CTX_COOKIE = "henosia.org";
|
|
21
|
-
const HENOSIA_AUTH_INVALID_SESSION_BODY = { error: "Your session is invalid or expired. Please reload the page to sign in again." };
|
|
22
13
|
//#endregion
|
|
23
|
-
export { HENOSIA_AUTH_GET_SESSION_PATH_NAME,
|
|
14
|
+
export { HENOSIA_AUTH_GET_SESSION_PATH_NAME, HENOSIA_AUTH_SIGN_IN_PATH_NAME, HENOSIA_ORGANIZATION_CTX_COOKIE };
|
package/package.json
CHANGED