-
Notifications
You must be signed in to change notification settings - Fork 13.9k
feat: OAuth login using login codes #40783
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
33eca86
de6d28b
48a1b7f
8fa7e0b
2b48af6
3f2f250
f8726a5
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,71 @@ | ||
| import { LoginCodes } from '@rocket.chat/models'; | ||
| import { ajv, validateBadRequestErrorResponse, validateUnauthorizedErrorResponse } from '@rocket.chat/rest-typings'; | ||
| import type { JSONSchemaType } from 'ajv'; | ||
| import { Accounts } from 'meteor/accounts-base'; | ||
|
|
||
| import type { ExtractRoutesFromAPI } from '../ApiClass'; | ||
| import { API } from '../api'; | ||
|
|
||
| const loginCodeRedeemResponse = ajv.compile<{ loginToken: string; userId: string }>({ | ||
| type: 'object', | ||
| properties: { | ||
| loginToken: { type: 'string' }, | ||
| userId: { type: 'string' }, | ||
| success: { type: 'boolean', enum: [true] }, | ||
| }, | ||
| required: ['loginToken', 'userId', 'success'], | ||
| additionalProperties: false, | ||
| }); | ||
|
|
||
| type LoginCodeRedeemParams = { code: string }; | ||
|
|
||
| const LoginCodeRedeemSchema: JSONSchemaType<LoginCodeRedeemParams> = { | ||
| type: 'object', | ||
| properties: { | ||
| code: { type: 'string', minLength: 64, maxLength: 64 }, | ||
| }, | ||
| required: ['code'], | ||
| additionalProperties: false, | ||
| }; | ||
|
|
||
| const isLoginCodeRedeemParamsPOST = ajv.compile<LoginCodeRedeemParams>(LoginCodeRedeemSchema); | ||
|
|
||
| const loginCodeEndpoints = API.v1.post( | ||
| 'loginCode.redeem', | ||
| { | ||
| authRequired: false, | ||
| body: isLoginCodeRedeemParamsPOST, | ||
| rateLimiterOptions: { intervalTimeInMS: 60000, numRequestsAllowed: 10 }, | ||
| response: { | ||
| 200: loginCodeRedeemResponse, | ||
| 400: validateBadRequestErrorResponse, | ||
| 401: validateUnauthorizedErrorResponse, | ||
| }, | ||
| }, | ||
| async function action() { | ||
| const { code } = this.bodyParams; | ||
|
|
||
| const loginCode = await LoginCodes.findOneNotExpiredByCodeAndDelete(code); | ||
|
|
||
| if (!loginCode) { | ||
| return API.v1.failure('error-invalid-code'); | ||
| } | ||
|
|
||
| const { userId } = loginCode; | ||
|
|
||
| const stampedToken = Accounts._generateStampedLoginToken(); | ||
| await Accounts._insertLoginToken(userId, stampedToken); | ||
|
|
||
| return API.v1.success({ | ||
| loginToken: stampedToken.token, | ||
| userId, | ||
| }); | ||
| }, | ||
| ); | ||
|
|
||
| type LoginCodeEndpoints = ExtractRoutesFromAPI<typeof loginCodeEndpoints>; | ||
|
|
||
| declare module '@rocket.chat/rest-typings' { | ||
| // eslint-disable-next-line @typescript-eslint/naming-convention, @typescript-eslint/no-empty-interface | ||
| interface Endpoints extends LoginCodeEndpoints {} | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -31,6 +31,7 @@ import { useLoginOtherClients } from './hooks/useLoginOtherClients'; | |
| import { useLoginViaQuery } from './hooks/useLoginViaQuery'; | ||
| import { useMessageLinkClicks } from './hooks/useMessageLinkClicks'; | ||
| import { useNotificationPermission } from './hooks/useNotificationPermission'; | ||
| import { useOAuthLogin } from './hooks/useOAuthLogin'; | ||
| import { useRedirectToSetupWizard } from './hooks/useRedirectToSetupWizard'; | ||
| import { useSettingsOnLoadSiteUrl } from './hooks/useSettingsOnLoadSiteUrl'; | ||
| import { useShareSessionWithOtherClients } from './hooks/useShareSessionWithOtherClients'; | ||
|
|
@@ -73,6 +74,7 @@ const AppLayout = () => { | |
| useCodeHighlight(); | ||
| useLoginViaQuery(); | ||
| useLoginOtherClients(); | ||
| useOAuthLogin(); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. P1: OAuth login error handling is overridden by an unconditional Prompt for AI agents
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. P1: Adding Prompt for AI agents |
||
| useShareSessionWithOtherClients(); | ||
| useLoadMissedMessages(); | ||
| useDesktopFavicon(); | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,46 @@ | ||
| import { useEndpoint, useRouter, useSearchParameter, useLoginWithToken } from '@rocket.chat/ui-contexts'; | ||
| import { useMutation } from '@tanstack/react-query'; | ||
| import { useEffect } from 'react'; | ||
|
|
||
| import { buildDeepLinkURL } from '../../../lib/buildAuthDeeplinkURL'; | ||
|
|
||
| export const useOAuthLogin = () => { | ||
| const router = useRouter(); | ||
| const loginCode = useSearchParameter('loginCode'); | ||
| const loginClient = useSearchParameter('loginClient'); | ||
| const redeemLoginCode = useEndpoint('POST', '/v1/loginCode.redeem'); | ||
| const loginWithToken = useLoginWithToken(); | ||
|
|
||
| const { mutate: redeemLoginCodeMutation } = useMutation({ | ||
| mutationFn: async (loginCode: string) => { | ||
| const { loginToken, userId } = await redeemLoginCode({ code: loginCode }); | ||
|
|
||
| if (!loginToken || !userId) { | ||
| throw new Error('Invalid response from login code redemption'); | ||
| } | ||
|
|
||
| return { loginToken, userId }; | ||
| }, | ||
| onSuccess: async ({ loginToken, userId }) => { | ||
| if (loginClient === 'desktop' || loginClient === 'mobile') { | ||
| window.location.href = buildDeepLinkURL(loginToken, userId); | ||
| return; | ||
| } | ||
|
|
||
| await loginWithToken(loginToken); | ||
| router.navigate('/home', { replace: true }); | ||
| }, | ||
| onError: (error) => { | ||
| console.error('Failed to redeem login code for client redirect', error); | ||
| router.navigate('/login', { replace: true }); | ||
| }, | ||
| }); | ||
|
|
||
| useEffect(() => { | ||
| if (!loginCode) { | ||
| return; | ||
| } | ||
|
|
||
| redeemLoginCodeMutation(loginCode); | ||
| }, [loginCode, redeemLoginCodeMutation]); | ||
| }; |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,140 @@ | ||
| import { randomBytes } from 'crypto'; | ||
|
|
||
| import type { ILoginCode, IUser } from '@rocket.chat/core-typings'; | ||
| import { expect } from 'chai'; | ||
| import { after, before, describe, it } from 'mocha'; | ||
| import { MongoClient } from 'mongodb'; | ||
|
|
||
| import { api, request, getCredentials } from '../../data/api-data'; | ||
| import type { TestUser } from '../../data/users.helper'; | ||
| import { createUser, deleteUser } from '../../data/users.helper'; | ||
| import { URL_MONGODB } from '../../e2e/config/constants'; | ||
|
|
||
| const CODE_TTL_MS = 60 * 1000; | ||
|
cubic-dev-ai[bot] marked this conversation as resolved.
|
||
|
|
||
| async function insertLoginCode(connection: MongoClient, userId: string, insertExpiredToken: boolean = false): Promise<string> { | ||
| const now = new Date(); | ||
| const code = randomBytes(32).toString('hex'); | ||
|
|
||
| let expireAt = new Date(now.getTime() + CODE_TTL_MS); | ||
|
|
||
| if (insertExpiredToken) { | ||
| expireAt = new Date(now.getTime() - 1); | ||
| } | ||
|
|
||
| await connection.db().collection<ILoginCode>('rocketchat_login_codes').insertOne({ | ||
| _id: code, | ||
| userId, | ||
| createdAt: now, | ||
| expireAt, | ||
| }); | ||
|
|
||
| return code; | ||
| } | ||
|
|
||
| describe('[Login Codes]', () => { | ||
| let connection: MongoClient; | ||
|
|
||
| before((done) => getCredentials(done)); | ||
|
|
||
| before(async () => { | ||
| connection = await MongoClient.connect(URL_MONGODB); | ||
| }); | ||
|
|
||
| after(async () => { | ||
| await connection.close(); | ||
| }); | ||
|
|
||
| describe('POST [/loginCode.redeem]', () => { | ||
| let testUser: TestUser<IUser>; | ||
|
|
||
| before(async () => { | ||
| testUser = await createUser(); | ||
| }); | ||
|
|
||
| after(async () => { | ||
| await deleteUser(testUser); | ||
| }); | ||
|
|
||
| it('should fail when code does not exist in the database', async () => { | ||
| await request | ||
| .post(api('loginCode.redeem')) | ||
| .send({ code: 'a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2' }) | ||
| .expect(400) | ||
| .expect((res) => { | ||
| expect(res.body).to.have.property('success', false); | ||
| }); | ||
| }); | ||
|
|
||
| it('should fail when code is an empty string', async () => { | ||
| await request | ||
| .post(api('loginCode.redeem')) | ||
| .send({ code: '' }) | ||
| .expect(400) | ||
| .expect((res) => { | ||
| expect(res.body).to.have.property('success', false); | ||
| expect(res.body).to.have.property('errorType', 'invalid-params'); | ||
| }); | ||
| }); | ||
|
|
||
| it('should return a loginToken and userId for a valid code', async () => { | ||
| const code = await insertLoginCode(connection, testUser._id); | ||
|
|
||
| await request | ||
| .post(api('loginCode.redeem')) | ||
| .send({ code }) | ||
| .expect(200) | ||
| .expect((res) => { | ||
| expect(res.body).to.have.property('success', true); | ||
| expect(res.body).to.have.property('loginToken').that.is.a('string').and.is.not.empty; | ||
| expect(res.body).to.have.property('userId', testUser._id); | ||
| }); | ||
| }); | ||
|
|
||
| it('should invalidate a code after it has been redeemed', async () => { | ||
| const code = await insertLoginCode(connection, testUser._id); | ||
|
|
||
| await request.post(api('loginCode.redeem')).send({ code }).expect(200); | ||
|
|
||
| await request | ||
| .post(api('loginCode.redeem')) | ||
| .send({ code }) | ||
| .expect(400) | ||
| .expect((res) => { | ||
| expect(res.body).to.have.property('success', false); | ||
| expect(res.body).to.have.property('error', 'error-invalid-code'); | ||
| }); | ||
| }); | ||
|
|
||
| it('should return a loginToken that can be used for subsequent authenticated requests', async () => { | ||
| const code = await insertLoginCode(connection, testUser._id); | ||
|
|
||
| const redeemRes = await request.post(api('loginCode.redeem')).send({ code }).expect(200); | ||
|
|
||
| const { loginToken, userId } = redeemRes.body; | ||
|
|
||
| await request | ||
| .get(api('me')) | ||
| .set('X-Auth-Token', loginToken) | ||
| .set('X-User-Id', userId) | ||
| .expect(200) | ||
| .expect((res) => { | ||
| expect(res.body).to.have.property('success', true); | ||
| expect(res.body).to.have.property('_id', testUser._id); | ||
| }); | ||
| }); | ||
|
|
||
| it('should fail when code is expired', async () => { | ||
| const code = await insertLoginCode(connection, testUser._id, true); | ||
|
|
||
| await request | ||
| .post(api('loginCode.redeem')) | ||
| .send({ code }) | ||
| .expect(400) | ||
| .expect((res) => { | ||
| expect(res.body).to.have.property('success', false); | ||
| expect(res.body).to.have.property('error', 'error-invalid-code'); | ||
| }); | ||
| }); | ||
| }); | ||
| }); | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| export interface ILoginCode { | ||
| _id: string; | ||
| userId: string; | ||
| createdAt: Date; | ||
| expireAt: Date; | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| import type { ILoginCode } from '@rocket.chat/core-typings'; | ||
|
|
||
| import type { IBaseModel } from './IBaseModel'; | ||
|
|
||
| export interface ILoginCodesModel extends IBaseModel<ILoginCode> { | ||
| createCode(userId: string): Promise<string>; | ||
| findOneNotExpiredByCodeAndDelete(code: string): Promise<ILoginCode | null>; | ||
| } |
Uh oh!
There was an error while loading. Please reload this page.