overnested / nestjs-octokit

Octokit module for NestJS
MIT License
12 stars 4 forks source link

How to refresh the auth token automatically? #2

Closed Helveg closed 2 years ago

Helveg commented 2 years ago

When authenticating as a GitHub App, the maximum expiration time is 10 minutes. This means that if the OctoService has been instantiated more than 10 minutes ago, the token expires and no more calls can be made:

[Nest] 5816  - 08/19/2022, 4:47:28 PM   ERROR [ExceptionsHandler] 'Expiration time' claim ('exp') must be a numeric value representing the future time at which the assertion expires
HttpError: 'Expiration time' claim ('exp') must be a numeric value representing the future time at which the assertion expires
    at C:\Users\pwd06\git\do-app-deployment-check\node_modules\nestjs-octokit\node_modules\@octokit\request\dist-src\fetch-wrapper.js:68:27
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at Job.doExecute (C:\Users\pwd06\git\do-app-deployment-check\node_modules\bottleneck\light.js:405:18)

How can the token be refreshed before calls are made? This is how I instantiate the module:

OctokitModule.forRootAsync({
      isGlobal: true,
      imports: [
        JwtModule.registerAsync({
          inject: [ConfigService],
          useFactory: async (config: ConfigService) => ({
            privateKey: config.get("GITHUB_PRIVATE_KEY")
          })
        }),
      ],
      inject: [JwtService, ConfigService],
      useFactory: async (jwt: JwtService, config: ConfigService) => ({
        octokitOptions: {
          auth: jwt.sign({}, {
            issuer: config.get("GITHUB_APP_IDENTIFIER"),
            expiresIn: 300,
            algorithm: 'RS256',
          }),
        },
      }),
    }),

The value for auth could easily be turned into an arrow function, and perhaps new octokits can be made on demand when the expiration time has passed?

An alternative would be to limit the injection scope to REQUEST perhaps? If that's the way to go, could we document this?