ニジカ投稿局 https://tv.nizika.tv
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

231 lines
6.8 KiB

  1. import express from 'express'
  2. import OAuth2Server, {
  3. InvalidClientError,
  4. InvalidGrantError,
  5. InvalidRequestError,
  6. Request,
  7. Response,
  8. UnauthorizedClientError,
  9. UnsupportedGrantTypeError
  10. } from '@node-oauth/oauth2-server'
  11. import { randomBytesPromise } from '@server/helpers/core-utils.js'
  12. import { isOTPValid } from '@server/helpers/otp.js'
  13. import { CONFIG } from '@server/initializers/config.js'
  14. import { UserRegistrationModel } from '@server/models/user/user-registration.js'
  15. import { MOAuthClient } from '@server/types/models/index.js'
  16. import { sha1 } from '@peertube/peertube-node-utils'
  17. import { HttpStatusCode, ServerErrorCode, UserRegistrationState } from '@peertube/peertube-models'
  18. import { OTP } from '../../initializers/constants.js'
  19. import { BypassLogin, getAccessToken, getClient, getRefreshToken, getUser, revokeToken, saveToken } from './oauth-model.js'
  20. class MissingTwoFactorError extends Error {
  21. code = HttpStatusCode.UNAUTHORIZED_401
  22. name = ServerErrorCode.MISSING_TWO_FACTOR
  23. }
  24. class InvalidTwoFactorError extends Error {
  25. code = HttpStatusCode.BAD_REQUEST_400
  26. name = ServerErrorCode.INVALID_TWO_FACTOR
  27. }
  28. class RegistrationWaitingForApproval extends Error {
  29. code = HttpStatusCode.BAD_REQUEST_400
  30. name = ServerErrorCode.ACCOUNT_WAITING_FOR_APPROVAL
  31. }
  32. class RegistrationApprovalRejected extends Error {
  33. code = HttpStatusCode.BAD_REQUEST_400
  34. name = ServerErrorCode.ACCOUNT_APPROVAL_REJECTED
  35. }
  36. /**
  37. *
  38. * Reimplement some functions of OAuth2Server to inject external auth methods
  39. *
  40. */
  41. const oAuthServer = new OAuth2Server({
  42. // Wants seconds
  43. accessTokenLifetime: CONFIG.OAUTH2.TOKEN_LIFETIME.ACCESS_TOKEN / 1000,
  44. refreshTokenLifetime: CONFIG.OAUTH2.TOKEN_LIFETIME.REFRESH_TOKEN / 1000,
  45. // See https://github.com/oauthjs/node-oauth2-server/wiki/Model-specification for the model specifications
  46. model: {
  47. getAccessToken,
  48. getClient,
  49. getRefreshToken,
  50. getUser,
  51. revokeToken,
  52. saveToken
  53. } as any // FIXME: typings
  54. })
  55. // ---------------------------------------------------------------------------
  56. async function handleOAuthToken (req: express.Request, options: { refreshTokenAuthName?: string, bypassLogin?: BypassLogin }) {
  57. const request = new Request(req)
  58. const { refreshTokenAuthName, bypassLogin } = options
  59. if (request.method !== 'POST') {
  60. throw new InvalidRequestError('Invalid request: method must be POST')
  61. }
  62. if (!request.is([ 'application/x-www-form-urlencoded' ])) {
  63. throw new InvalidRequestError('Invalid request: content must be application/x-www-form-urlencoded')
  64. }
  65. const clientId = request.body.client_id
  66. const clientSecret = request.body.client_secret
  67. if (!clientId || !clientSecret) {
  68. throw new InvalidClientError('Invalid client: cannot retrieve client credentials')
  69. }
  70. const client = await getClient(clientId, clientSecret)
  71. if (!client) {
  72. throw new InvalidClientError('Invalid client: client is invalid')
  73. }
  74. const grantType = request.body.grant_type
  75. if (!grantType) {
  76. throw new InvalidRequestError('Missing parameter: `grant_type`')
  77. }
  78. if (![ 'password', 'refresh_token' ].includes(grantType)) {
  79. throw new UnsupportedGrantTypeError('Unsupported grant type: `grant_type` is invalid')
  80. }
  81. if (!client.grants.includes(grantType)) {
  82. throw new UnauthorizedClientError('Unauthorized client: `grant_type` is invalid')
  83. }
  84. if (grantType === 'password') {
  85. return handlePasswordGrant({
  86. request,
  87. client,
  88. bypassLogin
  89. })
  90. }
  91. return handleRefreshGrant({
  92. request,
  93. client,
  94. refreshTokenAuthName
  95. })
  96. }
  97. function handleOAuthAuthenticate (
  98. req: express.Request,
  99. res: express.Response
  100. ) {
  101. return oAuthServer.authenticate(new Request(req), new Response(res))
  102. }
  103. export {
  104. MissingTwoFactorError,
  105. InvalidTwoFactorError,
  106. handleOAuthToken,
  107. handleOAuthAuthenticate
  108. }
  109. // ---------------------------------------------------------------------------
  110. async function handlePasswordGrant (options: {
  111. request: Request
  112. client: MOAuthClient
  113. bypassLogin?: BypassLogin
  114. }) {
  115. const { request, client, bypassLogin } = options
  116. if (!request.body.username) {
  117. throw new InvalidRequestError('Missing parameter: `username`')
  118. }
  119. if (!bypassLogin && !request.body.password) {
  120. throw new InvalidRequestError('Missing parameter: `password`')
  121. }
  122. const user = await getUser(request.body.username, request.body.password, bypassLogin)
  123. if (!user) {
  124. const registration = await UserRegistrationModel.loadByEmailOrUsername(request.body.username)
  125. if (registration?.state === UserRegistrationState.REJECTED) {
  126. throw new RegistrationApprovalRejected('Registration approval for this account has been rejected')
  127. } else if (registration?.state === UserRegistrationState.PENDING) {
  128. throw new RegistrationWaitingForApproval('Registration for this account is awaiting approval')
  129. }
  130. throw new InvalidGrantError('Invalid grant: user credentials are invalid')
  131. }
  132. if (user.otpSecret) {
  133. if (!request.headers[OTP.HEADER_NAME]) {
  134. throw new MissingTwoFactorError('Missing two factor header')
  135. }
  136. if (await isOTPValid({ encryptedSecret: user.otpSecret, token: request.headers[OTP.HEADER_NAME] }) !== true) {
  137. throw new InvalidTwoFactorError('Invalid two factor header')
  138. }
  139. }
  140. const token = await buildToken()
  141. return saveToken(token, client, user, { bypassLogin })
  142. }
  143. async function handleRefreshGrant (options: {
  144. request: Request
  145. client: MOAuthClient
  146. refreshTokenAuthName: string
  147. }) {
  148. const { request, client, refreshTokenAuthName } = options
  149. if (!request.body.refresh_token) {
  150. throw new InvalidRequestError('Missing parameter: `refresh_token`')
  151. }
  152. const refreshToken = await getRefreshToken(request.body.refresh_token)
  153. if (!refreshToken) {
  154. throw new InvalidGrantError('Invalid grant: refresh token is invalid')
  155. }
  156. if (refreshToken.client.id !== client.id) {
  157. throw new InvalidGrantError('Invalid grant: refresh token is invalid')
  158. }
  159. if (refreshToken.refreshTokenExpiresAt && refreshToken.refreshTokenExpiresAt < new Date()) {
  160. throw new InvalidGrantError('Invalid grant: refresh token has expired')
  161. }
  162. await revokeToken({ refreshToken: refreshToken.refreshToken })
  163. const token = await buildToken()
  164. return saveToken(token, client, refreshToken.user, { refreshTokenAuthName })
  165. }
  166. function generateRandomToken () {
  167. return randomBytesPromise(256)
  168. .then(buffer => sha1(buffer))
  169. }
  170. function getTokenExpiresAt (type: 'access' | 'refresh') {
  171. const lifetime = type === 'access'
  172. ? CONFIG.OAUTH2.TOKEN_LIFETIME.ACCESS_TOKEN
  173. : CONFIG.OAUTH2.TOKEN_LIFETIME.REFRESH_TOKEN
  174. return new Date(Date.now() + lifetime)
  175. }
  176. async function buildToken () {
  177. const [ accessToken, refreshToken ] = await Promise.all([ generateRandomToken(), generateRandomToken() ])
  178. return {
  179. accessToken,
  180. refreshToken,
  181. accessTokenExpiresAt: getTokenExpiresAt('access'),
  182. refreshTokenExpiresAt: getTokenExpiresAt('refresh')
  183. }
  184. }