@ai-digital-factory/identity-manager 1.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.
@@ -0,0 +1,40 @@
1
+ // src/constants.ts
2
+ var IDENTITY_PATH = "/api/identity/me";
3
+
4
+ // src/config.ts
5
+ function isPlaceholder(value) {
6
+ return value.includes("replace_me");
7
+ }
8
+ function normalizeHttpOrigin(value) {
9
+ try {
10
+ const url = new URL(value);
11
+ if (url.protocol !== "http:" && url.protocol !== "https:" || url.username || url.password || url.pathname !== "/" || url.search || url.hash) {
12
+ return null;
13
+ }
14
+ return url.origin;
15
+ } catch {
16
+ return null;
17
+ }
18
+ }
19
+ function getClientIdentityConfig(env) {
20
+ const publishableKey = env.VITE_IDENTITY_PUBLISHABLE_KEY?.trim();
21
+ if (!publishableKey || isPlaceholder(publishableKey)) {
22
+ return null;
23
+ }
24
+ return { publishableKey };
25
+ }
26
+ function getServerIdentityConfig(env) {
27
+ const secretKey = env.IDENTITY_SECRET_KEY?.trim();
28
+ const clientOriginValue = env.CLIENT_ORIGIN?.trim();
29
+ const clientOrigin = clientOriginValue ? normalizeHttpOrigin(clientOriginValue) : null;
30
+ if (!secretKey || isPlaceholder(secretKey) || !clientOriginValue || isPlaceholder(clientOriginValue) || !clientOrigin) {
31
+ return null;
32
+ }
33
+ return { secretKey, clientOrigin };
34
+ }
35
+
36
+ export {
37
+ IDENTITY_PATH,
38
+ getClientIdentityConfig,
39
+ getServerIdentityConfig
40
+ };
@@ -0,0 +1,23 @@
1
+ type IdentityStatus = "LOADING" | "SIGNED_OUT" | "SIGNED_IN";
2
+ type IdentityUser = {
3
+ id: string;
4
+ userName: string;
5
+ };
6
+ type SignInCredentials = {
7
+ username: string;
8
+ password: string;
9
+ };
10
+ type IdentityResult = {
11
+ ok: true;
12
+ } | {
13
+ ok: false;
14
+ error: string;
15
+ };
16
+ type IdentityState = {
17
+ status: IdentityStatus;
18
+ user: IdentityUser | null;
19
+ error: string | null;
20
+ signIn: (credentials: SignInCredentials) => Promise<IdentityResult>;
21
+ };
22
+
23
+ export type { IdentityUser as I, SignInCredentials as S, IdentityState as a, IdentityResult as b, IdentityStatus as c };
@@ -0,0 +1,164 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/express.ts
31
+ var express_exports = {};
32
+ __export(express_exports, {
33
+ identityMiddleware: () => identityMiddleware,
34
+ requireIdentity: () => requireIdentity
35
+ });
36
+ module.exports = __toCommonJS(express_exports);
37
+ var import_express = require("@clerk/express");
38
+ var import_cors = __toESM(require("cors"), 1);
39
+
40
+ // src/constants.ts
41
+ var IDENTITY_PATH = "/api/identity/me";
42
+
43
+ // src/config.ts
44
+ function isPlaceholder(value) {
45
+ return value.includes("replace_me");
46
+ }
47
+ function normalizeHttpOrigin(value) {
48
+ try {
49
+ const url = new URL(value);
50
+ if (url.protocol !== "http:" && url.protocol !== "https:" || url.username || url.password || url.pathname !== "/" || url.search || url.hash) {
51
+ return null;
52
+ }
53
+ return url.origin;
54
+ } catch {
55
+ return null;
56
+ }
57
+ }
58
+ function getServerIdentityConfig(env) {
59
+ const secretKey = env.IDENTITY_SECRET_KEY?.trim();
60
+ const clientOriginValue = env.CLIENT_ORIGIN?.trim();
61
+ const clientOrigin = clientOriginValue ? normalizeHttpOrigin(clientOriginValue) : null;
62
+ if (!secretKey || isPlaceholder(secretKey) || !clientOriginValue || isPlaceholder(clientOriginValue) || !clientOrigin) {
63
+ return null;
64
+ }
65
+ return { secretKey, clientOrigin };
66
+ }
67
+
68
+ // src/to-identity-user.ts
69
+ function toIdentityUser(user) {
70
+ const userName = user.username?.trim() || user.primaryEmailAddress?.emailAddress.trim() || user.id;
71
+ return {
72
+ id: user.id,
73
+ userName
74
+ };
75
+ }
76
+
77
+ // src/express.ts
78
+ var middlewareStack = null;
79
+ function getMiddlewareStack() {
80
+ if (middlewareStack) {
81
+ return middlewareStack;
82
+ }
83
+ const config = getServerIdentityConfig({
84
+ IDENTITY_SECRET_KEY: process.env.IDENTITY_SECRET_KEY,
85
+ CLIENT_ORIGIN: process.env.CLIENT_ORIGIN
86
+ });
87
+ if (!config) {
88
+ throw new Error(
89
+ "Identity configuration required. Set IDENTITY_SECRET_KEY and CLIENT_ORIGIN."
90
+ );
91
+ }
92
+ const clerkClient = (0, import_express.createClerkClient)({ secretKey: config.secretKey });
93
+ const attachSession = async (req, res, next) => {
94
+ try {
95
+ const user = await resolveIdentityUser(req, clerkClient);
96
+ if (req.method === "GET" && req.path === IDENTITY_PATH) {
97
+ res.set("Cache-Control", "private, no-store");
98
+ if (!user) {
99
+ return res.status(401).json({ error: "Authentication required." });
100
+ }
101
+ return res.json({ user });
102
+ }
103
+ req.user = user;
104
+ return next();
105
+ } catch (error) {
106
+ return next(error);
107
+ }
108
+ };
109
+ middlewareStack = [
110
+ (0, import_cors.default)({
111
+ origin: config.clientOrigin,
112
+ credentials: true
113
+ }),
114
+ (0, import_express.clerkMiddleware)({
115
+ secretKey: config.secretKey,
116
+ authorizedParties: [config.clientOrigin]
117
+ }),
118
+ attachSession
119
+ ];
120
+ return middlewareStack;
121
+ }
122
+ async function resolveIdentityUser(req, clerkClient) {
123
+ const { userId } = (0, import_express.getAuth)(req);
124
+ if (!userId) {
125
+ return null;
126
+ }
127
+ const user = await clerkClient.users.getUser(userId);
128
+ return toIdentityUser({
129
+ id: user.id,
130
+ username: user.username,
131
+ primaryEmailAddress: user.primaryEmailAddress
132
+ });
133
+ }
134
+ function runMiddlewareStack(stack, req, res, next) {
135
+ let index = 0;
136
+ const dispatch = (error) => {
137
+ if (error) {
138
+ next(error);
139
+ return;
140
+ }
141
+ const middleware = stack[index];
142
+ if (!middleware) {
143
+ next();
144
+ return;
145
+ }
146
+ index += 1;
147
+ middleware(req, res, dispatch);
148
+ };
149
+ dispatch();
150
+ }
151
+ var identityMiddleware = (req, res, next) => {
152
+ runMiddlewareStack(getMiddlewareStack(), req, res, next);
153
+ };
154
+ var requireIdentity = (req, res, next) => {
155
+ if (!req.user) {
156
+ return res.status(401).json({ error: "Authentication required." });
157
+ }
158
+ return next();
159
+ };
160
+ // Annotate the CommonJS export names for ESM import in node:
161
+ 0 && (module.exports = {
162
+ identityMiddleware,
163
+ requireIdentity
164
+ });
@@ -0,0 +1,7 @@
1
+ import { RequestHandler } from 'express';
2
+ export { I as IdentityUser } from './core-DSv5-9oR.js';
3
+
4
+ declare const identityMiddleware: RequestHandler;
5
+ declare const requireIdentity: RequestHandler;
6
+
7
+ export { identityMiddleware, requireIdentity };
@@ -0,0 +1,105 @@
1
+ import {
2
+ IDENTITY_PATH,
3
+ getServerIdentityConfig
4
+ } from "./chunk-7WCGUJ3C.js";
5
+
6
+ // src/express.ts
7
+ import { createClerkClient, clerkMiddleware, getAuth } from "@clerk/express";
8
+ import cors from "cors";
9
+
10
+ // src/to-identity-user.ts
11
+ function toIdentityUser(user) {
12
+ const userName = user.username?.trim() || user.primaryEmailAddress?.emailAddress.trim() || user.id;
13
+ return {
14
+ id: user.id,
15
+ userName
16
+ };
17
+ }
18
+
19
+ // src/express.ts
20
+ var middlewareStack = null;
21
+ function getMiddlewareStack() {
22
+ if (middlewareStack) {
23
+ return middlewareStack;
24
+ }
25
+ const config = getServerIdentityConfig({
26
+ IDENTITY_SECRET_KEY: process.env.IDENTITY_SECRET_KEY,
27
+ CLIENT_ORIGIN: process.env.CLIENT_ORIGIN
28
+ });
29
+ if (!config) {
30
+ throw new Error(
31
+ "Identity configuration required. Set IDENTITY_SECRET_KEY and CLIENT_ORIGIN."
32
+ );
33
+ }
34
+ const clerkClient = createClerkClient({ secretKey: config.secretKey });
35
+ const attachSession = async (req, res, next) => {
36
+ try {
37
+ const user = await resolveIdentityUser(req, clerkClient);
38
+ if (req.method === "GET" && req.path === IDENTITY_PATH) {
39
+ res.set("Cache-Control", "private, no-store");
40
+ if (!user) {
41
+ return res.status(401).json({ error: "Authentication required." });
42
+ }
43
+ return res.json({ user });
44
+ }
45
+ req.user = user;
46
+ return next();
47
+ } catch (error) {
48
+ return next(error);
49
+ }
50
+ };
51
+ middlewareStack = [
52
+ cors({
53
+ origin: config.clientOrigin,
54
+ credentials: true
55
+ }),
56
+ clerkMiddleware({
57
+ secretKey: config.secretKey,
58
+ authorizedParties: [config.clientOrigin]
59
+ }),
60
+ attachSession
61
+ ];
62
+ return middlewareStack;
63
+ }
64
+ async function resolveIdentityUser(req, clerkClient) {
65
+ const { userId } = getAuth(req);
66
+ if (!userId) {
67
+ return null;
68
+ }
69
+ const user = await clerkClient.users.getUser(userId);
70
+ return toIdentityUser({
71
+ id: user.id,
72
+ username: user.username,
73
+ primaryEmailAddress: user.primaryEmailAddress
74
+ });
75
+ }
76
+ function runMiddlewareStack(stack, req, res, next) {
77
+ let index = 0;
78
+ const dispatch = (error) => {
79
+ if (error) {
80
+ next(error);
81
+ return;
82
+ }
83
+ const middleware = stack[index];
84
+ if (!middleware) {
85
+ next();
86
+ return;
87
+ }
88
+ index += 1;
89
+ middleware(req, res, dispatch);
90
+ };
91
+ dispatch();
92
+ }
93
+ var identityMiddleware = (req, res, next) => {
94
+ runMiddlewareStack(getMiddlewareStack(), req, res, next);
95
+ };
96
+ var requireIdentity = (req, res, next) => {
97
+ if (!req.user) {
98
+ return res.status(401).json({ error: "Authentication required." });
99
+ }
100
+ return next();
101
+ };
102
+ export {
103
+ identityMiddleware,
104
+ requireIdentity
105
+ };
@@ -0,0 +1,13 @@
1
+ import * as react from 'react';
2
+ import { ReactNode } from 'react';
3
+ import { a as IdentityState } from './core-DSv5-9oR.js';
4
+ export { b as IdentityResult, c as IdentityStatus, I as IdentityUser, S as SignInCredentials } from './core-DSv5-9oR.js';
5
+
6
+ declare function IdentityProvider({ apiBaseUrl, children, }: {
7
+ apiBaseUrl: string;
8
+ children: ReactNode;
9
+ }): react.JSX.Element;
10
+
11
+ declare function useIdentity(): IdentityState;
12
+
13
+ export { IdentityProvider, IdentityState, useIdentity };
package/dist/react.js ADDED
@@ -0,0 +1,171 @@
1
+ "use client";
2
+ import {
3
+ IDENTITY_PATH,
4
+ getClientIdentityConfig
5
+ } from "./chunk-7WCGUJ3C.js";
6
+
7
+ // src/clerk-react.tsx
8
+ import {
9
+ ClerkProvider,
10
+ useAuth as useClerkAuth,
11
+ useClerk,
12
+ useSignIn
13
+ } from "@clerk/clerk-react";
14
+ import { useCallback, useEffect, useState } from "react";
15
+
16
+ // src/fetch-identity-user.ts
17
+ async function fetchIdentityUser(apiBaseUrl, getSessionToken) {
18
+ const token = await getSessionToken();
19
+ const headers = new Headers();
20
+ if (token) {
21
+ headers.set("Authorization", `Bearer ${token}`);
22
+ }
23
+ const response = await fetch(
24
+ `${apiBaseUrl.replace(/\/$/, "")}${IDENTITY_PATH}`,
25
+ {
26
+ credentials: "include",
27
+ headers
28
+ }
29
+ );
30
+ if (response.status === 401) {
31
+ return null;
32
+ }
33
+ if (!response.ok) {
34
+ throw new Error("Failed to resolve authenticated user.");
35
+ }
36
+ const payload = await response.json();
37
+ return payload.user;
38
+ }
39
+
40
+ // src/react-context.tsx
41
+ import { createContext, useContext } from "react";
42
+ import { jsx } from "react/jsx-runtime";
43
+ var IdentityContext = createContext(null);
44
+ function IdentityContextProvider({
45
+ value,
46
+ children
47
+ }) {
48
+ return /* @__PURE__ */ jsx(IdentityContext.Provider, { value, children });
49
+ }
50
+ function useIdentity() {
51
+ const context = useContext(IdentityContext);
52
+ if (!context) {
53
+ throw new Error("useIdentity must be used within an IdentityProvider.");
54
+ }
55
+ return context;
56
+ }
57
+
58
+ // src/clerk-react.tsx
59
+ import { jsx as jsx2 } from "react/jsx-runtime";
60
+ function useClerkIdentityState(apiBaseUrl) {
61
+ const { isLoaded: authLoaded, isSignedIn, getToken } = useClerkAuth();
62
+ const { isLoaded: signInLoaded, signIn } = useSignIn();
63
+ const { setActive } = useClerk();
64
+ const [user, setUser] = useState(null);
65
+ const [error, setError] = useState(null);
66
+ const [isResolvingUser, setIsResolvingUser] = useState(false);
67
+ const refreshUser = useCallback(async () => {
68
+ if (!isSignedIn) {
69
+ setUser(null);
70
+ return;
71
+ }
72
+ setIsResolvingUser(true);
73
+ setError(null);
74
+ try {
75
+ const resolvedUser = await fetchIdentityUser(
76
+ apiBaseUrl,
77
+ () => getToken()
78
+ );
79
+ setUser(resolvedUser);
80
+ } catch {
81
+ setUser(null);
82
+ setError("Failed to resolve authenticated user.");
83
+ } finally {
84
+ setIsResolvingUser(false);
85
+ }
86
+ }, [apiBaseUrl, getToken, isSignedIn]);
87
+ useEffect(() => {
88
+ if (!authLoaded) {
89
+ return;
90
+ }
91
+ void refreshUser();
92
+ }, [authLoaded, refreshUser]);
93
+ const status = !authLoaded || !signInLoaded || isResolvingUser ? "LOADING" : isSignedIn && user ? "SIGNED_IN" : "SIGNED_OUT";
94
+ return {
95
+ status,
96
+ user,
97
+ error,
98
+ signIn: async (credentials) => {
99
+ if (!signInLoaded) {
100
+ return {
101
+ ok: false,
102
+ error: "Authentication is still loading. Try again shortly."
103
+ };
104
+ }
105
+ try {
106
+ const result = await signIn.create({
107
+ identifier: credentials.username,
108
+ password: credentials.password
109
+ });
110
+ if (result.status !== "complete" || !result.createdSessionId) {
111
+ return {
112
+ ok: false,
113
+ error: "Additional sign-in verification is required."
114
+ };
115
+ }
116
+ await setActive({ session: result.createdSessionId });
117
+ await refreshUser();
118
+ return { ok: true };
119
+ } catch {
120
+ return { ok: false, error: "Invalid username or password." };
121
+ }
122
+ }
123
+ };
124
+ }
125
+ function ClerkIdentityProvider({
126
+ apiBaseUrl,
127
+ publishableKey,
128
+ children
129
+ }) {
130
+ return /* @__PURE__ */ jsx2(ClerkProvider, { publishableKey, children: /* @__PURE__ */ jsx2(ClerkIdentityContextProvider, { apiBaseUrl, children }) });
131
+ }
132
+ function ClerkIdentityContextProvider({
133
+ apiBaseUrl,
134
+ children
135
+ }) {
136
+ const value = useClerkIdentityState(apiBaseUrl);
137
+ return /* @__PURE__ */ jsx2(IdentityContextProvider, { value, children });
138
+ }
139
+
140
+ // src/provider.tsx
141
+ import { jsx as jsx3, jsxs } from "react/jsx-runtime";
142
+ function IdentityProvider({
143
+ apiBaseUrl,
144
+ children
145
+ }) {
146
+ const config = getClientIdentityConfig({
147
+ VITE_IDENTITY_PUBLISHABLE_KEY: import.meta.env.VITE_IDENTITY_PUBLISHABLE_KEY
148
+ });
149
+ if (!config) {
150
+ return /* @__PURE__ */ jsx3("main", { children: /* @__PURE__ */ jsxs("section", { children: [
151
+ /* @__PURE__ */ jsx3("p", { children: "Identity configuration required." }),
152
+ /* @__PURE__ */ jsxs("p", { children: [
153
+ "Set ",
154
+ /* @__PURE__ */ jsx3("code", { children: "VITE_IDENTITY_PUBLISHABLE_KEY" }),
155
+ " before starting the app."
156
+ ] })
157
+ ] }) });
158
+ }
159
+ return /* @__PURE__ */ jsx3(
160
+ ClerkIdentityProvider,
161
+ {
162
+ apiBaseUrl,
163
+ publishableKey: config.publishableKey,
164
+ children
165
+ }
166
+ );
167
+ }
168
+ export {
169
+ IdentityProvider,
170
+ useIdentity
171
+ };
package/package.json ADDED
@@ -0,0 +1,52 @@
1
+ {
2
+ "name": "@ai-digital-factory/identity-manager",
3
+ "version": "1.0.0",
4
+ "description": "Provider-neutral identity for Vite SPAs and Express API backends.",
5
+ "type": "module",
6
+ "exports": {
7
+ "./react": {
8
+ "types": "./dist/react.d.ts",
9
+ "import": "./dist/react.js"
10
+ },
11
+ "./express": {
12
+ "types": "./dist/express.d.ts",
13
+ "import": "./dist/express.js",
14
+ "require": "./dist/express.cjs"
15
+ }
16
+ },
17
+ "files": [
18
+ "dist"
19
+ ],
20
+ "publishConfig": {
21
+ "access": "public"
22
+ },
23
+ "dependencies": {
24
+ "@clerk/clerk-react": "^5.61.6",
25
+ "@clerk/express": "^1.7.0",
26
+ "cors": "^2.8.5"
27
+ },
28
+ "peerDependencies": {
29
+ "express": "^4.21.0 || ^5.0.0",
30
+ "react": "^19.0.0",
31
+ "react-dom": "^19.0.0"
32
+ },
33
+ "devDependencies": {
34
+ "@clerk/clerk-react": "^5.61.6",
35
+ "@clerk/express": "^1.7.0",
36
+ "@types/cors": "^2.8.19",
37
+ "@types/express": "^5.0.3",
38
+ "@types/react": "^19.2.2",
39
+ "@types/react-dom": "^19.2.2",
40
+ "express": "^5.1.0",
41
+ "react": "^19.2.0",
42
+ "react-dom": "^19.2.0",
43
+ "tsup": "^8.5.0",
44
+ "vite": "^7.1.5"
45
+ },
46
+ "scripts": {
47
+ "build": "tsup src/react.tsx src/express.ts --format esm --dts --clean --out-dir dist && tsup src/express.ts --format cjs --out-dir dist",
48
+ "check-types": "tsc --noEmit",
49
+ "lint": "tsc --noEmit",
50
+ "test": "vitest run --passWithNoTests"
51
+ }
52
+ }