@crossmint/client-sdk-auth 0.2.2 → 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.
- package/LICENSE +1 -1
- package/README.md +97 -0
- package/dist/CrossmintAuthClient.cjs +12 -0
- package/dist/CrossmintAuthClient.cjs.map +1 -0
- package/dist/CrossmintAuthClient.d.cts +35 -0
- package/dist/CrossmintAuthClient.d.ts +35 -0
- package/dist/CrossmintAuthClient.js +12 -0
- package/dist/CrossmintAuthClient.js.map +1 -0
- package/dist/chunk-5JXPQKM4.js +19 -0
- package/dist/chunk-5JXPQKM4.js.map +1 -0
- package/dist/chunk-7YATBCAU.js +229 -0
- package/dist/chunk-7YATBCAU.js.map +1 -0
- package/dist/chunk-BGMXXFQ4.cjs +19 -0
- package/dist/chunk-BGMXXFQ4.cjs.map +1 -0
- package/dist/chunk-BMYZMMVR.js +7 -0
- package/dist/chunk-BMYZMMVR.js.map +1 -0
- package/dist/chunk-F45I5NLI.cjs +46 -0
- package/dist/chunk-F45I5NLI.cjs.map +1 -0
- package/dist/chunk-ILL57KWX.cjs +229 -0
- package/dist/chunk-ILL57KWX.cjs.map +1 -0
- package/dist/chunk-JPRRZPBL.js +46 -0
- package/dist/chunk-JPRRZPBL.js.map +1 -0
- package/dist/chunk-MLMLBCSI.js +11 -0
- package/dist/chunk-MLMLBCSI.js.map +1 -0
- package/dist/chunk-QY4RIGNM.cjs +11 -0
- package/dist/chunk-QY4RIGNM.cjs.map +1 -0
- package/dist/chunk-TIUX4OOQ.cjs +7 -0
- package/dist/chunk-TIUX4OOQ.cjs.map +1 -0
- package/dist/chunk-TOXKCKTY.js +1 -0
- package/dist/chunk-TOXKCKTY.js.map +1 -0
- package/dist/chunk-VQ3HTIQ3.cjs +1 -0
- package/dist/chunk-VQ3HTIQ3.cjs.map +1 -0
- package/dist/index.cjs +28 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +7 -5
- package/dist/index.d.ts +7 -5
- package/dist/index.js +28 -1
- package/dist/index.js.map +1 -1
- package/dist/utils/constants.cjs +8 -0
- package/dist/utils/constants.cjs.map +1 -0
- package/dist/utils/constants.d.cts +3 -0
- package/dist/utils/constants.d.ts +3 -0
- package/dist/utils/constants.js +8 -0
- package/dist/utils/constants.js.map +1 -0
- package/dist/utils/cookies.cjs +12 -0
- package/dist/utils/cookies.cjs.map +1 -0
- package/dist/utils/cookies.d.cts +5 -0
- package/dist/utils/cookies.d.ts +5 -0
- package/dist/utils/cookies.js +12 -0
- package/dist/utils/cookies.js.map +1 -0
- package/dist/utils/index.cjs +21 -0
- package/dist/utils/index.cjs.map +1 -0
- package/dist/utils/index.d.cts +3 -0
- package/dist/utils/index.d.ts +3 -0
- package/dist/utils/index.js +21 -0
- package/dist/utils/index.js.map +1 -0
- package/dist/utils/jwt.cjs +8 -0
- package/dist/utils/jwt.cjs.map +1 -0
- package/dist/utils/jwt.d.cts +3 -0
- package/dist/utils/jwt.d.ts +3 -0
- package/dist/utils/jwt.js +8 -0
- package/dist/utils/jwt.js.map +1 -0
- package/package.json +8 -4
- package/src/CrossmintAuthClient.test.ts +406 -0
- package/src/CrossmintAuthClient.ts +241 -0
- package/src/index.ts +2 -1
- package/src/utils/constants.ts +1 -0
- package/src/utils/cookies.test.ts +44 -0
- package/src/utils/cookies.ts +13 -0
- package/src/utils/index.ts +2 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@crossmint/client-sdk-auth",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "1.0.0",
|
|
4
4
|
"repository": "https://github.com/Crossmint/crossmint-sdk",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"author": "Paella Labs Inc",
|
|
@@ -20,10 +20,14 @@
|
|
|
20
20
|
],
|
|
21
21
|
"dependencies": {
|
|
22
22
|
"jwt-decode": "4.0.0",
|
|
23
|
-
"@
|
|
23
|
+
"@farcaster/auth-kit": "0.6.0",
|
|
24
|
+
"@crossmint/client-sdk-base": "1.3.2",
|
|
25
|
+
"@crossmint/common-sdk-auth": "1.0.0",
|
|
26
|
+
"@crossmint/common-sdk-base": "0.3.0"
|
|
24
27
|
},
|
|
25
28
|
"scripts": {
|
|
26
|
-
"build": "tsup
|
|
27
|
-
"dev": "tsup
|
|
29
|
+
"build": "tsup",
|
|
30
|
+
"dev": "tsup --watch",
|
|
31
|
+
"test": "vitest run"
|
|
28
32
|
}
|
|
29
33
|
}
|
|
@@ -0,0 +1,406 @@
|
|
|
1
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
2
|
+
import type { StatusAPIResponse } from "@farcaster/auth-kit";
|
|
3
|
+
import { type Crossmint, CrossmintApiClient } from "@crossmint/common-sdk-base";
|
|
4
|
+
import type { AuthMaterialWithUser } from "@crossmint/common-sdk-auth";
|
|
5
|
+
import { CrossmintAuthClient } from "./CrossmintAuthClient";
|
|
6
|
+
import * as cookiesUtils from "./utils/cookies";
|
|
7
|
+
import { getJWTExpiration } from "./utils";
|
|
8
|
+
import { queueTask } from "@crossmint/client-sdk-base";
|
|
9
|
+
|
|
10
|
+
vi.mock("@crossmint/common-sdk-base");
|
|
11
|
+
vi.mock("./utils/cookies");
|
|
12
|
+
vi.mock("./utils/jwt");
|
|
13
|
+
vi.mock("@crossmint/client-sdk-base");
|
|
14
|
+
|
|
15
|
+
describe("CrossmintAuthClient", () => {
|
|
16
|
+
let crossmintAuthClient: CrossmintAuthClient;
|
|
17
|
+
const mockCrossmint = { projectId: "test-project-id" };
|
|
18
|
+
const mockApiClient = {
|
|
19
|
+
baseUrl: "https://api.crossmint.com",
|
|
20
|
+
get: vi.fn(),
|
|
21
|
+
post: vi.fn(),
|
|
22
|
+
};
|
|
23
|
+
const mockCallbacks = {
|
|
24
|
+
onLogout: vi.fn(),
|
|
25
|
+
onTokenRefresh: vi.fn(),
|
|
26
|
+
};
|
|
27
|
+
const mockConfig = {
|
|
28
|
+
callbacks: mockCallbacks,
|
|
29
|
+
refreshRoute: "http://example.com/custom/refresh",
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
beforeEach(() => {
|
|
33
|
+
vi.resetAllMocks();
|
|
34
|
+
vi.mocked(CrossmintApiClient).mockReturnValue(mockApiClient as unknown as CrossmintApiClient);
|
|
35
|
+
crossmintAuthClient = CrossmintAuthClient.from(mockCrossmint as unknown as Crossmint, mockConfig);
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
afterEach(() => {
|
|
39
|
+
vi.restoreAllMocks();
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
describe("from", () => {
|
|
43
|
+
it("should create a new CrossmintAuthClient instance with config", () => {
|
|
44
|
+
expect(crossmintAuthClient).toBeInstanceOf(CrossmintAuthClient);
|
|
45
|
+
expect(CrossmintApiClient).toHaveBeenCalledWith(mockCrossmint, expect.any(Object));
|
|
46
|
+
expect((crossmintAuthClient as any).callbacks).toEqual(mockConfig.callbacks);
|
|
47
|
+
expect((crossmintAuthClient as any).refreshRoute).toBe(mockConfig.refreshRoute);
|
|
48
|
+
});
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
describe("getUser", () => {
|
|
52
|
+
it("should fetch user data", async () => {
|
|
53
|
+
const mockUserData = { id: "user123", email: "user@example.com" };
|
|
54
|
+
mockApiClient.get.mockResolvedValue({
|
|
55
|
+
json: () => Promise.resolve(mockUserData),
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
const result = await crossmintAuthClient.getUser();
|
|
59
|
+
|
|
60
|
+
expect(result).toEqual(mockUserData);
|
|
61
|
+
expect(mockApiClient.get).toHaveBeenCalledWith("api/2024-09-26/sdk/auth/user", expect.any(Object));
|
|
62
|
+
});
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
describe("storeAuthMaterial", () => {
|
|
66
|
+
it("should store auth material in cookies", () => {
|
|
67
|
+
const mockAuthMaterial: AuthMaterialWithUser = {
|
|
68
|
+
jwt: "mock.jwt.token",
|
|
69
|
+
refreshToken: { secret: "refresh-token", expiresAt: "2023-12-31T23:59:59Z" },
|
|
70
|
+
user: { id: "user123" },
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
crossmintAuthClient.storeAuthMaterial(mockAuthMaterial);
|
|
74
|
+
|
|
75
|
+
expect(cookiesUtils.setCookie).toHaveBeenCalledWith("crossmint-jwt", mockAuthMaterial.jwt);
|
|
76
|
+
expect(cookiesUtils.setCookie).toHaveBeenCalledWith(
|
|
77
|
+
"crossmint-refresh-token",
|
|
78
|
+
mockAuthMaterial.refreshToken.secret,
|
|
79
|
+
mockAuthMaterial.refreshToken.expiresAt
|
|
80
|
+
);
|
|
81
|
+
});
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
describe("logout", () => {
|
|
85
|
+
beforeEach(() => {
|
|
86
|
+
mockApiClient.post.mockReset();
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
it("should call logout endpoint, clear auth cookies and call onLogout callback", async () => {
|
|
90
|
+
const mockCallbacks = { onLogout: vi.fn() };
|
|
91
|
+
const mockRefreshToken = "mock-refresh-token";
|
|
92
|
+
vi.mocked(cookiesUtils.getCookie).mockReturnValue(mockRefreshToken);
|
|
93
|
+
crossmintAuthClient = CrossmintAuthClient.from(mockCrossmint as unknown as Crossmint, {
|
|
94
|
+
callbacks: mockCallbacks,
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
await crossmintAuthClient.logout();
|
|
98
|
+
|
|
99
|
+
expect(mockApiClient.post).toHaveBeenCalledWith(
|
|
100
|
+
"api/2024-09-26/session/sdk/auth/logout",
|
|
101
|
+
expect.objectContaining({
|
|
102
|
+
headers: {
|
|
103
|
+
"Content-Type": "application/json",
|
|
104
|
+
},
|
|
105
|
+
body: JSON.stringify({
|
|
106
|
+
refresh: mockRefreshToken,
|
|
107
|
+
}),
|
|
108
|
+
})
|
|
109
|
+
);
|
|
110
|
+
expect(cookiesUtils.deleteCookie).toHaveBeenCalledWith("crossmint-refresh-token");
|
|
111
|
+
expect(cookiesUtils.deleteCookie).toHaveBeenCalledWith("crossmint-jwt");
|
|
112
|
+
expect(mockCallbacks.onLogout).toHaveBeenCalled();
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
it("should call custom logout route when configured", async () => {
|
|
116
|
+
const mockCallbacks = { onLogout: vi.fn() };
|
|
117
|
+
const customLogoutRoute = "/custom/logout";
|
|
118
|
+
const fetchSpy = vi.spyOn(global, "fetch").mockResolvedValue(new Response());
|
|
119
|
+
|
|
120
|
+
crossmintAuthClient = CrossmintAuthClient.from(mockCrossmint as unknown as Crossmint, {
|
|
121
|
+
callbacks: mockCallbacks,
|
|
122
|
+
logoutRoute: customLogoutRoute,
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
await crossmintAuthClient.logout();
|
|
126
|
+
|
|
127
|
+
expect(fetchSpy).toHaveBeenCalledWith(customLogoutRoute, { method: "POST" });
|
|
128
|
+
expect(mockApiClient.post).not.toHaveBeenCalled();
|
|
129
|
+
expect(cookiesUtils.deleteCookie).toHaveBeenCalledWith("crossmint-refresh-token");
|
|
130
|
+
expect(cookiesUtils.deleteCookie).toHaveBeenCalledWith("crossmint-jwt");
|
|
131
|
+
expect(mockCallbacks.onLogout).toHaveBeenCalled();
|
|
132
|
+
});
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
describe("handleRefreshAuthMaterial", () => {
|
|
136
|
+
const mockRefreshToken = "mock-refresh-token";
|
|
137
|
+
const mockAuthMaterial = {
|
|
138
|
+
jwt: "new.jwt.token",
|
|
139
|
+
refreshToken: { secret: "new-refresh-token", expiresAt: "2023-12-31T23:59:59Z" },
|
|
140
|
+
user: { id: "user123" },
|
|
141
|
+
};
|
|
142
|
+
|
|
143
|
+
beforeEach(() => {
|
|
144
|
+
vi.spyOn(crossmintAuthClient as any, "refreshAuthMaterial").mockResolvedValue(mockAuthMaterial);
|
|
145
|
+
vi.spyOn(crossmintAuthClient as any, "storeAuthMaterial").mockImplementation(() => {});
|
|
146
|
+
vi.mocked(getJWTExpiration).mockReturnValue(Date.now() / 1000 + 3600); // 1 hour from now
|
|
147
|
+
vi.mocked(queueTask).mockReturnValue({ cancel: vi.fn() } as any);
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
it("should refresh auth material and schedule next refresh", async () => {
|
|
151
|
+
crossmintAuthClient = CrossmintAuthClient.from(mockCrossmint as unknown as Crossmint, {
|
|
152
|
+
callbacks: mockCallbacks,
|
|
153
|
+
});
|
|
154
|
+
vi.spyOn(crossmintAuthClient as any, "refreshAuthMaterial").mockResolvedValue(mockAuthMaterial);
|
|
155
|
+
vi.spyOn(crossmintAuthClient as any, "storeAuthMaterial").mockImplementation(() => {});
|
|
156
|
+
|
|
157
|
+
await crossmintAuthClient.handleRefreshAuthMaterial(mockRefreshToken);
|
|
158
|
+
|
|
159
|
+
expect(crossmintAuthClient["refreshAuthMaterial"]).toHaveBeenCalledWith(mockRefreshToken);
|
|
160
|
+
expect(crossmintAuthClient["storeAuthMaterial"]).toHaveBeenCalledWith(mockAuthMaterial);
|
|
161
|
+
expect(queueTask).toHaveBeenCalledWith(expect.any(Function), expect.any(Number));
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
it("should not refresh if already refreshing", async () => {
|
|
165
|
+
(crossmintAuthClient as any).isRefreshing = true;
|
|
166
|
+
await crossmintAuthClient.handleRefreshAuthMaterial(mockRefreshToken);
|
|
167
|
+
|
|
168
|
+
expect(crossmintAuthClient["refreshAuthMaterial"]).not.toHaveBeenCalled();
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
it("should call onTokenRefresh callback if provided", async () => {
|
|
172
|
+
const mockCallback = vi.fn();
|
|
173
|
+
(crossmintAuthClient as any).callbacks.onTokenRefresh = mockCallback;
|
|
174
|
+
|
|
175
|
+
await crossmintAuthClient.handleRefreshAuthMaterial(mockRefreshToken);
|
|
176
|
+
|
|
177
|
+
expect(mockCallback).toHaveBeenCalledWith(mockAuthMaterial);
|
|
178
|
+
});
|
|
179
|
+
|
|
180
|
+
it("should handle errors and call logout", async () => {
|
|
181
|
+
const mockError = new Error("Refresh failed");
|
|
182
|
+
vi.spyOn(crossmintAuthClient as any, "refreshAuthMaterial").mockRejectedValue(mockError);
|
|
183
|
+
vi.spyOn(crossmintAuthClient, "logout").mockImplementation(() => Promise.resolve());
|
|
184
|
+
const consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
|
|
185
|
+
|
|
186
|
+
await crossmintAuthClient.handleRefreshAuthMaterial(mockRefreshToken);
|
|
187
|
+
|
|
188
|
+
expect(consoleErrorSpy).toHaveBeenCalledWith(mockError);
|
|
189
|
+
expect(crossmintAuthClient.logout).toHaveBeenCalled();
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
it("should use cookie if no refresh token is provided", async () => {
|
|
193
|
+
vi.mocked(cookiesUtils.getCookie).mockReturnValue(mockRefreshToken);
|
|
194
|
+
|
|
195
|
+
await crossmintAuthClient.handleRefreshAuthMaterial();
|
|
196
|
+
|
|
197
|
+
expect(crossmintAuthClient["refreshAuthMaterial"]).toHaveBeenCalledWith(mockRefreshToken);
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
it("should not refresh if no refresh token is available and no custom refresh route is set", async () => {
|
|
201
|
+
crossmintAuthClient = CrossmintAuthClient.from(mockCrossmint as unknown as Crossmint, {});
|
|
202
|
+
vi.spyOn(crossmintAuthClient as any, "refreshAuthMaterial").mockResolvedValue(mockAuthMaterial);
|
|
203
|
+
vi.mocked(cookiesUtils.getCookie).mockReturnValue(null as any);
|
|
204
|
+
|
|
205
|
+
await crossmintAuthClient.handleRefreshAuthMaterial();
|
|
206
|
+
|
|
207
|
+
expect(crossmintAuthClient["refreshAuthMaterial"]).not.toHaveBeenCalled();
|
|
208
|
+
});
|
|
209
|
+
|
|
210
|
+
it("should cancel previous refresh task before scheduling a new one", async () => {
|
|
211
|
+
const mockCancelTask = vi.fn();
|
|
212
|
+
(crossmintAuthClient as any).refreshTask = { cancel: mockCancelTask };
|
|
213
|
+
|
|
214
|
+
await crossmintAuthClient.handleRefreshAuthMaterial(mockRefreshToken);
|
|
215
|
+
|
|
216
|
+
expect(mockCancelTask).toHaveBeenCalled();
|
|
217
|
+
expect(queueTask).toHaveBeenCalled();
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
it("should not schedule refresh if JWT is invalid", async () => {
|
|
221
|
+
vi.mocked(getJWTExpiration).mockReturnValue(null as any);
|
|
222
|
+
|
|
223
|
+
await crossmintAuthClient.handleRefreshAuthMaterial(mockRefreshToken);
|
|
224
|
+
|
|
225
|
+
expect(queueTask).not.toHaveBeenCalled();
|
|
226
|
+
});
|
|
227
|
+
|
|
228
|
+
it("should not schedule refresh if time to expire is negative", async () => {
|
|
229
|
+
vi.mocked(getJWTExpiration).mockReturnValue(Date.now() / 1000 - 3600); // 1 hour ago
|
|
230
|
+
|
|
231
|
+
await crossmintAuthClient.handleRefreshAuthMaterial(mockRefreshToken);
|
|
232
|
+
|
|
233
|
+
expect(queueTask).not.toHaveBeenCalled();
|
|
234
|
+
});
|
|
235
|
+
|
|
236
|
+
it("should not store auth material if custom refresh route is set", async () => {
|
|
237
|
+
const spyStoreAuthMaterial = vi.spyOn(crossmintAuthClient, "storeAuthMaterial");
|
|
238
|
+
|
|
239
|
+
await crossmintAuthClient.handleRefreshAuthMaterial(mockRefreshToken);
|
|
240
|
+
|
|
241
|
+
expect(crossmintAuthClient["refreshAuthMaterial"]).toHaveBeenCalledWith(mockRefreshToken);
|
|
242
|
+
expect(spyStoreAuthMaterial).not.toHaveBeenCalled();
|
|
243
|
+
});
|
|
244
|
+
});
|
|
245
|
+
|
|
246
|
+
describe("getOAuthUrl", () => {
|
|
247
|
+
it("should fetch OAuth URL for a given provider", async () => {
|
|
248
|
+
const mockProvider = "google";
|
|
249
|
+
const mockOAuthUrl = "https://oauth.example.com/auth";
|
|
250
|
+
mockApiClient.get.mockResolvedValue({
|
|
251
|
+
json: () => Promise.resolve({ oauthUrl: mockOAuthUrl }),
|
|
252
|
+
});
|
|
253
|
+
|
|
254
|
+
const result = await crossmintAuthClient.getOAuthUrl(mockProvider);
|
|
255
|
+
|
|
256
|
+
expect(result).toBe(mockOAuthUrl);
|
|
257
|
+
expect(mockApiClient.get).toHaveBeenCalledWith(
|
|
258
|
+
"api/2024-09-26/session/sdk/auth/social/google/start",
|
|
259
|
+
expect.any(Object)
|
|
260
|
+
);
|
|
261
|
+
});
|
|
262
|
+
});
|
|
263
|
+
|
|
264
|
+
describe("sendEmailOtp", () => {
|
|
265
|
+
it("should send email OTP", async () => {
|
|
266
|
+
const mockEmail = "user@example.com";
|
|
267
|
+
const mockResponse = { success: true };
|
|
268
|
+
mockApiClient.post.mockResolvedValue({
|
|
269
|
+
json: () => Promise.resolve(mockResponse),
|
|
270
|
+
});
|
|
271
|
+
|
|
272
|
+
const result = await crossmintAuthClient.sendEmailOtp(mockEmail);
|
|
273
|
+
|
|
274
|
+
expect(result).toEqual(mockResponse);
|
|
275
|
+
expect(mockApiClient.post).toHaveBeenCalledWith(
|
|
276
|
+
"api/2024-09-26/session/sdk/auth/otps/send",
|
|
277
|
+
expect.objectContaining({
|
|
278
|
+
body: JSON.stringify({ email: mockEmail }),
|
|
279
|
+
})
|
|
280
|
+
);
|
|
281
|
+
});
|
|
282
|
+
});
|
|
283
|
+
|
|
284
|
+
describe("confirmEmailOtp", () => {
|
|
285
|
+
it("should confirm email OTP and return oneTimeSecret", async () => {
|
|
286
|
+
const mockEmail = "user@example.com";
|
|
287
|
+
const mockEmailId = "email-id-123";
|
|
288
|
+
const mockToken = "otp-token-456";
|
|
289
|
+
const mockOneTimeSecret = "one-time-secret-789";
|
|
290
|
+
mockApiClient.post.mockResolvedValue({
|
|
291
|
+
json: () => Promise.resolve({ callbackUrl: `https://example.com?oneTimeSecret=${mockOneTimeSecret}` }),
|
|
292
|
+
});
|
|
293
|
+
|
|
294
|
+
const result = await crossmintAuthClient.confirmEmailOtp(mockEmail, mockEmailId, mockToken);
|
|
295
|
+
|
|
296
|
+
expect(result).toBe(mockOneTimeSecret);
|
|
297
|
+
expect(mockApiClient.post).toHaveBeenCalledWith(
|
|
298
|
+
expect.stringContaining("api/2024-09-26/session/sdk/auth/authenticate"),
|
|
299
|
+
expect.any(Object)
|
|
300
|
+
);
|
|
301
|
+
});
|
|
302
|
+
});
|
|
303
|
+
|
|
304
|
+
describe("signInWithFarcaster", () => {
|
|
305
|
+
it("should sign in with Farcaster and return oneTimeSecret", async () => {
|
|
306
|
+
const mockFarcasterData = {
|
|
307
|
+
message: "mock-message",
|
|
308
|
+
signature: "mock-signature",
|
|
309
|
+
signatureParams: { domain: "example.com" },
|
|
310
|
+
};
|
|
311
|
+
const mockOneTimeSecret = "farcaster-one-time-secret-123";
|
|
312
|
+
mockApiClient.post.mockResolvedValue({
|
|
313
|
+
json: () => Promise.resolve({ callbackUrl: `https://example.com?oneTimeSecret=${mockOneTimeSecret}` }),
|
|
314
|
+
});
|
|
315
|
+
|
|
316
|
+
const result = await crossmintAuthClient.signInWithFarcaster(mockFarcasterData as StatusAPIResponse);
|
|
317
|
+
|
|
318
|
+
expect(result).toBe(mockOneTimeSecret);
|
|
319
|
+
const expectedCallbackUrl = `https://api.crossmint.com/api/2024-09-26/session/sdk/auth/callback?isPopup=false`;
|
|
320
|
+
const queryParams = new URLSearchParams({
|
|
321
|
+
signinAuthenticationMethod: "farcaster",
|
|
322
|
+
callbackUrl: expectedCallbackUrl,
|
|
323
|
+
});
|
|
324
|
+
expect(mockApiClient.post).toHaveBeenCalledWith(
|
|
325
|
+
expect.stringContaining(`api/2024-09-26/session/sdk/auth/authenticate?${queryParams}`),
|
|
326
|
+
expect.objectContaining({
|
|
327
|
+
body: JSON.stringify({
|
|
328
|
+
...mockFarcasterData,
|
|
329
|
+
domain: "example.com",
|
|
330
|
+
redirect: true,
|
|
331
|
+
callbackUrl: expectedCallbackUrl,
|
|
332
|
+
}),
|
|
333
|
+
headers: {
|
|
334
|
+
"Content-Type": "application/json",
|
|
335
|
+
},
|
|
336
|
+
})
|
|
337
|
+
);
|
|
338
|
+
});
|
|
339
|
+
});
|
|
340
|
+
|
|
341
|
+
describe("signInWithSmartWallet", () => {
|
|
342
|
+
it("should initiate smart wallet sign in", async () => {
|
|
343
|
+
const mockAddress = "0x1234567890abcdef";
|
|
344
|
+
const mockResponse = {
|
|
345
|
+
message: "Please sign this message",
|
|
346
|
+
nonce: "123456",
|
|
347
|
+
};
|
|
348
|
+
mockApiClient.post.mockResolvedValue({
|
|
349
|
+
json: () => Promise.resolve(mockResponse),
|
|
350
|
+
});
|
|
351
|
+
|
|
352
|
+
const result = await crossmintAuthClient.signInWithSmartWallet(mockAddress);
|
|
353
|
+
|
|
354
|
+
expect(result).toEqual(mockResponse);
|
|
355
|
+
const queryParams = new URLSearchParams({
|
|
356
|
+
signinAuthenticationMethod: "evm",
|
|
357
|
+
});
|
|
358
|
+
expect(mockApiClient.post).toHaveBeenCalledWith(
|
|
359
|
+
`https://api.crossmint.com/api/2024-09-26/session/sdk/auth/crypto_wallets/authenticate/start?${queryParams}`,
|
|
360
|
+
expect.objectContaining({
|
|
361
|
+
body: JSON.stringify({ walletAddress: mockAddress }),
|
|
362
|
+
headers: {
|
|
363
|
+
"Content-Type": "application/json",
|
|
364
|
+
},
|
|
365
|
+
})
|
|
366
|
+
);
|
|
367
|
+
});
|
|
368
|
+
});
|
|
369
|
+
|
|
370
|
+
describe("authenticateSmartWallet", () => {
|
|
371
|
+
it("should complete smart wallet authentication", async () => {
|
|
372
|
+
const mockAddress = "0x1234567890abcdef";
|
|
373
|
+
const mockSignature = "0xsignature123";
|
|
374
|
+
const mockResponse = {
|
|
375
|
+
success: true,
|
|
376
|
+
authMaterial: {
|
|
377
|
+
jwt: "mock.jwt.token",
|
|
378
|
+
refreshToken: { secret: "refresh-token" },
|
|
379
|
+
},
|
|
380
|
+
};
|
|
381
|
+
mockApiClient.post.mockResolvedValue({
|
|
382
|
+
json: () => Promise.resolve(mockResponse),
|
|
383
|
+
});
|
|
384
|
+
|
|
385
|
+
const result = await crossmintAuthClient.authenticateSmartWallet(mockAddress, mockSignature);
|
|
386
|
+
|
|
387
|
+
expect(result).toEqual(mockResponse);
|
|
388
|
+
const queryParams = new URLSearchParams({
|
|
389
|
+
signinAuthenticationMethod: "evm",
|
|
390
|
+
callbackUrl: `https://api.crossmint.com/api/2024-09-26/session/sdk/auth/we-dont-actually-use-this-anymore`,
|
|
391
|
+
});
|
|
392
|
+
expect(mockApiClient.post).toHaveBeenCalledWith(
|
|
393
|
+
`api/2024-09-26/session/sdk/auth/crypto_wallets/authenticate?${queryParams}`,
|
|
394
|
+
expect.objectContaining({
|
|
395
|
+
body: JSON.stringify({
|
|
396
|
+
walletAddress: mockAddress,
|
|
397
|
+
signature: mockSignature,
|
|
398
|
+
}),
|
|
399
|
+
headers: {
|
|
400
|
+
"Content-Type": "application/json",
|
|
401
|
+
},
|
|
402
|
+
})
|
|
403
|
+
);
|
|
404
|
+
});
|
|
405
|
+
});
|
|
406
|
+
});
|
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
import type { UseSignInData } from "@farcaster/auth-kit";
|
|
2
|
+
import {
|
|
3
|
+
AUTH_SDK_ROOT_ENDPOINT,
|
|
4
|
+
type AuthMaterialWithUser,
|
|
5
|
+
CROSSMINT_API_VERSION,
|
|
6
|
+
CrossmintAuth,
|
|
7
|
+
type CrossmintAuthOptions,
|
|
8
|
+
type OAuthProvider,
|
|
9
|
+
REFRESH_TOKEN_PREFIX,
|
|
10
|
+
SESSION_PREFIX,
|
|
11
|
+
} from "@crossmint/common-sdk-auth";
|
|
12
|
+
import type { Crossmint, CrossmintApiClient } from "@crossmint/common-sdk-base";
|
|
13
|
+
import { type CancellableTask, queueTask } from "@crossmint/client-sdk-base";
|
|
14
|
+
import { deleteCookie, getCookie, getJWTExpiration, setCookie, TIME_BEFORE_EXPIRING_JWT_IN_SECONDS } from "./utils";
|
|
15
|
+
|
|
16
|
+
type CrossmintAuthClientConfig = CrossmintAuthOptions & {
|
|
17
|
+
callbacks?: CrossmintAuthClientCallbacks;
|
|
18
|
+
logoutRoute?: string;
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
export class CrossmintAuthClient extends CrossmintAuth {
|
|
22
|
+
private callbacks: CrossmintAuthClientCallbacks;
|
|
23
|
+
private refreshTask: CancellableTask | null = null;
|
|
24
|
+
private isRefreshing = false;
|
|
25
|
+
private logoutRoute: string | null;
|
|
26
|
+
|
|
27
|
+
private constructor(crossmint: Crossmint, apiClient: CrossmintApiClient, config: CrossmintAuthClientConfig = {}) {
|
|
28
|
+
super(crossmint, apiClient, config);
|
|
29
|
+
this.callbacks = config.callbacks ?? {};
|
|
30
|
+
this.logoutRoute = config.logoutRoute ?? null;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
public static from(crossmint: Crossmint, config: CrossmintAuthClientConfig = {}): CrossmintAuthClient {
|
|
34
|
+
const authClient = new CrossmintAuthClient(crossmint, CrossmintAuth.defaultApiClient(crossmint), config);
|
|
35
|
+
// In case an instance is created on the server, we can't refresh as this stores cookies
|
|
36
|
+
if (typeof window !== "undefined") {
|
|
37
|
+
authClient.handleRefreshAuthMaterial();
|
|
38
|
+
}
|
|
39
|
+
return authClient;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
public async getUser() {
|
|
43
|
+
const result = await this.apiClient.get(`api/${CROSSMINT_API_VERSION}/sdk/auth/user`, {
|
|
44
|
+
headers: {
|
|
45
|
+
"Content-Type": "application/json",
|
|
46
|
+
},
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
const user = await result.json();
|
|
50
|
+
return user;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
public storeAuthMaterial(authMaterial: AuthMaterialWithUser) {
|
|
54
|
+
setCookie(SESSION_PREFIX, authMaterial.jwt);
|
|
55
|
+
setCookie(REFRESH_TOKEN_PREFIX, authMaterial.refreshToken.secret, authMaterial.refreshToken.expiresAt);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
public async logout() {
|
|
59
|
+
// Even if there's a server error, we want to clear the cookies
|
|
60
|
+
try {
|
|
61
|
+
if (this.logoutRoute != null) {
|
|
62
|
+
await this.logoutFromCustomRoute();
|
|
63
|
+
} else {
|
|
64
|
+
await this.logoutFromDefaultRoute(getCookie(REFRESH_TOKEN_PREFIX));
|
|
65
|
+
}
|
|
66
|
+
} catch (error) {
|
|
67
|
+
console.error(error);
|
|
68
|
+
} finally {
|
|
69
|
+
deleteCookie(REFRESH_TOKEN_PREFIX);
|
|
70
|
+
deleteCookie(SESSION_PREFIX);
|
|
71
|
+
this.callbacks.onLogout?.();
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
public async handleRefreshAuthMaterial(refreshTokenSecret?: string): Promise<void> {
|
|
76
|
+
const refreshToken = refreshTokenSecret ?? getCookie(REFRESH_TOKEN_PREFIX);
|
|
77
|
+
// If there is a custom refresh route, that endpoint will fetch the cookies itself
|
|
78
|
+
if ((refreshToken == null && this.refreshRoute == null) || this.isRefreshing) {
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
try {
|
|
83
|
+
this.isRefreshing = true;
|
|
84
|
+
const authMaterial = await this.refreshAuthMaterial(refreshToken);
|
|
85
|
+
|
|
86
|
+
// If a custom refresh route is set, storing in cookies is handled in the server
|
|
87
|
+
if (this.refreshRoute == null) {
|
|
88
|
+
this.storeAuthMaterial(authMaterial);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
this.callbacks.onTokenRefresh?.(authMaterial);
|
|
92
|
+
|
|
93
|
+
this.scheduleNextRefresh(authMaterial.jwt);
|
|
94
|
+
} catch (error) {
|
|
95
|
+
console.error(error);
|
|
96
|
+
this.logout();
|
|
97
|
+
} finally {
|
|
98
|
+
this.isRefreshing = false;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
public async getOAuthUrl(provider: OAuthProvider) {
|
|
103
|
+
const result = await this.apiClient.get(`${AUTH_SDK_ROOT_ENDPOINT}/social/${provider}/start`, {
|
|
104
|
+
headers: {
|
|
105
|
+
"Content-Type": "application/json",
|
|
106
|
+
},
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
const data = (await result.json()) as { oauthUrl: string };
|
|
110
|
+
return data.oauthUrl;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
public async sendEmailOtp(email: string) {
|
|
114
|
+
const result = await this.apiClient.post(`${AUTH_SDK_ROOT_ENDPOINT}/otps/send`, {
|
|
115
|
+
headers: {
|
|
116
|
+
"Content-Type": "application/json",
|
|
117
|
+
},
|
|
118
|
+
body: JSON.stringify({ email }),
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
return await result.json();
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
public async confirmEmailOtp(email: string, emailId: string, token: string) {
|
|
125
|
+
const queryParams = new URLSearchParams({
|
|
126
|
+
email,
|
|
127
|
+
signinAuthenticationMethod: "email",
|
|
128
|
+
token,
|
|
129
|
+
locale: "en",
|
|
130
|
+
state: emailId,
|
|
131
|
+
callbackUrl: `${this.apiClient.baseUrl}/${AUTH_SDK_ROOT_ENDPOINT}/we-dont-actually-use-this-anymore`,
|
|
132
|
+
});
|
|
133
|
+
const result = await this.apiClient.post(`${AUTH_SDK_ROOT_ENDPOINT}/authenticate?${queryParams}`, {
|
|
134
|
+
headers: {
|
|
135
|
+
"Content-Type": "application/json",
|
|
136
|
+
},
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
const resData = await result.json();
|
|
140
|
+
const callbackUrl = new URL(resData.callbackUrl);
|
|
141
|
+
|
|
142
|
+
// parse the oneTimeSecret from the callbackUrl response
|
|
143
|
+
return callbackUrl.searchParams.get("oneTimeSecret");
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
public async signInWithFarcaster(data: UseSignInData) {
|
|
147
|
+
const queryParams = new URLSearchParams({
|
|
148
|
+
signinAuthenticationMethod: "farcaster",
|
|
149
|
+
callbackUrl: `${this.apiClient.baseUrl}/${AUTH_SDK_ROOT_ENDPOINT}/callback?isPopup=false`,
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
const result = await this.apiClient.post(`${AUTH_SDK_ROOT_ENDPOINT}/authenticate?${queryParams}`, {
|
|
153
|
+
headers: {
|
|
154
|
+
"Content-Type": "application/json",
|
|
155
|
+
},
|
|
156
|
+
body: JSON.stringify({
|
|
157
|
+
...data,
|
|
158
|
+
domain: data.signatureParams.domain,
|
|
159
|
+
redirect: true,
|
|
160
|
+
callbackUrl: `${this.apiClient.baseUrl}/${AUTH_SDK_ROOT_ENDPOINT}/callback?isPopup=false`,
|
|
161
|
+
}),
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
const resData = await result.json();
|
|
165
|
+
const callbackUrl = new URL(resData.callbackUrl);
|
|
166
|
+
|
|
167
|
+
// parse the oneTimeSecret from the callbackUrl response
|
|
168
|
+
return callbackUrl.searchParams.get("oneTimeSecret");
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
public async signInWithSmartWallet(address: string) {
|
|
172
|
+
const queryParams = new URLSearchParams({
|
|
173
|
+
signinAuthenticationMethod: "evm",
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
const result = await this.apiClient.post(
|
|
177
|
+
`${AUTH_SDK_ROOT_ENDPOINT}/crypto_wallets/authenticate/start?${queryParams}`,
|
|
178
|
+
{
|
|
179
|
+
headers: {
|
|
180
|
+
"Content-Type": "application/json",
|
|
181
|
+
},
|
|
182
|
+
body: JSON.stringify({ walletAddress: address }),
|
|
183
|
+
}
|
|
184
|
+
);
|
|
185
|
+
return await result.json();
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
public async authenticateSmartWallet(address: string, signature: string) {
|
|
189
|
+
const queryParams = new URLSearchParams({
|
|
190
|
+
signinAuthenticationMethod: "evm",
|
|
191
|
+
callbackUrl: `${this.apiClient.baseUrl}/${AUTH_SDK_ROOT_ENDPOINT}/we-dont-actually-use-this-anymore`,
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
const result = await this.apiClient.post(
|
|
195
|
+
`${AUTH_SDK_ROOT_ENDPOINT}/crypto_wallets/authenticate?${queryParams}`,
|
|
196
|
+
{
|
|
197
|
+
headers: {
|
|
198
|
+
"Content-Type": "application/json",
|
|
199
|
+
},
|
|
200
|
+
body: JSON.stringify({ walletAddress: address, signature }),
|
|
201
|
+
}
|
|
202
|
+
);
|
|
203
|
+
return await result.json();
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
private async logoutFromCustomRoute(): Promise<Response> {
|
|
207
|
+
if (!this.logoutRoute) {
|
|
208
|
+
throw new Error("Custom logout route is not set");
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
return await fetch(this.logoutRoute, { method: "POST" });
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
private scheduleNextRefresh(jwt: string): void {
|
|
215
|
+
const jwtExpiration = getJWTExpiration(jwt);
|
|
216
|
+
if (!jwtExpiration) {
|
|
217
|
+
throw new Error("Invalid JWT");
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
const currentTime = Date.now() / 1000;
|
|
221
|
+
const timeToExpire = jwtExpiration - currentTime - TIME_BEFORE_EXPIRING_JWT_IN_SECONDS;
|
|
222
|
+
|
|
223
|
+
if (timeToExpire > 0) {
|
|
224
|
+
const endTime = Date.now() + timeToExpire * 1000;
|
|
225
|
+
this.cancelScheduledRefresh();
|
|
226
|
+
this.refreshTask = queueTask(() => this.handleRefreshAuthMaterial(), endTime);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
private cancelScheduledRefresh(): void {
|
|
231
|
+
if (this.refreshTask) {
|
|
232
|
+
this.refreshTask.cancel();
|
|
233
|
+
this.refreshTask = null;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
type CrossmintAuthClientCallbacks = {
|
|
239
|
+
onTokenRefresh?: (authMaterial: AuthMaterialWithUser) => void;
|
|
240
|
+
onLogout?: () => void;
|
|
241
|
+
};
|
package/src/index.ts
CHANGED