{"record":{"id":"30e8089ee815735a","repo":"yikart/AiToEarn","slug":"invalid-google-token","errorCode":null,"errorMessage":"Invalid Google token","messagePattern":"Invalid Google token","errorType":"exception","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"project/aitoearn-electron/server/src/modules/plat/google/google.service.ts","lineNumber":403,"sourceCode":"  /**\n   * Google登录\n   * @param clientId Google客户端ID\n   * @param credential Google认证凭证\n   * @returns Account\n   */\n  async googleLogin(clientId: string, credential: string): Promise<any> {\n    try {\n      console.log('Verifying Google token with:');\n      // 验证Google token\n      const ticket = await this.oauth2Client.verifyIdToken({\n        idToken: credential,\n        audience: clientId,\n      });\n      console.log('ticket',ticket)\n      const googleUser = ticket.getPayload();\n      console.log('payload',googleUser)\n      if (!googleUser) {\n        throw new Error('Invalid Google token');\n      }\n\n      console.log('Google login success, googleUser:', googleUser);\n\n      const googleAccount = {\n        googleId: googleUser.sub,\n        email: googleUser.email,\n        // accessToken: result.data.access_token,\n        refreshToken: null,\n        // expiresAt: result.data.expires_in\n      };\n\n      let userInfo: User | null = null;\n      // 优先用 Google ID 查找（最准确）\n      if (googleUser.sub) {\n        userInfo = await this.userModel.findOne({\n          'googleAccount.googleId': googleUser.sub,\n          status: UserStatus.OPEN,","sourceCodeStart":385,"sourceCodeEnd":421,"githubUrl":"https://github.com/yikart/AiToEarn/blob/d3aa8bea5b146a8675607cf0144d891aad3e9683/project/aitoearn-electron/server/src/modules/plat/google/google.service.ts#L385-L421","documentation":"googleLogin verifies a Google ID token with google-auth-library's OAuth2Client.verifyIdToken. After verification, ticket.getPayload() must return the decoded claims; if it returns null/undefined the token cannot be trusted and the service throws Error('Invalid Google token'). This guards against empty or malformed tokens reaching the login flow.","triggerScenarios":"Calling googleLogin with an idToken that is empty, malformed, or decodes to no payload — i.e. verifyIdToken resolves but getPayload() returns falsy.","commonSituations":"Frontend sends an empty string token when the user aborted Google Sign-In; wrong clientId/audience causing an unexpected payload shape; passing an access_token instead of an id_token; an outdated google-auth-library version behaving differently.","solutions":["Check the client is sending the real Google ID token (credential/id_token), not an access token or empty string","Verify the clientId passed as audience matches the OAuth client that issued the token","Validate the token string is non-empty before calling googleLogin","Upgrade google-auth-library to the latest version","Catch this in the controller and return 401 instead of a raw 500"],"exampleFix":"// before\nif (!googleUser) {\n  throw new Error('Invalid Google token');\n}\n// after\nif (!googleUser || !googleUser.sub || !googleUser.email) {\n  throw new UnauthorizedException('Invalid or incomplete Google token payload');\n}","handlingStrategy":"validation","validationCode":"if (typeof idToken !== 'string' || idToken.split('.').length !== 3) {\n  throw new UnauthorizedException('A valid Google id_token is required');\n}","typeGuard":"function hasGooglePayload(t: unknown): t is { sub: string; email: string } {\n  return !!t && typeof t === 'object' && 'sub' in t && typeof (t as any).sub === 'string';\n}","tryCatchPattern":"try {\n  await authService.googleLogin(idToken, clientId);\n} catch (err) {\n  if (err.message.includes('Invalid Google token')) {\n    return res.status(401).json({ error: 'Please sign in with Google again' });\n  }\n  throw err;\n}","preventionTips":["Send the id_token (credential), never the access_token","Confirm audience/clientId matches the OAuth client on both frontend and backend","Reject empty tokens client-side before calling the API","Keep google-auth-library up to date"],"tags":["google","oauth","id-token","authentication"],"backgroundTag":"invalid-google-token","analyzedSha":"d3aa8bea5b146a8675607cf0144d891aad3e9683","analyzedAt":"2026-08-31T14:19:24.185Z","schemaVersion":2},"datasetVersion":"2026-08-31T19:17:28.585Z"}