ronantakizawa/codereview-bench huggingface dataset:
Repository: logto-io/logto
File: packages/core/src/routes/experience/classes/libraries/adaptive-mfa-validator/index.ts (TypeScript)

Code before:

    if (contextOverride !== undefined) {
      return contextOverride;
    }

    if (this.adaptiveMfaContext) {
      return this.adaptiveMfaContext;
    }

    const context = parseAdaptiveMfaContext(this.getSignInContext());

    this.adaptiveMfaContext = context;
    return this.adaptiveMfaContext;
  }

  public getSignInContext(): Optional<Record<string, string>> {
    if (!EnvSet.values.isDevFeaturesEnabled) {
      return;
    }

    if (this.signInContext) {
      return this.signInContext;
    }

    this.signInContext = conditional(this.ctx && getInjectedHeaderValues(this.ctx.request.headers));
    return this.signInContext;
  }

  private buildEvaluationState(
    user: User,
    options: AdaptiveMfaEvaluationOptions
  ): AdaptiveMfaEvaluationState {
    return {
      user,
      now: options.now ?? new Date(),
      context: this.getCurrentContext(options.currentContext),
    };
  }

  private async evaluateRules(state: AdaptiveMfaEvaluationState): Promise<AdaptiveMfaResult> {
    const triggeredRules = new Set<TriggeredRule>();
    for (const ruleValidator of this.ruleValidators) {
      // eslint-disable-next-line no-await-in-loop
      const triggeredRule = await ruleValidator.validate(state);
      if (triggeredRule) {
        triggeredRules.add(triggeredRule);
      }
    }

    const triggeredRulesList = Array.from(triggeredRules);


Review comment (performance):
nit: Since all the logic here is synchronous and the overhead is relatively small, there’s no need to introduce an in-memory cache.

Code after:
    if (contextOverride !== undefined) {
      return contextOverride;
    }

    if (this.adaptiveMfaContext) {
      return this.adaptiveMfaContext;
    }

    const context = parseAdaptiveMfaContext(this.getSignInContext());

    this.adaptiveMfaContext = context;
    return this.adaptiveMfaContext;
  }

  public getSignInContext(): Optional<Record<string, string>> {
    if (!EnvSet.values.isDevFeaturesEnabled) {
      return;
    }

    return conditional(this.ctx && getInjectedHeaderValues(this.ctx.request.headers));
  }

  private buildEvaluationState(
    user: User,
    options: AdaptiveMfaEvaluationOptions
  ): AdaptiveMfaEvaluationState {
    return {
      user,
      now: options.now ?? new Date(),
      context: this.getCurrentContext(options.currentContext),
    };
  }

  private async evaluateRules(state: AdaptiveMfaEvaluationState): Promise<AdaptiveMfaResult> {
    const triggeredRules = new Set<TriggeredRule>();
    for (const ruleValidator of this.ruleValidators) {
      // eslint-disable-next-line no-await-in-loop
      const triggeredRule = await ruleValidator.validate(state);
      if (triggeredRule) {
        triggeredRules.add(triggeredRule);
      }
    }

    const triggeredRulesList = Array.from(triggeredRules);

    return {
      requiresMfa: triggeredRulesList.length > 0,
      triggeredRules: triggeredRulesList,
    };
  }
Repository: logto-io/logto
File: packages/experience/src/pages/PasskeySetup/index.tsx (TypeScript)

Code before:
type RegistrationState = {
  verificationId: string;
  options: WebAuthnRegistrationOptions;
};

const PasskeySetup = () => {
  const { state } = useLocation();
  const redirectTo = useGlobalRedirectTo();
  const [, continueFlowState] = validate(state, continueFlowStateGuard);

  const { handleBindPasskey } = usePasskeySignIn();
  const asyncCreateRegistrationOptions = useApi(createSignInWebAuthnRegistrationOptions);

  const [registrationResult, setRegistrationResult] = useState<RegistrationState>();
  const [isPreparing, setIsPreparing] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);

  const handleError = useErrorHandler();
  const onSubmitErrorHandlers = useSubmitInteractionErrorHandler(
    continueFlowState?.interactionEvent ?? InteractionEvent.SignIn,
    {
      replace: true,
    }
  );

  const asyncSkipFunction = useApi(
    continueFlowState?.interactionEvent === InteractionEvent.SignIn
      ? skipPasskey
      : skipPasskeySuggestionOnce
  );

  useEffect(() => {
    if (!browserSupportsWebAuthn()) {
      return;
    }

    (async () => {
      setIsPreparing(true);
      const [error, result] = await asyncCreateRegistrationOptions();
      setIsPreparing(false);

      if (error) {
        await handleError(error);
        return;
      }

      if (result) {
        setRegistrationResult(result);
      }
    })();
  }, [asyncCreateRegistrationOptions, handleError]);

Review comment (suggestion):
```suggestion
  const asyncSkipPasskeyBinding= useApi(
```

Code after:

const PasskeySetup = () => {
  const { state } = useLocation();
  const redirectTo = useGlobalRedirectTo();
  const [, continueFlowState] = validate(state, continueFlowStateGuard);

  const { handleBindPasskey } = usePasskeySignIn();
  const asyncCreateRegistrationOptions = useApi(createSignInWebAuthnRegistrationOptions);

  const [registrationResult, setRegistrationResult] = useState<RegistrationState>();
  const [isPreparing, setIsPreparing] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);

  const handleError = useErrorHandler();
  const onSubmitErrorHandlers = useSubmitInteractionErrorHandler(
    continueFlowState?.interactionEvent ?? InteractionEvent.SignIn,
    {
      replace: true,
    }
  );

  const asyncSkipPasskeyBinding = useApi(skipPasskeyBinding);

  useEffect(() => {
    if (!browserSupportsWebAuthn()) {
      return;
    }

    (async () => {
      setIsPreparing(true);
      const [error, result] = await asyncCreateRegistrationOptions();
      setIsPreparing(false);

      if (error) {
        await handleError(error);
        return;
      }

      if (result) {
        setRegistrationResult(result);
      }
    })();
  }, [asyncCreateRegistrationOptions, handleError]);

  const onCreatePasskey = useCallback(async () => {
    if (!registrationResult) {
      return;
    }

    setIsSubmitting(true);
    await handleBindPasskey(
Repository: logto-io/logto
File: packages/core/src/routes/experience/anonymous-routes/index.ts (TypeScript)

Code before:
import { webAuthnAuthenticationOptionsGuard } from '@logto/schemas';
import type Router from 'koa-router';
import { z } from 'zod';

import { EnvSet } from '#src/env-set/index.js';
import RequestError from '#src/errors/RequestError/index.js';
import koaGuard from '#src/middleware/koa-guard.js';
import { type WithInteractionDetailsContext } from '#src/middleware/koa-interaction-details.js';
import type TenantContext from '#src/tenants/TenantContext.js';
import assertThat from '#src/utils/assert-that.js';

import { koaQuotaGuard } from '../../../middleware/koa-quota-guard.js';
import { generateWebAuthnAuthenticationOptions } from '../../interaction/utils/webauthn.js';
import { SignInExperienceValidator } from '../classes/libraries/sign-in-experience-validator.js';
import { experienceRoutes } from '../const.js';

export default function experienceAnonymousRoutes<T extends WithInteractionDetailsContext>(
  router: Router<unknown, T>,
  tenantContext: TenantContext
) {
  const { libraries, queries, provider } = tenantContext;

  router.get(
    `${experienceRoutes.prefix}/sso-connectors`,
    koaGuard({
      query: z.object({
        email: z.string().email(),
      }),
      status: [200, 400],
      response: z.object({
        connectorIds: z.string().array(),
      }),
    }),
    async (ctx, next) => {
      const { email } = ctx.guard.query;

      assertThat(

Review comment (suggestion):
```suggestion
import { koaQuotaGuard } from '#src/middleware/koa-quota-guard.js';
```

Code after:
import { webAuthnAuthenticationOptionsGuard } from '@logto/schemas';
import type Router from 'koa-router';
import { z } from 'zod';

import { EnvSet } from '#src/env-set/index.js';
import RequestError from '#src/errors/RequestError/index.js';
import koaGuard from '#src/middleware/koa-guard.js';
import { type WithInteractionDetailsContext } from '#src/middleware/koa-interaction-details.js';
import type TenantContext from '#src/tenants/TenantContext.js';
import assertThat from '#src/utils/assert-that.js';

import { generateWebAuthnAuthenticationOptions } from '../../interaction/utils/webauthn.js';
import { SignInExperienceValidator } from '../classes/libraries/sign-in-experience-validator.js';
import { experienceRoutes } from '../const.js';

export default function experienceAnonymousRoutes<T extends WithInteractionDetailsContext>(
  router: Router<unknown, T>,
  tenantContext: TenantContext
) {
  const { libraries, queries, provider } = tenantContext;

  router.get(
    `${experienceRoutes.prefix}/sso-connectors`,
    koaGuard({
      query: z.object({
        email: z.string().email(),
      }),
      status: [200, 400],
      response: z.object({
        connectorIds: z.string().array(),
      }),
    }),
    async (ctx, next) => {
      const { email } = ctx.guard.query;

      assertThat(
        email.split('@')[1],
Repository: louislam/uptime-kuma
File: server/util-server.js (JavaScript)

Code before:
}


// ssl-checker by @dyaa
// param: res - response object from axios
// return an object containing the certificate information

const getDaysBetween = (validFrom, validTo) =>
    Math.round(Math.abs(+validFrom - +validTo) / 8.64e7);

const getDaysRemaining = (validFrom, validTo) => {
    const daysRemaining = getDaysBetween(validFrom, validTo);
    if (new Date(validTo).getTime() < new Date().getTime()) {
        return -daysRemaining;
    }
    return daysRemaining;
};

exports.checkCertificate = function (res) {
    const {
        valid_from,
        valid_to,
        subjectaltname,
        issuer,
        fingerprint,
    } = res.request.res.socket.getPeerCertificate(false);

    if (!valid_from || !valid_to || !subjectaltname) {
        reject(new Error('No certificate'));
        return;
    }

    const valid = res.request.res.socket.authorized || false;

    const validTo = new Date(valid_to);

    const validFor = subjectaltname
        .replace(/DNS:|IP Address:/g, "")
        .split(", ");

    const daysRemaining = getDaysRemaining(new Date(), validTo);

    return {
        valid,
        validFor,
        validTo,
        daysRemaining,
        issuer,
        fingerprint,
    };
}

Review comment (suggestion):
I just test the code, the problem is strange.

After started server, all monitor with https are able to get the info on the first heartbeat.

However, for the second heartbeat, res.request.res.socket.getPeerCertificate(false) return empty object {}. So it goes into "No certificate" error.

I am testing on Windows 10 (x64) Node.js 14.16.0

Code after:
}


// ssl-checker by @dyaa
// param: res - response object from axios
// return an object containing the certificate information

const getDaysBetween = (validFrom, validTo) =>
    Math.round(Math.abs(+validFrom - +validTo) / 8.64e7);

const getDaysRemaining = (validFrom, validTo) => {
    const daysRemaining = getDaysBetween(validFrom, validTo);
    if (new Date(validTo).getTime() < new Date().getTime()) {
        return -daysRemaining;
    }
    return daysRemaining;
};

exports.checkCertificate = function (res) {
    const {
        valid_from,
        valid_to,
        subjectaltname,
        issuer,
        fingerprint,
    } = res.request.res.socket.getPeerCertificate(false);

    if (!valid_from || !valid_to || !subjectaltname) {
        throw { message: 'No TLS certificate in response' };
    }

    const valid = res.request.res.socket.authorized || false;

    const validTo = new Date(valid_to);

    const validFor = subjectaltname
        .replace(/DNS:|IP Address:/g, "")
        .split(", ");

    const daysRemaining = getDaysRemaining(new Date(), validTo);

    return {
        valid,
        validFor,
        validTo,
        daysRemaining,
        issuer,
        fingerprint,
    };
}
Repository: louislam/uptime-kuma
File: server/server.js (JavaScript)

Code before:
 */
let jwtSecret = null;

/**
 * Main monitor list
 * @type {{}}
 */
let monitorList = {};

/**
 * Show Setup Page
 * @type {boolean}
 */
let needSetup = false;

(async () => {
    await initDatabase();

    console.log("Adding route")
    app.use('/', express.static("dist"));

    console.log("Adding /metrics")
     app.get('/metrics', function (req, res) {
   res.set('Content-Type', prom_client.register.contentType);
   res.end(prom_client.register.metrics());
 });

    app.get('*', function(request, response, next) {
        response.sendFile(process.cwd() + '/dist/index.html');
    });


    console.log("Adding socket handler")
    io.on('connection', async (socket) => {

        socket.emit("info", {
            version,
        })

        totalClient++;

        if (needSetup) {
            console.log("Redirect to setup page")
            socket.emit("setup")
        }

        socket.on('disconnect', () => {
            totalClient--;
        });

        // Public API

Review comment (suggestion):
```suggestion
    console.log("Adding /metrics")
    app.get('/metrics', function (req, res) {
        res.set('Content-Type', prom_client.register.contentType);
        res.end(prom_client.register.metrics());
    });
```

Code after:
 */
let monitorList = {};

/**
 * Show Setup Page
 * @type {boolean}
 */
let needSetup = false;

(async () => {
    await initDatabase();

    console.log("Adding route")
    app.use('/', express.static("dist"));
    app.use(apiMetrics())


    app.get('*', function(request, response, next) {
        response.sendFile(process.cwd() + '/dist/index.html');
    });


    console.log("Adding socket handler")
    io.on('connection', async (socket) => {

        socket.emit("info", {
            version,
        })

        totalClient++;

        if (needSetup) {
            console.log("Redirect to setup page")
            socket.emit("setup")
        }

        socket.on('disconnect', () => {
            totalClient--;
        });

        // Public API

        socket.on("loginByToken", async (token, callback) => {

            try {
                let decoded = jwt.verify(token, jwtSecret);

                console.log("Username from JWT: " + decoded.username)

                let user = await R.findOne("user", " username = ? AND active = 1 ", [
                    decoded.username
Repository: louislam/uptime-kuma
File: src/mixins/theme.js (JavaScript)

Code before:
export default {

    data() {
        return {
            system: (window.matchMedia("(prefers-color-scheme: dark)").matches) ? "dark" : "light",
            userTheme: localStorage.theme,
            userHeartbeatBar: localStorage.heartbeatBarTheme
        };
    },

    mounted() {
        // Default Light
        if (! this.userTheme) {
            this.userTheme = "light";
        }

        //Default Heartbeat Bar
        if (! this.userHeartbeatBar) {
            this.userHeartbeatBar = "normal";
        }

        document.body.classList.add(this.theme);
        this.updateThemeColorMeta();
    },

    computed: {
        theme() {
            if (this.userTheme === "auto") {
                return this.system;
            }
            return this.userTheme;
        }

Review comment (suggestion):
```suggestion
            userHeartbeatBar: localStorage.heartbeatBarTheme,
```

Code after:
export default {

    data() {
        return {
            system: (window.matchMedia("(prefers-color-scheme: dark)").matches) ? "dark" : "light",
            userTheme: localStorage.theme,
            userHeartbeatBar: localStorage.heartbeatBarTheme,
        };
    },

    mounted() {
        // Default Light
        if (! this.userTheme) {
            this.userTheme = "light";
        }

        // Default Heartbeat Bar
        if (!this.userHeartbeatBar) {
            this.userHeartbeatBar = "normal";
        }

        document.body.classList.add(this.theme);
        this.updateThemeColorMeta();
    },

    computed: {
        theme() {
            if (this.userTheme === "auto") {
                return this.system;
            }
            return this.userTheme;
        }
Repository: louislam/uptime-kuma
File: src/mixins/theme.js (JavaScript)

Code before:
export default {

    data() {
        return {
            system: (window.matchMedia("(prefers-color-scheme: dark)").matches) ? "dark" : "light",
            userTheme: localStorage.theme,
            userHeartbeatBar: localStorage.heartbeatBarTheme
        };
    },

    mounted() {
        // Default Light
        if (! this.userTheme) {
            this.userTheme = "light";
        }

        //Default Heartbeat Bar
        if (! this.userHeartbeatBar) {
            this.userHeartbeatBar = "normal";
        }

        document.body.classList.add(this.theme);
        this.updateThemeColorMeta();
    },

    computed: {
        theme() {
            if (this.userTheme === "auto") {
                return this.system;
            }
            return this.userTheme;
        }
    },

    watch: {
        userTheme(to, from) {
            localStorage.theme = to;
        },

        theme(to, from) {
            document.body.classList.remove(from);
            document.body.classList.add(this.theme);

Review comment (suggestion):
```suggestion
        // Default Heartbeat Bar
```

Code after:
export default {

    data() {
        return {
            system: (window.matchMedia("(prefers-color-scheme: dark)").matches) ? "dark" : "light",
            userTheme: localStorage.theme,
            userHeartbeatBar: localStorage.heartbeatBarTheme,
        };
    },

    mounted() {
        // Default Light
        if (! this.userTheme) {
            this.userTheme = "light";
        }

        // Default Heartbeat Bar
        if (!this.userHeartbeatBar) {
            this.userHeartbeatBar = "normal";
        }

        document.body.classList.add(this.theme);
        this.updateThemeColorMeta();
    },

    computed: {
        theme() {
            if (this.userTheme === "auto") {
                return this.system;
            }
            return this.userTheme;
        }
    },

    watch: {
        userTheme(to, from) {
            localStorage.theme = to;
        },

        theme(to, from) {
            document.body.classList.remove(from);
            document.body.classList.add(this.theme);
Repository: louislam/uptime-kuma
File: src/mixins/theme.js (JavaScript)

Code before:
export default {

    data() {
        return {
            system: (window.matchMedia("(prefers-color-scheme: dark)").matches) ? "dark" : "light",
            userTheme: localStorage.theme,
            userHeartbeatBar: localStorage.heartbeatBarTheme
        };
    },

    mounted() {
        // Default Light
        if (! this.userTheme) {
            this.userTheme = "light";
        }

        //Default Heartbeat Bar
        if (! this.userHeartbeatBar) {
            this.userHeartbeatBar = "normal";
        }

        document.body.classList.add(this.theme);
        this.updateThemeColorMeta();
    },

    computed: {
        theme() {
            if (this.userTheme === "auto") {
                return this.system;
            }
            return this.userTheme;
        }
    },

    watch: {
        userTheme(to, from) {
            localStorage.theme = to;
        },

        theme(to, from) {
            document.body.classList.remove(from);
            document.body.classList.add(this.theme);
            this.updateThemeColorMeta();

Review comment (suggestion):
```suggestion
        if (!this.userHeartbeatBar) {
```

Code after:
export default {

    data() {
        return {
            system: (window.matchMedia("(prefers-color-scheme: dark)").matches) ? "dark" : "light",
            userTheme: localStorage.theme,
            userHeartbeatBar: localStorage.heartbeatBarTheme,
        };
    },

    mounted() {
        // Default Light
        if (! this.userTheme) {
            this.userTheme = "light";
        }

        // Default Heartbeat Bar
        if (!this.userHeartbeatBar) {
            this.userHeartbeatBar = "normal";
        }

        document.body.classList.add(this.theme);
        this.updateThemeColorMeta();
    },

    computed: {
        theme() {
            if (this.userTheme === "auto") {
                return this.system;
            }
            return this.userTheme;
        }
    },

    watch: {
        userTheme(to, from) {
            localStorage.theme = to;
        },

        theme(to, from) {
            document.body.classList.remove(from);
            document.body.classList.add(this.theme);
            this.updateThemeColorMeta();
Repository: louislam/uptime-kuma
File: server/server.js (JavaScript)

Code before:
                    msg: "2FA Disabled.",
                })
            } catch (error) {
                callback({
                    ok: false,
                    msg: "Error while trying to change 2FA.",
                })
            }
        });

        socket.on("verifyToken", async (token, callback) => {
            let user = await R.findOne("user", " id = ? AND active = 1 ", [
                socket.userID,
            ])

            let verify = notp.totp.verify(token, user.twofa_secret);

            if (verify && verify.delta == 0) {
                callback({
                    ok: true,
                    valid: true,
                })
            } else {
                callback({
                    ok: false,
                    msg: "Token Invalid.",
                    valid: false,
                })
            }
        });

        socket.on("twoFAStatus", async (callback) => {
            checkLogin(socket)

            try {
                let user = await R.findOne("user", " id = ? AND active = 1 ", [
                    socket.userID,
                ])

                if (user.twofa_status == 1) {
                    callback({
                        ok: true,
                        status: true,
                    })
                } else {
                    callback({
                        ok: true,
                        status: false,
                    })
                }
            } catch (error) {

Review comment (suggestion):
```suggestion
                    msg: "Invalid Token.",
```

Code after:
                    msg: "2FA Disabled.",
                })
            } catch (error) {
                callback({
                    ok: false,
                    msg: "Error while trying to change 2FA.",
                })
            }
        });

        socket.on("verifyToken", async (token, callback) => {
            let user = await R.findOne("user", " id = ? AND active = 1 ", [
                socket.userID,
            ])

            let verify = notp.totp.verify(token, user.twofa_secret);

            if (verify && verify.delta == 0) {
                callback({
                    ok: true,
                    valid: true,
                })
            } else {
                callback({
                    ok: false,
                    msg: "Invalid Token.",
                    valid: false,
                })
            }
        });

        socket.on("twoFAStatus", async (callback) => {
            checkLogin(socket)

            try {
                let user = await R.findOne("user", " id = ? AND active = 1 ", [
                    socket.userID,
                ])

                if (user.twofa_status == 1) {
                    callback({
                        ok: true,
                        status: true,
                    })
                } else {
                    callback({
                        ok: true,
                        status: false,
                    })
                }
            } catch (error) {