isa-auth-server 0.0.0-stage → 0.2.3
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 +144 -0
- package/dist/index.d.ts +144 -0
- package/dist/index.js +617 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +572 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +33 -4
- package/README.md +0 -3
package/dist/index.js
ADDED
|
@@ -0,0 +1,617 @@
|
|
|
1
|
+
var __create = Object.create;
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
6
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
7
|
+
var __export = (target, all) => {
|
|
8
|
+
for (var name in all)
|
|
9
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
10
|
+
};
|
|
11
|
+
var __copyProps = (to, from, except, desc) => {
|
|
12
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
13
|
+
for (let key of __getOwnPropNames(from))
|
|
14
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
15
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
16
|
+
}
|
|
17
|
+
return to;
|
|
18
|
+
};
|
|
19
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
20
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
21
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
22
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
23
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
24
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
25
|
+
mod
|
|
26
|
+
));
|
|
27
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
28
|
+
|
|
29
|
+
// src/index.ts
|
|
30
|
+
var index_exports = {};
|
|
31
|
+
__export(index_exports, {
|
|
32
|
+
IsaAuthServer: () => IsaAuthServer,
|
|
33
|
+
JwtServerService: () => JwtServerService,
|
|
34
|
+
OAuthExchanger: () => OAuthExchanger,
|
|
35
|
+
createExpressAuthMiddleware: () => createExpressAuthMiddleware,
|
|
36
|
+
createExpressHandler: () => createExpressHandler,
|
|
37
|
+
createNextApiHandler: () => createNextApiHandler,
|
|
38
|
+
createNextRouteHandler: () => createNextRouteHandler,
|
|
39
|
+
parseSiweMessage: () => parseSiweMessage,
|
|
40
|
+
verifyPasskeyAssertionFormat: () => verifyPasskeyAssertionFormat,
|
|
41
|
+
verifyWorldIdProof: () => verifyWorldIdProof
|
|
42
|
+
});
|
|
43
|
+
module.exports = __toCommonJS(index_exports);
|
|
44
|
+
|
|
45
|
+
// src/tokenService.ts
|
|
46
|
+
var crypto = __toESM(require("crypto"));
|
|
47
|
+
function base64UrlEncode(str) {
|
|
48
|
+
return Buffer.from(str).toString("base64").replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
|
|
49
|
+
}
|
|
50
|
+
function base64UrlDecode(str) {
|
|
51
|
+
let base64 = str.replace(/-/g, "+").replace(/_/g, "/");
|
|
52
|
+
while (base64.length % 4) {
|
|
53
|
+
base64 += "=";
|
|
54
|
+
}
|
|
55
|
+
return Buffer.from(base64, "base64").toString("utf8");
|
|
56
|
+
}
|
|
57
|
+
var JwtServerService = class {
|
|
58
|
+
constructor(config) {
|
|
59
|
+
this.config = {
|
|
60
|
+
expiresInSeconds: 3600,
|
|
61
|
+
issuer: "isa-auth-server",
|
|
62
|
+
audience: "isa-auth-client",
|
|
63
|
+
...config
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
sign(payload, customExpiresIn) {
|
|
67
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
68
|
+
const exp = now + (customExpiresIn || this.config.expiresInSeconds || 3600);
|
|
69
|
+
const header = {
|
|
70
|
+
alg: "HS256",
|
|
71
|
+
typ: "JWT"
|
|
72
|
+
};
|
|
73
|
+
const claims = {
|
|
74
|
+
iss: this.config.issuer,
|
|
75
|
+
aud: this.config.audience,
|
|
76
|
+
iat: now,
|
|
77
|
+
exp,
|
|
78
|
+
...payload
|
|
79
|
+
};
|
|
80
|
+
const encodedHeader = base64UrlEncode(JSON.stringify(header));
|
|
81
|
+
const encodedPayload = base64UrlEncode(JSON.stringify(claims));
|
|
82
|
+
const dataToSign = `${encodedHeader}.${encodedPayload}`;
|
|
83
|
+
const signature = crypto.createHmac("sha256", this.config.secret).update(dataToSign).digest("base64").replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
|
|
84
|
+
return `${dataToSign}.${signature}`;
|
|
85
|
+
}
|
|
86
|
+
verify(token) {
|
|
87
|
+
try {
|
|
88
|
+
const parts = token.split(".");
|
|
89
|
+
if (parts.length !== 3) return null;
|
|
90
|
+
const [encodedHeader, encodedPayload, signature] = parts;
|
|
91
|
+
const header = JSON.parse(base64UrlDecode(encodedHeader));
|
|
92
|
+
if (!header || header.alg !== "HS256") {
|
|
93
|
+
return null;
|
|
94
|
+
}
|
|
95
|
+
const dataToSign = `${encodedHeader}.${encodedPayload}`;
|
|
96
|
+
const expectedSignature = crypto.createHmac("sha256", this.config.secret).update(dataToSign).digest("base64").replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
|
|
97
|
+
const sigBuf = Buffer.from(signature);
|
|
98
|
+
const expectedBuf = Buffer.from(expectedSignature);
|
|
99
|
+
if (sigBuf.length !== expectedBuf.length || !crypto.timingSafeEqual(sigBuf, expectedBuf)) {
|
|
100
|
+
return null;
|
|
101
|
+
}
|
|
102
|
+
const payload = JSON.parse(base64UrlDecode(encodedPayload));
|
|
103
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
104
|
+
if (typeof payload.nbf === "number" && payload.nbf > now) {
|
|
105
|
+
return null;
|
|
106
|
+
}
|
|
107
|
+
if (payload.exp && payload.exp < now) {
|
|
108
|
+
return null;
|
|
109
|
+
}
|
|
110
|
+
return payload;
|
|
111
|
+
} catch {
|
|
112
|
+
return null;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
};
|
|
116
|
+
|
|
117
|
+
// src/oauthExchanger.ts
|
|
118
|
+
var PROVIDER_ENDPOINTS = {
|
|
119
|
+
google: {
|
|
120
|
+
tokenUrl: "https://oauth2.googleapis.com/token",
|
|
121
|
+
userUrl: "https://www.googleapis.com/oauth2/v3/userinfo"
|
|
122
|
+
},
|
|
123
|
+
github: {
|
|
124
|
+
tokenUrl: "https://github.com/login/oauth/access_token",
|
|
125
|
+
userUrl: "https://api.github.com/user"
|
|
126
|
+
},
|
|
127
|
+
kakao: {
|
|
128
|
+
tokenUrl: "https://kauth.kakao.com/oauth/token",
|
|
129
|
+
userUrl: "https://kapi.kakao.com/v2/user/me"
|
|
130
|
+
},
|
|
131
|
+
naver: {
|
|
132
|
+
tokenUrl: "https://nid.naver.com/oauth2.0/token",
|
|
133
|
+
userUrl: "https://openapi.naver.com/v1/nid/me"
|
|
134
|
+
},
|
|
135
|
+
discord: {
|
|
136
|
+
tokenUrl: "https://discord.com/api/oauth2/token",
|
|
137
|
+
userUrl: "https://discord.com/api/users/@me"
|
|
138
|
+
},
|
|
139
|
+
line: {
|
|
140
|
+
tokenUrl: "https://api.line.me/oauth2/v2.1/token",
|
|
141
|
+
userUrl: "https://api.line.me/v2/profile"
|
|
142
|
+
},
|
|
143
|
+
meta: {
|
|
144
|
+
tokenUrl: "https://graph.facebook.com/v21.0/oauth/access_token",
|
|
145
|
+
userUrl: "https://graph.facebook.com/me?fields=id,name,email,picture"
|
|
146
|
+
},
|
|
147
|
+
facebook: {
|
|
148
|
+
tokenUrl: "https://graph.facebook.com/v21.0/oauth/access_token",
|
|
149
|
+
userUrl: "https://graph.facebook.com/me?fields=id,name,email,picture"
|
|
150
|
+
},
|
|
151
|
+
apple: {
|
|
152
|
+
tokenUrl: "https://appleid.apple.com/auth/token"
|
|
153
|
+
}
|
|
154
|
+
};
|
|
155
|
+
var OAuthExchanger = class {
|
|
156
|
+
constructor(configs = {}) {
|
|
157
|
+
this.configs = configs;
|
|
158
|
+
}
|
|
159
|
+
async exchangeCode(providerName, code, options = {}) {
|
|
160
|
+
const config = this.configs[providerName];
|
|
161
|
+
if (!config) {
|
|
162
|
+
throw new Error(`[ISA-AUTH SERVER] Provider "${providerName}" is not configured on the server.`);
|
|
163
|
+
}
|
|
164
|
+
const endpoints = PROVIDER_ENDPOINTS[providerName];
|
|
165
|
+
if (!endpoints) {
|
|
166
|
+
throw new Error(`[ISA-AUTH SERVER] Unknown provider "${providerName}".`);
|
|
167
|
+
}
|
|
168
|
+
const redirectUri = options.redirectUri || config.redirectUri;
|
|
169
|
+
if (!redirectUri && providerName !== "github") {
|
|
170
|
+
throw new Error(`[ISA-AUTH SERVER] redirectUri is required for ${providerName}.`);
|
|
171
|
+
}
|
|
172
|
+
const bodyParams = {
|
|
173
|
+
client_id: config.clientId,
|
|
174
|
+
client_secret: config.clientSecret,
|
|
175
|
+
code,
|
|
176
|
+
grant_type: "authorization_code"
|
|
177
|
+
};
|
|
178
|
+
if (redirectUri) {
|
|
179
|
+
bodyParams.redirect_uri = redirectUri;
|
|
180
|
+
}
|
|
181
|
+
if (options.codeVerifier) {
|
|
182
|
+
bodyParams.code_verifier = options.codeVerifier;
|
|
183
|
+
}
|
|
184
|
+
if (options.state) {
|
|
185
|
+
bodyParams.state = options.state;
|
|
186
|
+
}
|
|
187
|
+
const tokenHeaders = {
|
|
188
|
+
Accept: "application/json",
|
|
189
|
+
"Content-Type": "application/x-www-form-urlencoded"
|
|
190
|
+
};
|
|
191
|
+
const tokenRes = await fetch(endpoints.tokenUrl, {
|
|
192
|
+
method: "POST",
|
|
193
|
+
headers: tokenHeaders,
|
|
194
|
+
body: new URLSearchParams(bodyParams).toString()
|
|
195
|
+
});
|
|
196
|
+
if (!tokenRes.ok) {
|
|
197
|
+
const errText = await tokenRes.text();
|
|
198
|
+
throw new Error(`[ISA-AUTH SERVER] ${providerName} token exchange failed (${tokenRes.status}): ${errText}`);
|
|
199
|
+
}
|
|
200
|
+
const tokenData = await tokenRes.json();
|
|
201
|
+
const accessToken = tokenData.access_token || tokenData.accessToken;
|
|
202
|
+
if (!accessToken) {
|
|
203
|
+
throw new Error(`[ISA-AUTH SERVER] ${providerName} did not return access_token.`);
|
|
204
|
+
}
|
|
205
|
+
let profile = {};
|
|
206
|
+
if (endpoints.userUrl) {
|
|
207
|
+
const userRes = await fetch(endpoints.userUrl, {
|
|
208
|
+
headers: {
|
|
209
|
+
Authorization: `Bearer ${accessToken}`,
|
|
210
|
+
"User-Agent": "isa-auth-server",
|
|
211
|
+
Accept: "application/json"
|
|
212
|
+
}
|
|
213
|
+
});
|
|
214
|
+
if (userRes.ok) {
|
|
215
|
+
profile = await userRes.json();
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
const normalizedProfile = this.normalizeProfile(providerName, profile, tokenData);
|
|
219
|
+
return {
|
|
220
|
+
rawToken: tokenData,
|
|
221
|
+
profile: normalizedProfile
|
|
222
|
+
};
|
|
223
|
+
}
|
|
224
|
+
normalizeProfile(provider, profile, tokenData) {
|
|
225
|
+
switch (provider) {
|
|
226
|
+
case "google":
|
|
227
|
+
return {
|
|
228
|
+
id: profile.sub || profile.id,
|
|
229
|
+
name: profile.name,
|
|
230
|
+
email: profile.email,
|
|
231
|
+
avatar: profile.picture,
|
|
232
|
+
provider: "google"
|
|
233
|
+
};
|
|
234
|
+
case "github":
|
|
235
|
+
return {
|
|
236
|
+
id: String(profile.id),
|
|
237
|
+
name: profile.name || profile.login,
|
|
238
|
+
email: profile.email,
|
|
239
|
+
avatar: profile.avatar_url,
|
|
240
|
+
provider: "github"
|
|
241
|
+
};
|
|
242
|
+
case "kakao":
|
|
243
|
+
return {
|
|
244
|
+
id: String(profile.id),
|
|
245
|
+
name: profile.kakao_account?.profile?.nickname || profile.properties?.nickname,
|
|
246
|
+
email: profile.kakao_account?.email,
|
|
247
|
+
avatar: profile.kakao_account?.profile?.profile_image_url,
|
|
248
|
+
provider: "kakao"
|
|
249
|
+
};
|
|
250
|
+
case "naver":
|
|
251
|
+
return {
|
|
252
|
+
id: profile.response?.id,
|
|
253
|
+
name: profile.response?.name || profile.response?.nickname,
|
|
254
|
+
email: profile.response?.email,
|
|
255
|
+
avatar: profile.response?.profile_image,
|
|
256
|
+
provider: "naver"
|
|
257
|
+
};
|
|
258
|
+
case "discord":
|
|
259
|
+
return {
|
|
260
|
+
id: profile.id,
|
|
261
|
+
name: profile.global_name || profile.username,
|
|
262
|
+
email: profile.email,
|
|
263
|
+
avatar: profile.avatar ? `https://cdn.discordapp.com/avatars/${profile.id}/${profile.avatar}.png` : void 0,
|
|
264
|
+
provider: "discord"
|
|
265
|
+
};
|
|
266
|
+
case "line":
|
|
267
|
+
return {
|
|
268
|
+
id: profile.userId,
|
|
269
|
+
name: profile.displayName,
|
|
270
|
+
avatar: profile.pictureUrl,
|
|
271
|
+
provider: "line"
|
|
272
|
+
};
|
|
273
|
+
case "meta":
|
|
274
|
+
case "facebook":
|
|
275
|
+
return {
|
|
276
|
+
id: profile.id,
|
|
277
|
+
name: profile.name,
|
|
278
|
+
email: profile.email,
|
|
279
|
+
avatar: typeof profile.picture === "string" ? profile.picture : profile.picture?.data?.url,
|
|
280
|
+
provider
|
|
281
|
+
};
|
|
282
|
+
case "apple": {
|
|
283
|
+
let appleClaims = {};
|
|
284
|
+
if (tokenData.id_token && typeof tokenData.id_token === "string") {
|
|
285
|
+
const parts = tokenData.id_token.split(".");
|
|
286
|
+
if (parts.length === 3) {
|
|
287
|
+
try {
|
|
288
|
+
appleClaims = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
|
|
289
|
+
} catch {
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
return {
|
|
294
|
+
id: profile.sub || appleClaims.sub || "unknown",
|
|
295
|
+
name: profile.name || appleClaims.name,
|
|
296
|
+
email: profile.email || appleClaims.email,
|
|
297
|
+
provider: "apple"
|
|
298
|
+
};
|
|
299
|
+
}
|
|
300
|
+
default:
|
|
301
|
+
return {
|
|
302
|
+
id: profile.id || profile.sub || "unknown",
|
|
303
|
+
name: profile.name,
|
|
304
|
+
email: profile.email,
|
|
305
|
+
avatar: profile.picture || profile.avatar,
|
|
306
|
+
provider
|
|
307
|
+
};
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
};
|
|
311
|
+
|
|
312
|
+
// src/verifiers.ts
|
|
313
|
+
function parseSiweMessage(message) {
|
|
314
|
+
try {
|
|
315
|
+
const lines = message.split("\n");
|
|
316
|
+
const headerLine = lines[0];
|
|
317
|
+
const domainMatch = headerLine.match(/^(.+) wants you to sign in with your Ethereum account:/);
|
|
318
|
+
if (!domainMatch) return null;
|
|
319
|
+
const domain = domainMatch[1].trim();
|
|
320
|
+
const address = lines[1]?.trim();
|
|
321
|
+
if (!address || !address.startsWith("0x") || address.length !== 42) return null;
|
|
322
|
+
let uri = "";
|
|
323
|
+
let version = "1";
|
|
324
|
+
let chainId = 1;
|
|
325
|
+
let nonce = "";
|
|
326
|
+
let issuedAt = "";
|
|
327
|
+
let expirationTime;
|
|
328
|
+
let statement;
|
|
329
|
+
for (let i = 2; i < lines.length; i++) {
|
|
330
|
+
const line = lines[i].trim();
|
|
331
|
+
if (line.startsWith("URI: ")) uri = line.replace("URI: ", "").trim();
|
|
332
|
+
else if (line.startsWith("Version: ")) version = line.replace("Version: ", "").trim();
|
|
333
|
+
else if (line.startsWith("Chain ID: ")) chainId = parseInt(line.replace("Chain ID: ", "").trim(), 10) || 1;
|
|
334
|
+
else if (line.startsWith("Nonce: ")) nonce = line.replace("Nonce: ", "").trim();
|
|
335
|
+
else if (line.startsWith("Issued At: ")) issuedAt = line.replace("Issued At: ", "").trim();
|
|
336
|
+
else if (line.startsWith("Expiration Time: ")) expirationTime = line.replace("Expiration Time: ", "").trim();
|
|
337
|
+
else if (!line.includes(": ") && line.length > 0 && !statement) {
|
|
338
|
+
statement = line;
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
return {
|
|
342
|
+
domain,
|
|
343
|
+
address,
|
|
344
|
+
statement,
|
|
345
|
+
uri,
|
|
346
|
+
version,
|
|
347
|
+
chainId,
|
|
348
|
+
nonce,
|
|
349
|
+
issuedAt,
|
|
350
|
+
expirationTime
|
|
351
|
+
};
|
|
352
|
+
} catch {
|
|
353
|
+
return null;
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
async function verifyWorldIdProof(appId, action, proofPayload) {
|
|
357
|
+
try {
|
|
358
|
+
const verifyUrl = `https://developer.worldcoin.org/api/v2/verify/${appId}`;
|
|
359
|
+
const response = await fetch(verifyUrl, {
|
|
360
|
+
method: "POST",
|
|
361
|
+
headers: {
|
|
362
|
+
"Content-Type": "application/json"
|
|
363
|
+
},
|
|
364
|
+
body: JSON.stringify({
|
|
365
|
+
...proofPayload,
|
|
366
|
+
action
|
|
367
|
+
})
|
|
368
|
+
});
|
|
369
|
+
const result = await response.json();
|
|
370
|
+
if (response.ok && result.success) {
|
|
371
|
+
return { success: true, nullifierHash: result.nullifier_hash || proofPayload.nullifier_hash };
|
|
372
|
+
}
|
|
373
|
+
return {
|
|
374
|
+
success: false,
|
|
375
|
+
error: result.detail || result.code || "World ID proof verification failed"
|
|
376
|
+
};
|
|
377
|
+
} catch (error) {
|
|
378
|
+
return { success: false, error: error.message };
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
function verifyPasskeyAssertionFormat(assertion, expectedChallenge) {
|
|
382
|
+
try {
|
|
383
|
+
if (!assertion || !assertion.id || !assertion.response) {
|
|
384
|
+
return { success: false, error: "Invalid Passkey assertion payload structure." };
|
|
385
|
+
}
|
|
386
|
+
const { clientDataJSON, authenticatorData, signature, userHandle } = assertion.response;
|
|
387
|
+
if (!clientDataJSON || !authenticatorData || !signature) {
|
|
388
|
+
return { success: false, error: "Missing required WebAuthn assertion response fields." };
|
|
389
|
+
}
|
|
390
|
+
const clientDataStr = Buffer.from(clientDataJSON, "base64url").toString("utf8");
|
|
391
|
+
const clientData = JSON.parse(clientDataStr);
|
|
392
|
+
if (clientData.type !== "webauthn.get") {
|
|
393
|
+
return { success: false, error: `Invalid clientData type: ${clientData.type}` };
|
|
394
|
+
}
|
|
395
|
+
if (expectedChallenge && clientData.challenge !== expectedChallenge) {
|
|
396
|
+
return { success: false, error: "Challenge mismatch in Passkey assertion." };
|
|
397
|
+
}
|
|
398
|
+
const resolvedUserHandle = userHandle ? Buffer.from(userHandle, "base64url").toString("utf8") : assertion.id;
|
|
399
|
+
return { success: true, userHandle: resolvedUserHandle };
|
|
400
|
+
} catch (error) {
|
|
401
|
+
return { success: false, error: error.message };
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
// src/server.ts
|
|
406
|
+
var IsaAuthServer = class {
|
|
407
|
+
constructor(config) {
|
|
408
|
+
this.config = config;
|
|
409
|
+
this.jwtService = new JwtServerService(config.jwt);
|
|
410
|
+
this.oauthExchanger = new OAuthExchanger(config.providers || {});
|
|
411
|
+
}
|
|
412
|
+
async handleExchange(payload) {
|
|
413
|
+
if (!payload || !payload.type) {
|
|
414
|
+
throw new Error('[ISA-AUTH SERVER] Invalid exchange payload: "type" is required.');
|
|
415
|
+
}
|
|
416
|
+
let user = null;
|
|
417
|
+
let providerName = payload.provider || "unknown";
|
|
418
|
+
let rawResult = null;
|
|
419
|
+
switch (payload.type) {
|
|
420
|
+
case "oauth_code": {
|
|
421
|
+
if (!payload.provider || !payload.code) {
|
|
422
|
+
throw new Error('[ISA-AUTH SERVER] "provider" and "code" are required for oauth_code exchange.');
|
|
423
|
+
}
|
|
424
|
+
providerName = payload.provider;
|
|
425
|
+
const exchangeResult = await this.oauthExchanger.exchangeCode(payload.provider, payload.code, {
|
|
426
|
+
redirectUri: payload.redirectUri,
|
|
427
|
+
codeVerifier: payload.codeVerifier,
|
|
428
|
+
state: payload.state
|
|
429
|
+
});
|
|
430
|
+
user = exchangeResult.profile;
|
|
431
|
+
rawResult = exchangeResult.rawToken;
|
|
432
|
+
break;
|
|
433
|
+
}
|
|
434
|
+
case "web3_signature": {
|
|
435
|
+
if (!payload.address || !payload.signature || !payload.message) {
|
|
436
|
+
throw new Error("[ISA-AUTH SERVER] address, signature, and message are required for web3_signature exchange.");
|
|
437
|
+
}
|
|
438
|
+
providerName = "web3";
|
|
439
|
+
const parsed = parseSiweMessage(payload.message);
|
|
440
|
+
if (!parsed) {
|
|
441
|
+
throw new Error("[ISA-AUTH SERVER] Invalid SIWE message format.");
|
|
442
|
+
}
|
|
443
|
+
if (parsed.address.toLowerCase() !== payload.address.toLowerCase()) {
|
|
444
|
+
throw new Error("[ISA-AUTH SERVER] SIWE message address does not match signed address.");
|
|
445
|
+
}
|
|
446
|
+
user = {
|
|
447
|
+
id: payload.address.toLowerCase(),
|
|
448
|
+
address: payload.address,
|
|
449
|
+
name: `${payload.address.substring(0, 6)}...${payload.address.substring(payload.address.length - 4)}`,
|
|
450
|
+
chainId: payload.chainId || parsed.chainId,
|
|
451
|
+
provider: "web3"
|
|
452
|
+
};
|
|
453
|
+
rawResult = { signature: payload.signature, siwe: parsed };
|
|
454
|
+
break;
|
|
455
|
+
}
|
|
456
|
+
case "world_id_proof": {
|
|
457
|
+
providerName = "world";
|
|
458
|
+
const appId = this.config.worldId?.appId;
|
|
459
|
+
if (!appId) {
|
|
460
|
+
throw new Error("[ISA-AUTH SERVER] worldId.appId is not configured on the server.");
|
|
461
|
+
}
|
|
462
|
+
const action = payload.action || this.config.worldId?.action || "login";
|
|
463
|
+
const verifyRes = await verifyWorldIdProof(appId, action, payload.proof);
|
|
464
|
+
if (!verifyRes.success) {
|
|
465
|
+
throw new Error(`[ISA-AUTH SERVER] World ID verification failed: ${verifyRes.error}`);
|
|
466
|
+
}
|
|
467
|
+
user = {
|
|
468
|
+
id: verifyRes.nullifierHash,
|
|
469
|
+
name: `World ID (${verifyRes.nullifierHash.substring(0, 8)})`,
|
|
470
|
+
verified: true,
|
|
471
|
+
provider: "world"
|
|
472
|
+
};
|
|
473
|
+
rawResult = verifyRes;
|
|
474
|
+
break;
|
|
475
|
+
}
|
|
476
|
+
case "passkey_assertion": {
|
|
477
|
+
providerName = "passkey";
|
|
478
|
+
const passkeyRes = verifyPasskeyAssertionFormat(payload.assertion, payload.challenge);
|
|
479
|
+
if (!passkeyRes.success) {
|
|
480
|
+
throw new Error(`[ISA-AUTH SERVER] Passkey assertion verification failed: ${passkeyRes.error}`);
|
|
481
|
+
}
|
|
482
|
+
user = {
|
|
483
|
+
id: passkeyRes.userHandle || payload.assertion.id,
|
|
484
|
+
name: `Passkey User (${passkeyRes.userHandle || payload.assertion.id})`,
|
|
485
|
+
credentialId: payload.assertion.id,
|
|
486
|
+
provider: "passkey"
|
|
487
|
+
};
|
|
488
|
+
rawResult = payload.assertion;
|
|
489
|
+
break;
|
|
490
|
+
}
|
|
491
|
+
default:
|
|
492
|
+
throw new Error(`[ISA-AUTH SERVER] Unsupported exchange type: "${payload.type}".`);
|
|
493
|
+
}
|
|
494
|
+
if (this.config.onUserResolved) {
|
|
495
|
+
user = await this.config.onUserResolved(user, providerName, rawResult) || user;
|
|
496
|
+
}
|
|
497
|
+
if (!user.roles) {
|
|
498
|
+
user.roles = ["USER"];
|
|
499
|
+
}
|
|
500
|
+
if (!user.permissions) {
|
|
501
|
+
user.permissions = [];
|
|
502
|
+
}
|
|
503
|
+
const expiresIn = this.config.jwt.expiresInSeconds || 3600;
|
|
504
|
+
const accessToken = this.jwtService.sign({
|
|
505
|
+
sub: user.id,
|
|
506
|
+
name: user.name,
|
|
507
|
+
email: user.email,
|
|
508
|
+
roles: user.roles,
|
|
509
|
+
permissions: user.permissions,
|
|
510
|
+
provider: providerName
|
|
511
|
+
}, expiresIn);
|
|
512
|
+
const refreshToken = this.jwtService.sign({
|
|
513
|
+
sub: user.id,
|
|
514
|
+
type: "refresh",
|
|
515
|
+
provider: providerName
|
|
516
|
+
}, expiresIn * 7);
|
|
517
|
+
return {
|
|
518
|
+
accessToken,
|
|
519
|
+
refreshToken,
|
|
520
|
+
expiresIn,
|
|
521
|
+
tokenType: "Bearer",
|
|
522
|
+
user,
|
|
523
|
+
raw: rawResult
|
|
524
|
+
};
|
|
525
|
+
}
|
|
526
|
+
verifyToken(token) {
|
|
527
|
+
return this.jwtService.verify(token);
|
|
528
|
+
}
|
|
529
|
+
};
|
|
530
|
+
|
|
531
|
+
// src/adapters/express.ts
|
|
532
|
+
function createExpressHandler(server) {
|
|
533
|
+
return async (req, res) => {
|
|
534
|
+
try {
|
|
535
|
+
const payload = req.body;
|
|
536
|
+
const result = await server.handleExchange(payload);
|
|
537
|
+
return res.status(200).json(result);
|
|
538
|
+
} catch (error) {
|
|
539
|
+
return res.status(400).json({
|
|
540
|
+
error: "TOKEN_EXCHANGE_FAILED",
|
|
541
|
+
message: error.message || "Token exchange failed"
|
|
542
|
+
});
|
|
543
|
+
}
|
|
544
|
+
};
|
|
545
|
+
}
|
|
546
|
+
function createExpressAuthMiddleware(server) {
|
|
547
|
+
return (req, res, next) => {
|
|
548
|
+
const authHeader = req.headers.authorization;
|
|
549
|
+
if (!authHeader || !authHeader.startsWith("Bearer ")) {
|
|
550
|
+
return res.status(401).json({ error: "UNAUTHORIZED", message: "Missing Bearer token" });
|
|
551
|
+
}
|
|
552
|
+
const token = authHeader.substring(7);
|
|
553
|
+
const user = server.verifyToken(token);
|
|
554
|
+
if (!user) {
|
|
555
|
+
return res.status(401).json({ error: "INVALID_TOKEN", message: "Token is invalid or expired" });
|
|
556
|
+
}
|
|
557
|
+
req.user = user;
|
|
558
|
+
next();
|
|
559
|
+
};
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
// src/adapters/next.ts
|
|
563
|
+
function createNextApiHandler(server) {
|
|
564
|
+
return async (req, res) => {
|
|
565
|
+
if (req.method !== "POST") {
|
|
566
|
+
res.setHeader("Allow", ["POST"]);
|
|
567
|
+
return res.status(405).json({ error: "METHOD_NOT_ALLOWED", message: `Method ${req.method} Not Allowed` });
|
|
568
|
+
}
|
|
569
|
+
try {
|
|
570
|
+
const payload = req.body;
|
|
571
|
+
const result = await server.handleExchange(payload);
|
|
572
|
+
return res.status(200).json(result);
|
|
573
|
+
} catch (error) {
|
|
574
|
+
return res.status(400).json({
|
|
575
|
+
error: "TOKEN_EXCHANGE_FAILED",
|
|
576
|
+
message: error.message || "Token exchange failed"
|
|
577
|
+
});
|
|
578
|
+
}
|
|
579
|
+
};
|
|
580
|
+
}
|
|
581
|
+
function createNextRouteHandler(server) {
|
|
582
|
+
return async (request) => {
|
|
583
|
+
try {
|
|
584
|
+
const payload = await request.json();
|
|
585
|
+
const result = await server.handleExchange(payload);
|
|
586
|
+
return new Response(JSON.stringify(result), {
|
|
587
|
+
status: 200,
|
|
588
|
+
headers: { "Content-Type": "application/json" }
|
|
589
|
+
});
|
|
590
|
+
} catch (error) {
|
|
591
|
+
return new Response(
|
|
592
|
+
JSON.stringify({
|
|
593
|
+
error: "TOKEN_EXCHANGE_FAILED",
|
|
594
|
+
message: error.message || "Token exchange failed"
|
|
595
|
+
}),
|
|
596
|
+
{
|
|
597
|
+
status: 400,
|
|
598
|
+
headers: { "Content-Type": "application/json" }
|
|
599
|
+
}
|
|
600
|
+
);
|
|
601
|
+
}
|
|
602
|
+
};
|
|
603
|
+
}
|
|
604
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
605
|
+
0 && (module.exports = {
|
|
606
|
+
IsaAuthServer,
|
|
607
|
+
JwtServerService,
|
|
608
|
+
OAuthExchanger,
|
|
609
|
+
createExpressAuthMiddleware,
|
|
610
|
+
createExpressHandler,
|
|
611
|
+
createNextApiHandler,
|
|
612
|
+
createNextRouteHandler,
|
|
613
|
+
parseSiweMessage,
|
|
614
|
+
verifyPasskeyAssertionFormat,
|
|
615
|
+
verifyWorldIdProof
|
|
616
|
+
});
|
|
617
|
+
//# sourceMappingURL=index.js.map
|