feat: 完成passkey登录认证功能

This commit is contained in:
Baobhan Sith
2025-04-15 15:16:50 +08:00
parent 1f3631539b
commit 7649a7b69d
13 changed files with 1195 additions and 34 deletions
+326 -14
View File
@@ -8,14 +8,19 @@
"name": "@nexus-terminal/backend",
"version": "0.1.0",
"dependencies": {
"@simplewebauthn/server": "^13.1.1",
"@types/multer": "^1.4.12",
"@types/uuid": "^10.0.0",
"bcrypt": "^5.1.1",
"connect-sqlite3": "^0.9.15",
"express": "^5.1.0",
"express-session": "^1.18.1",
"https-proxy-agent": "^7.0.6",
"multer": "^1.4.5-lts.2",
"socks": "^2.8.4",
"sqlite3": "^5.1.7",
"ssh2": "^1.16.0",
"uuid": "^11.1.0",
"ws": "^8.18.1"
},
"devDependencies": {
@@ -51,6 +56,12 @@
"license": "MIT",
"optional": true
},
"node_modules/@hexagon/base64": {
"version": "1.1.28",
"resolved": "https://registry.npmjs.org/@hexagon/base64/-/base64-1.1.28.tgz",
"integrity": "sha512-lhqDEAvWixy3bZ+UOYbPwUbBkwBq5C1LAJ/xPC8Oi+lL54oyakv/npbA0aU2hgCsx/1NUd4IBvV03+aUBWxerw==",
"license": "MIT"
},
"node_modules/@jridgewell/resolve-uri": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz",
@@ -79,6 +90,12 @@
"@jridgewell/sourcemap-codec": "^1.4.10"
}
},
"node_modules/@levischuck/tiny-cbor": {
"version": "0.2.11",
"resolved": "https://registry.npmjs.org/@levischuck/tiny-cbor/-/tiny-cbor-0.2.11.tgz",
"integrity": "sha512-llBRm4dT4Z89aRsm6u2oEZ8tfwL/2l6BwpZ7JcyieouniDECM5AqNgr/y08zalEIvW3RSK4upYyybDcmjXqAow==",
"license": "MIT"
},
"node_modules/@mapbox/node-pre-gyp": {
"version": "1.0.11",
"resolved": "https://registry.npmjs.org/@mapbox/node-pre-gyp/-/node-pre-gyp-1.0.11.tgz",
@@ -138,6 +155,82 @@
"node": ">=10"
}
},
"node_modules/@peculiar/asn1-android": {
"version": "2.3.16",
"resolved": "https://registry.npmjs.org/@peculiar/asn1-android/-/asn1-android-2.3.16.tgz",
"integrity": "sha512-a1viIv3bIahXNssrOIkXZIlI2ePpZaNmR30d4aBL99mu2rO+mT9D6zBsp7H6eROWGtmwv0Ionp5olJurIo09dw==",
"license": "MIT",
"dependencies": {
"@peculiar/asn1-schema": "^2.3.15",
"asn1js": "^3.0.5",
"tslib": "^2.8.1"
}
},
"node_modules/@peculiar/asn1-ecc": {
"version": "2.3.15",
"resolved": "https://registry.npmjs.org/@peculiar/asn1-ecc/-/asn1-ecc-2.3.15.tgz",
"integrity": "sha512-/HtR91dvgog7z/WhCVdxZJ/jitJuIu8iTqiyWVgRE9Ac5imt2sT/E4obqIVGKQw7PIy+X6i8lVBoT6wC73XUgA==",
"license": "MIT",
"dependencies": {
"@peculiar/asn1-schema": "^2.3.15",
"@peculiar/asn1-x509": "^2.3.15",
"asn1js": "^3.0.5",
"tslib": "^2.8.1"
}
},
"node_modules/@peculiar/asn1-rsa": {
"version": "2.3.15",
"resolved": "https://registry.npmjs.org/@peculiar/asn1-rsa/-/asn1-rsa-2.3.15.tgz",
"integrity": "sha512-p6hsanvPhexRtYSOHihLvUUgrJ8y0FtOM97N5UEpC+VifFYyZa0iZ5cXjTkZoDwxJ/TTJ1IJo3HVTB2JJTpXvg==",
"license": "MIT",
"dependencies": {
"@peculiar/asn1-schema": "^2.3.15",
"@peculiar/asn1-x509": "^2.3.15",
"asn1js": "^3.0.5",
"tslib": "^2.8.1"
}
},
"node_modules/@peculiar/asn1-schema": {
"version": "2.3.15",
"resolved": "https://registry.npmjs.org/@peculiar/asn1-schema/-/asn1-schema-2.3.15.tgz",
"integrity": "sha512-QPeD8UA8axQREpgR5UTAfu2mqQmm97oUqahDtNdBcfj3qAnoXzFdQW+aNf/tD2WVXF8Fhmftxoj0eMIT++gX2w==",
"license": "MIT",
"dependencies": {
"asn1js": "^3.0.5",
"pvtsutils": "^1.3.6",
"tslib": "^2.8.1"
}
},
"node_modules/@peculiar/asn1-x509": {
"version": "2.3.15",
"resolved": "https://registry.npmjs.org/@peculiar/asn1-x509/-/asn1-x509-2.3.15.tgz",
"integrity": "sha512-0dK5xqTqSLaxv1FHXIcd4Q/BZNuopg+u1l23hT9rOmQ1g4dNtw0g/RnEi+TboB0gOwGtrWn269v27cMgchFIIg==",
"license": "MIT",
"dependencies": {
"@peculiar/asn1-schema": "^2.3.15",
"asn1js": "^3.0.5",
"pvtsutils": "^1.3.6",
"tslib": "^2.8.1"
}
},
"node_modules/@simplewebauthn/server": {
"version": "13.1.1",
"resolved": "https://registry.npmjs.org/@simplewebauthn/server/-/server-13.1.1.tgz",
"integrity": "sha512-1hsLpRHfSuMB9ee2aAdh0Htza/X3f4djhYISrggqGe3xopNjOcePiSDkDDoPzDYaaMCrbqGP1H2TYU7bgL9PmA==",
"license": "MIT",
"dependencies": {
"@hexagon/base64": "^1.1.27",
"@levischuck/tiny-cbor": "^0.2.2",
"@peculiar/asn1-android": "^2.3.10",
"@peculiar/asn1-ecc": "^2.3.8",
"@peculiar/asn1-rsa": "^2.3.8",
"@peculiar/asn1-schema": "^2.3.8",
"@peculiar/asn1-x509": "^2.3.8"
},
"engines": {
"node": ">=20.0.0"
}
},
"node_modules/@tootallnate/once": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/@tootallnate/once/-/once-1.1.2.tgz",
@@ -190,7 +283,6 @@
"version": "1.19.5",
"resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.19.5.tgz",
"integrity": "sha512-fB3Zu92ucau0iQ0JMCFQE7b/dv8Ot07NI3KaZIkIUNXq82k4eBAqUaneXfleGY9JWskeS9y+u0nXMyspcuQrCg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/connect": "*",
@@ -201,7 +293,6 @@
"version": "3.4.38",
"resolved": "https://registry.npmjs.org/@types/connect/-/connect-3.4.38.tgz",
"integrity": "sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/node": "*"
@@ -221,7 +312,6 @@
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/@types/express/-/express-5.0.1.tgz",
"integrity": "sha512-UZUw8vjpWFXuDnjFTh7/5c2TWDlQqeXHi6hcN7F2XSVT5P+WmUnnbFS3KA6Jnc6IsEqI2qCVu2bK0R0J4A8ZQQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/body-parser": "*",
@@ -233,7 +323,6 @@
"version": "5.0.6",
"resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-5.0.6.tgz",
"integrity": "sha512-3xhRnjJPkULekpSzgtoNYYcTWgEZkp4myc+Saevii5JPnHNvHMRlBSHDbs7Bh1iPPoVTERHEZXyhyLbMEsExsA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/node": "*",
@@ -256,21 +345,27 @@
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/@types/http-errors/-/http-errors-2.0.4.tgz",
"integrity": "sha512-D0CFMMtydbJAegzOyHjtiKPLlvnm3iTZyZRSZoLq2mRhDdmLfIWOCYPfQJ4cu2erKghU++QvjcUjp/5h7hESpA==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/mime": {
"version": "1.3.5",
"resolved": "https://registry.npmjs.org/@types/mime/-/mime-1.3.5.tgz",
"integrity": "sha512-/pyBZWSLD2n0dcHE3hq8s8ZvcETHtEuF+3E7XVt0Ig2nvsVQXdghHVcEkIWjy9A0wKfTn97a/PSDYohKIlnP/w==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/multer": {
"version": "1.4.12",
"resolved": "https://registry.npmjs.org/@types/multer/-/multer-1.4.12.tgz",
"integrity": "sha512-pQ2hoqvXiJt2FP9WQVLPRO+AmiIm/ZYkavPlIQnx282u4ZrVdztx0pkh3jjpQt0Kz+YI0YhSG264y08UJKoUQg==",
"license": "MIT",
"dependencies": {
"@types/express": "*"
}
},
"node_modules/@types/node": {
"version": "20.17.30",
"resolved": "https://registry.npmjs.org/@types/node/-/node-20.17.30.tgz",
"integrity": "sha512-7zf4YyHA+jvBNfVrk2Gtvs6x7E8V+YDW05bNfG2XkWDJfYRXrTiP/DsB2zSYTaHX0bGIujTBQdMVAhb+j7mwpg==",
"dev": true,
"license": "MIT",
"dependencies": {
"undici-types": "~6.19.2"
@@ -280,21 +375,18 @@
"version": "6.9.18",
"resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.9.18.tgz",
"integrity": "sha512-kK7dgTYDyGqS+e2Q4aK9X3D7q234CIZ1Bv0q/7Z5IwRDoADNU81xXJK/YVyLbLTZCoIwUoDoffFeF+p/eIklAA==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/range-parser": {
"version": "1.2.7",
"resolved": "https://registry.npmjs.org/@types/range-parser/-/range-parser-1.2.7.tgz",
"integrity": "sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/send": {
"version": "0.17.4",
"resolved": "https://registry.npmjs.org/@types/send/-/send-0.17.4.tgz",
"integrity": "sha512-x2EM6TJOybec7c52BX0ZspPodMsQUd5L6PRwOunVyVUhXiBSKf3AezDL8Dgvgt5o0UfKNfuA0eMLr2wLT4AiBA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/mime": "^1",
@@ -305,7 +397,6 @@
"version": "1.15.7",
"resolved": "https://registry.npmjs.org/@types/serve-static/-/serve-static-1.15.7.tgz",
"integrity": "sha512-W8Ym+h8nhuRwaKPaDw34QUkwsGi6Rc4yYqvKFo5rm2FUEhCFbzVWrxXUxuKK8TASjWsysJY0nsmNCGhCOIsrOw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/http-errors": "*",
@@ -364,6 +455,12 @@
"dev": true,
"license": "MIT"
},
"node_modules/@types/uuid": {
"version": "10.0.0",
"resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-10.0.0.tgz",
"integrity": "sha512-7gqG38EyHgyP1S+7+xomFtL+ZNHcKv6DwNaCZmJmo1vgMugyF3TCnXVg4t1uk89mLNwnLtnY3TpOpCOyp1/xHQ==",
"license": "MIT"
},
"node_modules/@types/ws": {
"version": "8.18.1",
"resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz",
@@ -481,6 +578,12 @@
"node": ">= 8"
}
},
"node_modules/append-field": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/append-field/-/append-field-1.0.0.tgz",
"integrity": "sha512-klpgFSWLW1ZEs8svjfb7g4qWY0YS5imI82dTg+QahUvJ8YqAY0P10Uk8tTyh9ZGuYEZEMaeJYCF5BFuX552hsw==",
"license": "MIT"
},
"node_modules/aproba": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/aproba/-/aproba-2.0.0.tgz",
@@ -517,6 +620,20 @@
"safer-buffer": "~2.1.0"
}
},
"node_modules/asn1js": {
"version": "3.0.6",
"resolved": "https://registry.npmjs.org/asn1js/-/asn1js-3.0.6.tgz",
"integrity": "sha512-UOCGPYbl0tv8+006qks/dTgV9ajs97X2p0FAbyS2iyCRrmLSRolDaHdp+v/CLgnzHc3fVB+CwYiUmei7ndFcgA==",
"license": "BSD-3-Clause",
"dependencies": {
"pvtsutils": "^1.3.6",
"pvutils": "^1.1.3",
"tslib": "^2.8.1"
},
"engines": {
"node": ">=12.0.0"
}
},
"node_modules/balanced-match": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
@@ -670,7 +787,6 @@
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz",
"integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==",
"dev": true,
"license": "MIT"
},
"node_modules/buildcheck": {
@@ -682,6 +798,17 @@
"node": ">=10.0.0"
}
},
"node_modules/busboy": {
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz",
"integrity": "sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==",
"dependencies": {
"streamsearch": "^1.1.0"
},
"engines": {
"node": ">=10.16.0"
}
},
"node_modules/bytes": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
@@ -809,6 +936,51 @@
"integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==",
"license": "MIT"
},
"node_modules/concat-stream": {
"version": "1.6.2",
"resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-1.6.2.tgz",
"integrity": "sha512-27HBghJxjiZtIk3Ycvn/4kbJk/1uZuJFfuPEns6LaEvpvG1f0hTea8lilrouyo9mVc2GWdcEZ8OLoGmSADlrCw==",
"engines": [
"node >= 0.8"
],
"license": "MIT",
"dependencies": {
"buffer-from": "^1.0.0",
"inherits": "^2.0.3",
"readable-stream": "^2.2.2",
"typedarray": "^0.0.6"
}
},
"node_modules/concat-stream/node_modules/readable-stream": {
"version": "2.3.8",
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz",
"integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==",
"license": "MIT",
"dependencies": {
"core-util-is": "~1.0.0",
"inherits": "~2.0.3",
"isarray": "~1.0.0",
"process-nextick-args": "~2.0.0",
"safe-buffer": "~5.1.1",
"string_decoder": "~1.1.1",
"util-deprecate": "~1.0.1"
}
},
"node_modules/concat-stream/node_modules/safe-buffer": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
"integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==",
"license": "MIT"
},
"node_modules/concat-stream/node_modules/string_decoder": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz",
"integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==",
"license": "MIT",
"dependencies": {
"safe-buffer": "~5.1.0"
}
},
"node_modules/connect-sqlite3": {
"version": "0.9.15",
"resolved": "https://registry.npmjs.org/connect-sqlite3/-/connect-sqlite3-0.9.15.tgz",
@@ -865,6 +1037,12 @@
"node": ">=6.6.0"
}
},
"node_modules/core-util-is": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz",
"integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==",
"license": "MIT"
},
"node_modules/cpu-features": {
"version": "0.0.10",
"resolved": "https://registry.npmjs.org/cpu-features/-/cpu-features-0.0.10.tgz",
@@ -1685,6 +1863,12 @@
"integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==",
"license": "MIT"
},
"node_modules/isarray": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz",
"integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==",
"license": "MIT"
},
"node_modules/isexe": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
@@ -1997,6 +2181,79 @@
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
"license": "MIT"
},
"node_modules/multer": {
"version": "1.4.5-lts.2",
"resolved": "https://registry.npmjs.org/multer/-/multer-1.4.5-lts.2.tgz",
"integrity": "sha512-VzGiVigcG9zUAoCNU+xShztrlr1auZOlurXynNvO9GiWD1/mTBbUljOKY+qMeazBqXgRnjzeEgJI/wyjJUHg9A==",
"license": "MIT",
"dependencies": {
"append-field": "^1.0.0",
"busboy": "^1.0.0",
"concat-stream": "^1.5.2",
"mkdirp": "^0.5.4",
"object-assign": "^4.1.1",
"type-is": "^1.6.4",
"xtend": "^4.0.0"
},
"engines": {
"node": ">= 6.0.0"
}
},
"node_modules/multer/node_modules/media-typer": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz",
"integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/multer/node_modules/mime-db": {
"version": "1.52.0",
"resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
"integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/multer/node_modules/mime-types": {
"version": "2.1.35",
"resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",
"integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
"license": "MIT",
"dependencies": {
"mime-db": "1.52.0"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/multer/node_modules/mkdirp": {
"version": "0.5.6",
"resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.6.tgz",
"integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==",
"license": "MIT",
"dependencies": {
"minimist": "^1.2.6"
},
"bin": {
"mkdirp": "bin/cmd.js"
}
},
"node_modules/multer/node_modules/type-is": {
"version": "1.6.18",
"resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz",
"integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==",
"license": "MIT",
"dependencies": {
"media-typer": "0.3.0",
"mime-types": "~2.1.24"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/nan": {
"version": "2.22.2",
"resolved": "https://registry.npmjs.org/nan/-/nan-2.22.2.tgz",
@@ -2313,6 +2570,12 @@
"node": ">=10"
}
},
"node_modules/process-nextick-args": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz",
"integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==",
"license": "MIT"
},
"node_modules/promise-inflight": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/promise-inflight/-/promise-inflight-1.0.1.tgz",
@@ -2357,6 +2620,24 @@
"once": "^1.3.1"
}
},
"node_modules/pvtsutils": {
"version": "1.3.6",
"resolved": "https://registry.npmjs.org/pvtsutils/-/pvtsutils-1.3.6.tgz",
"integrity": "sha512-PLgQXQ6H2FWCaeRak8vvk1GW462lMxB5s3Jm673N82zI4vqtVUPuZdffdZbPDFRoU8kAhItWFtPCWiPpp4/EDg==",
"license": "MIT",
"dependencies": {
"tslib": "^2.8.1"
}
},
"node_modules/pvutils": {
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/pvutils/-/pvutils-1.1.3.tgz",
"integrity": "sha512-pMpnA0qRdFp32b1sJl1wOJNxZLQ2cbQx+k6tjNtZ8CpvVhNqEPRgivZ2WOUev2YMajecdH7ctUPDvEe87nariQ==",
"license": "MIT",
"engines": {
"node": ">=6.0.0"
}
},
"node_modules/qs": {
"version": "6.14.0",
"resolved": "https://registry.npmjs.org/qs/-/qs-6.14.0.tgz",
@@ -2855,6 +3136,14 @@
"node": ">= 0.8"
}
},
"node_modules/streamsearch": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-1.1.0.tgz",
"integrity": "sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==",
"engines": {
"node": ">=10.0.0"
}
},
"node_modules/string_decoder": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz",
@@ -3126,6 +3415,12 @@
"strip-json-comments": "^2.0.0"
}
},
"node_modules/tslib": {
"version": "2.8.1",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
"license": "0BSD"
},
"node_modules/tunnel-agent": {
"version": "0.6.0",
"resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz",
@@ -3158,6 +3453,12 @@
"node": ">= 0.6"
}
},
"node_modules/typedarray": {
"version": "0.0.6",
"resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz",
"integrity": "sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA==",
"license": "MIT"
},
"node_modules/typescript": {
"version": "5.8.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.8.3.tgz",
@@ -3188,7 +3489,6 @@
"version": "6.19.8",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.19.8.tgz",
"integrity": "sha512-ve2KP6f/JnbPBFyobGHuerC9g1FYGn/F8n1LWTwNxCEzd6IfqTwUQcNXgEtmmQ6DlRrC1hrSrBnCZPokRrDHjw==",
"dev": true,
"license": "MIT"
},
"node_modules/unique-filename": {
@@ -3226,6 +3526,19 @@
"integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",
"license": "MIT"
},
"node_modules/uuid": {
"version": "11.1.0",
"resolved": "https://registry.npmjs.org/uuid/-/uuid-11.1.0.tgz",
"integrity": "sha512-0/A9rDy9P7cJ+8w1c9WD9V//9Wj15Ce2MPz8Ri6032usz+NfePxx5AcN3bN+r6ZL6jEo066/yNYB3tn4pQEx+A==",
"funding": [
"https://github.com/sponsors/broofa",
"https://github.com/sponsors/ctavan"
],
"license": "MIT",
"bin": {
"uuid": "dist/esm/bin/uuid"
}
},
"node_modules/v8-compile-cache-lib": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz",
@@ -3314,7 +3627,6 @@
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",
"integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=0.4"
+3 -1
View File
@@ -6,9 +6,10 @@
"scripts": {
"build": "tsc",
"start": "node dist/index.js",
"dev": "npx ts-node-dev --respawn --transpile-only src/index.ts"
"dev": "cross-env NODE_ENV=development npx ts-node-dev --respawn --transpile-only src/index.ts"
},
"dependencies": {
"@simplewebauthn/server": "^13.1.1",
"@types/multer": "^1.4.12",
"@types/uuid": "^10.0.0",
"bcrypt": "^5.1.1",
@@ -32,6 +33,7 @@
"@types/sqlite3": "^3.1.11",
"@types/ssh2": "^1.15.5",
"@types/ws": "^8.18.1",
"cross-env": "^7.0.3",
"ts-node-dev": "^2.0.0",
"typescript": "^5.0.0"
}
+82 -6
View File
@@ -1,11 +1,13 @@
import { Request, Response } from 'express';
import bcrypt from 'bcrypt';
import { getDb } from '../database';
import sqlite3, { RunResult } from 'sqlite3'; // 导入 RunResult 类型
import speakeasy from 'speakeasy'; // 导入 speakeasy
import qrcode from 'qrcode'; // 导入 qrcode
import sqlite3, { RunResult } from 'sqlite3';
import speakeasy from 'speakeasy';
import qrcode from 'qrcode';
import { PasskeyService } from '../services/passkey.service'; // 导入 PasskeyService
const db = getDb(); // 获取数据库实例
const db = getDb();
const passkeyService = new PasskeyService(); // 实例化 PasskeyService
// 用户数据结构占位符 (理想情况下应定义在共享的 types 文件中)
interface User {
@@ -21,8 +23,9 @@ declare module 'express-session' {
interface SessionData {
userId?: number;
username?: string;
tempTwoFactorSecret?: string; // 用于存储设置过程中的临时密钥
requiresTwoFactor?: boolean; // 标记登录流程是否需要 2FA 验证
tempTwoFactorSecret?: string;
requiresTwoFactor?: boolean;
currentChallenge?: string; // 用于存储 Passkey 操作的挑战
}
}
@@ -341,6 +344,79 @@ export const setup2FA = async (req: Request, res: Response): Promise<void> => {
}
};
// --- 新增 Passkey 相关方法 ---
/**
* 生成 Passkey 注册选项 (POST /api/v1/auth/passkey/register-options)
*/
export const generatePasskeyRegistrationOptions = async (req: Request, res: Response): Promise<void> => {
const userId = req.session.userId;
const username = req.session.username; // Passkey 需要用户名
if (!userId || !username || req.session.requiresTwoFactor) {
res.status(401).json({ message: '用户未认证或认证未完成。' });
return;
}
try {
const options = await passkeyService.generateRegistrationOptions(username);
// 将 challenge 存储在 session 中,用于后续验证
req.session.currentChallenge = options.challenge;
res.json(options);
} catch (error: any) {
console.error(`用户 ${userId} 生成 Passkey 注册选项时出错:`, error);
res.status(500).json({ message: '生成 Passkey 注册选项失败。', error: error.message });
}
};
/**
* 验证 Passkey 注册响应 (POST /api/v1/auth/passkey/verify-registration)
*/
export const verifyPasskeyRegistration = async (req: Request, res: Response): Promise<void> => {
const userId = req.session.userId;
const expectedChallenge = req.session.currentChallenge;
const { registrationResponse, name } = req.body; // name 是用户给 Passkey 起的名字 (可选)
if (!userId || req.session.requiresTwoFactor) {
res.status(401).json({ message: '用户未认证或认证未完成。' });
return;
}
if (!expectedChallenge) {
res.status(400).json({ message: '未找到预期的挑战,请重新生成注册选项。' });
return;
}
if (!registrationResponse) {
res.status(400).json({ message: '缺少注册响应数据。' });
return;
}
// 清除 session 中的 challenge,无论成功与否
delete req.session.currentChallenge;
try {
const verification = await passkeyService.verifyRegistration(
registrationResponse,
expectedChallenge,
name
);
if (verification.verified) {
res.status(201).json({ message: 'Passkey 注册成功!', verified: true });
} else {
console.error(`用户 ${userId} Passkey 注册验证失败:`, verification);
res.status(400).json({ message: 'Passkey 注册验证失败。', verified: false });
}
} catch (error: any) {
console.error(`用户 ${userId} 验证 Passkey 注册时出错:`, error);
res.status(500).json({ message: '验证 Passkey 注册失败。', error: error.message });
}
};
/**
* 验证并激活 2FA (POST /api/v1/auth/2fa/verify)
*/
+10 -1
View File
@@ -6,7 +6,9 @@ import {
setup2FA,
verifyAndActivate2FA,
disable2FA,
getAuthStatus // 导入获取状态的方法
getAuthStatus, // 导入获取状态的方法
generatePasskeyRegistrationOptions, // 导入 Passkey 方法
verifyPasskeyRegistration // 导入 Passkey 方法
} from './auth.controller';
import { isAuthenticated } from './auth.middleware';
@@ -34,6 +36,13 @@ router.delete('/2fa', isAuthenticated, disable2FA);
// GET /api/v1/auth/status - 获取当前认证状态 (需要认证)
router.get('/status', isAuthenticated, getAuthStatus);
// --- Passkey 管理接口 (都需要认证) ---
// POST /api/v1/auth/passkey/register-options - 生成 Passkey 注册选项
router.post('/passkey/register-options', isAuthenticated, generatePasskeyRegistrationOptions);
// POST /api/v1/auth/passkey/verify-registration - 验证 Passkey 注册响应
router.post('/passkey/verify-registration', isAuthenticated, verifyPasskeyRegistration);
// 未来可以添加的其他认证相关路由
// router.post('/logout', logout); // 登出
+22
View File
@@ -28,6 +28,19 @@ CREATE TABLE IF NOT EXISTS api_keys (
);
`;
const createPasskeysTableSQL = `
CREATE TABLE IF NOT EXISTS passkeys (
id INTEGER PRIMARY KEY AUTOINCREMENT,
credential_id TEXT UNIQUE NOT NULL, -- Base64URL encoded
public_key TEXT NOT NULL, -- Base64URL encoded
counter INTEGER NOT NULL,
transports TEXT, -- JSON array as string, e.g., '["internal", "usb"]'
name TEXT, -- User-provided name for the key
created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now')),
updated_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now'))
);
`;
export const runMigrations = async (db: Database): Promise<void> => {
try {
// 创建 settings 表 (如果不存在)
@@ -74,6 +87,15 @@ export const runMigrations = async (db: Database): Promise<void> => {
});
});
// 创建 passkeys 表 (如果不存在)
await new Promise<void>((resolve, reject) => {
db.run(createPasskeysTableSQL, (err: Error | null) => {
if (err) return reject(new Error(`创建 passkeys 表时出错: ${err.message}`));
console.log('Passkeys 表已检查/创建。');
resolve();
});
});
console.log('所有数据库迁移已完成。');
} catch (error) {
console.error('数据库迁移过程中出错:', error);
@@ -0,0 +1,175 @@
import { Database } from 'sqlite3';
import { getDb } from '../database';
// 定义 Passkey 数据库记录的接口
export interface PasskeyRecord {
id: number;
credential_id: string; // Base64URL encoded
public_key: string; // Base64URL encoded
counter: number;
transports: string | null; // JSON string or null
name: string | null;
created_at: number;
updated_at: number;
}
export class PasskeyRepository {
private db: Database;
constructor() {
this.db = getDb();
}
/**
* 保存新的 Passkey 凭证
* @param credentialId Base64URL 编码的凭证 ID
* @param publicKey Base64URL 编码的公钥
* @param counter 签名计数器
* @param transports 传输方式 (JSON 字符串)
* @param name 用户提供的名称 (可选)
* @returns Promise<number> 新插入记录的 ID
*/
async savePasskey(
credentialId: string,
publicKey: string,
counter: number,
transports: string | null,
name?: string
): Promise<number> {
const sql = `
INSERT INTO passkeys (credential_id, public_key, counter, transports, name, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, strftime('%s', 'now'), strftime('%s', 'now'))
`;
return new Promise((resolve, reject) => {
this.db.run(sql, [credentialId, publicKey, counter, transports, name ?? null], function (err) {
if (err) {
console.error('保存 Passkey 时出错:', err.message);
return reject(new Error(`保存 Passkey 时出错: ${err.message}`));
}
resolve(this.lastID);
});
});
}
/**
* 根据 Credential ID 获取 Passkey 记录
* @param credentialId Base64URL 编码的凭证 ID
* @returns Promise<PasskeyRecord | null> 找到的记录或 null
*/
async getPasskeyByCredentialId(credentialId: string): Promise<PasskeyRecord | null> {
const sql = `SELECT * FROM passkeys WHERE credential_id = ?`;
return new Promise((resolve, reject) => {
this.db.get(sql, [credentialId], (err, row: PasskeyRecord) => {
if (err) {
console.error('按 Credential ID 获取 Passkey 时出错:', err.message);
return reject(new Error(`按 Credential ID 获取 Passkey 时出错: ${err.message}`));
}
resolve(row || null);
});
});
}
/**
* 获取所有已注册的 Passkey 记录
* @returns Promise<PasskeyRecord[]> 所有记录的数组
*/
async getAllPasskeys(): Promise<PasskeyRecord[]> {
const sql = `SELECT id, credential_id, name, transports, created_at FROM passkeys ORDER BY created_at DESC`; // 仅选择必要字段
return new Promise((resolve, reject) => {
this.db.all(sql, [], (err, rows: PasskeyRecord[]) => {
if (err) {
console.error('获取所有 Passkey 时出错:', err.message);
return reject(new Error(`获取所有 Passkey 时出错: ${err.message}`));
}
resolve(rows);
});
});
}
/**
* 更新 Passkey 的签名计数器
* @param credentialId Base64URL 编码的凭证 ID
* @param newCounter 新的计数器值
* @returns Promise<void>
*/
async updatePasskeyCounter(credentialId: string, newCounter: number): Promise<void> {
const sql = `UPDATE passkeys SET counter = ?, updated_at = strftime('%s', 'now') WHERE credential_id = ?`;
return new Promise((resolve, reject) => {
this.db.run(sql, [newCounter, credentialId], function (err) {
if (err) {
console.error('更新 Passkey 计数器时出错:', err.message);
return reject(new Error(`更新 Passkey 计数器时出错: ${err.message}`));
}
if (this.changes === 0) {
return reject(new Error(`未找到 Credential ID 为 ${credentialId} 的 Passkey 进行更新`));
}
resolve();
});
});
}
/**
* 根据 ID 删除 Passkey
* @param id Passkey 记录的 ID
* @returns Promise<void>
*/
async deletePasskeyById(id: number): Promise<void> {
const sql = `DELETE FROM passkeys WHERE id = ?`;
return new Promise((resolve, reject) => {
this.db.run(sql, [id], function (err) {
if (err) {
console.error('按 ID 删除 Passkey 时出错:', err.message);
return reject(new Error(`按 ID 删除 Passkey 时出错: ${err.message}`));
}
if (this.changes === 0) {
return reject(new Error(`未找到 ID 为 ${id} 的 Passkey 进行删除`));
}
console.log(`ID 为 ${id} 的 Passkey 已删除。`);
resolve();
});
});
}
/**
* 根据 Credential ID 删除 Passkey
* @param credentialId Base64URL 编码的凭证 ID
* @returns Promise<void>
*/
async deletePasskeyByCredentialId(credentialId: string): Promise<void> {
const sql = `DELETE FROM passkeys WHERE credential_id = ?`;
return new Promise((resolve, reject) => {
this.db.run(sql, [credentialId], function (err) {
if (err) {
console.error('按 Credential ID 删除 Passkey 时出错:', err.message);
return reject(new Error(`按 Credential ID 删除 Passkey 时出错: ${err.message}`));
}
if (this.changes === 0) {
// It's possible the user tries to delete a non-existent key, maybe not an error?
console.warn(`尝试删除不存在的 Credential ID: ${credentialId}`);
} else {
console.log(`Credential ID 为 ${credentialId} 的 Passkey 已删除。`);
}
resolve();
});
});
}
/**
* 根据 credential_id 或 name 前缀模糊查找 Passkey 记录(自动补全)
* @param prefix 前缀字符串
* @returns Promise<PasskeyRecord[]> 匹配的记录数组
*/
async searchPasskeyByPrefix(prefix: string): Promise<PasskeyRecord[]> {
const sql = `SELECT * FROM passkeys WHERE credential_id LIKE ? OR name LIKE ? ORDER BY created_at DESC`;
const likePrefix = `${prefix}%`;
return new Promise((resolve, reject) => {
this.db.all(sql, [likePrefix, likePrefix], (err, rows: PasskeyRecord[]) => {
if (err) {
console.error('模糊查找 Passkey 时出错:', err.message);
return reject(new Error(`模糊查找 Passkey 时出错: ${err.message}`));
}
resolve(rows);
});
});
}
}
@@ -0,0 +1,256 @@
import {
generateRegistrationOptions,
verifyRegistrationResponse,
generateAuthenticationOptions,
verifyAuthenticationResponse,
VerifiedRegistrationResponse,
VerifiedAuthenticationResponse,
} from '@simplewebauthn/server';
import type {
GenerateRegistrationOptionsOpts,
GenerateAuthenticationOptionsOpts,
VerifyRegistrationResponseOpts,
VerifyAuthenticationResponseOpts,
RegistrationResponseJSON,
AuthenticationResponseJSON,
// AuthenticatorDevice is not typically needed here
} from '@simplewebauthn/server'; // Import types directly from the package
import { PasskeyRepository, PasskeyRecord } from '../repositories/passkey.repository';
import { settingsService } from './settings.service'; // Import the exported object
// 定义 Relying Party (RP) 信息 - 这些应该来自配置或设置
// TODO: 从 SettingsService 或环境变量获取这些值
const rpName = 'Nexus Terminal';
// 重要: rpID 应该是你的网站域名 (不包含协议和端口)
// 对于本地开发,通常是 'localhost'
const rpID = process.env.NODE_ENV === 'development' ? 'localhost' : 'YOUR_PRODUCTION_DOMAIN'; // 需要替换为实际域名
// 重要: origin 应该是你的前端应用的完整源 (包含协议和端口)
const expectedOrigin = process.env.FRONTEND_URL || 'http://localhost:5173'; // 确保与前端 URL 匹配
export class PasskeyService {
private passkeyRepository: PasskeyRepository;
// No need to instantiate settingsService if it's an object export
// private settingsService: typeof settingsService; // Use typeof for the object type
constructor() {
this.passkeyRepository = new PasskeyRepository();
// this.settingsService = settingsService; // Assign the imported object if needed
// TODO: Load rpID, rpName, expectedOrigin using settingsService.getSetting()
}
/**
* 生成 Passkey 注册选项 (挑战)
*/
async generateRegistrationOptions(userName: string = 'nexus-user') { // WebAuthn 需要一个用户名
// 暂时不获取已存在的凭证,允许同一用户注册多个设备
// const existingCredentials = await this.passkeyRepository.getAllPasskeys();
const options: GenerateRegistrationOptionsOpts = {
rpName,
rpID,
userID: Buffer.from(userName), // userID should be a Buffer/Uint8Array
userName: userName,
// 不建议排除已存在的凭证,除非有特定原因
// excludeCredentials: existingCredentials.map(cred => ({
// id: cred.credential_id, // 需要是 Base64URL 格式,存储时确保是这个格式
// type: 'public-key',
// transports: cred.transports ? JSON.parse(cred.transports) : undefined,
// })),
authenticatorSelection: {
// authenticatorAttachment: 'platform', // 倾向于平台认证器 (如 Windows Hello, Touch ID)
userVerification: 'preferred', // 倾向于需要用户验证 (PIN, 生物识别)
residentKey: 'preferred', // 倾向于创建可发现凭证 (存储在认证器上)
},
// 可选:增加超时时间
timeout: 60000, // 60 秒
// attestation: 'none', // Temporarily remove to resolve TS error, 'none' is often default
};
const registrationOptions = await generateRegistrationOptions(options);
// TODO: 需要将生成的 challenge 临时存储起来 (例如在 session 或 内存缓存中),以便后续验证
// 这里暂时返回 challenge,让 Controller 处理存储
return registrationOptions;
}
/**
* 验证 Passkey 注册响应
* @param registrationResponse 来自客户端的注册响应
* @param expectedChallenge 之前生成的、临时存储的挑战
* @param passkeyName 用户为这个 Passkey 起的名字 (可选)
*/
async verifyRegistration(
registrationResponse: RegistrationResponseJSON,
expectedChallenge: string,
passkeyName?: string
): Promise<VerifiedRegistrationResponse> {
const verificationOptions: VerifyRegistrationResponseOpts = {
response: registrationResponse,
expectedChallenge: expectedChallenge,
expectedOrigin: expectedOrigin,
expectedRPID: rpID,
requireUserVerification: true, // 强制要求用户验证, simplewebauthn defaults this to true now
};
let verification: VerifiedRegistrationResponse;
try {
verification = await verifyRegistrationResponse(verificationOptions);
} catch (error: any) {
console.error('Passkey 注册验证时发生异常:', error);
// Provide more context in the error
const err = error as Error;
throw new Error(`Passkey registration verification failed: ${err.message || err}`);
}
if (verification.verified && verification.registrationInfo) {
// Use type assertion to bypass strict type checking for registrationInfo properties
const registrationInfo = verification.registrationInfo as any;
const { credentialPublicKey, credentialID, counter } = registrationInfo;
// Optional: Access other potential properties if needed
// const { credentialDeviceType, credentialBackedUp } = registrationInfo;
// 将公钥和 ID 转换为 Base64URL 字符串存储 (如果它们还不是)
// @simplewebauthn/server 返回的是 Buffer,需要转换
const credentialIdBase64Url = Buffer.from(credentialID).toString('base64url');
const publicKeyBase64Url = Buffer.from(credentialPublicKey).toString('base64url');
// 获取 transports 信息
const transports = registrationResponse.response.transports ?? null;
// 保存到数据库
await this.passkeyRepository.savePasskey(
credentialIdBase64Url,
publicKeyBase64Url,
counter,
transports ? JSON.stringify(transports) : null,
passkeyName
);
console.log(`Passkey 注册成功: ${credentialIdBase64Url}, Name: ${passkeyName ?? 'N/A'}`);
} else {
console.error('Passkey 注册验证失败:', verification);
}
return verification;
}
/**
* 生成 Passkey 认证选项 (挑战)
*/
async generateAuthenticationOptions(): Promise<ReturnType<typeof generateAuthenticationOptions>> {
// 可选:可以只允许已注册的凭证进行认证
// const allowedCredentials = (await this.passkeyRepository.getAllPasskeys()).map(cred => ({
// id: cred.credential_id, // 确保是 Base64URL 格式
// type: 'public-key',
// transports: cred.transports ? JSON.parse(cred.transports) : undefined,
// }));
const options: GenerateAuthenticationOptionsOpts = {
rpID,
// allowCredentials: allowedCredentials, // 如果只想允许已注册的凭证
userVerification: 'preferred', // 倾向于需要用户验证
timeout: 60000, // 60 秒
};
const authenticationOptions = await generateAuthenticationOptions(options);
// TODO: 需要将生成的 challenge 临时存储起来,以便后续验证
// 这里暂时返回 challenge,让 Controller 处理存储
return authenticationOptions;
}
/**
* 验证 Passkey 认证响应
* @param authenticationResponse 来自客户端的认证响应
* @param expectedChallenge 之前生成的、临时存储的挑战
*/
async verifyAuthentication(
authenticationResponse: AuthenticationResponseJSON,
expectedChallenge: string
): Promise<VerifiedAuthenticationResponse> {
const credentialIdBase64Url = authenticationResponse.id; // 客户端传回的 ID 已经是 Base64URL
const authenticator = await this.passkeyRepository.getPasskeyByCredentialId(credentialIdBase64Url);
if (!authenticator) {
throw new Error(`未找到 Credential ID 为 ${credentialIdBase64Url} 的认证器`);
}
// 将存储的公钥从 Base64URL 转回 Buffer
// const authenticatorPublicKeyBuffer = Buffer.from(authenticator.public_key, 'base64url'); // Moved lookup after verification
// Prepare the verification options object - authenticator is looked up internally by the library
// based on the response's credential ID, or requires allowCredentials
const verificationOptions: VerifyAuthenticationResponseOpts = {
response: authenticationResponse,
expectedChallenge: expectedChallenge,
expectedOrigin: expectedOrigin,
expectedRPID: rpID,
// We need to provide a way for the library to get the authenticator details.
// Option 1: Provide `allowCredentials` (if known beforehand)
// Option 2: Let the library handle it (requires authenticator to be discoverable/resident key)
// Option 3 (Most robust): Provide the authenticator directly after fetching it.
// The library likely uses the credential ID from the response to find the authenticator,
// especially with discoverable credentials, or requires `allowCredentials`.
// Re-adding the authenticator property based on the new error message,
// ensuring the structure matches what the library likely expects.
authenticator: {
credentialID: Buffer.from(authenticator.credential_id, 'base64url'),
credentialPublicKey: Buffer.from(authenticator.public_key, 'base64url'),
counter: authenticator.counter,
transports: authenticator.transports ? JSON.parse(authenticator.transports) : undefined,
},
requireUserVerification: true, // simplewebauthn defaults this to true now
} as any; // Use type assertion to bypass strict property check for 'authenticator'
let verification: VerifiedAuthenticationResponse;
try {
verification = await verifyAuthenticationResponse(verificationOptions);
} catch (error: any) {
// If verification fails, log the error but potentially re-throw a more generic one
console.error('Passkey 认证验证时发生异常:', error);
const err = error as Error;
// Check if the error is due to the authenticator not being found (already handled)
if (!err.message.includes(credentialIdBase64Url)) {
throw new Error(`Passkey authentication verification failed: ${err.message || err}`);
}
// If error is related to authenticator not found, rethrow the original specific error
throw error;
}
if (verification.verified && verification.authenticationInfo) {
const { newCounter } = verification.authenticationInfo;
// 更新数据库中的计数器
await this.passkeyRepository.updatePasskeyCounter(authenticator.credential_id, newCounter);
console.log(`Passkey 认证成功: ${authenticator.credential_id}`);
} else {
console.error('Passkey 认证验证失败:', verification);
}
return verification;
}
/**
* 获取所有已注册 Passkey 的简要信息 (用于管理)
*/
async listPasskeys(): Promise<Partial<PasskeyRecord>[]> {
// 只返回 ID, Name, Transports, CreatedAt 以减少暴露敏感信息
const keys = await this.passkeyRepository.getAllPasskeys();
return keys.map(k => ({
id: k.id,
name: k.name,
transports: k.transports,
created_at: k.created_at
}));
}
/**
* 根据 ID 删除 Passkey
* @param id Passkey 记录的 ID
*/
async deletePasskey(id: number): Promise<void> {
await this.passkeyRepository.deletePasskeyById(id);
}
}