@authdog/nextjs-app 1.0.1 → 2.0.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/dist/index.d.mts +13 -3
- package/dist/index.d.ts +13 -3
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/index.server.d.mts +2 -2
- package/dist/index.server.d.ts +2 -2
- package/dist/index.server.js +1 -1
- package/dist/index.server.js.map +1 -1
- package/dist/index.server.mjs +1 -1
- package/dist/index.server.mjs.map +1 -1
- package/package.json +69 -44
- package/dist/commons-CoLIU2e7.d.mts +0 -7
- package/dist/commons-CoLIU2e7.d.ts +0 -7
package/dist/index.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import React from 'react';
|
|
2
|
-
export {
|
|
2
|
+
export { PublicKeyPayload, assertTrustedIdentityHost, getPublicKeyPayload, validateAndParsePublicKey } from '@authdog/node-commons';
|
|
3
3
|
|
|
4
4
|
declare const getTokenFromUri: (url: string) => string | null;
|
|
5
5
|
interface AuthdogUser {
|
|
@@ -57,8 +57,18 @@ declare const fetchUserData: (publicKey: string, token: string) => Promise<Authd
|
|
|
57
57
|
declare const browserCookiesOptions: {
|
|
58
58
|
maxAge: number;
|
|
59
59
|
path: string;
|
|
60
|
-
|
|
60
|
+
secure: boolean;
|
|
61
|
+
sameSite: "lax";
|
|
61
62
|
};
|
|
63
|
+
/**
|
|
64
|
+
* Clears the client-side Authdog session: removes the locally stored token and
|
|
65
|
+
* notifies hooks (`useAuth`/`useUser`) via the {@link TOKEN_UPDATED_EVENT}.
|
|
66
|
+
*
|
|
67
|
+
* Note: this only clears the browser-side token. The server-side session cookie
|
|
68
|
+
* (and its hash) must also be cleared via the server logout handler
|
|
69
|
+
* (`logoutHandler`) to fully log the user out.
|
|
70
|
+
*/
|
|
71
|
+
declare const clearAuthdogSession: () => void;
|
|
62
72
|
|
|
63
73
|
declare const AuthdogProvider: ({ children, }: {
|
|
64
74
|
children: React.ReactNode;
|
|
@@ -79,4 +89,4 @@ interface UseUserResult {
|
|
|
79
89
|
}
|
|
80
90
|
declare const useUser: () => UseUserResult;
|
|
81
91
|
|
|
82
|
-
export { AuthdogProvider, type UseAuthResult, type UseUserResult, browserCookiesOptions, fetchUserData, getTokenFromUri, useAuth, useUser, validatePublicKey };
|
|
92
|
+
export { AuthdogProvider, type UseAuthResult, type UseUserResult, browserCookiesOptions, clearAuthdogSession, fetchUserData, getTokenFromUri, useAuth, useUser, validatePublicKey };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import React from 'react';
|
|
2
|
-
export {
|
|
2
|
+
export { PublicKeyPayload, assertTrustedIdentityHost, getPublicKeyPayload, validateAndParsePublicKey } from '@authdog/node-commons';
|
|
3
3
|
|
|
4
4
|
declare const getTokenFromUri: (url: string) => string | null;
|
|
5
5
|
interface AuthdogUser {
|
|
@@ -57,8 +57,18 @@ declare const fetchUserData: (publicKey: string, token: string) => Promise<Authd
|
|
|
57
57
|
declare const browserCookiesOptions: {
|
|
58
58
|
maxAge: number;
|
|
59
59
|
path: string;
|
|
60
|
-
|
|
60
|
+
secure: boolean;
|
|
61
|
+
sameSite: "lax";
|
|
61
62
|
};
|
|
63
|
+
/**
|
|
64
|
+
* Clears the client-side Authdog session: removes the locally stored token and
|
|
65
|
+
* notifies hooks (`useAuth`/`useUser`) via the {@link TOKEN_UPDATED_EVENT}.
|
|
66
|
+
*
|
|
67
|
+
* Note: this only clears the browser-side token. The server-side session cookie
|
|
68
|
+
* (and its hash) must also be cleared via the server logout handler
|
|
69
|
+
* (`logoutHandler`) to fully log the user out.
|
|
70
|
+
*/
|
|
71
|
+
declare const clearAuthdogSession: () => void;
|
|
62
72
|
|
|
63
73
|
declare const AuthdogProvider: ({ children, }: {
|
|
64
74
|
children: React.ReactNode;
|
|
@@ -79,4 +89,4 @@ interface UseUserResult {
|
|
|
79
89
|
}
|
|
80
90
|
declare const useUser: () => UseUserResult;
|
|
81
91
|
|
|
82
|
-
export { AuthdogProvider, type UseAuthResult, type UseUserResult, browserCookiesOptions, fetchUserData, getTokenFromUri, useAuth, useUser, validatePublicKey };
|
|
92
|
+
export { AuthdogProvider, type UseAuthResult, type UseUserResult, browserCookiesOptions, clearAuthdogSession, fetchUserData, getTokenFromUri, useAuth, useUser, validatePublicKey };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";"use client";var
|
|
1
|
+
"use strict";"use client";var D=Object.create;var T=Object.defineProperty;var C=Object.getOwnPropertyDescriptor;var F=Object.getOwnPropertyNames;var G=Object.getPrototypeOf,z=Object.prototype.hasOwnProperty;var V=(e,t)=>{for(var r in t)T(e,r,{get:t[r],enumerable:!0})},k=(e,t,r,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of F(t))!z.call(e,n)&&n!==r&&T(e,n,{get:()=>t[n],enumerable:!(a=C(t,n))||a.enumerable});return e};var Y=(e,t,r)=>(r=e!=null?D(G(e)):{},k(t||!e||!e.__esModule?T(r,"default",{value:e,enumerable:!0}):r,e)),B=e=>k(T({},"__esModule",{value:!0}),e);var Z={};V(Z,{AuthdogProvider:()=>I,assertTrustedIdentityHost:()=>l.assertTrustedIdentityHost,browserCookiesOptions:()=>S,clearAuthdogSession:()=>b,fetchUserData:()=>v,getPublicKeyPayload:()=>l.getPublicKeyPayload,getTokenFromUri:()=>N,useAuth:()=>L,useUser:()=>R,validateAndParsePublicKey:()=>l.validateAndParsePublicKey,validatePublicKey:()=>K});module.exports=B(Z);var U=require("@authdog/node-commons");var l=require("@authdog/node-commons");var u="token",c="token-updated";var N=e=>new URL(e).searchParams.get("token"),K=e=>{if(!e)throw new Error("Public key is not defined");if(!e.startsWith("pk_"))throw new Error("Invalid public key")},v=async(e,t)=>{var s;let{identityHost:r,environmentId:a}=(0,l.validateAndParsePublicKey)(e),n=await(0,U.fetchUserData)(r,a,t);if(!(0,U.isAuthenticatedUserInfo)(n)){let m=((s=n==null?void 0:n.meta)==null?void 0:s.code)??"unknown";throw new Error(`Failed to fetch user info (status ${m})`)}return n},S={maxAge:3600*24*7,path:"/",secure:!0,sameSite:"lax"},b=()=>{typeof window>"u"||(window.localStorage.removeItem(u),window.dispatchEvent(new Event(c)))};var h=Y(require("react"));var H=/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/,I=({children:e})=>((0,h.useEffect)(()=>{let t=new URLSearchParams(window.location.search).get("token");t&&(H.test(t)&&(localStorage.setItem(u,t),window.dispatchEvent(new Event(c))),window.history.replaceState({},document.title,"/"))},[]),h.default.createElement(h.default.Fragment,null,e));var w=require("react");var L=()=>{let[e,t]=(0,w.useState)(null),[r,a]=(0,w.useState)(!0);return(0,w.useEffect)(()=>{if(typeof window>"u"){t(null),a(!1);return}let n=()=>window.localStorage.getItem(u),s=()=>{let p=n();t(E=>E===p?E:p)};s(),a(!1);let m=()=>{s()},d=p=>{p.key===u&&s()};return window.addEventListener(c,m),window.addEventListener("storage",d),()=>{window.removeEventListener(c,m),window.removeEventListener("storage",d)}},[]),{token:e,isAuthenticated:!!e,isLoading:r}};var o=require("react");var O=process.env.NEXT_PUBLIC_PK_AUTHDOG,R=()=>{let[e,t]=(0,o.useState)(null),[r,a]=(0,o.useState)(!1),[n,s]=(0,o.useState)(null),[m,d]=(0,o.useState)(null),[p,E]=(0,o.useState)(!1),f=(0,o.useRef)(!0);(0,o.useEffect)(()=>()=>{f.current=!1},[]),(0,o.useEffect)(()=>{if(typeof window>"u"){t(null),a(!0);return}let i=()=>window.localStorage.getItem(u),g=()=>{let A=i();t(_=>_===A?_:A)};g(),a(!0);let x=()=>{g()},P=A=>{A.key===u&&g()};return window.addEventListener(c,x),window.addEventListener("storage",P),()=>{window.removeEventListener(c,x),window.removeEventListener("storage",P)}},[]);let y=(0,o.useCallback)(async()=>{if(!e){f.current&&(s(null),d(null),E(!1));return}if(!O){let i=new Error("NEXT_PUBLIC_PK_AUTHDOG environment variable is not set");throw f.current&&(d(i),s(null)),i}f.current&&E(!0);try{let i=await v(O,e);f.current&&(s((i==null?void 0:i.user)??null),d(null))}catch(i){let g=i instanceof Error?i:new Error("Unexpected error fetching Authdog user");throw process.env.NODE_ENV!=="production"&&console.error("Error fetching Authdog user profile:",g),f.current&&(s(null),d(g)),g}finally{f.current&&E(!1)}},[e]);return(0,o.useEffect)(()=>{r&&y().catch(()=>{})},[y,r]),{user:n,isLoading:!r||p,error:m,refetch:y}};0&&(module.exports={AuthdogProvider,assertTrustedIdentityHost,browserCookiesOptions,clearAuthdogSession,fetchUserData,getPublicKeyPayload,getTokenFromUri,useAuth,useUser,validateAndParsePublicKey,validatePublicKey});
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/commons.ts","../src/client/session.ts","../src/client/Provider.tsx","../src/client/constants.ts","../src/hooks/use-auth.ts","../src/hooks/use-user.ts"],"sourcesContent":["\"use client\";\nexport * from \"./client\";\nexport * from \"./commons\";\nexport * from \"./hooks\";\n","export interface PublicKeyPayload {\n environmentId: string;\n identityHost: string;\n}\n\nexport const getPublicKeyPayload = (publicKey: string): PublicKeyPayload => {\n if (!publicKey) {\n throw new Error(\"Public key is not defined\");\n }\n\n if (!publicKey.startsWith(\"pk_\")) {\n throw new Error(\"Invalid public key\");\n }\n\n try {\n return JSON.parse(\n Buffer.from(publicKey.replace(\"pk_\", \"\"), \"base64\").toString(\"utf-8\"),\n );\n } catch (e) {\n throw new Error(\"Failed to parse public key\");\n }\n};\n","import { getPublicKeyPayload } from \"../commons\";\n\nexport const getTokenFromUri = (url: string): string | null => {\n return new URL(url).searchParams.get(\"token\");\n};\n\nexport interface AuthdogUser {\n id: string;\n environmentId: string;\n externalId: string;\n userName: string;\n displayName: string;\n nickName: string;\n profileUrl: string;\n title: string;\n userType: string;\n preferredLanguage: string | null;\n locale: string | null;\n timezone: string | null;\n active: boolean;\n provider: string;\n lastLogin: string;\n createdAt: string;\n updatedAt: string;\n names: {\n id: string;\n userId: string;\n formatted: string | null;\n familyName: string;\n givenName: string;\n middleName: string | null;\n honorificPrefix: string | null;\n honorificSuffix: string | null;\n createdAt: string;\n updatedAt: string;\n };\n addresses: [];\n emails: {\n value: string;\n primary: boolean;\n type: string;\n }[];\n phoneNumbers: [];\n ims: [];\n photos: {\n value: string;\n type: string;\n }[];\n}\n\nexport interface AuthdogUserResponse {\n user: AuthdogUser;\n meta: {\n code: number;\n message: string;\n };\n}\n\nexport const validatePublicKey = (publicKey: string) => {\n if (!publicKey) {\n throw new Error(\"Public key is not defined\");\n }\n\n if (!publicKey.startsWith(\"pk_\")) {\n throw new Error(\"Invalid public key\");\n }\n};\n\nexport const fetchUserData = async (\n publicKey: string,\n token: string,\n): Promise<AuthdogUserResponse | null> => {\n validatePublicKey(publicKey);\n const publicKeyObj = getPublicKeyPayload(publicKey);\n const userData = await fetch(\n `${publicKeyObj?.identityHost}/oidc/${publicKeyObj?.environmentId}/userinfo`,\n {\n headers: {\n authorization: `Bearer ${token}`,\n },\n },\n );\n\n if (!userData.ok) {\n throw new Error(\"Failed to fetch user info\");\n }\n\n return await userData.json();\n};\n\nexport const browserCookiesOptions = {\n maxAge: 60 * 60 * 24 * 7, // 1 week\n path: \"/\",\n httpOnly: true,\n};\n","\"use client\";\n\nimport React, { useEffect } from \"react\";\n\nimport { TOKEN_STORAGE_KEY, TOKEN_UPDATED_EVENT } from \"./constants\";\n\nexport const AuthdogProvider = ({\n children,\n}: {\n children: React.ReactNode;\n}) => {\n useEffect(() => {\n const token = new URLSearchParams(window.location.search).get(\"token\");\n if (token) {\n localStorage.setItem(TOKEN_STORAGE_KEY, token);\n window.dispatchEvent(new Event(TOKEN_UPDATED_EVENT));\n window.history.replaceState({}, document.title, \"/\");\n }\n }, []);\n return <>{children}</>;\n};\n","export const TOKEN_STORAGE_KEY = \"token\";\nexport const TOKEN_UPDATED_EVENT = \"token-updated\";\nexport const TOKEN_POLL_INTERVAL_MS = 500;\nexport const TOKEN_POLL_MAX_ATTEMPTS = 10;\n","\"use client\";\n\nimport { useEffect, useState } from \"react\";\nimport {\n TOKEN_POLL_INTERVAL_MS,\n TOKEN_POLL_MAX_ATTEMPTS,\n TOKEN_STORAGE_KEY,\n TOKEN_UPDATED_EVENT,\n} from \"../client/constants\";\n\nexport interface UseAuthResult {\n token: string | null;\n isAuthenticated: boolean;\n isLoading: boolean;\n}\n\nexport const useAuth = (): UseAuthResult => {\n const [token, setToken] = useState<string | null>(null);\n const [isLoading, setIsLoading] = useState(true);\n\n useEffect(() => {\n if (typeof window === \"undefined\") {\n setToken(null);\n setIsLoading(false);\n return;\n }\n\n const readTokenFromStorage = () =>\n window.localStorage.getItem(TOKEN_STORAGE_KEY);\n\n const syncToken = () => {\n const nextToken = readTokenFromStorage();\n setToken((currentToken) =>\n currentToken === nextToken ? currentToken : nextToken,\n );\n };\n\n syncToken();\n setIsLoading(false);\n\n const handleTokenUpdate = () => {\n syncToken();\n };\n\n const handleStorageChange = (event: StorageEvent) => {\n if (event.key === TOKEN_STORAGE_KEY) {\n syncToken();\n }\n };\n\n window.addEventListener(TOKEN_UPDATED_EVENT, handleTokenUpdate);\n window.addEventListener(\"storage\", handleStorageChange);\n\n let pollCount = 0;\n const pollInterval = window.setInterval(() => {\n pollCount++;\n syncToken();\n\n if (pollCount >= TOKEN_POLL_MAX_ATTEMPTS) {\n window.clearInterval(pollInterval);\n }\n }, TOKEN_POLL_INTERVAL_MS);\n\n return () => {\n window.removeEventListener(TOKEN_UPDATED_EVENT, handleTokenUpdate);\n window.removeEventListener(\"storage\", handleStorageChange);\n window.clearInterval(pollInterval);\n };\n }, []);\n\n return {\n token,\n isAuthenticated: Boolean(token),\n isLoading,\n };\n};\n","\"use client\";\n\nimport { useCallback, useEffect, useRef, useState } from \"react\";\n\nimport {\n TOKEN_POLL_INTERVAL_MS,\n TOKEN_POLL_MAX_ATTEMPTS,\n TOKEN_STORAGE_KEY,\n TOKEN_UPDATED_EVENT,\n} from \"../client/constants\";\nimport { fetchUserData, type AuthdogUser } from \"../client/session\";\n\nconst PUBLIC_KEY = process.env.NEXT_PUBLIC_PK_AUTHDOG;\n\nexport interface UseUserResult {\n user: AuthdogUser | null;\n isLoading: boolean;\n error: Error | null;\n refetch: () => Promise<void>;\n}\n\nexport const useUser = (): UseUserResult => {\n const [token, setToken] = useState<string | null>(null);\n const [isTokenInitialized, setIsTokenInitialized] = useState(false);\n const [user, setUser] = useState<AuthdogUser | null>(null);\n const [error, setError] = useState<Error | null>(null);\n const [isFetching, setIsFetching] = useState(false);\n const isMountedRef = useRef(true);\n\n useEffect(() => {\n return () => {\n isMountedRef.current = false;\n };\n }, []);\n\n useEffect(() => {\n if (typeof window === \"undefined\") {\n setToken(null);\n setIsTokenInitialized(true);\n return;\n }\n\n const readTokenFromStorage = () =>\n window.localStorage.getItem(TOKEN_STORAGE_KEY);\n\n const syncToken = () => {\n const nextToken = readTokenFromStorage();\n setToken((currentToken) =>\n currentToken === nextToken ? currentToken : nextToken,\n );\n };\n\n syncToken();\n setIsTokenInitialized(true);\n\n const handleTokenUpdate = () => {\n syncToken();\n };\n\n const handleStorageChange = (event: StorageEvent) => {\n if (event.key === TOKEN_STORAGE_KEY) {\n syncToken();\n }\n };\n\n window.addEventListener(TOKEN_UPDATED_EVENT, handleTokenUpdate);\n window.addEventListener(\"storage\", handleStorageChange);\n\n let pollCount = 0;\n const pollInterval = window.setInterval(() => {\n pollCount++;\n syncToken();\n\n if (pollCount >= TOKEN_POLL_MAX_ATTEMPTS) {\n window.clearInterval(pollInterval);\n }\n }, TOKEN_POLL_INTERVAL_MS);\n\n return () => {\n window.removeEventListener(TOKEN_UPDATED_EVENT, handleTokenUpdate);\n window.removeEventListener(\"storage\", handleStorageChange);\n window.clearInterval(pollInterval);\n };\n }, []);\n\n const fetchProfile = useCallback(async () => {\n if (!token) {\n if (isMountedRef.current) {\n setUser(null);\n setError(null);\n setIsFetching(false);\n }\n return;\n }\n\n if (!PUBLIC_KEY) {\n const publicKeyError = new Error(\n \"NEXT_PUBLIC_PK_AUTHDOG environment variable is not set\",\n );\n if (isMountedRef.current) {\n setError(publicKeyError);\n setUser(null);\n }\n throw publicKeyError;\n }\n\n if (isMountedRef.current) {\n setIsFetching(true);\n }\n\n try {\n const response = await fetchUserData(PUBLIC_KEY, token);\n if (isMountedRef.current) {\n setUser(response?.user ?? null);\n setError(null);\n }\n } catch (err) {\n const nextError =\n err instanceof Error\n ? err\n : new Error(\"Unexpected error fetching Authdog user\");\n if (process.env.NODE_ENV !== \"production\") {\n console.error(\"Error fetching Authdog user profile:\", nextError);\n }\n if (isMountedRef.current) {\n setUser(null);\n setError(nextError);\n }\n throw nextError;\n } finally {\n if (isMountedRef.current) {\n setIsFetching(false);\n }\n }\n }, [token]);\n\n useEffect(() => {\n if (!isTokenInitialized) {\n return;\n }\n\n fetchProfile().catch(() => {\n /* error is already stored in state */\n });\n }, [fetchProfile, isTokenInitialized]);\n\n return {\n user,\n isLoading: !isTokenInitialized || isFetching,\n error,\n refetch: fetchProfile,\n };\n};\n"],"mappings":"ukBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,qBAAAE,EAAA,0BAAAC,EAAA,kBAAAC,EAAA,wBAAAC,EAAA,oBAAAC,EAAA,YAAAC,EAAA,YAAAC,EAAA,sBAAAC,IAAA,eAAAC,EAAAV,GCKO,IAAMW,EAAuBC,GAAwC,CAC1E,GAAI,CAACA,EACH,MAAM,IAAI,MAAM,2BAA2B,EAG7C,GAAI,CAACA,EAAU,WAAW,KAAK,EAC7B,MAAM,IAAI,MAAM,oBAAoB,EAGtC,GAAI,CACF,OAAO,KAAK,MACV,OAAO,KAAKA,EAAU,QAAQ,MAAO,EAAE,EAAG,QAAQ,EAAE,SAAS,OAAO,CACtE,CACF,MAAY,CACV,MAAM,IAAI,MAAM,4BAA4B,CAC9C,C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cAC3B,QAAQ,MAAM,uCAAwCC,CAAS,EAE7DjB,EAAa,UACfL,EAAQ,IAAI,EACZE,EAASoB,CAAS,GAEdA,CACR,QAAE,CACIjB,EAAa,SACfD,EAAc,EAAK,CAEvB,CACF,EAAG,CAACT,CAAK,CAAC,EAEV,sBAAU,IAAM,CACTE,GAILoB,EAAa,EAAE,MAAM,IAAM,CAE3B,CAAC,CACH,EAAG,CAACA,EAAcpB,CAAkB,CAAC,EAE9B,CACL,KAAAE,EACA,UAAW,CAACF,GAAsBM,EAClC,MAAAF,EACA,QAASgB,CACX,CACF","names":["index_exports","__export","AuthdogProvider","browserCookiesOptions","fetchUserData","getPublicKeyPayload","getTokenFromUri","useAuth","useUser","validatePublicKey","__toCommonJS","getPublicKeyPayload","publicKey","getTokenFromUri","url","validatePublicKey","publicKey","fetchUserData","token","publicKeyObj","getPublicKeyPayload","userData","browserCookiesOptions","import_react","TOKEN_STORAGE_KEY","TOKEN_UPDATED_EVENT","AuthdogProvider","children","token","TOKEN_STORAGE_KEY","TOKEN_UPDATED_EVENT","React","import_react","useAuth","token","setToken","isLoading","setIsLoading","readTokenFromStorage","TOKEN_STORAGE_KEY","syncToken","nextToken","currentToken","handleTokenUpdate","handleStorageChange","event","TOKEN_UPDATED_EVENT","pollCount","pollInterval","import_react","PUBLIC_KEY","useUser","token","setToken","isTokenInitialized","setIsTokenInitialized","user","setUser","error","setError","isFetching","setIsFetching","isMountedRef","readTokenFromStorage","TOKEN_STORAGE_KEY","syncToken","nextToken","currentToken","handleTokenUpdate","handleStorageChange","event","TOKEN_UPDATED_EVENT","pollCount","pollInterval","fetchProfile","publicKeyError","response","fetchUserData","err","nextError"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/client/session.ts","../src/commons.ts","../src/client/constants.ts","../src/client/Provider.tsx","../src/hooks/useAuth.ts","../src/hooks/useUser.ts"],"sourcesContent":["\"use client\";\nexport * from \"./client\";\nexport * from \"./commons\";\nexport * from \"./hooks\";\n","import {\n fetchUserData as fetchUserInfo,\n isAuthenticatedUserInfo,\n} from \"@authdog/node-commons\";\nimport { validateAndParsePublicKey } from \"../commons\";\nimport { TOKEN_STORAGE_KEY, TOKEN_UPDATED_EVENT } from \"./constants\";\n\nexport const getTokenFromUri = (url: string): string | null => {\n return new URL(url).searchParams.get(\"token\");\n};\n\nexport interface AuthdogUser {\n id: string;\n environmentId: string;\n externalId: string;\n userName: string;\n displayName: string;\n nickName: string;\n profileUrl: string;\n title: string;\n userType: string;\n preferredLanguage: string | null;\n locale: string | null;\n timezone: string | null;\n active: boolean;\n provider: string;\n lastLogin: string;\n createdAt: string;\n updatedAt: string;\n names: {\n id: string;\n userId: string;\n formatted: string | null;\n familyName: string;\n givenName: string;\n middleName: string | null;\n honorificPrefix: string | null;\n honorificSuffix: string | null;\n createdAt: string;\n updatedAt: string;\n };\n addresses: [];\n emails: {\n value: string;\n primary: boolean;\n type: string;\n }[];\n phoneNumbers: [];\n ims: [];\n photos: {\n value: string;\n type: string;\n }[];\n}\n\nexport interface AuthdogUserResponse {\n user: AuthdogUser;\n meta: {\n code: number;\n message: string;\n };\n}\n\nexport const validatePublicKey = (publicKey: string) => {\n if (!publicKey) {\n throw new Error(\"Public key is not defined\");\n }\n\n if (!publicKey.startsWith(\"pk_\")) {\n throw new Error(\"Invalid public key\");\n }\n};\n\nexport const fetchUserData = async (\n publicKey: string,\n token: string,\n): Promise<AuthdogUserResponse | null> => {\n const { identityHost, environmentId } = validateAndParsePublicKey(publicKey);\n\n const userData = await fetchUserInfo(identityHost, environmentId, token);\n\n if (!isAuthenticatedUserInfo(userData)) {\n const status = userData?.meta?.code ?? \"unknown\";\n throw new Error(`Failed to fetch user info (status ${status})`);\n }\n\n return userData as unknown as AuthdogUserResponse;\n};\n\nexport const browserCookiesOptions = {\n maxAge: 60 * 60 * 24 * 7, // 1 week\n path: \"/\",\n secure: true,\n sameSite: \"lax\" as const,\n};\n\n/**\n * Clears the client-side Authdog session: removes the locally stored token and\n * notifies hooks (`useAuth`/`useUser`) via the {@link TOKEN_UPDATED_EVENT}.\n *\n * Note: this only clears the browser-side token. The server-side session cookie\n * (and its hash) must also be cleared via the server logout handler\n * (`logoutHandler`) to fully log the user out.\n */\nexport const clearAuthdogSession = (): void => {\n if (typeof window === \"undefined\") {\n return;\n }\n window.localStorage.removeItem(TOKEN_STORAGE_KEY);\n window.dispatchEvent(new Event(TOKEN_UPDATED_EVENT));\n};\n","export {\n validateAndParsePublicKey,\n // Backwards-compatible alias of `validateAndParsePublicKey`.\n getPublicKeyPayload,\n assertTrustedIdentityHost,\n type PublicKeyPayload,\n} from \"@authdog/node-commons\";\n","export const TOKEN_STORAGE_KEY = \"token\";\nexport const TOKEN_UPDATED_EVENT = \"token-updated\";\n","\"use client\";\n\nimport React, { useEffect } from \"react\";\n\nimport { TOKEN_STORAGE_KEY, TOKEN_UPDATED_EVENT } from \"./constants\";\n\nconst JWT_PATTERN = /^[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+$/;\n\nexport const AuthdogProvider = ({\n children,\n}: {\n children: React.ReactNode;\n}) => {\n useEffect(() => {\n const token = new URLSearchParams(window.location.search).get(\"token\");\n if (token) {\n if (JWT_PATTERN.test(token)) {\n localStorage.setItem(TOKEN_STORAGE_KEY, token);\n window.dispatchEvent(new Event(TOKEN_UPDATED_EVENT));\n }\n // Always strip the token from the URL, even if it was rejected.\n window.history.replaceState({}, document.title, \"/\");\n }\n }, []);\n return <>{children}</>;\n};\n","\"use client\";\n\nimport { useEffect, useState } from \"react\";\nimport { TOKEN_STORAGE_KEY, TOKEN_UPDATED_EVENT } from \"../client/constants\";\n\nexport interface UseAuthResult {\n token: string | null;\n isAuthenticated: boolean;\n isLoading: boolean;\n}\n\nexport const useAuth = (): UseAuthResult => {\n const [token, setToken] = useState<string | null>(null);\n const [isLoading, setIsLoading] = useState(true);\n\n useEffect(() => {\n if (typeof window === \"undefined\") {\n setToken(null);\n setIsLoading(false);\n return;\n }\n\n const readTokenFromStorage = () =>\n window.localStorage.getItem(TOKEN_STORAGE_KEY);\n\n const syncToken = () => {\n const nextToken = readTokenFromStorage();\n setToken((currentToken) =>\n currentToken === nextToken ? currentToken : nextToken,\n );\n };\n\n syncToken();\n setIsLoading(false);\n\n const handleTokenUpdate = () => {\n syncToken();\n };\n\n const handleStorageChange = (event: StorageEvent) => {\n if (event.key === TOKEN_STORAGE_KEY) {\n syncToken();\n }\n };\n\n window.addEventListener(TOKEN_UPDATED_EVENT, handleTokenUpdate);\n window.addEventListener(\"storage\", handleStorageChange);\n\n return () => {\n window.removeEventListener(TOKEN_UPDATED_EVENT, handleTokenUpdate);\n window.removeEventListener(\"storage\", handleStorageChange);\n };\n }, []);\n\n return {\n token,\n isAuthenticated: Boolean(token),\n isLoading,\n };\n};\n","\"use client\";\n\nimport { useCallback, useEffect, useRef, useState } from \"react\";\n\nimport { TOKEN_STORAGE_KEY, TOKEN_UPDATED_EVENT } from \"../client/constants\";\nimport { fetchUserData, type AuthdogUser } from \"../client/session\";\n\nconst PUBLIC_KEY = process.env.NEXT_PUBLIC_PK_AUTHDOG;\n\nexport interface UseUserResult {\n user: AuthdogUser | null;\n isLoading: boolean;\n error: Error | null;\n refetch: () => Promise<void>;\n}\n\nexport const useUser = (): UseUserResult => {\n const [token, setToken] = useState<string | null>(null);\n const [isTokenInitialized, setIsTokenInitialized] = useState(false);\n const [user, setUser] = useState<AuthdogUser | null>(null);\n const [error, setError] = useState<Error | null>(null);\n const [isFetching, setIsFetching] = useState(false);\n const isMountedRef = useRef(true);\n\n useEffect(() => {\n return () => {\n isMountedRef.current = false;\n };\n }, []);\n\n useEffect(() => {\n if (typeof window === \"undefined\") {\n setToken(null);\n setIsTokenInitialized(true);\n return;\n }\n\n const readTokenFromStorage = () =>\n window.localStorage.getItem(TOKEN_STORAGE_KEY);\n\n const syncToken = () => {\n const nextToken = readTokenFromStorage();\n setToken((currentToken) =>\n currentToken === nextToken ? currentToken : nextToken,\n );\n };\n\n syncToken();\n setIsTokenInitialized(true);\n\n const handleTokenUpdate = () => {\n syncToken();\n };\n\n const handleStorageChange = (event: StorageEvent) => {\n if (event.key === TOKEN_STORAGE_KEY) {\n syncToken();\n }\n };\n\n window.addEventListener(TOKEN_UPDATED_EVENT, handleTokenUpdate);\n window.addEventListener(\"storage\", handleStorageChange);\n\n return () => {\n window.removeEventListener(TOKEN_UPDATED_EVENT, handleTokenUpdate);\n window.removeEventListener(\"storage\", handleStorageChange);\n };\n }, []);\n\n const fetchProfile = useCallback(async () => {\n if (!token) {\n if (isMountedRef.current) {\n setUser(null);\n setError(null);\n setIsFetching(false);\n }\n return;\n }\n\n if (!PUBLIC_KEY) {\n const publicKeyError = new Error(\n \"NEXT_PUBLIC_PK_AUTHDOG environment variable is not set\",\n );\n if (isMountedRef.current) {\n setError(publicKeyError);\n setUser(null);\n }\n throw publicKeyError;\n }\n\n if (isMountedRef.current) {\n setIsFetching(true);\n }\n\n try {\n const response = await fetchUserData(PUBLIC_KEY, token);\n if (isMountedRef.current) {\n setUser(response?.user ?? null);\n setError(null);\n }\n } catch (err) {\n const nextError =\n err instanceof Error\n ? err\n : new Error(\"Unexpected error fetching Authdog user\");\n if (process.env.NODE_ENV !== \"production\") {\n console.error(\"Error fetching Authdog user profile:\", nextError);\n }\n if (isMountedRef.current) {\n setUser(null);\n setError(nextError);\n }\n throw nextError;\n } finally {\n if (isMountedRef.current) {\n setIsFetching(false);\n }\n }\n }, [token]);\n\n useEffect(() => {\n if (!isTokenInitialized) {\n return;\n }\n\n fetchProfile().catch(() => {});\n }, [fetchProfile, isTokenInitialized]);\n\n return {\n user,\n isLoading: !isTokenInitialized || isFetching,\n error,\n refetch: fetchProfile,\n };\n};\n"],"mappings":"ukBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,qBAAAE,EAAA,oFAAAC,EAAA,wBAAAC,EAAA,kBAAAC,EAAA,kEAAAC,EAAA,YAAAC,EAAA,YAAAC,EAAA,gFAAAC,IAAA,eAAAC,E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CAAS,GAEdA,CACR,QAAE,CACIf,EAAa,SACfD,EAAc,EAAK,CAEvB,CACF,EAAG,CAACT,CAAK,CAAC,EAEV,sBAAU,IAAM,CACTE,GAILkB,EAAa,EAAE,MAAM,IAAM,CAAC,CAAC,CAC/B,EAAG,CAACA,EAAclB,CAAkB,CAAC,EAE9B,CACL,KAAAE,EACA,UAAW,CAACF,GAAsBM,EAClC,MAAAF,EACA,QAASc,CACX,CACF","names":["index_exports","__export","AuthdogProvider","browserCookiesOptions","clearAuthdogSession","fetchUserData","getTokenFromUri","useAuth","useUser","validatePublicKey","__toCommonJS","import_node_commons","import_node_commons","TOKEN_STORAGE_KEY","TOKEN_UPDATED_EVENT","getTokenFromUri","url","validatePublicKey","publicKey","fetchUserData","token","_a","identityHost","environmentId","userData","fetchUserInfo","status","browserCookiesOptions","clearAuthdogSession","TOKEN_STORAGE_KEY","TOKEN_UPDATED_EVENT","import_react","JWT_PATTERN","AuthdogProvider","children","token","TOKEN_STORAGE_KEY","TOKEN_UPDATED_EVENT","React","import_react","useAuth","token","setToken","isLoading","setIsLoading","readTokenFromStorage","TOKEN_STORAGE_KEY","syncToken","nextToken","currentToken","handleTokenUpdate","handleStorageChange","event","TOKEN_UPDATED_EVENT","import_react","PUBLIC_KEY","useUser","token","setToken","isTokenInitialized","setIsTokenInitialized","user","setUser","error","setError","isFetching","setIsFetching","isMountedRef","readTokenFromStorage","TOKEN_STORAGE_KEY","syncToken","nextToken","currentToken","handleTokenUpdate","handleStorageChange","event","TOKEN_UPDATED_EVENT","fetchProfile","publicKeyError","response","fetchUserData","err","nextError"]}
|
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use client";
|
|
1
|
+
"use client";import{fetchUserData as N,isAuthenticatedUserInfo as K}from"@authdog/node-commons";import{validateAndParsePublicKey as w,getPublicKeyPayload as k,assertTrustedIdentityHost as H}from"@authdog/node-commons";var o="token",s="token-updated";var S=e=>new URL(e).searchParams.get("token"),b=e=>{if(!e)throw new Error("Public key is not defined");if(!e.startsWith("pk_"))throw new Error("Invalid public key")},A=async(e,t)=>{var r;let{identityHost:a,environmentId:l}=w(e),i=await N(a,l,t);if(!K(i)){let f=((r=i==null?void 0:i.meta)==null?void 0:r.code)??"unknown";throw new Error(`Failed to fetch user info (status ${f})`)}return i},I={maxAge:3600*24*7,path:"/",secure:!0,sameSite:"lax"},L=()=>{typeof window>"u"||(window.localStorage.removeItem(o),window.dispatchEvent(new Event(s)))};import x,{useEffect as O}from"react";var R=/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/,D=({children:e})=>(O(()=>{let t=new URLSearchParams(window.location.search).get("token");t&&(R.test(t)&&(localStorage.setItem(o,t),window.dispatchEvent(new Event(s))),window.history.replaceState({},document.title,"/"))},[]),x.createElement(x.Fragment,null,e));import{useEffect as C,useState as P}from"react";var F=()=>{let[e,t]=P(null),[a,l]=P(!0);return C(()=>{if(typeof window>"u"){t(null),l(!1);return}let i=()=>window.localStorage.getItem(o),r=()=>{let g=i();t(m=>m===g?m:g)};r(),l(!1);let f=()=>{r()},u=g=>{g.key===o&&r()};return window.addEventListener(s,f),window.addEventListener("storage",u),()=>{window.removeEventListener(s,f),window.removeEventListener("storage",u)}},[]),{token:e,isAuthenticated:!!e,isLoading:a}};import{useCallback as G,useEffect as T,useRef as z,useState as p}from"react";var _=process.env.NEXT_PUBLIC_PK_AUTHDOG,V=()=>{let[e,t]=p(null),[a,l]=p(!1),[i,r]=p(null),[f,u]=p(null),[g,m]=p(!1),c=z(!0);T(()=>()=>{c.current=!1},[]),T(()=>{if(typeof window>"u"){t(null),l(!0);return}let n=()=>window.localStorage.getItem(o),d=()=>{let E=n();t(y=>y===E?y:E)};d(),l(!0);let U=()=>{d()},v=E=>{E.key===o&&d()};return window.addEventListener(s,U),window.addEventListener("storage",v),()=>{window.removeEventListener(s,U),window.removeEventListener("storage",v)}},[]);let h=G(async()=>{if(!e){c.current&&(r(null),u(null),m(!1));return}if(!_){let n=new Error("NEXT_PUBLIC_PK_AUTHDOG environment variable is not set");throw c.current&&(u(n),r(null)),n}c.current&&m(!0);try{let n=await A(_,e);c.current&&(r((n==null?void 0:n.user)??null),u(null))}catch(n){let d=n instanceof Error?n:new Error("Unexpected error fetching Authdog user");throw process.env.NODE_ENV!=="production"&&console.error("Error fetching Authdog user profile:",d),c.current&&(r(null),u(d)),d}finally{c.current&&m(!1)}},[e]);return T(()=>{a&&h().catch(()=>{})},[h,a]),{user:i,isLoading:!a||g,error:f,refetch:h}};export{D as AuthdogProvider,H as assertTrustedIdentityHost,I as browserCookiesOptions,L as clearAuthdogSession,A as fetchUserData,k as getPublicKeyPayload,S as getTokenFromUri,F as useAuth,V as useUser,w as validateAndParsePublicKey,b as validatePublicKey};
|
|
2
2
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/commons.ts","../src/client/session.ts","../src/client/Provider.tsx","../src/client/constants.ts","../src/hooks/use-auth.ts","../src/hooks/use-user.ts"],"sourcesContent":["export interface PublicKeyPayload {\n environmentId: string;\n identityHost: string;\n}\n\nexport const getPublicKeyPayload = (publicKey: string): PublicKeyPayload => {\n if (!publicKey) {\n throw new Error(\"Public key is not defined\");\n }\n\n if (!publicKey.startsWith(\"pk_\")) {\n throw new Error(\"Invalid public key\");\n }\n\n try {\n return JSON.parse(\n Buffer.from(publicKey.replace(\"pk_\", \"\"), \"base64\").toString(\"utf-8\"),\n );\n } catch (e) {\n throw new Error(\"Failed to parse public key\");\n }\n};\n","import { getPublicKeyPayload } from \"../commons\";\n\nexport const getTokenFromUri = (url: string): string | null => {\n return new URL(url).searchParams.get(\"token\");\n};\n\nexport interface AuthdogUser {\n id: string;\n environmentId: string;\n externalId: string;\n userName: string;\n displayName: string;\n nickName: string;\n profileUrl: string;\n title: string;\n userType: string;\n preferredLanguage: string | null;\n locale: string | null;\n timezone: string | null;\n active: boolean;\n provider: string;\n lastLogin: string;\n createdAt: string;\n updatedAt: string;\n names: {\n id: string;\n userId: string;\n formatted: string | null;\n familyName: string;\n givenName: string;\n middleName: string | null;\n honorificPrefix: string | null;\n honorificSuffix: string | null;\n createdAt: string;\n updatedAt: string;\n };\n addresses: [];\n emails: {\n value: string;\n primary: boolean;\n type: string;\n }[];\n phoneNumbers: [];\n ims: [];\n photos: {\n value: string;\n type: string;\n }[];\n}\n\nexport interface AuthdogUserResponse {\n user: AuthdogUser;\n meta: {\n code: number;\n message: string;\n };\n}\n\nexport const validatePublicKey = (publicKey: string) => {\n if (!publicKey) {\n throw new Error(\"Public key is not defined\");\n }\n\n if (!publicKey.startsWith(\"pk_\")) {\n throw new Error(\"Invalid public key\");\n }\n};\n\nexport const fetchUserData = async (\n publicKey: string,\n token: string,\n): Promise<AuthdogUserResponse | null> => {\n validatePublicKey(publicKey);\n const publicKeyObj = getPublicKeyPayload(publicKey);\n const userData = await fetch(\n `${publicKeyObj?.identityHost}/oidc/${publicKeyObj?.environmentId}/userinfo`,\n {\n headers: {\n authorization: `Bearer ${token}`,\n },\n },\n );\n\n if (!userData.ok) {\n throw new Error(\"Failed to fetch user info\");\n }\n\n return await userData.json();\n};\n\nexport const browserCookiesOptions = {\n maxAge: 60 * 60 * 24 * 7, // 1 week\n path: \"/\",\n httpOnly: true,\n};\n","\"use client\";\n\nimport React, { useEffect } from \"react\";\n\nimport { TOKEN_STORAGE_KEY, TOKEN_UPDATED_EVENT } from \"./constants\";\n\nexport const AuthdogProvider = ({\n children,\n}: {\n children: React.ReactNode;\n}) => {\n useEffect(() => {\n const token = new URLSearchParams(window.location.search).get(\"token\");\n if (token) {\n localStorage.setItem(TOKEN_STORAGE_KEY, token);\n window.dispatchEvent(new Event(TOKEN_UPDATED_EVENT));\n window.history.replaceState({}, document.title, \"/\");\n }\n }, []);\n return <>{children}</>;\n};\n","export const TOKEN_STORAGE_KEY = \"token\";\nexport const TOKEN_UPDATED_EVENT = \"token-updated\";\nexport const TOKEN_POLL_INTERVAL_MS = 500;\nexport const TOKEN_POLL_MAX_ATTEMPTS = 10;\n","\"use client\";\n\nimport { useEffect, useState } from \"react\";\nimport {\n TOKEN_POLL_INTERVAL_MS,\n TOKEN_POLL_MAX_ATTEMPTS,\n TOKEN_STORAGE_KEY,\n TOKEN_UPDATED_EVENT,\n} from \"../client/constants\";\n\nexport interface UseAuthResult {\n token: string | null;\n isAuthenticated: boolean;\n isLoading: boolean;\n}\n\nexport const useAuth = (): UseAuthResult => {\n const [token, setToken] = useState<string | null>(null);\n const [isLoading, setIsLoading] = useState(true);\n\n useEffect(() => {\n if (typeof window === \"undefined\") {\n setToken(null);\n setIsLoading(false);\n return;\n }\n\n const readTokenFromStorage = () =>\n window.localStorage.getItem(TOKEN_STORAGE_KEY);\n\n const syncToken = () => {\n const nextToken = readTokenFromStorage();\n setToken((currentToken) =>\n currentToken === nextToken ? currentToken : nextToken,\n );\n };\n\n syncToken();\n setIsLoading(false);\n\n const handleTokenUpdate = () => {\n syncToken();\n };\n\n const handleStorageChange = (event: StorageEvent) => {\n if (event.key === TOKEN_STORAGE_KEY) {\n syncToken();\n }\n };\n\n window.addEventListener(TOKEN_UPDATED_EVENT, handleTokenUpdate);\n window.addEventListener(\"storage\", handleStorageChange);\n\n let pollCount = 0;\n const pollInterval = window.setInterval(() => {\n pollCount++;\n syncToken();\n\n if (pollCount >= TOKEN_POLL_MAX_ATTEMPTS) {\n window.clearInterval(pollInterval);\n }\n }, TOKEN_POLL_INTERVAL_MS);\n\n return () => {\n window.removeEventListener(TOKEN_UPDATED_EVENT, handleTokenUpdate);\n window.removeEventListener(\"storage\", handleStorageChange);\n window.clearInterval(pollInterval);\n };\n }, []);\n\n return {\n token,\n isAuthenticated: Boolean(token),\n isLoading,\n };\n};\n","\"use client\";\n\nimport { useCallback, useEffect, useRef, useState } from \"react\";\n\nimport {\n TOKEN_POLL_INTERVAL_MS,\n TOKEN_POLL_MAX_ATTEMPTS,\n TOKEN_STORAGE_KEY,\n TOKEN_UPDATED_EVENT,\n} from \"../client/constants\";\nimport { fetchUserData, type AuthdogUser } from \"../client/session\";\n\nconst PUBLIC_KEY = process.env.NEXT_PUBLIC_PK_AUTHDOG;\n\nexport interface UseUserResult {\n user: AuthdogUser | null;\n isLoading: boolean;\n error: Error | null;\n refetch: () => Promise<void>;\n}\n\nexport const useUser = (): UseUserResult => {\n const [token, setToken] = useState<string | null>(null);\n const [isTokenInitialized, setIsTokenInitialized] = useState(false);\n const [user, setUser] = useState<AuthdogUser | null>(null);\n const [error, setError] = useState<Error | null>(null);\n const [isFetching, setIsFetching] = useState(false);\n const isMountedRef = useRef(true);\n\n useEffect(() => {\n return () => {\n isMountedRef.current = false;\n };\n }, []);\n\n useEffect(() => {\n if (typeof window === \"undefined\") {\n setToken(null);\n setIsTokenInitialized(true);\n return;\n }\n\n const readTokenFromStorage = () =>\n window.localStorage.getItem(TOKEN_STORAGE_KEY);\n\n const syncToken = () => {\n const nextToken = readTokenFromStorage();\n setToken((currentToken) =>\n currentToken === nextToken ? currentToken : nextToken,\n );\n };\n\n syncToken();\n setIsTokenInitialized(true);\n\n const handleTokenUpdate = () => {\n syncToken();\n };\n\n const handleStorageChange = (event: StorageEvent) => {\n if (event.key === TOKEN_STORAGE_KEY) {\n syncToken();\n }\n };\n\n window.addEventListener(TOKEN_UPDATED_EVENT, handleTokenUpdate);\n window.addEventListener(\"storage\", handleStorageChange);\n\n let pollCount = 0;\n const pollInterval = window.setInterval(() => {\n pollCount++;\n syncToken();\n\n if (pollCount >= TOKEN_POLL_MAX_ATTEMPTS) {\n window.clearInterval(pollInterval);\n }\n }, TOKEN_POLL_INTERVAL_MS);\n\n return () => {\n window.removeEventListener(TOKEN_UPDATED_EVENT, handleTokenUpdate);\n window.removeEventListener(\"storage\", handleStorageChange);\n window.clearInterval(pollInterval);\n };\n }, []);\n\n const fetchProfile = useCallback(async () => {\n if (!token) {\n if (isMountedRef.current) {\n setUser(null);\n setError(null);\n setIsFetching(false);\n }\n return;\n }\n\n if (!PUBLIC_KEY) {\n const publicKeyError = new Error(\n \"NEXT_PUBLIC_PK_AUTHDOG environment variable is not set\",\n );\n if (isMountedRef.current) {\n setError(publicKeyError);\n setUser(null);\n }\n throw publicKeyError;\n }\n\n if (isMountedRef.current) {\n setIsFetching(true);\n }\n\n try {\n const response = await fetchUserData(PUBLIC_KEY, token);\n if (isMountedRef.current) {\n setUser(response?.user ?? null);\n setError(null);\n }\n } catch (err) {\n const nextError =\n err instanceof Error\n ? err\n : new Error(\"Unexpected error fetching Authdog user\");\n if (process.env.NODE_ENV !== \"production\") {\n console.error(\"Error fetching Authdog user profile:\", nextError);\n }\n if (isMountedRef.current) {\n setUser(null);\n setError(nextError);\n }\n throw nextError;\n } finally {\n if (isMountedRef.current) {\n setIsFetching(false);\n }\n }\n }, [token]);\n\n useEffect(() => {\n if (!isTokenInitialized) {\n return;\n }\n\n fetchProfile().catch(() => {\n /* error is already stored in state */\n });\n }, [fetchProfile, isTokenInitialized]);\n\n return {\n user,\n isLoading: !isTokenInitialized || isFetching,\n error,\n refetch: fetchProfile,\n };\n};\n"],"mappings":"aAKO,IAAMA,EAAuBC,GAAwC,CAC1E,GAAI,CAACA,EACH,MAAM,IAAI,MAAM,2BAA2B,EAG7C,GAAI,CAACA,EAAU,WAAW,KAAK,EAC7B,MAAM,IAAI,MAAM,oBAAoB,EAGtC,GAAI,CACF,OAAO,KAAK,MACV,OAAO,KAAKA,EAAU,QAAQ,MAAO,EAAE,EAAG,QAAQ,EAAE,SAAS,OAAO,CACtE,CACF,MAAY,CACV,MAAM,IAAI,MAAM,4BAA4B,CAC9C,CACF,ECnBO,IAAMC,EAAmBC,GACvB,IAAI,IAAIA,CAAG,EAAE,aAAa,IAAI,OAAO,EAuDjCC,EAAqBC,GAAsB,CACtD,GAAI,CAACA,EACH,MAAM,IAAI,MAAM,2BAA2B,EAG7C,GAAI,CAACA,EAAU,WAAW,KAAK,EAC7B,MAAM,IAAI,MAAM,oBA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Aa,SACfD,EAAc,EAAK,CAEvB,CACF,EAAG,CAACV,CAAK,CAAC,EAEV,OAAAa,EAAU,IAAM,CACTV,GAILsB,EAAa,EAAE,MAAM,IAAM,CAE3B,CAAC,CACH,EAAG,CAACA,EAActB,CAAkB,CAAC,EAE9B,CACL,KAAAE,EACA,UAAW,CAACF,GAAsBM,EAClC,MAAAF,EACA,QAASkB,CACX,CACF","names":["getPublicKeyPayload","publicKey","getTokenFromUri","url","validatePublicKey","publicKey","fetchUserData","token","publicKeyObj","getPublicKeyPayload","userData","browserCookiesOptions","React","useEffect","TOKEN_STORAGE_KEY","TOKEN_UPDATED_EVENT","AuthdogProvider","children","useEffect","token","TOKEN_STORAGE_KEY","TOKEN_UPDATED_EVENT","React","useEffect","useState","useAuth","token","setToken","useState","isLoading","setIsLoading","useEffect","readTokenFromStorage","TOKEN_STORAGE_KEY","syncToken","nextToken","currentToken","handleTokenUpdate","handleStorageChange","event","TOKEN_UPDATED_EVENT","pollCount","pollInterval","useCallback","useEffect","useRef","useState","PUBLIC_KEY","useUser","token","setToken","useState","isTokenInitialized","setIsTokenInitialized","user","setUser","error","setError","isFetching","setIsFetching","isMountedRef","useRef","useEffect","readTokenFromStorage","TOKEN_STORAGE_KEY","syncToken","nextToken","currentToken","handleTokenUpdate","handleStorageChange","event","TOKEN_UPDATED_EVENT","pollCount","pollInterval","fetchProfile","useCallback","publicKeyError","response","fetchUserData","err","nextError"]}
|
|
1
|
+
{"version":3,"sources":["../src/client/session.ts","../src/commons.ts","../src/client/constants.ts","../src/client/Provider.tsx","../src/hooks/useAuth.ts","../src/hooks/useUser.ts"],"sourcesContent":["import {\n fetchUserData as fetchUserInfo,\n isAuthenticatedUserInfo,\n} from \"@authdog/node-commons\";\nimport { validateAndParsePublicKey } from \"../commons\";\nimport { TOKEN_STORAGE_KEY, TOKEN_UPDATED_EVENT } from \"./constants\";\n\nexport const getTokenFromUri = (url: string): string | null => {\n return new URL(url).searchParams.get(\"token\");\n};\n\nexport interface AuthdogUser {\n id: string;\n environmentId: string;\n externalId: string;\n userName: string;\n displayName: string;\n nickName: string;\n profileUrl: string;\n title: string;\n userType: string;\n preferredLanguage: string | null;\n locale: string | null;\n timezone: string | null;\n active: boolean;\n provider: string;\n lastLogin: string;\n createdAt: string;\n updatedAt: string;\n names: {\n id: string;\n userId: string;\n formatted: string | null;\n familyName: string;\n givenName: string;\n middleName: string | null;\n honorificPrefix: string | null;\n honorificSuffix: string | null;\n createdAt: string;\n updatedAt: string;\n };\n addresses: [];\n emails: {\n value: string;\n primary: boolean;\n type: string;\n }[];\n phoneNumbers: [];\n ims: [];\n photos: {\n value: string;\n type: string;\n }[];\n}\n\nexport interface AuthdogUserResponse {\n user: AuthdogUser;\n meta: {\n code: number;\n message: string;\n };\n}\n\nexport const validatePublicKey = (publicKey: string) => {\n if (!publicKey) {\n throw new Error(\"Public key is not defined\");\n }\n\n if (!publicKey.startsWith(\"pk_\")) {\n throw new Error(\"Invalid public key\");\n }\n};\n\nexport const fetchUserData = async (\n publicKey: string,\n token: string,\n): Promise<AuthdogUserResponse | null> => {\n const { identityHost, environmentId } = validateAndParsePublicKey(publicKey);\n\n const userData = await fetchUserInfo(identityHost, environmentId, token);\n\n if (!isAuthenticatedUserInfo(userData)) {\n const status = userData?.meta?.code ?? \"unknown\";\n throw new Error(`Failed to fetch user info (status ${status})`);\n }\n\n return userData as unknown as AuthdogUserResponse;\n};\n\nexport const browserCookiesOptions = {\n maxAge: 60 * 60 * 24 * 7, // 1 week\n path: \"/\",\n secure: true,\n sameSite: \"lax\" as const,\n};\n\n/**\n * Clears the client-side Authdog session: removes the locally stored token and\n * notifies hooks (`useAuth`/`useUser`) via the {@link TOKEN_UPDATED_EVENT}.\n *\n * Note: this only clears the browser-side token. The server-side session cookie\n * (and its hash) must also be cleared via the server logout handler\n * (`logoutHandler`) to fully log the user out.\n */\nexport const clearAuthdogSession = (): void => {\n if (typeof window === \"undefined\") {\n return;\n }\n window.localStorage.removeItem(TOKEN_STORAGE_KEY);\n window.dispatchEvent(new Event(TOKEN_UPDATED_EVENT));\n};\n","export {\n validateAndParsePublicKey,\n // Backwards-compatible alias of `validateAndParsePublicKey`.\n getPublicKeyPayload,\n assertTrustedIdentityHost,\n type PublicKeyPayload,\n} from \"@authdog/node-commons\";\n","export const TOKEN_STORAGE_KEY = \"token\";\nexport const TOKEN_UPDATED_EVENT = \"token-updated\";\n","\"use client\";\n\nimport React, { useEffect } from \"react\";\n\nimport { TOKEN_STORAGE_KEY, TOKEN_UPDATED_EVENT } from \"./constants\";\n\nconst JWT_PATTERN = /^[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+$/;\n\nexport const AuthdogProvider = ({\n children,\n}: {\n children: React.ReactNode;\n}) => {\n useEffect(() => {\n const token = new URLSearchParams(window.location.search).get(\"token\");\n if (token) {\n if (JWT_PATTERN.test(token)) {\n localStorage.setItem(TOKEN_STORAGE_KEY, token);\n window.dispatchEvent(new Event(TOKEN_UPDATED_EVENT));\n }\n // Always strip the token from the URL, even if it was rejected.\n window.history.replaceState({}, document.title, \"/\");\n }\n }, []);\n return <>{children}</>;\n};\n","\"use client\";\n\nimport { useEffect, useState } from \"react\";\nimport { TOKEN_STORAGE_KEY, TOKEN_UPDATED_EVENT } from \"../client/constants\";\n\nexport interface UseAuthResult {\n token: string | null;\n isAuthenticated: boolean;\n isLoading: boolean;\n}\n\nexport const useAuth = (): UseAuthResult => {\n const [token, setToken] = useState<string | null>(null);\n const [isLoading, setIsLoading] = useState(true);\n\n useEffect(() => {\n if (typeof window === \"undefined\") {\n setToken(null);\n setIsLoading(false);\n return;\n }\n\n const readTokenFromStorage = () =>\n window.localStorage.getItem(TOKEN_STORAGE_KEY);\n\n const syncToken = () => {\n const nextToken = readTokenFromStorage();\n setToken((currentToken) =>\n currentToken === nextToken ? currentToken : nextToken,\n );\n };\n\n syncToken();\n setIsLoading(false);\n\n const handleTokenUpdate = () => {\n syncToken();\n };\n\n const handleStorageChange = (event: StorageEvent) => {\n if (event.key === TOKEN_STORAGE_KEY) {\n syncToken();\n }\n };\n\n window.addEventListener(TOKEN_UPDATED_EVENT, handleTokenUpdate);\n window.addEventListener(\"storage\", handleStorageChange);\n\n return () => {\n window.removeEventListener(TOKEN_UPDATED_EVENT, handleTokenUpdate);\n window.removeEventListener(\"storage\", handleStorageChange);\n };\n }, []);\n\n return {\n token,\n isAuthenticated: Boolean(token),\n isLoading,\n };\n};\n","\"use client\";\n\nimport { useCallback, useEffect, useRef, useState } from \"react\";\n\nimport { TOKEN_STORAGE_KEY, TOKEN_UPDATED_EVENT } from \"../client/constants\";\nimport { fetchUserData, type AuthdogUser } from \"../client/session\";\n\nconst PUBLIC_KEY = process.env.NEXT_PUBLIC_PK_AUTHDOG;\n\nexport interface UseUserResult {\n user: AuthdogUser | null;\n isLoading: boolean;\n error: Error | null;\n refetch: () => Promise<void>;\n}\n\nexport const useUser = (): UseUserResult => {\n const [token, setToken] = useState<string | null>(null);\n const [isTokenInitialized, setIsTokenInitialized] = useState(false);\n const [user, setUser] = useState<AuthdogUser | null>(null);\n const [error, setError] = useState<Error | null>(null);\n const [isFetching, setIsFetching] = useState(false);\n const isMountedRef = useRef(true);\n\n useEffect(() => {\n return () => {\n isMountedRef.current = false;\n };\n }, []);\n\n useEffect(() => {\n if (typeof window === \"undefined\") {\n setToken(null);\n setIsTokenInitialized(true);\n return;\n }\n\n const readTokenFromStorage = () =>\n window.localStorage.getItem(TOKEN_STORAGE_KEY);\n\n const syncToken = () => {\n const nextToken = readTokenFromStorage();\n setToken((currentToken) =>\n currentToken === nextToken ? currentToken : nextToken,\n );\n };\n\n syncToken();\n setIsTokenInitialized(true);\n\n const handleTokenUpdate = () => {\n syncToken();\n };\n\n const handleStorageChange = (event: StorageEvent) => {\n if (event.key === TOKEN_STORAGE_KEY) {\n syncToken();\n }\n };\n\n window.addEventListener(TOKEN_UPDATED_EVENT, handleTokenUpdate);\n window.addEventListener(\"storage\", handleStorageChange);\n\n return () => {\n window.removeEventListener(TOKEN_UPDATED_EVENT, handleTokenUpdate);\n window.removeEventListener(\"storage\", handleStorageChange);\n };\n }, []);\n\n const fetchProfile = useCallback(async () => {\n if (!token) {\n if (isMountedRef.current) {\n setUser(null);\n setError(null);\n setIsFetching(false);\n }\n return;\n }\n\n if (!PUBLIC_KEY) {\n const publicKeyError = new Error(\n \"NEXT_PUBLIC_PK_AUTHDOG environment variable is not set\",\n );\n if (isMountedRef.current) {\n setError(publicKeyError);\n setUser(null);\n }\n throw publicKeyError;\n }\n\n if (isMountedRef.current) {\n setIsFetching(true);\n }\n\n try {\n const response = await fetchUserData(PUBLIC_KEY, token);\n if (isMountedRef.current) {\n setUser(response?.user ?? null);\n setError(null);\n }\n } catch (err) {\n const nextError =\n err instanceof Error\n ? err\n : new Error(\"Unexpected error fetching Authdog user\");\n if (process.env.NODE_ENV !== \"production\") {\n console.error(\"Error fetching Authdog user profile:\", nextError);\n }\n if (isMountedRef.current) {\n setUser(null);\n setError(nextError);\n }\n throw nextError;\n } finally {\n if (isMountedRef.current) {\n setIsFetching(false);\n }\n }\n }, [token]);\n\n useEffect(() => {\n if (!isTokenInitialized) {\n return;\n }\n\n fetchProfile().catch(() => {});\n }, [fetchProfile, isTokenInitialized]);\n\n return {\n user,\n isLoading: !isTokenInitialized || isFetching,\n error,\n refetch: fetchProfile,\n };\n};\n"],"mappings":"aAAA,OACE,iBAAiBA,EACjB,2BAAAC,MACK,wBCHP,OACE,6BAAAC,EAEA,uBAAAC,EACA,6BAAAC,MAEK,wBCNA,IAAMC,EAAoB,QACpBC,EAAsB,gBFM5B,IAAMC,EAAmBC,GACvB,IAAI,IAAIA,CAAG,EAAE,aAAa,IAAI,OAAO,EAuDjCC,EAAqBC,GAAsB,CACtD,GAAI,CAACA,EACH,MAAM,IAAI,MAAM,2BAA2B,EAG7C,GAAI,CAACA,EAAU,WAAW,KAAK,EAC7B,MAAM,IAAI,MAAM,oBAAoB,CAExC,EAEaC,EAAgB,MAC3BD,EAC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AACF,GAAsBM,EAClC,MAAAF,EACA,QAASgB,CACX,CACF","names":["fetchUserInfo","isAuthenticatedUserInfo","validateAndParsePublicKey","getPublicKeyPayload","assertTrustedIdentityHost","TOKEN_STORAGE_KEY","TOKEN_UPDATED_EVENT","getTokenFromUri","url","validatePublicKey","publicKey","fetchUserData","token","_a","identityHost","environmentId","validateAndParsePublicKey","userData","fetchUserInfo","isAuthenticatedUserInfo","status","browserCookiesOptions","clearAuthdogSession","TOKEN_STORAGE_KEY","TOKEN_UPDATED_EVENT","React","useEffect","JWT_PATTERN","AuthdogProvider","children","useEffect","token","TOKEN_STORAGE_KEY","TOKEN_UPDATED_EVENT","React","useEffect","useState","useAuth","token","setToken","useState","isLoading","setIsLoading","useEffect","readTokenFromStorage","TOKEN_STORAGE_KEY","syncToken","nextToken","currentToken","handleTokenUpdate","handleStorageChange","event","TOKEN_UPDATED_EVENT","useCallback","useEffect","useRef","useState","PUBLIC_KEY","useUser","token","setToken","useState","isTokenInitialized","setIsTokenInitialized","user","setUser","error","setError","isFetching","setIsFetching","isMountedRef","useRef","useEffect","readTokenFromStorage","TOKEN_STORAGE_KEY","syncToken","nextToken","currentToken","handleTokenUpdate","handleStorageChange","event","TOKEN_UPDATED_EVENT","fetchProfile","useCallback","publicKeyError","response","fetchUserData","err","nextError"]}
|
package/dist/index.server.d.mts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { NextRequest, NextResponse } from 'next/server';
|
|
2
2
|
import * as next_dist_compiled__edge_runtime_cookies from 'next/dist/compiled/@edge-runtime/cookies';
|
|
3
|
-
import
|
|
3
|
+
import * as _authdog_node_commons from '@authdog/node-commons';
|
|
4
4
|
|
|
5
5
|
declare const useAuthMiddleware: (publicKey: string) => (request: NextRequest) => Promise<NextResponse<unknown>>;
|
|
6
6
|
|
|
@@ -8,6 +8,6 @@ declare const getSessionCookie: (publicKey: string) => Promise<next_dist_compile
|
|
|
8
8
|
|
|
9
9
|
declare const logoutHandler: (req: NextRequest) => Promise<Response>;
|
|
10
10
|
|
|
11
|
-
declare const getServerSidePayloadPublicKey: (publicKey: string) => PublicKeyPayload;
|
|
11
|
+
declare const getServerSidePayloadPublicKey: (publicKey: string) => _authdog_node_commons.PublicKeyPayload;
|
|
12
12
|
|
|
13
13
|
export { getServerSidePayloadPublicKey, getSessionCookie, logoutHandler, useAuthMiddleware };
|
package/dist/index.server.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { NextRequest, NextResponse } from 'next/server';
|
|
2
2
|
import * as next_dist_compiled__edge_runtime_cookies from 'next/dist/compiled/@edge-runtime/cookies';
|
|
3
|
-
import
|
|
3
|
+
import * as _authdog_node_commons from '@authdog/node-commons';
|
|
4
4
|
|
|
5
5
|
declare const useAuthMiddleware: (publicKey: string) => (request: NextRequest) => Promise<NextResponse<unknown>>;
|
|
6
6
|
|
|
@@ -8,6 +8,6 @@ declare const getSessionCookie: (publicKey: string) => Promise<next_dist_compile
|
|
|
8
8
|
|
|
9
9
|
declare const logoutHandler: (req: NextRequest) => Promise<Response>;
|
|
10
10
|
|
|
11
|
-
declare const getServerSidePayloadPublicKey: (publicKey: string) => PublicKeyPayload;
|
|
11
|
+
declare const getServerSidePayloadPublicKey: (publicKey: string) => _authdog_node_commons.PublicKeyPayload;
|
|
12
12
|
|
|
13
13
|
export { getServerSidePayloadPublicKey, getSessionCookie, logoutHandler, useAuthMiddleware };
|
package/dist/index.server.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";
|
|
1
|
+
"use strict";var h=Object.create;var p=Object.defineProperty;var A=Object.getOwnPropertyDescriptor;var q=Object.getOwnPropertyNames;var k=Object.getPrototypeOf,_=Object.prototype.hasOwnProperty;var w=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),I=(t,e)=>{for(var o in e)p(t,o,{get:e[o],enumerable:!0})},l=(t,e,o,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of q(e))!_.call(t,r)&&r!==o&&p(t,r,{get:()=>e[r],enumerable:!(i=A(e,r))||i.enumerable});return t};var b=(t,e,o)=>(o=t!=null?h(k(t)):{},l(e||!t||!t.__esModule?p(o,"default",{value:t,enumerable:!0}):o,t)),U=t=>l(p({},"__esModule",{value:!0}),t);var f=w((n,g)=>{"use strict";var s={NextRequest:require("next/dist/server/web/spec-extension/request").NextRequest,NextResponse:require("next/dist/server/web/spec-extension/response").NextResponse,ImageResponse:require("next/dist/server/web/spec-extension/image-response").ImageResponse,userAgentFromString:require("next/dist/server/web/spec-extension/user-agent").userAgentFromString,userAgent:require("next/dist/server/web/spec-extension/user-agent").userAgent,URLPattern:require("next/dist/server/web/spec-extension/url-pattern").URLPattern,after:require("next/dist/server/after").after,connection:require("next/dist/server/request/connection").connection};g.exports=s;n.NextRequest=s.NextRequest;n.NextResponse=s.NextResponse;n.ImageResponse=s.ImageResponse;n.userAgentFromString=s.userAgentFromString;n.userAgent=s.userAgent;n.URLPattern=s.URLPattern;n.after=s.after;n.connection=s.connection});var K={};I(K,{getServerSidePayloadPublicKey:()=>d,getSessionCookie:()=>R,logoutHandler:()=>v,useAuthMiddleware:()=>y});module.exports=U(K);var z=require("server-only");var x=b(f()),c=require("@authdog/node-commons"),y=t=>{let e=(0,c.validateAndParsePublicKey)(t);return async o=>{let i=x.NextResponse.next(),r={maxAge:3600*24*7,path:"/",httpOnly:!0,secure:process.env.NODE_ENV==="production",sameSite:"lax"},u=new URL(o.nextUrl).searchParams.get("token");if(u){let m=await(0,c.fetchUserData)(e.identityHost,e.environmentId,u);(0,c.isAuthenticatedUserInfo)(m)&&(i.cookies.set({name:`user_session_${e.environmentId}`,value:JSON.stringify(m.user),...r}),i.cookies.set({name:`user_session_hash_${e.environmentId}`,value:u,...r}))}return i}};var P=require("next/headers");var a=require("@authdog/node-commons");var R=async t=>{if(!t)throw new Error("Public key is not defined");let e=(0,a.validateAndParsePublicKey)(t);return(await(0,P.cookies)()).get(`user_session_${e==null?void 0:e.environmentId}`)};var N=require("next/headers");var d=t=>{if(!t)throw new Error("Public key is not defined");return(0,a.validateAndParsePublicKey)(t)};var v=async t=>{let e=await(0,N.cookies)(),o=process.env.PK_AUTHDOG;if(!o)throw new Error("Public key is not defined");let r=(await d(o)).environmentId,u={value:"",path:"/",maxAge:0,httpOnly:!0,secure:process.env.NODE_ENV==="production",sameSite:"lax"},m=`user_session_${r}`;e.set({name:m,...u});let S=`user_session_hash_${r}`;return e.set({name:S,...u}),new Response(JSON.stringify({message:"Logout successfully",success:!0}),{status:200,headers:{"Content-Type":"application/json"}})};0&&(module.exports={getServerSidePayloadPublicKey,getSessionCookie,logoutHandler,useAuthMiddleware});
|
|
2
2
|
//# sourceMappingURL=index.server.js.map
|
package/dist/index.server.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["
|
|
1
|
+
{"version":3,"sources":["../node_modules/next/server.js","../src/index.server.ts","../src/server/middleware.ts","../src/server/cookies.ts","../src/commons.ts","../src/server/logout.ts","../src/server/publicKey.ts"],"sourcesContent":["const serverExports = {\n NextRequest: require('next/dist/server/web/spec-extension/request')\n .NextRequest,\n NextResponse: require('next/dist/server/web/spec-extension/response')\n .NextResponse,\n ImageResponse: require('next/dist/server/web/spec-extension/image-response')\n .ImageResponse,\n userAgentFromString: require('next/dist/server/web/spec-extension/user-agent')\n .userAgentFromString,\n userAgent: require('next/dist/server/web/spec-extension/user-agent')\n .userAgent,\n URLPattern: require('next/dist/server/web/spec-extension/url-pattern')\n .URLPattern,\n after: require('next/dist/server/after').after,\n connection: require('next/dist/server/request/connection').connection,\n}\n\n// https://nodejs.org/api/esm.html#commonjs-namespaces\n// When importing CommonJS modules, the module.exports object is provided as the default export\nmodule.exports = serverExports\n\n// make import { xxx } from 'next/server' work\nexports.NextRequest = serverExports.NextRequest\nexports.NextResponse = serverExports.NextResponse\nexports.ImageResponse = serverExports.ImageResponse\nexports.userAgentFromString = serverExports.userAgentFromString\nexports.userAgent = serverExports.userAgent\nexports.URLPattern = serverExports.URLPattern\nexports.after = serverExports.after\nexports.connection = serverExports.connection\n","import \"server-only\";\nexport * from \"./server\";\n","import { NextResponse, type NextRequest } from \"next/server\";\nimport {\n validateAndParsePublicKey,\n fetchUserData,\n isAuthenticatedUserInfo,\n} from \"@authdog/node-commons\";\n\nexport const useAuthMiddleware = (publicKey: string) => {\n const publicKeyObj = validateAndParsePublicKey(publicKey);\n\n return async (request: NextRequest) => {\n const response = NextResponse.next();\n const options = {\n maxAge: 60 * 60 * 24 * 7, // 1 week\n path: \"/\",\n httpOnly: true,\n secure: process.env.NODE_ENV === \"production\",\n sameSite: \"lax\" as const,\n };\n\n const tokenFromUri = new URL(request.nextUrl).searchParams.get(\"token\");\n\n if (tokenFromUri) {\n const userData = await fetchUserData(\n publicKeyObj.identityHost,\n publicKeyObj.environmentId,\n tokenFromUri,\n );\n\n if (isAuthenticatedUserInfo(userData)) {\n response.cookies.set({\n name: `user_session_${publicKeyObj.environmentId}`,\n value: JSON.stringify(userData.user),\n ...options,\n });\n\n response.cookies.set({\n name: `user_session_hash_${publicKeyObj.environmentId}`,\n value: tokenFromUri,\n ...options,\n });\n }\n }\n // TODO: token from cookies\n\n return response;\n };\n};\n","import { cookies } from \"next/headers\";\nimport { validateAndParsePublicKey } from \"../commons\";\n\nexport const getSessionCookie = async (publicKey: string) => {\n if (!publicKey) {\n throw new Error(\"Public key is not defined\");\n }\n const publicKeyObj = validateAndParsePublicKey(publicKey);\n const cookieStore = await cookies();\n return cookieStore.get(`user_session_${publicKeyObj?.environmentId}`);\n};\n","export {\n validateAndParsePublicKey,\n // Backwards-compatible alias of `validateAndParsePublicKey`.\n getPublicKeyPayload,\n assertTrustedIdentityHost,\n type PublicKeyPayload,\n} from \"@authdog/node-commons\";\n","import { cookies } from \"next/headers\";\nimport { NextRequest } from \"next/server\";\nimport { getServerSidePayloadPublicKey } from \"./publicKey\";\n\nexport const logoutHandler = async (req: NextRequest) => {\n const cookiesStore = await cookies();\n\n const publicKey = process.env.PK_AUTHDOG as string;\n\n if (!publicKey) {\n throw new Error(\"Public key is not defined\");\n }\n\n const payload = await getServerSidePayloadPublicKey(publicKey);\n\n const environmentId = payload.environmentId;\n\n const deleteOptions = {\n value: \"\",\n path: \"/\",\n maxAge: 0,\n httpOnly: true,\n secure: process.env.NODE_ENV === \"production\",\n sameSite: \"lax\" as const,\n };\n\n const cookieNameSession = `user_session_${environmentId}`;\n cookiesStore.set({ name: cookieNameSession, ...deleteOptions });\n\n const cookieNameHash = `user_session_hash_${environmentId}`;\n cookiesStore.set({ name: cookieNameHash, ...deleteOptions });\n\n return new Response(\n JSON.stringify({\n message: \"Logout successfully\",\n success: true,\n }),\n {\n status: 200,\n headers: {\n \"Content-Type\": \"application/json\",\n },\n },\n );\n};\n","import { validateAndParsePublicKey } from \"../commons\";\nexport const getServerSidePayloadPublicKey = (publicKey: string) => {\n if (!publicKey) {\n throw new Error(\"Public key is not defined\");\n }\n return validateAndParsePublicKey(publicKey);\n};\n"],"mappings":"onBAAA,IAAAA,EAAAC,EAAA,CAAAC,EAAAC,IAAA,kBAAMC,EAAgB,CACpB,YAAa,QAAQ,6CAA6C,EAC/D,YACH,aAAc,QAAQ,8CAA8C,EACjE,aACH,cAAe,QAAQ,oDAAoD,EACxE,cACH,oBAAqB,QAAQ,gDAAgD,EAC1E,oBACH,UAAW,QAAQ,gDAAgD,EAChE,UACH,WAAY,QAAQ,iDAAiD,EAClE,WACH,MAAO,QAAQ,wBAAwB,EAAE,MACzC,WAAY,QAAQ,qCAAqC,EAAE,UAC7D,EAIAD,EAAO,QAAUC,EAGjBF,EAAQ,YAAcE,EAAc,YACpCF,EAAQ,aAAeE,EAAc,aACrCF,EAAQ,cAAgBE,EAAc,cACtCF,EAAQ,oBAAsBE,EAAc,oBAC5CF,EAAQ,UAAYE,EAAc,UAClCF,EAAQ,WAAaE,EAAc,WACnCF,EAAQ,MAAQE,EAAc,MAC9BF,EAAQ,WAAaE,EAAc,aC7BnC,IAAAC,EAAA,GAA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M,WAAQ,EAE7BC,EAAY,QAAQ,IAAI,WAE9B,GAAI,CAACA,EACH,MAAM,IAAI,MAAM,2BAA2B,EAK7C,IAAMC,GAFU,MAAMC,EAA8BF,CAAS,GAE/B,cAExBG,EAAgB,CACpB,MAAO,GACP,KAAM,IACN,OAAQ,EACR,SAAU,GACV,OAAQ,QAAQ,IAAI,WAAa,aACjC,SAAU,KACZ,EAEMC,EAAoB,gBAAgBH,CAAa,GACvDF,EAAa,IAAI,CAAE,KAAMK,EAAmB,GAAGD,CAAc,CAAC,EAE9D,IAAME,EAAiB,qBAAqBJ,CAAa,GACzD,OAAAF,EAAa,IAAI,CAAE,KAAMM,EAAgB,GAAGF,CAAc,CAAC,EAEpD,IAAI,SACT,KAAK,UAAU,CACb,QAAS,sBACT,QAAS,EACX,CAAC,EACD,CACE,OAAQ,IACR,QAAS,CACP,eAAgB,kBAClB,CACF,CACF,CACF","names":["require_server","__commonJSMin","exports","module","serverExports","index_server_exports","__export","getServerSidePayloadPublicKey","getSessionCookie","logoutHandler","useAuthMiddleware","__toCommonJS","import_server_only","import_server","import_node_commons","useAuthMiddleware","publicKey","publicKeyObj","request","response","options","tokenFromUri","userData","import_headers","import_node_commons","getSessionCookie","publicKey","publicKeyObj","import_headers","getServerSidePayloadPublicKey","publicKey","logoutHandler","req","cookiesStore","publicKey","environmentId","getServerSidePayloadPublicKey","deleteOptions","cookieNameSession","cookieNameHash"]}
|
package/dist/index.server.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
var y=Object.create;var d=Object.defineProperty;var P=Object.getOwnPropertyDescriptor;var R=Object.getOwnPropertyNames;var N=Object.getPrototypeOf,v=Object.prototype.hasOwnProperty;var i=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,o)=>(typeof require<"u"?require:e)[o]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var S=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var h=(t,e,o,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of R(e))!v.call(t,r)&&r!==o&&d(t,r,{get:()=>e[r],enumerable:!(a=P(e,r))||a.enumerable});return t};var A=(t,e,o)=>(o=t!=null?y(N(t)):{},h(e||!t||!t.__esModule?d(o,"default",{value:t,enumerable:!0}):o,t));var g=S((n,l)=>{"use strict";var s={NextRequest:i("next/dist/server/web/spec-extension/request").NextRequest,NextResponse:i("next/dist/server/web/spec-extension/response").NextResponse,ImageResponse:i("next/dist/server/web/spec-extension/image-response").ImageResponse,userAgentFromString:i("next/dist/server/web/spec-extension/user-agent").userAgentFromString,userAgent:i("next/dist/server/web/spec-extension/user-agent").userAgent,URLPattern:i("next/dist/server/web/spec-extension/url-pattern").URLPattern,after:i("next/dist/server/after").after,connection:i("next/dist/server/request/connection").connection};l.exports=s;n.NextRequest=s.NextRequest;n.NextResponse=s.NextResponse;n.ImageResponse=s.ImageResponse;n.userAgentFromString=s.userAgentFromString;n.userAgent=s.userAgent;n.URLPattern=s.URLPattern;n.after=s.after;n.connection=s.connection});import"server-only";var f=A(g());import{validateAndParsePublicKey as q,fetchUserData as k,isAuthenticatedUserInfo as _}from"@authdog/node-commons";var w=t=>{let e=q(t);return async o=>{let a=f.NextResponse.next(),r={maxAge:3600*24*7,path:"/",httpOnly:!0,secure:process.env.NODE_ENV==="production",sameSite:"lax"},u=new URL(o.nextUrl).searchParams.get("token");if(u){let c=await k(e.identityHost,e.environmentId,u);_(c)&&(a.cookies.set({name:`user_session_${e.environmentId}`,value:JSON.stringify(c.user),...r}),a.cookies.set({name:`user_session_hash_${e.environmentId}`,value:u,...r}))}return a}};import{cookies as I}from"next/headers";import{validateAndParsePublicKey as m,getPublicKeyPayload as F,assertTrustedIdentityHost as $}from"@authdog/node-commons";var b=async t=>{if(!t)throw new Error("Public key is not defined");let e=m(t);return(await I()).get(`user_session_${e==null?void 0:e.environmentId}`)};import{cookies as U}from"next/headers";var p=t=>{if(!t)throw new Error("Public key is not defined");return m(t)};var K=async t=>{let e=await U(),o=process.env.PK_AUTHDOG;if(!o)throw new Error("Public key is not defined");let r=(await p(o)).environmentId,u={value:"",path:"/",maxAge:0,httpOnly:!0,secure:process.env.NODE_ENV==="production",sameSite:"lax"},c=`user_session_${r}`;e.set({name:c,...u});let x=`user_session_hash_${r}`;return e.set({name:x,...u}),new Response(JSON.stringify({message:"Logout successfully",success:!0}),{status:200,headers:{"Content-Type":"application/json"}})};export{p as getServerSidePayloadPublicKey,b as getSessionCookie,K as logoutHandler,w as useAuthMiddleware};
|
|
2
2
|
//# sourceMappingURL=index.server.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["
|
|
1
|
+
{"version":3,"sources":["../node_modules/next/server.js","../src/index.server.ts","../src/server/middleware.ts","../src/server/cookies.ts","../src/commons.ts","../src/server/logout.ts","../src/server/publicKey.ts"],"sourcesContent":["const serverExports = {\n NextRequest: require('next/dist/server/web/spec-extension/request')\n .NextRequest,\n NextResponse: require('next/dist/server/web/spec-extension/response')\n .NextResponse,\n ImageResponse: require('next/dist/server/web/spec-extension/image-response')\n .ImageResponse,\n userAgentFromString: require('next/dist/server/web/spec-extension/user-agent')\n .userAgentFromString,\n userAgent: require('next/dist/server/web/spec-extension/user-agent')\n .userAgent,\n URLPattern: require('next/dist/server/web/spec-extension/url-pattern')\n .URLPattern,\n after: require('next/dist/server/after').after,\n connection: require('next/dist/server/request/connection').connection,\n}\n\n// https://nodejs.org/api/esm.html#commonjs-namespaces\n// When importing CommonJS modules, the module.exports object is provided as the default export\nmodule.exports = serverExports\n\n// make import { xxx } from 'next/server' work\nexports.NextRequest = serverExports.NextRequest\nexports.NextResponse = serverExports.NextResponse\nexports.ImageResponse = serverExports.ImageResponse\nexports.userAgentFromString = serverExports.userAgentFromString\nexports.userAgent = serverExports.userAgent\nexports.URLPattern = serverExports.URLPattern\nexports.after = serverExports.after\nexports.connection = serverExports.connection\n","import \"server-only\";\nexport * from \"./server\";\n","import { NextResponse, type NextRequest } from \"next/server\";\nimport {\n validateAndParsePublicKey,\n fetchUserData,\n isAuthenticatedUserInfo,\n} from \"@authdog/node-commons\";\n\nexport const useAuthMiddleware = (publicKey: string) => {\n const publicKeyObj = validateAndParsePublicKey(publicKey);\n\n return async (request: NextRequest) => {\n const response = NextResponse.next();\n const options = {\n maxAge: 60 * 60 * 24 * 7, // 1 week\n path: \"/\",\n httpOnly: true,\n secure: process.env.NODE_ENV === \"production\",\n sameSite: \"lax\" as const,\n };\n\n const tokenFromUri = new URL(request.nextUrl).searchParams.get(\"token\");\n\n if (tokenFromUri) {\n const userData = await fetchUserData(\n publicKeyObj.identityHost,\n publicKeyObj.environmentId,\n tokenFromUri,\n );\n\n if (isAuthenticatedUserInfo(userData)) {\n response.cookies.set({\n name: `user_session_${publicKeyObj.environmentId}`,\n value: JSON.stringify(userData.user),\n ...options,\n });\n\n response.cookies.set({\n name: `user_session_hash_${publicKeyObj.environmentId}`,\n value: tokenFromUri,\n ...options,\n });\n }\n }\n // TODO: token from cookies\n\n return response;\n };\n};\n","import { cookies } from \"next/headers\";\nimport { validateAndParsePublicKey } from \"../commons\";\n\nexport const getSessionCookie = async (publicKey: string) => {\n if (!publicKey) {\n throw new Error(\"Public key is not defined\");\n }\n const publicKeyObj = validateAndParsePublicKey(publicKey);\n const cookieStore = await cookies();\n return cookieStore.get(`user_session_${publicKeyObj?.environmentId}`);\n};\n","export {\n validateAndParsePublicKey,\n // Backwards-compatible alias of `validateAndParsePublicKey`.\n getPublicKeyPayload,\n assertTrustedIdentityHost,\n type PublicKeyPayload,\n} from \"@authdog/node-commons\";\n","import { cookies } from \"next/headers\";\nimport { NextRequest } from \"next/server\";\nimport { getServerSidePayloadPublicKey } from \"./publicKey\";\n\nexport const logoutHandler = async (req: NextRequest) => {\n const cookiesStore = await cookies();\n\n const publicKey = process.env.PK_AUTHDOG as string;\n\n if (!publicKey) {\n throw new Error(\"Public key is not defined\");\n }\n\n const payload = await getServerSidePayloadPublicKey(publicKey);\n\n const environmentId = payload.environmentId;\n\n const deleteOptions = {\n value: \"\",\n path: \"/\",\n maxAge: 0,\n httpOnly: true,\n secure: process.env.NODE_ENV === \"production\",\n sameSite: \"lax\" as const,\n };\n\n const cookieNameSession = `user_session_${environmentId}`;\n cookiesStore.set({ name: cookieNameSession, ...deleteOptions });\n\n const cookieNameHash = `user_session_hash_${environmentId}`;\n cookiesStore.set({ name: cookieNameHash, ...deleteOptions });\n\n return new Response(\n JSON.stringify({\n message: \"Logout successfully\",\n success: true,\n }),\n {\n status: 200,\n headers: {\n \"Content-Type\": \"application/json\",\n },\n },\n );\n};\n","import { validateAndParsePublicKey } from \"../commons\";\nexport const getServerSidePayloadPublicKey = (publicKey: string) => {\n if (!publicKey) {\n throw new Error(\"Public key is not defined\");\n }\n return validateAndParsePublicKey(publicKey);\n};\n"],"mappings":"kwBAAA,IAAAA,EAAAC,EAAA,CAAAC,EAAAC,IAAA,kBAAMC,EAAgB,CACpB,YAAa,EAAQ,6CAA6C,EAC/D,YACH,aAAc,EAAQ,8CAA8C,EACjE,aACH,cAAe,EAAQ,oDAAoD,EACxE,cACH,oBAAqB,EAAQ,gDAAgD,EAC1E,oBACH,UAAW,EAAQ,gDAAgD,EAChE,UACH,WAAY,EAAQ,iDAAiD,EAClE,WACH,MAAO,EAAQ,wBAAwB,EAAE,MACzC,WAAY,EAAQ,qCAAqC,EAAE,UAC7D,EAIAD,EAAO,QAAUC,EAGjBF,EAAQ,YAAcE,EAAc,YACpCF,EAAQ,aAAeE,EAAc,aACrCF,EAAQ,cAAgBE,EAAc,cACtCF,EAAQ,oBAAsBE,EAAc,oBAC5CF,EAAQ,UAAYE,EAAc,UAClCF,EAAQ,WAAaE,EAAc,WACnCF,EAAQ,MAAQE,EAAc,MAC9BF,EAAQ,WAAaE,EAAc,aC7BnC,MAAO,cCAP,IAAAC,EAA+C,OAC/C,OACE,6BAAAC,EACA,iBAAAC,EACA,2BAAAC,MAC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C,IAAMC,GAFU,MAAMC,EAA8BF,CAAS,GAE/B,cAExBG,EAAgB,CACpB,MAAO,GACP,KAAM,IACN,OAAQ,EACR,SAAU,GACV,OAAQ,QAAQ,IAAI,WAAa,aACjC,SAAU,KACZ,EAEMC,EAAoB,gBAAgBH,CAAa,GACvDH,EAAa,IAAI,CAAE,KAAMM,EAAmB,GAAGD,CAAc,CAAC,EAE9D,IAAME,EAAiB,qBAAqBJ,CAAa,GACzD,OAAAH,EAAa,IAAI,CAAE,KAAMO,EAAgB,GAAGF,CAAc,CAAC,EAEpD,IAAI,SACT,KAAK,UAAU,CACb,QAAS,sBACT,QAAS,EACX,CAAC,EACD,CACE,OAAQ,IACR,QAAS,CACP,eAAgB,kBAClB,CACF,CACF,CACF","names":["require_server","__commonJSMin","exports","module","serverExports","import_server","validateAndParsePublicKey","fetchUserData","isAuthenticatedUserInfo","useAuthMiddleware","publicKey","publicKeyObj","request","response","options","tokenFromUri","userData","cookies","validateAndParsePublicKey","getPublicKeyPayload","assertTrustedIdentityHost","getSessionCookie","publicKey","publicKeyObj","validateAndParsePublicKey","cookies","cookies","getServerSidePayloadPublicKey","publicKey","validateAndParsePublicKey","logoutHandler","req","cookiesStore","cookies","publicKey","environmentId","getServerSidePayloadPublicKey","deleteOptions","cookieNameSession","cookieNameHash"]}
|
package/package.json
CHANGED
|
@@ -1,48 +1,73 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
2
|
+
"name": "@authdog/nextjs-app",
|
|
3
|
+
"version": "2.0.0",
|
|
4
|
+
"description": "Authdog Next.js SDK",
|
|
5
|
+
"source": "src/index.ts",
|
|
6
|
+
"main": "./dist/index.js",
|
|
7
|
+
"module": "./dist/index.mjs",
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"types": "./dist/index.d.ts",
|
|
12
|
+
"import": "./dist/index.mjs",
|
|
13
|
+
"require": "./dist/index.js"
|
|
14
|
+
},
|
|
15
|
+
"./client": {
|
|
16
|
+
"types": "./dist/index.d.ts",
|
|
17
|
+
"import": "./dist/index.mjs",
|
|
18
|
+
"require": "./dist/index.js"
|
|
19
|
+
},
|
|
20
|
+
"./server": {
|
|
21
|
+
"types": "./dist/index.server.d.ts",
|
|
22
|
+
"import": "./dist/index.server.mjs",
|
|
23
|
+
"require": "./dist/index.server.js"
|
|
24
|
+
}
|
|
13
25
|
},
|
|
14
|
-
"
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
26
|
+
"files": [
|
|
27
|
+
"dist/"
|
|
28
|
+
],
|
|
29
|
+
"sideEffects": false,
|
|
30
|
+
"repository": {
|
|
31
|
+
"type": "git",
|
|
32
|
+
"url": "git+https://github.com/authdog-labs/web-sdk.git",
|
|
33
|
+
"directory": "packages/nextjs-app"
|
|
34
|
+
},
|
|
35
|
+
"homepage": "https://github.com/authdog-labs/web-sdk/tree/main/packages/nextjs-app#readme",
|
|
36
|
+
"bugs": {
|
|
37
|
+
"url": "https://github.com/authdog-labs/web-sdk/issues"
|
|
38
|
+
},
|
|
39
|
+
"scripts": {
|
|
40
|
+
"format": "prettier --config .prettierrc.json --write \"**/*.{ts,md}\"",
|
|
41
|
+
"type-check": "tsc",
|
|
42
|
+
"clean": "rm -rf dist",
|
|
43
|
+
"build": "bun run clean && tsup",
|
|
44
|
+
"test": "vitest run",
|
|
45
|
+
"ship": "bun run build && bun publish --access public"
|
|
46
|
+
},
|
|
47
|
+
"dependencies": {
|
|
48
|
+
"@authdog/node-commons": "workspace:*",
|
|
49
|
+
"server-only": "^0.0.1"
|
|
50
|
+
},
|
|
51
|
+
"peerDependencies": {
|
|
52
|
+
"next": ">=15 <17",
|
|
53
|
+
"react": "^18.2.0 || ^19.0.0",
|
|
54
|
+
"react-dom": "^18.2.0 || ^19.0.0"
|
|
55
|
+
},
|
|
56
|
+
"devDependencies": {
|
|
57
|
+
"@types/node": "^22.10.5",
|
|
58
|
+
"@types/react": "^19.1.0",
|
|
59
|
+
"@types/react-dom": "^19.1.0",
|
|
60
|
+
"dotenv": "^16.4.7",
|
|
61
|
+
"next": "^16.1.5",
|
|
62
|
+
"prettier": "^3.4.2",
|
|
63
|
+
"react": "^19.1.0",
|
|
64
|
+
"react-dom": "^19.1.0",
|
|
65
|
+
"tsup": "^8.3.5",
|
|
66
|
+
"typescript": "^5.7.2",
|
|
67
|
+
"vitest": "^2.1.8"
|
|
68
|
+
},
|
|
69
|
+
"publishConfig": {
|
|
70
|
+
"registry": "https://registry.npmjs.org/",
|
|
71
|
+
"access": "public"
|
|
18
72
|
}
|
|
19
|
-
},
|
|
20
|
-
"files": [
|
|
21
|
-
"dist/"
|
|
22
|
-
],
|
|
23
|
-
"dependencies": {
|
|
24
|
-
"next": "^15.1.0",
|
|
25
|
-
"react": "^19.1.0"
|
|
26
|
-
},
|
|
27
|
-
"devDependencies": {
|
|
28
|
-
"@types/next": "^9.0.0",
|
|
29
|
-
"@types/node": "^22.10.5",
|
|
30
|
-
"@types/react": "^19.1.0",
|
|
31
|
-
"dotenv": "^16.4.7",
|
|
32
|
-
"prettier": "^3.4.2",
|
|
33
|
-
"tsup": "^8.3.5",
|
|
34
|
-
"typescript": "^5.7.2",
|
|
35
|
-
"vitest": "^2.1.8"
|
|
36
|
-
},
|
|
37
|
-
"publishConfig": {
|
|
38
|
-
"registry": "https://registry.npmjs.org/",
|
|
39
|
-
"access": "public"
|
|
40
|
-
},
|
|
41
|
-
"scripts": {
|
|
42
|
-
"format": "prettier --config .prettierrc.json --write \"**/*.{ts,md}\"",
|
|
43
|
-
"type-check": "tsc",
|
|
44
|
-
"clean": "rm -rf dist",
|
|
45
|
-
"build": "pnpm clean && tsup",
|
|
46
|
-
"ship": "pnpm build && pnpm publish --access public --no-git-checks"
|
|
47
|
-
}
|
|
48
73
|
}
|