core&ui: add passkey login support

This commit is contained in:
undefined committed 2025-05-01 02:38:51 +08:00
1 parent d6865d86e5
commit 5b3bcd1134
8 files changed
+82 -23

No files matched your search

+1 -1
View File
@@ -81,7 +81,7 @@ export const projection = <T, S extends ProjectionSchema<T>>(input: T, schema: S
for (const key of Reflect.ownKeys(input)) { for (const key of Reflect.ownKeys(input)) {
const schemaIt = schema[key]; const schemaIt = schema[key];
if (!schemaIt) continue; if (!schemaIt) continue;
if (schemaIt === 1) result[key] = input[key]; if (schemaIt === 1 || !input[key]) result[key] = input[key];
else result[key] = projection(input[key], schemaIt); else result[key] = projection(input[key], schemaIt);
} }
return result; return result;
+2
View File
@@ -307,6 +307,8 @@ class HomeSecurityHandler extends Handler {
type: 'public-key', type: 'public-key',
})), })),
authenticatorSelection: { authenticatorSelection: {
residentKey: 'required',
userVerification: 'preferred',
authenticatorAttachment: type, authenticatorAttachment: type,
}, },
}); });
+33 -13
View File
@@ -1,7 +1,7 @@
import { generateAuthenticationOptions, verifyAuthenticationResponse } from '@simplewebauthn/server'; import { generateAuthenticationOptions, verifyAuthenticationResponse } from '@simplewebauthn/server';
import { isoBase64URL } from '@simplewebauthn/server/helpers'; import { isoBase64URL } from '@simplewebauthn/server/helpers';
import moment from 'moment-timezone'; import moment from 'moment-timezone';
import type { Binary } from 'mongodb'; import { Binary } from 'mongodb';
import Schema from 'schemastery'; import Schema from 'schemastery';
import type { Context } from '../context'; import type { Context } from '../context';
import { import {
@@ -148,28 +148,41 @@ class UserWebauthnHandler extends Handler {
} }
@param('uname', Types.Username, true) @param('uname', Types.Username, true)
async get(domainId: string, uname: string) { @param('login', Types.Boolean)
const udoc = this.user._id ? this.user : ((await user.getByEmail(domainId, uname)) || await user.getByUname(domainId, uname)); async get(domainId: string, uname: string, login: boolean) {
if (!udoc._id) throw new UserNotFoundError(uname || 'user'); let allowCredentials = [];
if (!udoc.authn) throw new AuthOperationError('authn', 'disabled'); let uid = 0;
const options = await generateAuthenticationOptions({ if (!login) {
allowCredentials: udoc._authenticators.map((authenticator) => ({ const udoc = this.user._id ? this.user : ((await user.getByEmail(domainId, uname)) || await user.getByUname(domainId, uname));
if (!udoc._id) throw new UserNotFoundError(uname || 'user');
if (!udoc.authn) throw new AuthOperationError('authn', 'disabled');
allowCredentials = udoc._authenticators.map((authenticator) => ({
id: isoBase64URL.fromBuffer(authenticator.credentialID.buffer), id: isoBase64URL.fromBuffer(authenticator.credentialID.buffer),
})), }));
uid = udoc._id;
}
const options = await generateAuthenticationOptions({
allowCredentials,
rpID: this.getAuthnHost(), rpID: this.getAuthnHost(),
userVerification: 'preferred', userVerification: 'preferred',
}); });
await token.add(token.TYPE_WEBAUTHN, 60, { uid: udoc._id }, options.challenge); await token.add(token.TYPE_WEBAUTHN, 60, { uid: login ? 'login' : uid }, options.challenge);
this.session.challenge = options.challenge; this.session.challenge = options.challenge;
this.response.body.authOptions = options; this.response.body.authOptions = options;
} }
async post({ domainId, result }) { async post({ domainId, result, redirect }) {
const challenge = this.session.challenge; const challenge = this.session.challenge;
if (!challenge) throw new ForbiddenError(); if (!challenge) throw new ForbiddenError();
const tdoc = await token.get(challenge, token.TYPE_WEBAUTHN); const tdoc = await token.get(challenge, token.TYPE_WEBAUTHN);
if (!tdoc) throw new InvalidTokenError(token.TYPE_TEXTS[token.TYPE_WEBAUTHN]); if (!tdoc) throw new InvalidTokenError(token.TYPE_TEXTS[token.TYPE_WEBAUTHN]);
const udoc = await user.getById(domainId, tdoc.uid); const udoc = await (tdoc.uid === 'login'
? (async () => {
const u = await user.coll.findOne({ 'authenticators.credentialID': Binary.createFromBase64(result.id) });
return u ? await user.getById(domainId, u._id) : null;
})()
: user.getById(domainId, tdoc.uid));
if (!udoc) throw new NotFoundError();
const parseId = (id: Binary) => Buffer.from(id.toString('hex'), 'hex').toString('base64url'); const parseId = (id: Binary) => Buffer.from(id.toString('hex'), 'hex').toString('base64url');
const authenticator = udoc._authenticators?.find((c) => parseId(c.credentialID) === result.id); const authenticator = udoc._authenticators?.find((c) => parseId(c.credentialID) === result.id);
if (!authenticator) throw new ValidationError('authenticator'); if (!authenticator) throw new ValidationError('authenticator');
@@ -187,8 +200,15 @@ class UserWebauthnHandler extends Handler {
if (!verification?.verified) throw new ValidationError('authenticator'); if (!verification?.verified) throw new ValidationError('authenticator');
authenticator.counter = verification.authenticationInfo.newCounter; authenticator.counter = verification.authenticationInfo.newCounter;
await user.setById(udoc._id, { authenticators: udoc._authenticators }); await user.setById(udoc._id, { authenticators: udoc._authenticators });
await token.update(challenge, token.TYPE_WEBAUTHN, 60, { verified: true }); if (tdoc.uid === 'login') {
this.back(); await successfulAuth.call(this, await user.getById(domainId, udoc._id));
await token.del(challenge, token.TYPE_WEBAUTHN);
this.response.redirect = redirect || ((this.request.referer || '/login').endsWith('/login')
? this.url('homepage') : this.request.referer);
} else {
await token.update(challenge, token.TYPE_WEBAUTHN, 60, { verified: true });
this.back();
}
} }
} }
@@ -1,9 +1,12 @@
import { browserSupportsWebAuthnAutofill, startAuthentication } from '@simplewebauthn/browser';
import $ from 'jquery'; import $ from 'jquery';
import responsiveCutoff from 'vj/breakpoints.json'; import responsiveCutoff from 'vj/breakpoints.json';
import DomDialog from 'vj/components/dialog/DomDialog'; import DomDialog from 'vj/components/dialog/DomDialog';
import { InfoDialog } from 'vj/components/dialog/index'; import { InfoDialog } from 'vj/components/dialog/index';
import { AutoloadPage } from 'vj/misc/Page'; import { AutoloadPage } from 'vj/misc/Page';
import { i18n, mediaQuery, tpl } from 'vj/utils'; import {
i18n, mediaQuery, request, tpl,
} from 'vj/utils';
const signinDialogPage = new AutoloadPage('signinDialogPage', null, () => { const signinDialogPage = new AutoloadPage('signinDialogPage', null, () => {
const signInDialog = DomDialog.getOrConstruct($('.dialog--signin'), { const signInDialog = DomDialog.getOrConstruct($('.dialog--signin'), {
@@ -11,13 +14,47 @@ const signinDialogPage = new AutoloadPage('signinDialogPage', null, () => {
cancelByEsc: true, cancelByEsc: true,
}); });
let authnInitialized = false;
async function initPasskey() {
if (authnInitialized) return;
authnInitialized = true;
const support = await browserSupportsWebAuthnAutofill();
if (!support) return;
const authnInfo = await request.get('/user/webauthn', { login: true });
if (!authnInfo.authOptions) return;
const result = await startAuthentication({ optionsJSON: authnInfo.authOptions, useBrowserAutofill: true })
.catch((e) => {
Notification.error(i18n('Failed to get credential: {0}', e));
return null;
});
if (!result) return;
try {
const authn = await request.post('/user/webauthn', {
result,
});
if (authn.url) window.location.href = authn.url;
else if (authn.error) throw new Error(authn.error);
} catch (err) {
Notification.error(err.message);
console.error(err);
}
}
if (window.location.href.endsWith('/login')) initPasskey();
function show() {
signInDialog.show();
initPasskey();
}
// don't show quick login dialog if in mobile // don't show quick login dialog if in mobile
if ($('[name="nav_login"]').length > 0) { if ($('[name="nav_login"]').length > 0) {
// nav // nav
$('[name="nav_login"]').on('click', (ev) => { $('[name="nav_login"]').on('click', (ev) => {
if (mediaQuery.isBelow(responsiveCutoff.mobile)) return; if (mediaQuery.isBelow(responsiveCutoff.mobile)) return;
if (ev.shiftKey || ev.metaKey || ev.ctrlKey) return; if (ev.shiftKey || ev.metaKey || ev.ctrlKey) return;
signInDialog.show(); show();
ev.preventDefault(); ev.preventDefault();
}); });
} }
@@ -36,7 +73,7 @@ const signinDialogPage = new AutoloadPage('signinDialogPage', null, () => {
return; return;
} }
} }
signInDialog.show(); show();
}; };
$('[data-lostpass]').on('click', (e) => { $('[data-lostpass]').on('click', (e) => {
+3 -3
View File
@@ -21,7 +21,7 @@
"@fontsource/source-code-pro": "^5.2.5", "@fontsource/source-code-pro": "^5.2.5",
"@fontsource/ubuntu-mono": "^5.2.5", "@fontsource/ubuntu-mono": "^5.2.5",
"@hydrooj/utils": "workspace:^", "@hydrooj/utils": "workspace:^",
"@sentry/browser": "^9.14.0", "@sentry/browser": "^9.15.0",
"@sentry/webpack-plugin": "^3.3.1", "@sentry/webpack-plugin": "^3.3.1",
"@simplewebauthn/browser": "13.1.0", "@simplewebauthn/browser": "13.1.0",
"@svgr/webpack": "^8.1.0", "@svgr/webpack": "^8.1.0",
@@ -50,8 +50,8 @@
"clipboard": "^2.0.11", "clipboard": "^2.0.11",
"copy-webpack-plugin": "^13.0.0", "copy-webpack-plugin": "^13.0.0",
"cordis": "4.0.0-beta.2", "cordis": "4.0.0-beta.2",
"core-js": "^3.41.0", "core-js": "^3.42.0",
"core-js-compat": "^3.41.0", "core-js-compat": "^3.42.0",
"css-loader": "^7.1.2", "css-loader": "^7.1.2",
"diff": "^7.0.0", "diff": "^7.0.0",
"diff-dom": "^5.1.4", "diff-dom": "^5.1.4",
@@ -20,7 +20,7 @@
<div class="row"><div class="columns"> <div class="row"><div class="columns">
<label class="material textbox"> <label class="material textbox">
{{ _('Username') }} {{ _('Username') }}
<input name="uname" type="text" data-autofocus> <input name="uname" type="text" data-autofocus autocomplete="username webauthn">
</label> </label>
</div></div> </div></div>
<div class="row"><div class="columns"> <div class="row"><div class="columns">
@@ -8,7 +8,7 @@
<div class="row"><div class="columns"> <div class="row"><div class="columns">
<label class="inverse material textbox"> <label class="inverse material textbox">
{{ _('Username') }} {{ _('Username') }}
<input name="uname" type="text" autofocus> <input name="uname" type="text" autofocus autocomplete="username webauthn">
</label> </label>
</div></div> </div></div>
<div class="row"><div class="columns"> <div class="row"><div class="columns">
+1 -1
View File
@@ -16,6 +16,6 @@
"@types/react": "^19.1.2", "@types/react": "^19.1.2",
"@types/react-dom": "^19.1.2", "@types/react-dom": "^19.1.2",
"@vitejs/plugin-react-swc": "^3.9.0", "@vitejs/plugin-react-swc": "^3.9.0",
"vite": "^6.3.3" "vite": "^6.3.4"
} }
} }