{"record":{"id":"15a70756f6a1167d","repo":"yikart/AiToEarn","slug":"state","errorCode":null,"errorMessage":"无效的state参数","messagePattern":"无效的state参数","errorType":"validation","errorClass":"BadRequestException","httpStatus":400,"severity":"warning","filePath":"project/aitoearn-electron/server/src/modules/plat/youtube/youtube.controller.ts","lineNumber":86,"sourceCode":"  @Public()\n  @Get('auth/callback')\n  async handleAuthCallback(\n    // @GetToken() systemToken: TokenInfo,\n    @Query('code') code: string,\n    @Query('state') state: string,\n    // @Query('userId') userId: string,\n    @Res() res: Response\n  ) {\n\n    if (!code || !state) {\n      throw new BadRequestException('授权参数不完整');\n    }\n      // 解析state参数以获取token\n      let stateData;\n      try {\n        stateData = JSON.parse(decodeURIComponent(state));\n      } catch (error) {\n        throw new BadRequestException('无效的state参数');\n      }\n\n      const { originalState, userId, email } = stateData;\n\n      // 现在您可以使用token变量\n      console.log('Retrieved userId and originalState:', userId, originalState, email);\n\n    try {\n      const results = await this.youtubeAuthService.handleAuthorizationCode(code, originalState, userId);\n      // 重定向到前端页面，带上token\n      // return res.redirect(`/auth/success?token=${token}`);\n      // return results\n      const render_msg = {\n        message: \"授权成功！ 这里是添加账号成功后的前端页面，\" ,\n        datas: results\n      };\n\n      return res.render('google/index', render_msg);","sourceCodeStart":68,"sourceCodeEnd":104,"githubUrl":"https://github.com/yikart/AiToEarn/blob/d3aa8bea5b146a8675607cf0144d891aad3e9683/project/aitoearn-electron/server/src/modules/plat/youtube/youtube.controller.ts#L68-L104","documentation":"The 'state' query parameter in the OAuth callback must be a URI-encoded JSON string containing originalState, userId and email. If decodeURIComponent(state) or JSON.parse fails, BadRequestException '无效的state参数' (invalid state parameter) is thrown.","triggerScenarios":"The state value was double-encoded or not encoded at all so JSON.parse receives malformed input; a client modified/truncated the state; the callback is invoked manually with a non-JSON state value.","commonSituations":"Building the auth URL manually and passing JSON without encodeURIComponent (raw {,},\" characters break parsing after framework decoding); passing state that was already decoded once by a proxy; frontend builds state differently than the callback expects (schema mismatch).","solutions":["When creating the auth URL, always URI-encode the JSON: encodeURIComponent(JSON.stringify({originalState, userId, email}))","Log the received raw state value before parsing to spot encoding issues","Ensure no middleware/proxy double-decodes the query string","Align the state schema between the code that builds the URL and the callback handler"],"exampleFix":"// before\nconst state = JSON.stringify({ originalState, userId, email }); // raw JSON in URL\nconst url = `${authUrl}&state=${state}`;\n// after\nconst state = encodeURIComponent(JSON.stringify({ originalState, userId, email }));\nconst url = `${authUrl}&state=${state}`;","handlingStrategy":"type-guard","validationCode":"const raw = decodeURIComponent(state);\nconst parsed = JSON.parse(raw); // wrap in try\nif (!('originalState' in parsed) || !('userId' in parsed) || !('email' in parsed)) {\n  throw new Error('state JSON missing required fields');\n}","typeGuard":"function isValidState(v: unknown): v is { originalState: string; userId: string; email: string } {\n  return !!v && typeof v === 'object' &&\n    typeof (v as any).originalState === 'string' &&\n    typeof (v as any).userId === 'string' &&\n    typeof (v as any).email === 'string';\n}","tryCatchPattern":"try {\n  stateData = JSON.parse(decodeURIComponent(state));\n  if (!isValidState(stateData)) throw new Error('bad state schema');\n} catch {\n  return res.status(400).send('invalid state');\n}","preventionTips":["Always encodeURIComponent(JSON.stringify(state)) when building the auth URL","Keep the state schema defined in one shared module for builder and parser","Log the raw state on parse failure to diagnose encoding issues","Avoid proxies that rewrite/re-decode query strings"],"tags":["oauth","json","encoding","http-400"],"backgroundTag":"invalid-oauth-state","analyzedSha":"d3aa8bea5b146a8675607cf0144d891aad3e9683","analyzedAt":"2026-08-31T14:19:24.185Z","schemaVersion":2},"datasetVersion":"2026-08-31T19:17:28.585Z"}